From 6ab5c9334d1b6594d79fc03ec3790252caa15e34 Mon Sep 17 00:00:00 2001 From: Renan DelValle Date: Thu, 27 Dec 2018 11:31:51 -0800 Subject: [PATCH] gorealis v2 refactor (#5) * Changing default timeout for start maintenance. * Upgrading dependencies to gorealis v2 and thrift 0.12.0 * Refactored to update to gorealis v2. --- CHANGELOG | 4 + Gopkg.lock | 15 +- Gopkg.toml | 8 +- cmd/fetch.go | 8 +- cmd/kill.go | 12 +- cmd/root.go | 12 +- cmd/set.go | 8 +- cmd/start.go | 26 +- cmd/stop.go | 18 +- debian/changelog | 6 + .../git.apache.org/thrift.git/.eslintignore | 9 + .../git.apache.org/thrift.git/.eslintrc.json | 24 + .../thrift.git/.github/stale.yml | 59 + vendor/git.apache.org/thrift.git/.gitignore | 155 +- .../git.apache.org/thrift.git/.rustfmt.toml | 64 + vendor/git.apache.org/thrift.git/.travis.yml | 304 +- vendor/git.apache.org/thrift.git/CHANGES | 547 + .../git.apache.org/thrift.git/CMakeLists.txt | 9 +- .../git.apache.org/thrift.git/CONTRIBUTING.md | 155 +- vendor/git.apache.org/thrift.git/Dockerfile | 61 - vendor/git.apache.org/thrift.git/LANGUAGES.md | 355 + vendor/git.apache.org/thrift.git/Makefile.am | 14 +- vendor/git.apache.org/thrift.git/NOTICE | 4 +- vendor/git.apache.org/thrift.git/README.md | 86 +- .../thrift.git/Thrift-swift3.podspec | 16 + .../git.apache.org/thrift.git/Thrift.podspec | 10 +- .../thrift.git/aclocal/ax_boost_base.m4 | 247 +- .../thrift.git/aclocal/ax_check_openssl.m4 | 6 +- ...mpare_version.m4 => ax_compare_version.m4} | 4 +- .../aclocal/ax_cxx_compile_stdcxx.m4 | 948 + .../aclocal/ax_cxx_compile_stdcxx_11.m4 | 160 +- .../thrift.git/aclocal/ax_javac_and_java.m4 | 2 +- .../thrift.git/aclocal/ax_lua.m4 | 6 +- .../aclocal/ax_prog_dotnetcore_version.m4 | 61 + .../aclocal/ax_prog_haxe_version.m4 | 4 +- .../aclocal/ax_prog_perl_modules.m4 | 4 +- vendor/git.apache.org/thrift.git/appveyor.yml | 147 +- vendor/git.apache.org/thrift.git/bootstrap.sh | 9 +- vendor/git.apache.org/thrift.git/bower.json | 2 +- .../build/appveyor/download_openssl.py | 41 - .../build/cmake/ConfigureChecks.cmake | 25 +- .../build/cmake/DefineCMakeDefaults.cmake | 25 +- .../build/cmake/DefineOptions.cmake | 37 +- .../build/cmake/DefinePlatformSpecifc.cmake | 59 +- .../thrift.git/build/cmake/FindLibevent.cmake | 10 +- .../thrift.git/build/cmake/config.h.in | 18 +- .../thrift.git/build/docker/README.md | 201 +- .../thrift.git/build/docker/Vagrantfile | 59 - .../thrift.git/build/docker/centos/Dockerfile | 142 - .../build/docker/centos6/Dockerfile | 54 - .../thrift.git/build/docker/debian/Dockerfile | 192 - .../thrift.git/build/docker/scripts/cmake.sh | 4 +- .../thrift.git/build/docker/ubuntu/Dockerfile | 209 - .../thrift.git/compiler/cpp/CMakeLists.txt | 41 +- .../thrift.git/compiler/cpp/Makefile.am | 12 +- .../thrift.git/compiler/cpp/README.md | 196 +- .../thrift.git/compiler/cpp/compiler.vcxproj | 11 +- .../compiler/cpp/compiler.vcxproj.filters | 5 +- .../compiler/cpp/src/thrift/audit/t_audit.cpp | 4 +- .../src/thrift/generate/t_as3_generator.cc | 142 +- .../src/thrift/generate/t_c_glib_generator.cc | 151 +- .../cpp/src/thrift/generate/t_cl_generator.cc | 558 + .../src/thrift/generate/t_cocoa_generator.cc | 188 +- .../src/thrift/generate/t_cpp_generator.cc | 469 +- .../src/thrift/generate/t_csharp_generator.cc | 296 +- .../cpp/src/thrift/generate/t_d_generator.cc | 52 +- .../src/thrift/generate/t_dart_generator.cc | 144 +- .../src/thrift/generate/t_delphi_generator.cc | 371 +- .../src/thrift/generate/t_erl_generator.cc | 240 +- .../cpp/src/thrift/generate/t_generator.cc | 84 +- .../cpp/src/thrift/generate/t_generator.h | 148 +- .../cpp/src/thrift/generate/t_go_generator.cc | 673 +- .../cpp/src/thrift/generate/t_gv_generator.cc | 8 +- .../src/thrift/generate/t_haxe_generator.cc | 154 +- .../cpp/src/thrift/generate/t_hs_generator.cc | 168 +- .../src/thrift/generate/t_html_generator.cc | 20 +- .../src/thrift/generate/t_java_generator.cc | 572 +- .../src/thrift/generate/t_javame_generator.cc | 218 +- .../cpp/src/thrift/generate/t_js_generator.cc | 994 +- .../src/thrift/generate/t_json_generator.cc | 74 +- .../src/thrift/generate/t_lua_generator.cc | 102 +- .../thrift/generate/t_netcore_generator.cc | 3117 ++ .../src/thrift/generate/t_netcore_generator.h | 137 + .../src/thrift/generate/t_ocaml_generator.cc | 92 +- .../cpp/src/thrift/generate/t_oop_generator.h | 8 +- .../src/thrift/generate/t_perl_generator.cc | 207 +- .../src/thrift/generate/t_php_generator.cc | 607 +- .../cpp/src/thrift/generate/t_py_generator.cc | 523 +- .../cpp/src/thrift/generate/t_rb_generator.cc | 33 +- .../cpp/src/thrift/generate/t_rs_generator.cc | 3339 ++ .../cpp/src/thrift/generate/t_st_generator.cc | 55 +- .../src/thrift/generate/t_swift_generator.cc | 2168 +- .../src/thrift/generate/t_xml_generator.cc | 13 +- .../src/thrift/generate/t_xsd_generator.cc | 4 +- .../thrift-t_php_generator.o-a60a38e9 | 0 .../compiler/cpp/src/thrift/main.cc | 9 +- .../cpp/src/thrift/parse/t_base_type.h | 6 +- .../cpp/src/thrift/parse/t_const_value.h | 72 +- .../cpp/src/thrift/parse/t_function.h | 15 +- .../compiler/cpp/src/thrift/parse/t_scope.h | 21 +- .../compiler/cpp/src/thrift/parse/t_type.h | 1 + .../compiler/cpp/src/thrift/parse/t_typedef.h | 7 +- .../compiler/cpp/src/thrift/platform.h | 7 +- .../compiler/cpp/src/thrift/plugin/plugin.cc | 53 +- .../cpp/src/thrift/plugin/plugin.thrift | 21 +- .../cpp/src/thrift/plugin/plugin_output.cc | 82 +- .../cpp/src/thrift/plugin/type_util.h | 1 + .../compiler/cpp/src/thrift/thriftl.ll | 126 +- .../compiler/cpp/src/thrift/thrifty.yy | 8 + .../compiler/cpp/src/thrift/windows/config.h | 8 +- .../compiler/cpp/test/CMakeLists.txt | 15 + .../thrift.git/compiler/cpp/test/Makefile.am | 13 +- .../thrift.git/compiler/cpp/test/bincat.sh | 3 + .../cpp/test/compiler/Included.thrift | 18 + .../cpp/test/compiler/Including.thrift | 7 + .../compiler/cpp/test/compiler/Single.thrift | 1 + .../cpp/test/compiler/staleness_check.py | 142 + .../test/keyword-samples/const1_return.thrift | 1 + .../test/keyword-samples/enum1_return.thrift | 2 + .../test/keyword-samples/enum2_return.thrift | 3 + .../keyword-samples/exception1_return.thrift | 1 + .../keyword-samples/exception2_return.thrift | 3 + .../keyword-samples/service1_return.thrift | 1 + .../keyword-samples/service2_return.thrift | 3 + .../keyword-samples/service3_return.thrift | 3 + .../keyword-samples/service4_return.thrift | 5 + .../keyword-samples/struct1_return.thrift | 1 + .../keyword-samples/struct2_return.thrift | 3 + .../keyword-samples/typedef1_return.thrift | 1 + .../test/keyword-samples/union1_return.thrift | 1 + .../test/keyword-samples/union2_return.thrift | 3 + .../cpp/test/plugin/conversion_test.cc | 6 +- .../cpp/test/plugin_stability_test.sh | 32 + .../compiler/cpp/tests/CMakeLists.txt | 153 + .../thrift.git/compiler/cpp/tests/README.md | 88 + .../compiler/cpp/tests/catch/catch.hpp | 11508 ++++++ .../t_netcore_generator_functional_tests.cc | 339 + ...core_generator_functional_tests_helpers.cc | 237 + ...tcore_generator_functional_tests_helpers.h | 34 + .../t_netcore_generator_helpers_tests.cc | 209 + ..._netcore_generator_initialization_tests.cc | 74 + .../compiler/cpp/tests/tests_main.cc | 19 + .../git.apache.org/thrift.git/composer.json | 19 +- vendor/git.apache.org/thrift.git/configure.ac | 332 +- .../contrib/Rebus/Properties/AssemblyInfo.cs | 4 +- .../contrib/fb303/cpp/FacebookBase.h | 1 + .../thrift.git/contrib/fb303/if/fb303.thrift | 1 + .../contrib/fb303/java/build.properties | 5 + .../thrift.git/contrib/fb303/java/build.xml | 30 +- .../py/fb303_scripts/fb303_simple_mgmt.py | 33 +- .../thrift.git/contrib/fb303/py/setup.py | 2 +- .../contrib/thrift-maven-plugin/pom.xml | 16 +- .../thrift/maven/AbstractThriftMojo.java | 33 +- .../thrift/maven/ThriftTestCompileMojo.java | 19 + .../thrift/maven/TestAbstractThriftMojo.java | 102 + .../thrift.git/contrib/thrift.spec | 4 +- .../contrib/vagrant/centos-6.5/README.md | 2 +- .../thrift.git/contrib/zeromq/TZmqServer.cpp | 2 +- .../thrift.git/contrib/zeromq/TZmqServer.h | 4 +- .../contrib/zeromq/csharp/ThriftZMQ.csproj | 6 +- .../thrift.git/contrib/zeromq/test-client.cpp | 4 +- .../thrift.git/contrib/zeromq/test-client.py | 4 +- .../contrib/zeromq/test-receiver.cpp | 2 +- .../thrift.git/contrib/zeromq/test-sender.cpp | 2 +- .../thrift.git/contrib/zeromq/test-server.cpp | 4 +- .../thrift.git/contrib/zeromq/test-server.py | 2 +- .../thrift.git/debian/changelog | 20 +- .../git.apache.org/thrift.git/debian/control | 17 +- vendor/git.apache.org/thrift.git/debian/rules | 18 +- vendor/git.apache.org/thrift.git/doap.rdf | 26 +- .../thrift.git/doc/images/cgrn.png | Bin 0 -> 1125 bytes .../thrift.git/doc/images/cred.png | Bin 0 -> 1169 bytes .../thrift.git/doc/images/credfull.png | Bin 0 -> 1057 bytes .../thrift.git/doc/images/cyel.png | Bin 0 -> 946 bytes .../thrift.git/doc/images/thrift-layers.png | Bin 0 -> 27211 bytes .../thrift.git/doc/install/debian.md | 30 +- .../thrift.git/doc/specs/idl.md | 2 +- .../doc/specs/thrift-compact-protocol.md | 2 +- vendor/git.apache.org/thrift.git/dub.json | 28 + .../git.apache.org/thrift.git/lib/Makefile.am | 13 + .../thrift.git/lib/as3/build.properties | 5 + .../thrift.git/lib/as3/build.xml | 38 +- .../thrift.git/lib/c_glib/CMakeLists.txt | 14 + .../thrift.git/lib/c_glib/Makefile.am | 19 +- .../thrift.git/lib/c_glib/README.md | 15 + .../processor/thrift_multiplexed_processor.c | 346 + .../processor/thrift_multiplexed_processor.h | 114 + .../c_glib/protocol/thrift_binary_protocol.c | 19 +- .../c_glib/protocol/thrift_compact_protocol.c | 26 +- .../protocol/thrift_multiplexed_protocol.c | 158 + .../protocol/thrift_multiplexed_protocol.h | 76 + .../thrift/c_glib/protocol/thrift_protocol.c | 53 +- .../protocol/thrift_protocol_decorator.c | 623 + .../protocol/thrift_protocol_decorator.h | 72 + .../protocol/thrift_stored_message_protocol.c | 192 + .../protocol/thrift_stored_message_protocol.h | 78 + .../src/thrift/c_glib/server/thrift_server.c | 35 +- .../transport/thrift_buffered_transport.c | 3 +- .../transport/thrift_framed_transport.c | 3 +- .../c_glib/transport/thrift_memory_buffer.c | 1 - .../c_glib/transport/thrift_platform_socket.h | 120 + .../c_glib/transport/thrift_server_socket.c | 4 +- .../c_glib/transport/thrift_server_socket.h | 2 +- .../thrift/c_glib/transport/thrift_socket.c | 52 +- .../thrift/c_glib/transport/thrift_socket.h | 5 +- .../c_glib/transport/thrift_ssl_socket.c | 806 + .../c_glib/transport/thrift_ssl_socket.h | 218 + .../thrift.git/lib/c_glib/test/CMakeLists.txt | 2 + .../thrift.git/lib/c_glib/test/Makefile.am | 17 +- .../lib/c_glib/test/testbinaryprotocol.c | 287 +- .../lib/c_glib/test/testbufferedtransport.c | 275 +- .../lib/c_glib/test/testcompactprotocol.c | 643 +- .../lib/c_glib/test/testcontainertest.c | 15 +- .../lib/c_glib/test/testdebugproto.c | 9 +- .../lib/c_glib/test/testfdtransport.c | 57 +- .../lib/c_glib/test/testframedtransport.c | 276 +- .../lib/c_glib/test/testmemorybuffer.c | 53 +- .../lib/c_glib/test/testoptionalrequired.c | 31 +- .../lib/c_glib/test/testsimpleserver.c | 7 +- .../thrift.git/lib/c_glib/test/teststruct.c | 3 +- .../lib/c_glib/test/testthrifttest.c | 9 +- .../lib/c_glib/test/testthrifttestclient.cpp | 37 +- .../lib/c_glib/test/testtransportsocket.c | 295 +- .../lib/c_glib/test/testtransportsslsocket.c | 542 + .../cl/Makefile.am} | 36 +- .../thrift.git/lib/cl/README.md | 253 + .../lib/cl/READMES/readme-cassandra.lisp | 64 + .../thrift.git/lib/cl/ensure-externals.sh | 16 + .../thrift.git/lib/cl/load-locally.lisp | 23 + .../lib/cl/test/make-test-binary.lisp | 31 + .../thrift.git/lib/cocoa/src/Thrift.h | 2 +- .../thrift.git/lib/cocoa/src/protocol/TBase.h | 4 +- .../lib/cocoa/src/server/TSocketServer.h | 4 + .../lib/cocoa/src/server/TSocketServer.m | 133 +- .../cocoa/src/transport/TNSStreamTransport.m | 2 +- .../cocoa/src/transport/TSocketTransport.h | 2 + .../cocoa/src/transport/TSocketTransport.m | 68 +- .../thrift.git/lib/cpp/CMakeLists.txt | 6 +- .../thrift.git/lib/cpp/Makefile.am | 17 +- .../thrift.git/lib/cpp/README.md | 48 +- .../thrift.git/lib/cpp/libthrift.vcxproj | 3 + .../thrift.git/lib/cpp/libthriftnb.vcxproj | 15 +- .../lib/cpp/libthriftnb.vcxproj.filters | 20 +- .../lib/cpp/src/thrift/TDispatchProcessor.h | 8 +- .../thrift.git/lib/cpp/src/thrift/TOutput.cpp | 8 +- .../lib/cpp/src/thrift/TProcessor.h | 34 +- .../thrift.git/lib/cpp/src/thrift/TToString.h | 35 +- .../src/thrift/async/TAsyncBufferProcessor.h | 10 +- .../cpp/src/thrift/async/TAsyncChannel.cpp | 2 +- .../lib/cpp/src/thrift/async/TAsyncChannel.h | 2 +- .../thrift/async/TAsyncDispatchProcessor.h | 8 +- .../cpp/src/thrift/async/TAsyncProcessor.h | 24 +- .../thrift/async/TAsyncProtocolProcessor.cpp | 10 +- .../thrift/async/TAsyncProtocolProcessor.h | 14 +- .../thrift/async/TConcurrentClientSyncInfo.h | 4 +- .../src/thrift/async/TEvhttpClientChannel.cpp | 7 +- .../src/thrift/async/TEvhttpClientChannel.h | 6 +- .../cpp/src/thrift/async/TEvhttpServer.cpp | 14 +- .../lib/cpp/src/thrift/async/TEvhttpServer.h | 8 +- .../src/thrift/concurrency/BoostMonitor.cpp | 6 +- .../cpp/src/thrift/concurrency/BoostMutex.cpp | 4 +- .../thrift/concurrency/BoostThreadFactory.cpp | 67 +- .../thrift/concurrency/BoostThreadFactory.h | 11 +- .../src/thrift/concurrency/FunctionRunner.h | 16 +- .../cpp/src/thrift/concurrency/Monitor.cpp | 9 +- .../lib/cpp/src/thrift/concurrency/Mutex.cpp | 101 +- .../lib/cpp/src/thrift/concurrency/Mutex.h | 17 +- .../thrift/concurrency/PosixThreadFactory.cpp | 88 +- .../thrift/concurrency/PosixThreadFactory.h | 10 +- .../cpp/src/thrift/concurrency/StdMutex.cpp | 4 + .../thrift/concurrency/StdThreadFactory.cpp | 74 +- .../src/thrift/concurrency/StdThreadFactory.h | 8 +- .../lib/cpp/src/thrift/concurrency/Thread.h | 17 +- .../src/thrift/concurrency/ThreadManager.cpp | 14 +- .../src/thrift/concurrency/ThreadManager.h | 19 +- .../src/thrift/concurrency/TimerManager.cpp | 60 +- .../cpp/src/thrift/concurrency/TimerManager.h | 47 +- .../lib/cpp/src/thrift/cxxfunctional.h | 132 - .../src/thrift/processor/PeekProcessor.cpp | 26 +- .../cpp/src/thrift/processor/PeekProcessor.h | 30 +- .../cpp/src/thrift/processor/StatsProcessor.h | 8 +- .../thrift/processor/TMultiplexedProcessor.h | 111 +- .../cpp/src/thrift/protocol/TBinaryProtocol.h | 12 +- .../src/thrift/protocol/TCompactProtocol.h | 12 +- .../src/thrift/protocol/TCompactProtocol.tcc | 4 +- .../src/thrift/protocol/TDebugProtocol.cpp | 22 +- .../cpp/src/thrift/protocol/TDebugProtocol.h | 12 +- .../src/thrift/protocol/THeaderProtocol.cpp | 6 +- .../cpp/src/thrift/protocol/THeaderProtocol.h | 34 +- .../cpp/src/thrift/protocol/TJSONProtocol.cpp | 62 +- .../cpp/src/thrift/protocol/TJSONProtocol.h | 23 +- .../thrift/protocol/TMultiplexedProtocol.h | 2 +- .../lib/cpp/src/thrift/protocol/TProtocol.h | 22 +- .../src/thrift/protocol/TProtocolDecorator.h | 4 +- .../cpp/src/thrift/protocol/TProtocolTap.h | 6 +- .../src/thrift/protocol/TVirtualProtocol.h | 4 +- .../cpp/src/thrift/qt/TQIODeviceTransport.cpp | 8 +- .../cpp/src/thrift/qt/TQIODeviceTransport.h | 6 +- .../lib/cpp/src/thrift/qt/TQTcpServer.cpp | 9 +- .../lib/cpp/src/thrift/qt/TQTcpServer.h | 18 +- .../src/thrift/server/TConnectedClient.cpp | 2 +- .../cpp/src/thrift/server/TConnectedClient.h | 22 +- .../src/thrift/server/TNonblockingServer.cpp | 439 +- .../src/thrift/server/TNonblockingServer.h | 139 +- .../lib/cpp/src/thrift/server/TServer.h | 140 +- .../src/thrift/server/TServerFramework.cpp | 13 +- .../cpp/src/thrift/server/TServerFramework.h | 46 +- .../cpp/src/thrift/server/TSimpleServer.cpp | 2 +- .../lib/cpp/src/thrift/server/TSimpleServer.h | 42 +- .../src/thrift/server/TThreadPoolServer.cpp | 4 +- .../cpp/src/thrift/server/TThreadPoolServer.h | 54 +- .../cpp/src/thrift/server/TThreadedServer.cpp | 22 +- .../cpp/src/thrift/server/TThreadedServer.h | 66 +- .../thrift.git/lib/cpp/src/thrift/stdcxx.h | 129 + .../cpp/src/thrift/transport/PlatformSocket.h | 8 + .../thrift/transport/TBufferTransports.cpp | 10 +- .../src/thrift/transport/TBufferTransports.h | 57 +- .../cpp/src/thrift/transport/TFDTransport.cpp | 2 +- .../src/thrift/transport/TFileTransport.cpp | 35 +- .../cpp/src/thrift/transport/TFileTransport.h | 39 +- .../src/thrift/transport/THeaderTransport.cpp | 41 +- .../src/thrift/transport/THeaderTransport.h | 26 +- .../cpp/src/thrift/transport/THttpClient.cpp | 11 +- .../cpp/src/thrift/transport/THttpClient.h | 2 +- .../cpp/src/thrift/transport/THttpServer.cpp | 29 +- .../cpp/src/thrift/transport/THttpServer.h | 6 +- .../src/thrift/transport/THttpTransport.cpp | 17 +- .../cpp/src/thrift/transport/THttpTransport.h | 4 +- .../transport/TNonblockingSSLServerSocket.cpp | 58 + .../transport/TNonblockingSSLServerSocket.h | 77 + .../transport/TNonblockingServerSocket.cpp | 548 + .../transport/TNonblockingServerSocket.h | 137 + .../transport/TNonblockingServerTransport.h | 101 + .../lib/cpp/src/thrift/transport/TPipe.cpp | 9 +- .../lib/cpp/src/thrift/transport/TPipe.h | 2 +- .../cpp/src/thrift/transport/TPipeServer.cpp | 23 +- .../cpp/src/thrift/transport/TPipeServer.h | 6 +- .../src/thrift/transport/TSSLServerSocket.cpp | 8 +- .../src/thrift/transport/TSSLServerSocket.h | 12 +- .../cpp/src/thrift/transport/TSSLSocket.cpp | 386 +- .../lib/cpp/src/thrift/transport/TSSLSocket.h | 96 +- .../src/thrift/transport/TServerSocket.cpp | 48 +- .../cpp/src/thrift/transport/TServerSocket.h | 39 +- .../src/thrift/transport/TServerTransport.h | 17 +- .../thrift/transport/TShortReadTransport.h | 6 +- .../lib/cpp/src/thrift/transport/TSocket.cpp | 55 +- .../lib/cpp/src/thrift/transport/TSocket.h | 21 +- .../cpp/src/thrift/transport/TSocketPool.cpp | 21 +- .../cpp/src/thrift/transport/TSocketPool.h | 14 +- .../lib/cpp/src/thrift/transport/TTransport.h | 4 +- .../thrift/transport/TTransportException.cpp | 2 - .../thrift/transport/TTransportException.h | 16 + .../src/thrift/transport/TTransportUtils.cpp | 17 +- .../src/thrift/transport/TTransportUtils.h | 50 +- .../src/thrift/transport/TZlibTransport.cpp | 11 +- .../cpp/src/thrift/transport/TZlibTransport.h | 16 +- .../windows/OverlappedSubmissionThread.h | 2 +- .../src/thrift/windows/TWinsockSingleton.h | 5 +- .../lib/cpp/src/thrift/windows/config.h | 31 +- .../lib/cpp/test/AllProtocolTests.tcc | 10 +- .../lib/cpp/test/AnnotationTest.cpp | 68 + .../thrift.git/lib/cpp/test/Base64Test.cpp | 4 + .../thrift.git/lib/cpp/test/Benchmark.cpp | 21 +- .../thrift.git/lib/cpp/test/CMakeLists.txt | 60 +- .../lib/cpp/test/DebugProtoTest.cpp | 7 +- .../thrift.git/lib/cpp/test/EnumTest.cpp | 35 +- .../thrift.git/lib/cpp/test/GenericHelpers.h | 31 +- .../thrift.git/lib/cpp/test/JSONProtoTest.cpp | 41 +- .../thrift.git/lib/cpp/test/Makefile.am | 75 +- .../lib/cpp/test/OneWayHTTPTest.cpp | 242 + .../thrift.git/lib/cpp/test/OneWayTest.thrift | 46 + .../lib/cpp/test/OpenSSLManualInitTest.cpp | 1 - .../lib/cpp/test/OptionalRequiredTest.cpp | 6 +- .../thrift.git/lib/cpp/test/RecursiveTest.cpp | 15 +- .../cpp/test/RenderedDoubleConstantsTest.cpp | 122 + .../thrift.git/lib/cpp/test/SecurityTest.cpp | 62 +- .../lib/cpp/test/SpecializationTest.cpp | 4 +- .../lib/cpp/test/TBufferBaseTest.cpp | 9 +- .../lib/cpp/test/TFileTransportTest.cpp | 31 +- .../lib/cpp/test/TMemoryBufferTest.cpp | 63 +- .../cpp/test/TNonblockingSSLServerTest.cpp | 293 + .../lib/cpp/test/TNonblockingServerTest.cpp | 85 +- .../lib/cpp/test/TPipeInterruptTest.cpp | 9 +- .../lib/cpp/test/TPipedTransportTest.cpp | 8 +- .../lib/cpp/test/TSSLSocketInterruptTest.cpp | 80 +- .../lib/cpp/test/TServerIntegrationTest.cpp | 108 +- .../lib/cpp/test/TServerSocketTest.cpp | 4 +- .../lib/cpp/test/TServerTransportTest.cpp | 8 +- .../lib/cpp/test/TSocketInterruptTest.cpp | 25 +- .../thrift.git/lib/cpp/test/TransportTest.cpp | 55 +- .../thrift.git/lib/cpp/test/ZlibTest.cpp | 64 +- .../lib/cpp/test/concurrency/MutexTest.cpp | 123 + .../{ => concurrency}/RWMutexStarveTest.cpp | 30 +- .../lib/cpp/test/concurrency/Tests.cpp | 53 +- .../cpp/test/concurrency/ThreadFactoryTests.h | 46 +- .../cpp/test/concurrency/ThreadManagerTests.h | 6 +- .../cpp/test/concurrency/TimerManagerTests.h | 166 +- .../lib/cpp/test/processor/EventLog.cpp | 3 +- .../lib/cpp/test/processor/Handlers.h | 32 +- .../lib/cpp/test/processor/ProcessorTest.cpp | 180 +- .../lib/cpp/test/processor/ServerThread.cpp | 4 +- .../lib/cpp/test/processor/ServerThread.h | 19 +- .../lib/cpp/test/qt/TQTcpServerTest.cpp | 42 +- .../thrift.git/lib/csharp/Makefile.am | 32 +- .../Properties/AssemblyInfo.cs | 4 +- .../ThriftMSBuildTask.csproj | 4 +- .../csharp/src/Collections/TCollections.cs | 4 +- .../lib/csharp/src/Net35/ExtensionsNet35.cs | 31 + .../lib/csharp/src/Properties/AssemblyInfo.cs | 4 +- .../lib/csharp/src/Protocol/TAbstractBase.cs | 6 +- .../lib/csharp/src/Protocol/TBase.cs | 4 +- .../csharp/src/Protocol/TBinaryProtocol.cs | 64 +- .../csharp/src/Protocol/TCompactProtocol.cs | 406 +- .../lib/csharp/src/Protocol/TJSONProtocol.cs | 132 +- .../src/Protocol/TMultiplexedProcessor.cs | 115 +- .../src/Protocol/TMultiplexedProtocol.cs | 90 +- .../lib/csharp/src/Protocol/TProtocol.cs | 6 +- .../csharp/src/Protocol/TProtocolDecorator.cs | 35 +- .../csharp/src/Protocol/TProtocolException.cs | 8 +- .../lib/csharp/src/Protocol/TProtocolUtil.cs | 3 +- .../lib/csharp/src/Server/TServer.cs | 230 +- .../csharp/src/Server/TServerEventHandler.cs | 43 +- .../lib/csharp/src/Server/TSimpleServer.cs | 284 +- .../csharp/src/Server/TThreadPoolServer.cs | 430 +- .../lib/csharp/src/Server/TThreadedServer.cs | 434 +- .../lib/csharp/src/TApplicationException.cs | 9 +- .../thrift.git/lib/csharp/src/TException.cs | 4 +- .../csharp/src/TPrototypeProcessorFactory.cs | 2 +- .../csharp/src/TSingletonProcessorFactory.cs | 2 +- .../lib/csharp/src/Thrift.45.csproj | 12 +- .../thrift.git/lib/csharp/src/Thrift.csproj | 20 +- .../src/Transport/TBufferedTransport.cs | 61 +- .../csharp/src/Transport/TFramedTransport.cs | 37 +- .../lib/csharp/src/Transport/THttpClient.cs | 83 +- .../lib/csharp/src/Transport/TMemoryBuffer.cs | 62 +- .../Transport/TNamedPipeClientTransport.cs | 26 +- .../Transport/TNamedPipeServerTransport.cs | 94 +- .../lib/csharp/src/Transport/TServerSocket.cs | 66 +- .../csharp/src/Transport/TServerTransport.cs | 7 +- .../src/Transport/TSilverlightSocket.cs | 12 +- .../lib/csharp/src/Transport/TSocket.cs | 56 +- .../src/Transport/TSocketVersionizer.cs | 78 + .../csharp/src/Transport/TStreamTransport.cs | 32 +- .../csharp/src/Transport/TTLSServerSocket.cs | 18 +- .../lib/csharp/src/Transport/TTLSSocket.cs | 10 +- .../lib/csharp/src/Transport/TTransport.cs | 4 +- .../src/Transport/TTransportException.cs | 8 +- .../csharp/src/Transport/TTransportFactory.cs | 2 +- .../test/JSON/Properties/AssemblyInfo.cs | 6 +- .../Multiplex/Client/MultiplexClient.csproj | 4 +- .../Client/Properties/AssemblyInfo.cs | 10 +- .../Multiplex/Server/MultiplexServer.csproj | 4 +- .../Server/Properties/AssemblyInfo.cs | 10 +- .../Controllers/HomeController.cs | 8 +- .../ThriftMVCTest/Properties/AssemblyInfo.cs | 6 +- .../test/ThriftMVCTest/SecondServiceImpl.cs | 14 +- .../thrift.git/lib/d/Makefile.am | 2 +- .../lib/d/src/thrift/async/socket.d | 1 + .../thrift.git/lib/d/src/thrift/base.d | 2 +- .../lib/d/src/thrift/internal/ssl_bio.d | 2 +- .../thrift.git/lib/d/src/thrift/server/base.d | 32 + .../lib/d/src/thrift/server/nonblocking.d | 10 +- .../lib/d/src/thrift/server/simple.d | 4 +- .../lib/d/src/thrift/server/taskpool.d | 4 +- .../lib/d/src/thrift/server/threaded.d | 4 +- .../lib/d/src/thrift/server/transport/base.d | 24 +- .../lib/d/src/thrift/transport/file.d | 11 +- .../lib/d/src/thrift/transport/http.d | 2 +- .../lib/d/src/thrift/transport/socket.d | 7 +- .../lib/d/src/thrift/transport/ssl.d | 12 +- .../thrift.git/lib/d/test/Makefile.am | 2 - .../thrift.git/lib/d/test/client_pool_test.d | 46 +- .../lib/d/test/serialization_benchmark.d | 6 +- .../lib/d/test/thrift_test_server.d | 58 +- .../thrift.git/lib/dart/Makefile.am | 5 + .../lib/src/transport/t_framed_transport.dart | 120 +- .../lib/src/transport/t_socket_transport.dart | 4 +- .../thrift.git/lib/dart/pubspec.yaml | 2 +- .../transport/t_framed_transport_test.dart | 175 + .../lib/delphi/DelphiThrift.groupproj | 156 + .../lib/delphi/src/Thrift.Exception.pas | 62 + .../delphi/src/Thrift.Processor.Multiplex.pas | 75 +- .../delphi/src/Thrift.Protocol.Compact.pas | 110 +- .../lib/delphi/src/Thrift.Protocol.JSON.pas | 72 +- .../delphi/src/Thrift.Protocol.Multiplex.pas | 8 +- .../lib/delphi/src/Thrift.Protocol.pas | 757 +- .../lib/delphi/src/Thrift.Stream.pas | 93 +- .../lib/delphi/src/Thrift.Transport.Pipes.pas | 217 +- .../lib/delphi/src/Thrift.Transport.pas | 367 +- .../lib/delphi/src/Thrift.Utils.pas | 41 +- .../thrift.git/lib/delphi/src/Thrift.pas | 45 +- .../ConsoleHelper.pas} | 9 +- .../thrift.git/lib/delphi/test/TestClient.pas | 519 +- .../thrift.git/lib/delphi/test/TestServer.pas | 43 +- .../lib/delphi/test/TestServerEvents.pas | 2 +- .../thrift.git/lib/delphi/test/client.dpr | 2 +- .../ReservedIncluded.thrift} | 36 +- .../delphi/test/keywords/ReservedKeywords.dpr | 15 + .../test/keywords/ReservedKeywords.thrift | 138 + .../multiplexed/Multiplex.Server.Main.pas | 2 +- .../multiplexed/Multiplex.Test.Client.dpr | 2 +- .../multiplexed/Multiplex.Test.Server.dpr | 3 +- .../test/serializer/TestSerializer.Data.pas | 5 +- .../delphi/test/serializer/TestSerializer.dpr | 3 +- .../thrift.git/lib/delphi/test/server.dpr | 2 +- .../delphi/test/skip/skiptest_version1.dpr | 6 +- .../delphi/test/skip/skiptest_version2.dpr | 6 +- .../test/typeregistry/TestTypeRegistry.dpr | 2 +- .../thrift.git/lib/erl/Makefile.am | 10 + .../thrift.git/lib/erl/coding_standards.md | 2 + .../lib/erl/include/thrift_protocol.hrl | 12 +- .../thrift.git/lib/erl/rebar.test.config | 2 +- .../lib/erl/src/thrift_framed_transport.erl | 3 +- .../lib/erl/src/thrift_protocol.erl | 15 +- .../erl/src/thrift_reconnecting_client.erl | 6 +- .../lib/erl/src/thrift_transport.erl | 2 - .../lib/erl/test/Thrift_omit_with.thrift | 22 + .../thrift.git/lib/erl/test/test_const.erl | 54 + .../thrift.git/lib/erl/test/test_omit.erl | 79 + .../test/test_rendered_double_constants.erl | 68 + .../lib/erl/test/thrift_test_test.erl | 12 - .../thrift.git/lib/go/Makefile.am | 7 +- .../thrift.git/lib/go/README.md | 4 +- .../thrift.git/lib/go/test/Makefile.am | 14 +- .../lib/go/test/RequiredFieldTest.thrift | 7 + .../lib/go/test/UnionBinaryTest.thrift | 25 + .../go/test/dontexportrwtest/compile_test.go | 9 +- .../lib/go/test/tests/client_error_test.go | 229 +- .../thrift.git/lib/go/test/tests/context.go | 26 + .../test/tests/multiplexed_protocol_test.go | 164 +- .../lib/go/test/tests/one_way_test.go | 13 +- .../lib/go/test/tests/protocol_mock.go | 6 +- .../lib/go/test/tests/protocols_test.go | 2 +- .../lib/go/test/tests/required_fields_test.go | 35 + .../go/test/tests/struct_args_rets_test.go | 2 +- .../lib/go/test/tests/thrifttest_driver.go | 62 +- .../lib/go/test/tests/thrifttest_handler.go | 49 +- .../lib/go/test/tests/union_binary_test.go | 36 + .../lib/go/thrift/application_exception.go | 46 +- .../go/thrift/application_exception_test.go | 6 +- .../lib/go/thrift/binary_protocol.go | 11 +- .../lib/go/thrift/buffered_transport.go | 5 +- .../thrift.git/lib/go/thrift/client.go | 85 + .../thrift/{processor.go => common_test.go} | 12 +- .../lib/go/thrift/compact_protocol.go | 13 +- .../lib/go/thrift/compact_protocol_test.go | 7 + .../thrift.git/lib/go/thrift/context.go | 24 + .../lib/go/thrift/debug_protocol.go | 5 +- .../lib/go/thrift/framed_transport.go | 7 +- .../thrift.git/lib/go/thrift/http_client.go | 6 +- .../lib/go/thrift/http_transport.go | 35 +- .../lib/go/thrift/iostream_transport.go | 3 +- .../thrift.git/lib/go/thrift/json_protocol.go | 5 +- .../lib/go/thrift/json_protocol_test.go | 41 +- .../thrift.git/lib/go/thrift/memory_buffer.go | 3 +- .../lib/go/thrift/multiplexed_protocol.go | 7 +- .../lib/go/thrift/processor_factory.go | 12 + .../thrift.git/lib/go/thrift/protocol.go | 6 +- .../thrift.git/lib/go/thrift/protocol_test.go | 56 +- .../thrift.git/lib/go/thrift/serializer.go | 16 +- .../lib/go/thrift/serializer_test.go | 5 +- .../lib/go/thrift/serializer_types_test.go | 2 +- .../thrift.git/lib/go/thrift/server_socket.go | 31 +- .../lib/go/thrift/server_socket_test.go | 10 + .../lib/go/thrift/simple_json_protocol.go | 5 +- .../go/thrift/simple_json_protocol_test.go | 49 +- .../thrift.git/lib/go/thrift/simple_server.go | 73 +- .../lib/go/thrift/simple_server_test.go | 156 + .../thrift.git/lib/go/thrift/socket.go | 3 +- .../lib/go/thrift/ssl_server_socket.go | 5 +- .../thrift.git/lib/go/thrift/ssl_socket.go | 12 +- .../thrift.git/lib/go/thrift/transport.go | 9 +- .../lib/go/thrift/transport_test.go | 7 +- .../lib/go/thrift/zlib_transport.go | 24 +- .../lib/go/thrift/zlib_transport_test.go | 29 + .../thrift.git/lib/haxe/README.md | 12 +- .../thrift.git/lib/haxe/haxelib.json | 2 +- .../apache/thrift/protocol/TProtocolUtil.hx | 2 +- .../org/apache/thrift/server/TSimpleServer.hx | 5 + .../thrift.git/lib/haxe/test/Makefile.am | 1 - .../thrift.git/lib/hs/CMakeLists.txt | 2 +- .../thrift.git/lib/hs/Makefile.am | 2 +- .../thrift.git/lib/hs/Thrift.cabal | 12 +- .../thrift.git/lib/hs/src/Thrift.hs | 4 +- .../thrift.git/lib/hs/src/Thrift/Protocol.hs | 41 +- .../lib/hs/src/Thrift/Protocol/Binary.hs | 55 +- .../lib/hs/src/Thrift/Protocol/Compact.hs | 62 +- .../lib/hs/src/Thrift/Protocol/Header.hs | 141 + .../lib/hs/src/Thrift/Protocol/JSON.hs | 58 +- .../thrift.git/lib/hs/src/Thrift/Server.hs | 6 +- .../lib/hs/src/Thrift/Transport/Handle.hs | 14 +- .../lib/hs/src/Thrift/Transport/Header.hs | 354 + .../thrift.git/lib/java/CMakeLists.txt | 71 +- .../thrift.git/lib/java/Makefile.am | 48 +- .../thrift.git/lib/java/README.md | 128 +- .../thrift.git/lib/java/android/build.gradle | 38 +- .../thrift.git/lib/java/build.gradle | 64 + .../thrift.git/lib/java/build.xml | 414 - .../code_quality_tools/findbugs-filter.xml | 51 + .../{build.properties => gradle.properties} | 26 +- .../java/gradle/additionalArtifacts.gradle | 40 + .../lib/java/gradle/cloverCoverage.gradle | 48 + .../lib/java/gradle/codeQualityChecks.gradle | 40 + .../lib/java/gradle/environment.gradle | 73 + .../lib/java/gradle/functionalTests.gradle | 155 + .../lib/java/gradle/generateTestThrift.gradle | 119 + .../lib/java/gradle/publishing.gradle | 119 + .../java/gradle/sourceConfiguration.gradle | 84 + .../lib/java/gradle/unitTests.gradle | 82 + .../gradle/wrapper/gradle-wrapper.properties | 5 + .../thrift.git/lib/java/gradlew | 172 + .../thrift.git/lib/java/gradlew.bat | 84 + .../thrift.git/lib/java/settings.gradle | 20 + .../apache/thrift/AsyncProcessFunction.java | 1 - .../org/apache/thrift/ProcessFunction.java | 48 +- .../org/apache/thrift/TAsyncProcessor.java | 9 +- .../src/org/apache/thrift/TEnumHelper.java | 1 - .../apache/thrift/TMultiplexedProcessor.java | 17 +- .../src/org/apache/thrift/TServiceClient.java | 1 - .../apache/thrift/annotation/Nullable.java | 33 + .../thrift/protocol/TBinaryProtocol.java | 1 + .../apache/thrift/protocol/TProtocolUtil.java | 3 +- .../server/AbstractNonblockingServer.java | 48 +- .../thrift/server/TExtensibleServlet.java | 6 +- .../org/apache/thrift/server/THsHaServer.java | 3 + .../thrift/server/TThreadPoolServer.java | 64 +- .../server/TThreadedSelectorServer.java | 108 +- .../apache/thrift/transport/TByteBuffer.java | 2 +- .../transport/TFastFramedTransport.java | 8 +- .../thrift/transport/TFileTransport.java | 2 +- .../thrift/transport/TFramedTransport.java | 15 +- .../apache/thrift/transport/THttpClient.java | 3 + .../transport/TNonblockingServerSocket.java | 2 +- .../transport/TSSLTransportFactory.java | 68 +- .../thrift/transport/TSaslTransport.java | 4 +- .../thrift/transport/TServerSocket.java | 2 +- .../org/apache/thrift/transport/TSocket.java | 8 +- .../java/test/org/apache/thrift/Fixtures.java | 2 +- .../test/org/apache/thrift/TestDeepCopy.java | 34 + .../org/apache/thrift/TestEnumContainers.java | 81 + .../thrift/TestMultiplexedProcessor.java | 86 + .../thrift/TestRenderedDoubleConstants.java | 179 + .../test/org/apache/thrift/TestReuse.java | 3 - .../org/apache/thrift/TestUnsafeBinaries.java | 146 + .../thrift/protocol/TestTProtocolUtil.java | 14 - .../protocol/TestTSimpleJSONProtocol.java | 2 +- .../apache/thrift/server/ServerTestBase.java | 98 +- .../org/apache/thrift/test/TestClient.java | 34 +- .../org/apache/thrift/test/TestServer.java | 72 +- .../transport/TestTFastFramedTransport.java | 6 +- .../transport/TestTFramedTransport.java | 28 + .../transport/TestTSSLTransportFactory.java | 10 +- ...TestTSSLTransportFactoryStreamedStore.java | 62 + .../transport/TestTSimpleFileTransport.java | 18 +- .../thrift.git/lib/js/Gruntfile.js | 246 +- .../thrift.git/lib/js/Makefile.am | 9 +- .../thrift.git/lib/js/README.md | 17 +- .../thrift.git/lib/js/package-lock.json | 3777 ++ .../thrift.git/lib/js/package.json | 20 +- .../thrift.git/lib/js/src/thrift.js | 118 +- .../thrift.git/lib/js/test/build.properties | 5 + .../thrift.git/lib/js/test/build.xml | 46 +- .../lib/js/test/deep-constructor.test.js | 76 +- .../thrift.git/lib/js/test/jsTestDriver.conf | 1 + .../thrift.git/lib/js/test/phantom-client.js | 136 +- .../thrift.git/lib/js/test/phantomjs-qunit.js | 24 +- .../thrift.git/lib/js/test/server_http.js | 34 +- .../thrift.git/lib/js/test/server_https.js | 34 +- .../thrift.git/lib/js/test/test-async.js | 428 +- .../lib/js/test/test-deep-constructor.html | 6 +- .../lib/js/test/test-double-rendering.html | 55 + .../lib/js/test/test-double-rendering.js | 143 + .../thrift.git/lib/js/test/test-es6.html | 62 + .../thrift.git/lib/js/test/test-es6.js | 374 + .../thrift.git/lib/js/test/test-jq.js | 145 +- .../thrift.git/lib/js/test/test-nojq.html | 4 +- .../thrift.git/lib/js/test/test-nojq.js | 21 +- .../thrift.git/lib/js/test/test.html | 9 +- .../thrift.git/lib/js/test/test.js | 377 +- .../thrift.git/lib/js/test/test_handler.js | 44 +- .../thrift.git/lib/js/test/testws.html | 10 +- .../thrift.git/lib/json/schema.json | 16 +- .../thrift.git/lib/lua/Makefile.am | 4 +- .../thrift.git/lib/lua/TFramedTransport.lua | 2 +- .../thrift.git/lib/lua/THttpTransport.lua | 2 +- .../thrift.git/lib/lua/Thrift.lua | 2 +- .../thrift.git/lib/lua/src/luabpack.c | 6 +- .../thrift.git/lib/lua/src/socket.h | 4 +- .../thrift.git/lib/lua/src/usocket.c | 44 +- .../thrift.git/lib/netcore/Makefile.am | 41 + .../thrift.git/lib/netcore/README.md | 24 + .../Tests/Thrift.IntegrationTests/.gitignore | 2 + .../Protocols/ProtocolsOperationsTests.cs | 502 + .../Thrift.IntegrationTests.csproj | 29 + .../.gitignore | 4 + .../CassandraTest.thrift | 705 + .../Properties/AssemblyInfo.cs | 40 + ...rift.PublicInterfaces.Compile.Tests.csproj | 36 + .../Collections/TCollectionsTests.cs | 83 + .../Thrift.Tests/Collections/THashSetTests.cs | 71 + .../Protocols/TJsonProtocolHelperTests.cs | 172 + .../Protocols/TJsonProtocolTests.cs | 67 + .../Tests/Thrift.Tests/Thrift.Tests.csproj | 18 + .../thrift.git/lib/netcore/Thrift.sln | 85 + .../Thrift/Collections/TCollections.cs | 101 + .../netcore/Thrift/Collections/THashSet.cs | 67 + .../lib/netcore/Thrift/ITAsyncProcessor.cs | 29 + .../lib/netcore/Thrift/ITProcessorFactory.cs | 28 + .../netcore/Thrift/Properties/AssemblyInfo.cs | 56 + .../Thrift/Protocols/Entities/TField.cs | 37 + .../Thrift/Protocols/Entities/TList.cs | 33 + .../netcore/Thrift/Protocols/Entities/TMap.cs | 36 + .../Thrift/Protocols/Entities/TMessage.cs | 37 + .../Thrift/Protocols/Entities/TMessageType.cs | 28 + .../netcore/Thrift/Protocols/Entities/TSet.cs | 38 + .../Thrift/Protocols/Entities/TStruct.cs | 30 + .../Thrift/Protocols/Entities/TType.cs | 37 + .../Thrift/Protocols/ITProtocolFactory.cs | 27 + .../netcore/Thrift/Protocols/TAbstractBase.cs | 28 + .../lib/netcore/Thrift/Protocols/TBase.cs | 28 + .../Thrift/Protocols/TBinaryProtocol.cs | 613 + .../Thrift/Protocols/TCompactProtocol.cs | 922 + .../netcore/Thrift/Protocols/TJSONProtocol.cs | 981 + .../Thrift/Protocols/TMultiplexedProtocol.cs | 91 + .../lib/netcore/Thrift/Protocols/TProtocol.cs | 376 + .../Thrift/Protocols/TProtocolDecorator.cs | 247 + .../Thrift/Protocols/TProtocolException.cs | 59 + .../Protocols/Utilities/TBase64Helper.cs | 101 + .../Protocols/Utilities/TBase64Utils.cs | 101 + .../Utilities/TJsonProtocolConstants.cs | 61 + .../Utilities/TJsonProtocolHelper.cs | 176 + .../Protocols/Utilities/TProtocolUtil.cs | 110 + .../netcore/Thrift/Server/AsyncBaseServer.cs | 183 + .../lib/netcore/Thrift/Server/TBaseServer.cs | 79 + .../Thrift/Server/TServerEventHandler.cs | 54 + .../Thrift/SingletonTProcessorFactory.cs | 38 + .../netcore/Thrift/TApplicationException.cs | 150 + .../lib/netcore/Thrift/TBaseClient.cs | 91 + .../lib/netcore/Thrift/TException.cs | 34 + .../netcore/Thrift/TMultiplexedProcessor.cs | 143 + .../lib/netcore/Thrift/Thrift.csproj | 31 + .../Client/TBufferedClientTransport.cs | 206 + .../Client/TFramedClientTransport.cs | 201 + .../Transports/Client/THttpClientTransport.cs | 226 + .../Client/TMemoryBufferClientTransport.cs | 97 + .../Client/TNamedPipeClientTransport.cs | 95 + .../Client/TSocketClientTransport.cs | 139 + .../Client/TStreamClientTransport.cs | 110 + .../Client/TTlsSocketClientTransport.cs | 237 + .../Transports/Server/THttpServerTransport.cs | 98 + .../Server/TNamedPipeServerTransport.cs | 191 + .../Server/TServerFramedTransport.cs | 150 + .../Server/TServerSocketTransport.cs | 174 + .../Server/TTlsServerSocketTransport.cs | 177 + .../Thrift/Transports/TClientTransport.cs | 179 + .../Thrift/Transports/TServerTransport.cs | 54 + .../Thrift/Transports/TTransportException.cs | 58 + .../Thrift/Transports/TTransportFactory.cs | 35 + .../thrift.git/lib/netcore/build.cmd | 27 + .../thrift.git/lib/netcore/build.sh | 32 + .../thrift.git/lib/netcore/runtests.cmd | 28 + .../thrift.git/lib/netcore/runtests.sh | 26 + .../thrift.git/lib/nodejs/Makefile.am | 8 +- .../thrift.git/lib/nodejs/README.md | 39 +- .../lib/nodejs/examples/httpServer.py | 3 +- .../lib/nodejs/lib/thrift/binary_protocol.js | 7 +- .../lib/nodejs/lib/thrift/browser.js | 2 + .../nodejs/lib/thrift/buffered_transport.js | 8 + .../lib/nodejs/lib/thrift/compact_protocol.js | 1 - .../lib/nodejs/lib/thrift/connection.js | 46 +- .../lib/nodejs/lib/thrift/http_connection.js | 45 +- .../thrift.git/lib/nodejs/lib/thrift/index.js | 7 + .../lib/nodejs/lib/thrift/json_protocol.js | 64 +- .../thrift.git/lib/nodejs/lib/thrift/log.js | 73 +- .../nodejs/lib/thrift/multiplexed_protocol.js | 10 +- .../lib/nodejs/lib/thrift/server.js | 6 + .../lib/nodejs/lib/thrift/web_server.js | 21 +- .../lib/nodejs/lib/thrift/ws_transport.js | 4 +- .../thrift.git/lib/nodejs/test/binary.test.js | 143 +- .../lib/nodejs/test/browser_client.js | 27 - .../thrift.git/lib/nodejs/test/client.js | 146 +- .../lib/nodejs/test/deep-constructor.test.js | 335 +- .../thrift.git/lib/nodejs/test/exceptions.js | 177 +- .../thrift.git/lib/nodejs/test/helpers.js | 38 +- .../thrift.git/lib/nodejs/test/server.js | 130 +- .../thrift.git/lib/nodejs/test/test-cases.js | 246 +- .../thrift.git/lib/nodejs/test/testAll.sh | 41 +- .../thrift.git/lib/nodejs/test/test_driver.js | 408 +- .../lib/nodejs/test/test_handler.js | 129 +- .../thrift.git/lib/nodets/.gitignore | 1 + .../thrift.git/lib/nodets/Makefile.am | 45 + .../thrift.git/lib/nodets/coding_standards.md | 1 + .../thrift.git/lib/nodets/test/client.ts | 63 + .../thrift.git/lib/nodets/test/runClient.sh | 18 + .../thrift.git/lib/nodets/test/runServer.sh | 20 + .../thrift.git/lib/nodets/test/server.ts | 26 + .../thrift.git/lib/nodets/test/test-cases.ts | 113 + .../thrift.git/lib/nodets/test/testAll.sh | 38 + .../thrift.git/lib/nodets/test/test_driver.ts | 278 + .../lib/nodets/test/test_handler.ts | 299 + .../thrift.git/lib/nodets/test/tsconfig.json | 22 + .../thrift.git/lib/ocaml/.gitignore | 11 + .../thrift.git/lib/ocaml/DEVELOPMENT | 76 + .../thrift.git/lib/ocaml/OCamlMakefile | 1231 - .../thrift.git/lib/ocaml/README-OCamlMakefile | 643 - .../thrift.git/lib/ocaml/_oasis | 2 +- .../git.apache.org/thrift.git/lib/ocaml/descr | 1 + .../git.apache.org/thrift.git/lib/ocaml/opam | 8 + .../git.apache.org/thrift.git/lib/ocaml/url | 2 + .../thrift.git/lib/perl/MANIFEST.SKIP | 13 + .../thrift.git/lib/perl/Makefile.PL | 21 +- .../thrift.git/lib/perl/Makefile.am | 3 + .../thrift.git/lib/perl/README.md | 105 +- .../thrift.git/lib/perl/build-cpan-dist.sh | 53 + .../thrift.git/lib/perl/coding_standards.md | 3 +- .../thrift.git/lib/perl/lib/Thrift.pm | 173 +- .../lib/perl/lib/Thrift/BinaryProtocol.pm | 47 +- .../lib/perl/lib/Thrift/BufferedTransport.pm | 5 +- .../lib/perl/lib/Thrift/Exception.pm | 161 + .../lib/perl/lib/Thrift/FramedTransport.pm | 7 +- .../lib/perl/lib/Thrift/HttpClient.pm | 90 +- .../lib/perl/lib/Thrift/MemoryBuffer.pm | 14 +- .../lib/perl/lib/Thrift/MessageType.pm | 19 +- .../perl/lib/Thrift/MultiplexedProcessor.pm | 68 +- .../perl/lib/Thrift/MultiplexedProtocol.pm | 21 +- .../lib/perl/lib/Thrift/Protocol.pm | 189 +- .../lib/perl/lib/Thrift/ProtocolDecorator.pm | 35 +- .../lib/perl/lib/Thrift/SSLServerSocket.pm | 36 +- .../lib/perl/lib/Thrift/SSLSocket.pm | 61 +- .../thrift.git/lib/perl/lib/Thrift/Server.pm | 118 +- .../lib/perl/lib/Thrift/ServerSocket.pm | 35 +- .../thrift.git/lib/perl/lib/Thrift/Socket.pm | 116 +- .../lib/perl/lib/Thrift/Transport.pm | 29 +- .../thrift.git/lib/perl/lib/Thrift/Type.pm | 50 + .../lib/perl/lib/Thrift/UnixServerSocket.pm | 14 +- .../lib/perl/lib/Thrift/UnixSocket.pm | 15 +- .../thrift.git/lib/perl/test/multiplex.t | 16 +- .../thrift.git/lib/perl/test/processor.t | 4 +- .../thrift.git/lib/perl/tools/FixupDist.pl | 35 + .../thrift.git/lib/php/Makefile.am | 107 +- .../thrift.git/lib/php/README.md | 33 +- .../thrift.git/lib/php/coding_standards.md | 6 +- .../thrift.git/lib/php/lib/Base/TBase.php | 382 + .../ClassLoader/ThriftClassLoader.php | 46 +- .../lib/Exception/TApplicationException.php | 76 + .../lib/php/lib/Exception/TException.php | 384 + .../Exception/TProtocolException.php | 22 +- .../Exception/TTransportException.php | 18 +- .../Factory/TBinaryProtocolFactory.php | 22 +- .../Factory/TCompactProtocolFactory.php | 14 +- .../Factory/TJSONProtocolFactory.php | 0 .../{Thrift => }/Factory/TProtocolFactory.php | 12 +- .../Factory/TStringFuncFactory.php | 18 +- .../lib/php/lib/Factory/TTransportFactory.php | 18 + .../Protocol/JSON/BaseContext.php | 0 .../Protocol/JSON/ListContext.php | 0 .../Protocol/JSON/LookaheadReader.php | 0 .../Protocol/JSON/PairContext.php | 0 .../SimpleJSON/CollectionMapKeyException.php | 0 .../Protocol/SimpleJSON/Context.php | 1 - .../Protocol/SimpleJSON/ListContext.php | 0 .../Protocol/SimpleJSON/MapContext.php | 4 - .../Protocol/SimpleJSON/StructContext.php | 5 +- .../lib/php/lib/Protocol/TBinaryProtocol.php | 453 + .../Protocol/TBinaryProtocolAccelerated.php | 67 + .../lib/php/lib/Protocol/TCompactProtocol.php | 739 + .../{Thrift => }/Protocol/TJSONProtocol.php | 100 +- .../Protocol/TMultiplexedProtocol.php | 0 .../lib/php/lib/Protocol/TProtocol.php | 350 + .../Protocol/TProtocolDecorator.php | 1 + .../Protocol/TSimpleJSONProtocol.php | 9 +- .../php/lib/Serializer/TBinarySerializer.php | 87 + .../lib/php/lib/Server/TForkingServer.php | 125 + .../lib/php/lib/Server/TSSLServerSocket.php | 97 + .../thrift.git/lib/php/lib/Server/TServer.php | 102 + .../lib/php/lib/Server/TServerSocket.php | 124 + .../lib/php/lib/Server/TServerTransport.php | 56 + .../lib/php/lib/Server/TSimpleServer.php | 60 + .../lib/php/lib/StoredMessageProtocol.php | 53 + .../php/lib/{Thrift => }/StringFunc/Core.php | 0 .../lib/{Thrift => }/StringFunc/Mbstring.php | 0 .../{Thrift => }/StringFunc/TStringFunc.php | 0 .../{Thrift => }/TMultiplexedProcessor.php | 29 +- .../lib/php/lib/Thrift/Base/TBase.php | 380 - .../Exception/TApplicationException.php | 76 - .../php/lib/Thrift/Exception/TException.php | 383 - .../lib/Thrift/Factory/TTransportFactory.php | 18 - .../lib/Thrift/Protocol/TBinaryProtocol.php | 453 - .../Protocol/TBinaryProtocolAccelerated.php | 65 - .../lib/Thrift/Protocol/TCompactProtocol.php | 739 - .../lib/php/lib/Thrift/Protocol/TProtocol.php | 352 - .../Thrift/Serializer/TBinarySerializer.php | 85 - .../php/lib/Thrift/Server/TForkingServer.php | 120 - .../lib/Thrift/Server/TSSLServerSocket.php | 94 - .../lib/php/lib/Thrift/Server/TServer.php | 100 - .../php/lib/Thrift/Server/TServerSocket.php | 122 - .../lib/Thrift/Server/TServerTransport.php | 56 - .../php/lib/Thrift/Server/TSimpleServer.php | 58 - .../Thrift/Transport/TBufferedTransport.php | 181 - .../php/lib/Thrift/Transport/TCurlClient.php | 231 - .../lib/Thrift/Transport/TFramedTransport.php | 193 - .../php/lib/Thrift/Transport/THttpClient.php | 229 - .../lib/Thrift/Transport/TMemoryBuffer.php | 100 - .../php/lib/Thrift/Transport/TPhpStream.php | 123 - .../php/lib/Thrift/Transport/TSSLSocket.php | 112 - .../lib/php/lib/Thrift/Transport/TSocket.php | 337 - .../php/lib/Thrift/Transport/TSocketPool.php | 300 - .../php/lib/Thrift/Transport/TTransport.php | 95 - .../php/lib/Transport/TBufferedTransport.php | 206 + .../lib/php/lib/Transport/TCurlClient.php | 276 + .../php/lib/Transport/TFramedTransport.php | 192 + .../lib/php/lib/Transport/THttpClient.php | 258 + .../lib/php/lib/Transport/TMemoryBuffer.php | 106 + .../{Thrift => }/Transport/TNullTransport.php | 29 +- .../lib/php/lib/Transport/TPhpStream.php | 124 + .../lib/php/lib/Transport/TSSLSocket.php | 117 + .../lib/php/lib/Transport/TSocket.php | 366 + .../lib/php/lib/Transport/TSocketPool.php | 310 + .../lib/php/lib/Transport/TTransport.php | 98 + .../php/lib/{Thrift => }/Type/TConstant.php | 8 +- .../lib/{Thrift => }/Type/TMessageType.php | 8 +- .../lib/php/lib/{Thrift => }/Type/TType.php | 34 +- .../thrift_protocol/php_thrift_protocol.cpp | 1304 +- .../ext/thrift_protocol/php_thrift_protocol.h | 1 + .../thrift_protocol/php_thrift_protocol7.cpp | 1020 - .../thrift.git/lib/php/test/Fixtures.php | 194 + .../test/JsonSerialize/JsonSerializeTest.php | 116 + .../thrift.git/lib/php/test/Makefile.am | 38 +- .../BinarySerializerTest.php} | 48 +- .../test/Protocol/TJSONProtocolFixtures.php | 74 + .../php/test/Protocol/TJSONProtocolTest.php | 518 + .../Protocol/TSimpleJSONProtocolFixtures.php | 67 + .../test/Protocol/TSimpleJSONProtocolTest.php | 254 + .../lib/php/test/Test/Thrift/Fixtures.php | 194 - .../JsonSerialize/JsonSerializeTest.php | 116 - .../Thrift/Protocol/TestTJSONProtocol.php | 583 - .../Protocol/TestTSimpleJSONProtocol.php | 300 - .../php/test/Test/Thrift/TestValidators.php | 156 - .../php/test/Validator/BaseValidatorTest.php | 154 + .../lib/php/test/Validator/ValidatorTest.php | 41 + .../php/test/Validator/ValidatorTestOop.php | 41 + .../thrift.git/lib/py/MANIFEST.in | 1 + .../thrift.git/lib/py/Makefile.am | 1 + .../git.apache.org/thrift.git/lib/py/setup.py | 11 +- .../lib/py/src/TMultiplexedProcessor.py | 5 +- .../thrift.git/lib/py/src/TRecursive.py | 83 + .../thrift.git/lib/py/src/Thrift.py | 4 +- .../thrift.git/lib/py/src/compat.py | 6 + .../thrift.git/lib/py/src/ext/binary.h | 9 +- .../thrift.git/lib/py/src/ext/compact.h | 3 +- .../thrift.git/lib/py/src/ext/module.cpp | 7 +- .../thrift.git/lib/py/src/ext/protocol.h | 4 +- .../thrift.git/lib/py/src/ext/protocol.tcc | 22 +- .../thrift.git/lib/py/src/ext/types.cpp | 8 +- .../thrift.git/lib/py/src/ext/types.h | 1 + .../thrift.git/lib/py/src/protocol/TBase.py | 6 +- .../lib/py/src/protocol/TCompactProtocol.py | 3 + .../lib/py/src/protocol/THeaderProtocol.py | 225 + .../py/src/protocol/TMultiplexedProtocol.py | 5 +- .../lib/py/src/protocol/TProtocol.py | 5 +- .../lib/py/src/protocol/TProtocolDecorator.py | 36 +- .../lib/py/src/server/THttpServer.py | 23 +- .../lib/py/src/server/TNonblockingServer.py | 132 +- .../thrift.git/lib/py/src/server/TServer.py | 73 +- .../lib/py/src/transport/THeaderTransport.py | 352 + .../lib/py/src/transport/THttpClient.py | 51 +- .../lib/py/src/transport/TSSLSocket.py | 6 +- .../lib/py/src/transport/TSocket.py | 11 +- .../lib/py/src/transport/TTransport.py | 11 +- .../lib/py/src/transport/TTwisted.py | 8 +- .../lib/py/src/transport/sslcompat.py | 7 +- .../thrift.git/lib/py/test/test_sslsocket.py | 17 +- .../thrift.git/lib/py/test/thrift_json.py | 1 + .../thrift.git/lib/rb/lib/thrift/processor.rb | 11 +- .../rb/lib/thrift/protocol/base_protocol.rb | 10 +- .../rb/lib/thrift/protocol/binary_protocol.rb | 9 +- .../protocol/binary_protocol_accelerated.rb | 8 + .../lib/thrift/protocol/compact_protocol.rb | 8 + .../rb/lib/thrift/protocol/json_protocol.rb | 10 +- .../thrift/protocol/multiplexed_protocol.rb | 6 +- .../lib/rb/lib/thrift/server/base_server.rb | 10 +- .../lib/rb/lib/thrift/server/simple_server.rb | 6 +- .../lib/thrift/server/thread_pool_server.rb | 6 +- .../rb/lib/thrift/server/threaded_server.rb | 6 +- .../thrift/transport/base_server_transport.rb | 2 +- .../rb/lib/thrift/transport/base_transport.rb | 8 + .../thrift/transport/buffered_transport.rb | 10 +- .../lib/thrift/transport/framed_transport.rb | 10 +- .../thrift/transport/http_client_transport.rb | 4 + .../thrift/transport/io_stream_transport.rb | 5 +- .../transport/memory_buffer_transport.rb | 4 + .../rb/lib/thrift/transport/server_socket.rb | 7 +- .../lib/rb/lib/thrift/transport/socket.rb | 6 +- .../lib/thrift/transport/ssl_server_socket.rb | 4 + .../lib/rb/lib/thrift/transport/ssl_socket.rb | 4 + .../thrift/transport/unix_server_socket.rb | 6 +- .../rb/lib/thrift/transport/unix_socket.rb | 6 +- .../lib/rb/spec/base_protocol_spec.rb | 149 +- .../lib/rb/spec/base_transport_spec.rb | 272 +- .../spec/binary_protocol_accelerated_spec.rb | 8 +- .../lib/rb/spec/binary_protocol_spec.rb | 24 +- .../rb/spec/binary_protocol_spec_shared.rb | 143 +- .../thrift.git/lib/rb/spec/bytes_spec.rb | 76 +- .../thrift.git/lib/rb/spec/client_spec.rb | 83 +- .../lib/rb/spec/compact_protocol_spec.rb | 31 +- .../thrift.git/lib/rb/spec/exception_spec.rb | 108 +- .../thrift.git/lib/rb/spec/flat_spec.rb | 10 +- .../lib/rb/spec/http_client_spec.rb | 80 +- .../lib/rb/spec/json_protocol_spec.rb | 284 +- .../thrift.git/lib/rb/spec/namespaced_spec.rb | 10 +- .../lib/rb/spec/nonblocking_server_spec.rb | 32 +- .../thrift.git/lib/rb/spec/processor_spec.rb | 52 +- .../thrift.git/lib/rb/spec/serializer_spec.rb | 40 +- .../lib/rb/spec/server_socket_spec.rb | 49 +- .../thrift.git/lib/rb/spec/server_spec.rb | 144 +- .../thrift.git/lib/rb/spec/socket_spec.rb | 39 +- .../lib/rb/spec/socket_spec_shared.rb | 62 +- .../lib/rb/spec/ssl_server_socket_spec.rb | 34 + .../thrift.git/lib/rb/spec/ssl_socket_spec.rb | 48 +- .../rb/spec/struct_nested_containers_spec.rb | 48 +- .../thrift.git/lib/rb/spec/struct_spec.rb | 240 +- .../lib/rb/spec/thin_http_server_spec.rb | 36 +- .../thrift.git/lib/rb/spec/types_spec.rb | 109 +- .../thrift.git/lib/rb/spec/union_spec.rb | 84 +- .../lib/rb/spec/unix_socket_spec.rb | 77 +- .../thrift.git/lib/rb/thrift.gemspec | 21 +- .../thrift.git/lib/rs/Cargo.toml | 19 + .../thrift.git/lib/rs/Makefile.am | 46 + .../thrift.git/lib/rs/README.md | 111 + .../thrift.git/lib/rs/src/autogen.rs | 45 + .../thrift.git/lib/rs/src/errors.rs | 670 + .../thrift.git/lib/rs/src/lib.rs | 87 + .../thrift.git/lib/rs/src/protocol/binary.rs | 957 + .../thrift.git/lib/rs/src/protocol/compact.rs | 2386 ++ .../thrift.git/lib/rs/src/protocol/mod.rs | 969 + .../lib/rs/src/protocol/multiplexed.rs | 239 + .../thrift.git/lib/rs/src/protocol/stored.rs | 196 + .../thrift.git/lib/rs/src/server/mod.rs | 124 + .../lib/rs/src/server/multiplexed.rs | 351 + .../thrift.git/lib/rs/src/server/threaded.rs | 234 + .../lib/rs/src/transport/buffered.rs | 483 + .../thrift.git/lib/rs/src/transport/framed.rs | 459 + .../thrift.git/lib/rs/src/transport/mem.rs | 385 + .../thrift.git/lib/rs/src/transport/mod.rs | 291 + .../thrift.git/lib/rs/src/transport/socket.rs | 168 + .../thrift.git/lib/rs/test/Cargo.toml | 15 + .../thrift.git/lib/rs/test/Makefile.am | 54 + .../rs/test/src/bin/kitchen_sink_client.rs | 239 + .../rs/test/src/bin/kitchen_sink_server.rs | 313 + .../thrift.git/lib/rs/test/src/lib.rs | 57 + .../lib/rs/test/thrifts/Base_One.thrift | 84 + .../lib/rs/test/thrifts/Base_Two.thrift | 50 + .../lib/rs/test/thrifts/Midlayer.thrift | 71 + .../lib/rs/test/thrifts/Ultimate.thrift | 66 + .../thrift.git/lib/st/package.xml | 6 +- .../thrift.git/lib/swift/Package.swift | 24 + .../thrift.git/lib/swift/README.md | 216 + .../lib/swift/Sources/LinuxHelper.swift | 46 + .../lib/swift/Sources/TApplicationError.swift | 157 + .../lib/swift/Sources/TBinary.swift | 32 + .../lib/swift/Sources/TBinaryProtocol.swift | 384 + .../lib/swift/Sources/TClient.swift | 55 + .../lib/swift/Sources/TCompactProtocol.swift | 575 + .../thrift.git/lib/swift/Sources/TEnum.swift | 32 + .../thrift.git/lib/swift/Sources/TError.swift | 77 + .../swift/Sources/TFileHandleTransport.swift | 56 + .../lib/swift/Sources/TFileTransport.swift | 101 + .../lib/swift/Sources/TFramedTransport.swift | 123 + .../swift/Sources/THTTPSessionTransport.swift | 184 + .../thrift.git/lib/swift/Sources/TList.swift | 138 + .../thrift.git/lib/swift/Sources/TMap.swift | 194 + .../Sources/TMemoryBufferTransport.swift | 74 + .../swift/Sources/TMultiplexedProtocol.swift | 47 + .../lib/swift/Sources/TProcessor.swift | 29 + .../lib/swift/Sources/TProtocol.swift | 182 + .../lib/swift/Sources/TProtocolError.swift | 146 + .../swift/Sources/TSSLSocketTransport.swift | 229 + .../Sources/TSSLSocketTransportError.swift | 48 + .../lib/swift/Sources/TSerializable.swift | 136 + .../thrift.git/lib/swift/Sources/TSet.swift | 189 + .../lib/swift/Sources/TSocketServer.swift | 149 + .../lib/swift/Sources/TSocketTransport.swift | 210 + .../lib/swift/Sources/TStreamTransport.swift | 143 + .../lib/swift/Sources/TStruct.swift | 100 + .../lib/swift/Sources/TTransport.swift | 64 + .../lib/swift/Sources/TTransportError.swift | 86 + .../lib/swift/Sources/TWrappedProtocol.swift | 208 + .../thrift.git/lib/swift/Sources/Thrift.swift | 3 + .../lib/swift/Tests/LinuxMain.swift | 8 + .../ThriftTests/TBinaryProtocolTests.swift | 168 + .../ThriftTests/TCompactProtocolTests.swift | 210 + .../swift/Tests/ThriftTests/ThriftTests.swift | 18 + .../thrift.git/package-lock.json | 2183 ++ vendor/git.apache.org/thrift.git/package.json | 36 +- .../git.apache.org/thrift.git/phpcs.xml.dist | 25 + .../thrift.git/pull_request_template.md | 19 + .../thrift.git/sonar-project.properties | 8 +- .../thrift.git/test/AnnotationTest.thrift | 9 + .../thrift.git/test/ConstantsDemo.thrift | 1 + .../test/DoubleConstantsTest.thrift | 17 + .../thrift.git/test/EnumContainersTest.thrift | 46 + .../thrift.git/test/EnumTest.thrift | 5 + .../thrift.git/test/JavaDeepCopyTest.thrift | 19 + .../thrift.git/test/JavaTypes.thrift | 5 + .../thrift.git/test/Makefile.am | 20 + .../thrift.git/test/ThriftTest.thrift | 6 +- .../thrift.git/test/UnsafeTypes.thrift | 24 + .../thrift.git/test/c_glib/Makefile.am | 4 +- .../thrift.git/test/c_glib/src/test_client.c | 366 +- .../thrift.git/test/c_glib/src/test_server.c | 71 +- .../src/thrift_second_service_handler.c | 69 + .../src/thrift_second_service_handler.h | 73 + .../thrift.git/test/cl/Makefile.am | 42 + .../thrift.git/test/cl/implementation.lisp | 136 + .../thrift.git/test/cl/make-test-client.lisp | 93 + .../thrift.git/test/cl/make-test-server.lisp | 80 + .../thrift.git/test/cl/tests.lisp | 240 + .../thrift.git/test/cpp/CMakeLists.txt | 9 +- .../thrift.git/test/cpp/Makefile.am | 14 +- .../test/cpp/realloc/realloc_test.c | 107 - .../thrift.git/test/cpp/src/StressTest.cpp | 83 +- .../test/cpp/src/StressTestNonBlocking.cpp | 84 +- .../thrift.git/test/cpp/src/TestClient.cpp | 383 +- .../thrift.git/test/cpp/src/TestServer.cpp | 261 +- .../thrift.git/test/crossrunner/collect.py | 4 +- .../thrift.git/test/crossrunner/report.py | 23 +- .../thrift.git/test/crossrunner/run.py | 212 +- .../thrift.git/test/crossrunner/test.py | 18 +- .../thrift.git/test/crossrunner/util.py | 4 + .../thrift.git/test/csharp/Makefile.am | 8 + .../test/csharp/Properties/AssemblyInfo.cs | 10 +- .../thrift.git/test/csharp/TestClient.cs | 90 +- .../thrift.git/test/csharp/TestServer.cs | 82 +- .../thrift.git/test/csharp/ThriftTest.csproj | 4 +- .../thrift.git/test/dart/Makefile.am | 3 +- .../test/dart/test_client/pubspec.yaml | 2 +- .../thrift.git/test/erl/Makefile.am | 2 - .../thrift.git/test/erl/src/test_client.erl | 10 +- .../test/erl/src/test_thrift_server.erl | 2 +- .../test/erl/src/thrift_test.app.src | 2 +- .../thrift.git/test/features/Makefile.am | 2 + .../test/features/container_limit.py | 2 +- .../test/features/known_failures_Linux.json | 84 +- .../thrift.git/test/features/nosslv3.sh | 59 + .../thrift.git/test/features/string_limit.py | 3 +- .../thrift.git/test/features/tests.json | 24 +- .../thrift.git/test/features/tls.sh | 71 + .../thrift.git/test/go/Makefile.am | 11 +- .../thrift.git/test/go/src/bin/stress/main.go | 17 +- .../test/go/src/bin/testclient/main.go | 104 +- .../test/go/src/bin/testserver/main.go | 1 + .../thrift.git/test/go/src/common/client.go | 27 +- .../test/go/src/common/clientserver_test.go | 188 +- .../test/go/src/common/context_test.go | 98 + .../test/go/src/common/mock_handler.go | 289 - .../test/go/src/common/printing_handler.go | 51 +- .../test/go/src/common/simple_handler.go | 2 +- .../thrift.git/test/haxe/Makefile.am | 29 +- .../thrift.git/test/haxe/make_all.sh | 2 +- .../thrift.git/test/haxe/src/TestClient.hx | 63 +- .../test/haxe/src/TestServerHandler.hx | 27 +- .../thrift.git/test/hs/Makefile.am | 2 - .../thrift.git/test/hs/TestClient.hs | 6 +- .../thrift.git/test/hs/TestServer.hs | 15 +- .../thrift.git/test/known_failures_Linux.json | 473 +- .../thrift.git/test/netcore/Client/.gitignore | 2 + .../test/netcore/Client/Client.csproj | 31 + .../thrift.git/test/netcore/Client/Program.cs | 72 + .../netcore/Client/Properties/AssemblyInfo.cs | 43 + .../test/netcore/Client/TestClient.cs | 943 + .../thrift.git/test/netcore/Makefile.am | 41 + .../thrift.git/test/netcore/README.md | 20 + .../thrift.git/test/netcore/Server/.gitignore | 2 + .../thrift.git/test/netcore/Server/Program.cs | 72 + .../netcore/Server/Properties/AssemblyInfo.cs | 43 + .../test/netcore/Server/Server.csproj | 31 + .../test/netcore/Server/TestServer.cs | 594 + .../thrift.git/test/netcore/ThriftTest.sln | 64 + .../thrift.git/test/netcore/build.cmd | 25 + .../thrift.git/test/netcore/build.sh | 26 + .../thrift.git/test/perl/Makefile.am | 2 - .../thrift.git/test/perl/TestClient.pl | 215 +- .../thrift.git/test/perl/TestServer.pl | 275 +- .../thrift.git/test/php/Makefile.am | 19 +- .../php/{TestPsr4.php => TestClassmap.php} | 2 +- .../thrift.git/test/php/TestClient.php | 79 +- .../thrift.git/test/php/test_php.ini | 2 + .../thrift.git/test/py.tornado/test_suite.py | 22 +- .../thrift.git/test/py.twisted/Makefile.am | 1 - .../thrift.git/test/py.twisted/test_suite.py | 21 +- .../thrift.git/test/py/FastbinaryTest.py | 5 + .../thrift.git/test/py/Makefile.am | 19 +- .../thrift.git/test/py/RunClientServer.py | 4 +- .../thrift.git/test/py/SerializationTest.py | 67 + .../thrift.git/test/py/TestClient.py | 132 +- .../thrift.git/test/py/TestEof.py | 1 + .../thrift.git/test/py/TestFrozen.py | 1 + .../test/py/TestRenderedDoubleConstants.py | 177 + .../thrift.git/test/py/TestServer.py | 55 +- .../thrift.git/test/py/TestSocket.py | 7 +- .../thrift.git/test/py/generate.cmake | 14 + .../git.apache.org/thrift.git/test/rb/Gemfile | 6 +- .../thrift.git/test/rb/Makefile.am | 3 +- .../test/rb/generation/test_recursive.rb | 41 + .../test/rb/integration/TestClient.rb | 42 +- .../test/rb/integration/TestServer.rb | 57 +- .../thrift.git/test/rs/Cargo.toml | 17 + .../thrift.git/test/rs/Makefile.am | 40 + .../thrift.git/test/rs/src/bin/test_client.rs | 605 + .../thrift.git/test/rs/src/bin/test_server.rs | 398 + .../thrift.git/test/rs/src/lib.rs | 23 + vendor/git.apache.org/thrift.git/test/test.py | 38 +- .../git.apache.org/thrift.git/test/tests.json | 293 +- .../thrift.git/test/valgrind.suppress | 44 + .../thrift.git/tutorial/Makefile.am | 12 + .../thrift.git/tutorial/c_glib/Makefile.am | 7 +- .../thrift.git/tutorial/cl/Makefile.am | 65 + .../tutorial/cl/ensure-externals.sh | 1 + .../thrift.git/tutorial/cl/load-locally.lisp | 22 + .../tutorial/cl/make-tutorial-client.lisp | 51 + .../tutorial/cl/make-tutorial-server.lisp | 29 + .../tutorial/cl/shared-implementation.lisp | 25 + .../tutorial/cl/thrift-tutorial.asd | 17 + .../tutorial/cl/tutorial-implementation.lisp | 41 + .../thrift.git/tutorial/cpp/CMakeLists.txt | 8 +- .../thrift.git/tutorial/cpp/CppClient.cpp | 7 +- .../thrift.git/tutorial/cpp/CppServer.cpp | 41 +- .../thrift.git/tutorial/cpp/Makefile.am | 2 - .../CsharpClient/Properties/AssemblyInfo.cs | 10 +- .../CsharpServer/Properties/AssemblyInfo.cs | 10 +- .../thrift.git/tutorial/dart/Makefile.am | 6 +- .../tutorial/dart/client/pubspec.yaml | 2 +- .../tutorial/dart/console_client/pubspec.yaml | 2 +- .../tutorial/dart/server/pubspec.yaml | 2 +- .../delphi/DelphiClient/DelphiClient.dpr | 20 +- .../delphi/DelphiClient/DelphiClient.dproj | 238 +- .../delphi/DelphiServer/DelphiServer.dpr | 18 +- .../delphi/DelphiServer/DelphiServer.dproj | 236 +- .../thrift.git/tutorial/erl/client.erl | 6 +- .../thrift.git/tutorial/erl/client.sh | 38 +- .../thrift.git/tutorial/erl/json_client.erl | 4 +- .../thrift.git/tutorial/erl/server.erl | 20 +- .../thrift.git/tutorial/erl/server.sh | 38 +- .../thrift.git/tutorial/go/Makefile.am | 22 +- .../thrift.git/tutorial/go/src/client.go | 20 +- .../thrift.git/tutorial/go/src/handler.go | 11 +- .../thrift.git/tutorial/go/src/main.go | 2 +- .../thrift.git/tutorial/go/src/server.go | 2 +- .../thrift.git/tutorial/haxe/Makefile.am | 31 +- .../thrift.git/tutorial/hs/LICENSE | 239 + .../thrift.git/tutorial/hs/Makefile.am | 3 + .../tutorial/hs/ThriftTutorial.cabal | 4 +- .../thrift.git/tutorial/java/build.xml | 16 +- .../thrift.git/tutorial/js/build.xml | 18 +- .../thrift.git/tutorial/netcore/.gitignore | 1 + .../tutorial/netcore/Client/Client.csproj | 19 + .../tutorial/netcore/Client/Program.cs | 355 + .../netcore/Client/Properties/AssemblyInfo.cs | 40 + .../Client/Properties/launchSettings.json | 8 + .../tutorial/netcore/Client/ThriftTest.pfx | Bin 0 -> 2661 bytes .../tutorial/netcore/Interfaces/.gitignore | 3 + .../netcore/Interfaces/Interfaces.csproj | 30 + .../Interfaces/Properties/AssemblyInfo.cs | 40 + .../thrift.git/tutorial/netcore/Makefile.am | 42 + .../thrift.git/tutorial/netcore/README.md | 278 + .../tutorial/netcore/Server/Program.cs | 428 + .../netcore/Server/Properties/AssemblyInfo.cs | 40 + .../Server/Properties/launchSettings.json | 8 + .../tutorial/netcore/Server/Server.csproj | 26 + .../tutorial/netcore/Server/ThriftTest.pfx | Bin 0 -> 2661 bytes .../thrift.git/tutorial/netcore/Tutorial.sln | 78 + .../thrift.git/tutorial/netcore/build.cmd | 25 + .../thrift.git/tutorial/netcore/build.sh | 26 + .../thrift.git/tutorial/nodejs/Makefile.am | 2 - .../thrift.git/tutorial/nodejs/NodeClient.js | 2 +- .../tutorial/nodejs/NodeClientPromise.js | 2 +- .../thrift.git/tutorial/ocaml/_oasis | 2 +- .../thrift.git/tutorial/perl/PerlClient.pl | 12 +- .../thrift.git/tutorial/perl/PerlServer.pl | 16 +- .../thrift.git/tutorial/php/PhpClient.php | 2 +- .../thrift.git/tutorial/php/PhpServer.php | 2 +- .../tutorial/py.tornado/Makefile.am | 2 - .../tutorial/py.twisted/Makefile.am | 2 - .../thrift.git/tutorial/py/Makefile.am | 2 - .../thrift.git/tutorial/py/PythonClient.py | 1 + .../thrift.git/tutorial/py/PythonServer.py | 3 +- .../thrift.git/tutorial/rb/Makefile.am | 2 - .../thrift.git/tutorial/rs/Cargo.toml | 16 + .../thrift.git/tutorial/rs/Makefile.am | 52 + .../thrift.git/tutorial/rs/README.md | 317 + .../tutorial/rs/src/bin/tutorial_client.rs | 130 + .../tutorial/rs/src/bin/tutorial_server.rs | 179 + .../thrift.git/tutorial/rs/src/lib.rs | 23 + .../thrift.git/tutorial/shared.thrift | 2 + .../thrift.git/tutorial/tutorial.thrift | 3 + .../gorealis/.aurora-config/security.ini | 5 + .../github.com/paypal/gorealis/.gitattributes | 3 + vendor/github.com/paypal/gorealis/.travis.yml | 2 +- vendor/github.com/paypal/gorealis/Gopkg.lock | 24 +- vendor/github.com/paypal/gorealis/Gopkg.toml | 3 +- vendor/github.com/paypal/gorealis/clusters.go | 11 + .../paypal/gorealis/clusters_test.go | 2 +- .../github.com/paypal/gorealis/container.go | 37 +- .../paypal/gorealis/docker-compose.yml | 6 + vendor/github.com/paypal/gorealis/errors.go | 2 +- .../paypal/gorealis/examples/client.go | 231 +- .../paypal/gorealis/examples/jsonClient.go | 27 +- .../apache/aurora/GoUnusedProtection__.go | 7 + .../gen-go/apache/aurora/auroraAPI-consts.go | 58 + .../gen-go/apache/aurora/auroraAPI.go | 31576 ++++++++++++++++ .../aurora_admin-remote.go | 201 +- .../aurora_scheduler_manager-remote.go | 143 +- .../gen-go/apache/aurora/auroraadmin.go | 5870 --- .../apache/aurora/auroraschedulermanager.go | 5115 --- .../gen-go/apache/aurora/constants.go | 89 - .../read_only_scheduler-remote.go | 83 +- .../gen-go/apache/aurora/readonlyscheduler.go | 4293 --- .../gorealis/gen-go/apache/aurora/ttypes.go | 16424 -------- .../paypal/gorealis/generateBindings.sh | 2 +- vendor/github.com/paypal/gorealis/go.mod | 10 + vendor/github.com/paypal/gorealis/go.sum | 9 + vendor/github.com/paypal/gorealis/job.go | 308 +- .../github.com/paypal/gorealis/jobUpdate.go | 232 + vendor/github.com/paypal/gorealis/logger.go | 6 +- vendor/github.com/paypal/gorealis/monitors.go | 86 +- vendor/github.com/paypal/gorealis/realis.go | 954 +- .../paypal/gorealis/realis_e2e_test.go | 299 +- .../paypal/gorealis/response/response.go | 13 - vendor/github.com/paypal/gorealis/retry.go | 39 +- .../github.com/paypal/gorealis/runTestsMac.sh | 2 +- vendor/github.com/paypal/gorealis/task.go | 367 + .../github.com/paypal/gorealis/task_test.go | 57 + .../github.com/paypal/gorealis/updatejob.go | 154 - vendor/github.com/paypal/gorealis/util.go | 75 + vendor/github.com/paypal/gorealis/zk_test.go | 2 +- 1335 files changed, 137431 insertions(+), 61530 deletions(-) create mode 100644 vendor/git.apache.org/thrift.git/.eslintignore create mode 100644 vendor/git.apache.org/thrift.git/.eslintrc.json create mode 100644 vendor/git.apache.org/thrift.git/.github/stale.yml create mode 100644 vendor/git.apache.org/thrift.git/.rustfmt.toml delete mode 100644 vendor/git.apache.org/thrift.git/Dockerfile create mode 100644 vendor/git.apache.org/thrift.git/LANGUAGES.md create mode 100644 vendor/git.apache.org/thrift.git/Thrift-swift3.podspec rename vendor/git.apache.org/thrift.git/aclocal/{m4_ax_compare_version.m4 => ax_compare_version.m4} (98%) create mode 100644 vendor/git.apache.org/thrift.git/aclocal/ax_cxx_compile_stdcxx.m4 create mode 100644 vendor/git.apache.org/thrift.git/aclocal/ax_prog_dotnetcore_version.m4 delete mode 100644 vendor/git.apache.org/thrift.git/build/appveyor/download_openssl.py delete mode 100644 vendor/git.apache.org/thrift.git/build/docker/Vagrantfile delete mode 100644 vendor/git.apache.org/thrift.git/build/docker/centos/Dockerfile delete mode 100644 vendor/git.apache.org/thrift.git/build/docker/centos6/Dockerfile delete mode 100644 vendor/git.apache.org/thrift.git/build/docker/debian/Dockerfile delete mode 100644 vendor/git.apache.org/thrift.git/build/docker/ubuntu/Dockerfile create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_cl_generator.cc create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_netcore_generator.cc create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_netcore_generator.h create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_rs_generator.cc create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/thrift-t_php_generator.o-a60a38e9 create mode 100755 vendor/git.apache.org/thrift.git/compiler/cpp/test/bincat.sh create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/test/compiler/Included.thrift create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/test/compiler/Including.thrift create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/test/compiler/Single.thrift create mode 100755 vendor/git.apache.org/thrift.git/compiler/cpp/test/compiler/staleness_check.py create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/const1_return.thrift create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/enum1_return.thrift create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/enum2_return.thrift create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/exception1_return.thrift create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/exception2_return.thrift create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/service1_return.thrift create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/service2_return.thrift create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/service3_return.thrift create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/service4_return.thrift create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/struct1_return.thrift create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/struct2_return.thrift create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/typedef1_return.thrift create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/union1_return.thrift create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/union2_return.thrift create mode 100755 vendor/git.apache.org/thrift.git/compiler/cpp/test/plugin_stability_test.sh create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/tests/CMakeLists.txt create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/tests/README.md create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/tests/catch/catch.hpp create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests.cc create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests_helpers.cc create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests_helpers.h create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/tests/netcore/t_netcore_generator_helpers_tests.cc create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/tests/netcore/t_netcore_generator_initialization_tests.cc create mode 100644 vendor/git.apache.org/thrift.git/compiler/cpp/tests/tests_main.cc create mode 100644 vendor/git.apache.org/thrift.git/contrib/fb303/java/build.properties create mode 100644 vendor/git.apache.org/thrift.git/contrib/thrift-maven-plugin/src/test/java/org/apache/thrift/maven/TestAbstractThriftMojo.java create mode 100644 vendor/git.apache.org/thrift.git/doc/images/cgrn.png create mode 100644 vendor/git.apache.org/thrift.git/doc/images/cred.png create mode 100644 vendor/git.apache.org/thrift.git/doc/images/credfull.png create mode 100644 vendor/git.apache.org/thrift.git/doc/images/cyel.png create mode 100644 vendor/git.apache.org/thrift.git/doc/images/thrift-layers.png create mode 100644 vendor/git.apache.org/thrift.git/dub.json create mode 100644 vendor/git.apache.org/thrift.git/lib/as3/build.properties create mode 100644 vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/processor/thrift_multiplexed_processor.c create mode 100644 vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/processor/thrift_multiplexed_processor.h create mode 100644 vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_multiplexed_protocol.c create mode 100644 vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_multiplexed_protocol.h create mode 100644 vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_protocol_decorator.c create mode 100644 vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_protocol_decorator.h create mode 100644 vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_stored_message_protocol.c create mode 100644 vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_stored_message_protocol.h create mode 100644 vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_platform_socket.h create mode 100644 vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_ssl_socket.c create mode 100644 vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_ssl_socket.h create mode 100644 vendor/git.apache.org/thrift.git/lib/c_glib/test/testtransportsslsocket.c rename vendor/git.apache.org/thrift.git/{build/docker/check_unmodified.sh => lib/cl/Makefile.am} (55%) mode change 100755 => 100644 create mode 100644 vendor/git.apache.org/thrift.git/lib/cl/README.md create mode 100644 vendor/git.apache.org/thrift.git/lib/cl/READMES/readme-cassandra.lisp create mode 100755 vendor/git.apache.org/thrift.git/lib/cl/ensure-externals.sh create mode 100644 vendor/git.apache.org/thrift.git/lib/cl/load-locally.lisp create mode 100644 vendor/git.apache.org/thrift.git/lib/cl/test/make-test-binary.lisp delete mode 100644 vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/cxxfunctional.h create mode 100644 vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/stdcxx.h create mode 100644 vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TNonblockingSSLServerSocket.cpp create mode 100644 vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TNonblockingSSLServerSocket.h create mode 100644 vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TNonblockingServerSocket.cpp create mode 100644 vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TNonblockingServerSocket.h create mode 100644 vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TNonblockingServerTransport.h create mode 100644 vendor/git.apache.org/thrift.git/lib/cpp/test/AnnotationTest.cpp create mode 100644 vendor/git.apache.org/thrift.git/lib/cpp/test/OneWayHTTPTest.cpp create mode 100644 vendor/git.apache.org/thrift.git/lib/cpp/test/OneWayTest.thrift create mode 100644 vendor/git.apache.org/thrift.git/lib/cpp/test/RenderedDoubleConstantsTest.cpp create mode 100644 vendor/git.apache.org/thrift.git/lib/cpp/test/TNonblockingSSLServerTest.cpp create mode 100644 vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/MutexTest.cpp rename vendor/git.apache.org/thrift.git/lib/cpp/test/{ => concurrency}/RWMutexStarveTest.cpp (82%) create mode 100644 vendor/git.apache.org/thrift.git/lib/csharp/src/Net35/ExtensionsNet35.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TSocketVersionizer.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/dart/test/transport/t_framed_transport_test.dart create mode 100644 vendor/git.apache.org/thrift.git/lib/delphi/DelphiThrift.groupproj create mode 100644 vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Exception.pas rename vendor/git.apache.org/thrift.git/lib/delphi/{src/Thrift.Console.pas => test/ConsoleHelper.pas} (96%) rename vendor/git.apache.org/thrift.git/lib/delphi/test/{codegen/ReservedKeywords.thrift => keywords/ReservedIncluded.thrift} (64%) create mode 100644 vendor/git.apache.org/thrift.git/lib/delphi/test/keywords/ReservedKeywords.dpr create mode 100644 vendor/git.apache.org/thrift.git/lib/delphi/test/keywords/ReservedKeywords.thrift create mode 100644 vendor/git.apache.org/thrift.git/lib/erl/test/Thrift_omit_with.thrift create mode 100644 vendor/git.apache.org/thrift.git/lib/erl/test/test_const.erl create mode 100644 vendor/git.apache.org/thrift.git/lib/erl/test/test_omit.erl create mode 100644 vendor/git.apache.org/thrift.git/lib/erl/test/test_rendered_double_constants.erl create mode 100644 vendor/git.apache.org/thrift.git/lib/go/test/RequiredFieldTest.thrift create mode 100644 vendor/git.apache.org/thrift.git/lib/go/test/UnionBinaryTest.thrift create mode 100644 vendor/git.apache.org/thrift.git/lib/go/test/tests/context.go create mode 100644 vendor/git.apache.org/thrift.git/lib/go/test/tests/union_binary_test.go create mode 100644 vendor/git.apache.org/thrift.git/lib/go/thrift/client.go rename vendor/git.apache.org/thrift.git/lib/go/thrift/{processor.go => common_test.go} (74%) create mode 100644 vendor/git.apache.org/thrift.git/lib/go/thrift/context.go create mode 100644 vendor/git.apache.org/thrift.git/lib/go/thrift/simple_server_test.go create mode 100644 vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Protocol/Header.hs create mode 100644 vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Transport/Header.hs create mode 100644 vendor/git.apache.org/thrift.git/lib/java/build.gradle delete mode 100644 vendor/git.apache.org/thrift.git/lib/java/build.xml create mode 100644 vendor/git.apache.org/thrift.git/lib/java/code_quality_tools/findbugs-filter.xml rename vendor/git.apache.org/thrift.git/lib/java/{build.properties => gradle.properties} (56%) create mode 100644 vendor/git.apache.org/thrift.git/lib/java/gradle/additionalArtifacts.gradle create mode 100644 vendor/git.apache.org/thrift.git/lib/java/gradle/cloverCoverage.gradle create mode 100644 vendor/git.apache.org/thrift.git/lib/java/gradle/codeQualityChecks.gradle create mode 100644 vendor/git.apache.org/thrift.git/lib/java/gradle/environment.gradle create mode 100644 vendor/git.apache.org/thrift.git/lib/java/gradle/functionalTests.gradle create mode 100644 vendor/git.apache.org/thrift.git/lib/java/gradle/generateTestThrift.gradle create mode 100644 vendor/git.apache.org/thrift.git/lib/java/gradle/publishing.gradle create mode 100644 vendor/git.apache.org/thrift.git/lib/java/gradle/sourceConfiguration.gradle create mode 100644 vendor/git.apache.org/thrift.git/lib/java/gradle/unitTests.gradle create mode 100644 vendor/git.apache.org/thrift.git/lib/java/gradle/wrapper/gradle-wrapper.properties create mode 100755 vendor/git.apache.org/thrift.git/lib/java/gradlew create mode 100644 vendor/git.apache.org/thrift.git/lib/java/gradlew.bat create mode 100644 vendor/git.apache.org/thrift.git/lib/java/settings.gradle create mode 100644 vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/annotation/Nullable.java create mode 100644 vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestDeepCopy.java create mode 100644 vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestEnumContainers.java create mode 100644 vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestMultiplexedProcessor.java create mode 100644 vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestRenderedDoubleConstants.java create mode 100644 vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestUnsafeBinaries.java create mode 100644 vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/transport/TestTSSLTransportFactoryStreamedStore.java create mode 100644 vendor/git.apache.org/thrift.git/lib/js/package-lock.json create mode 100644 vendor/git.apache.org/thrift.git/lib/js/test/build.properties create mode 100644 vendor/git.apache.org/thrift.git/lib/js/test/test-double-rendering.html create mode 100644 vendor/git.apache.org/thrift.git/lib/js/test/test-double-rendering.js create mode 100644 vendor/git.apache.org/thrift.git/lib/js/test/test-es6.html create mode 100644 vendor/git.apache.org/thrift.git/lib/js/test/test-es6.js create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Makefile.am create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/README.md create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.IntegrationTests/.gitignore create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.IntegrationTests/Protocols/ProtocolsOperationsTests.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.IntegrationTests/Thrift.IntegrationTests.csproj create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/.gitignore create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/CassandraTest.thrift create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/Properties/AssemblyInfo.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/Thrift.PublicInterfaces.Compile.Tests.csproj create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.Tests/Collections/TCollectionsTests.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.Tests/Collections/THashSetTests.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.Tests/Protocols/TJsonProtocolHelperTests.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.Tests/Protocols/TJsonProtocolTests.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.Tests/Thrift.Tests.csproj create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift.sln create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Collections/TCollections.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Collections/THashSet.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/ITAsyncProcessor.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/ITProcessorFactory.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Properties/AssemblyInfo.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TField.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TList.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TMap.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TMessage.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TMessageType.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TSet.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TStruct.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TType.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/ITProtocolFactory.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TAbstractBase.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TBase.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TBinaryProtocol.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TCompactProtocol.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TJSONProtocol.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TMultiplexedProtocol.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TProtocol.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TProtocolDecorator.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TProtocolException.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Utilities/TBase64Helper.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Utilities/TBase64Utils.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Utilities/TJsonProtocolConstants.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Utilities/TJsonProtocolHelper.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Utilities/TProtocolUtil.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Server/AsyncBaseServer.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Server/TBaseServer.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Server/TServerEventHandler.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/SingletonTProcessorFactory.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/TApplicationException.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/TBaseClient.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/TException.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/TMultiplexedProcessor.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Thrift.csproj create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TBufferedClientTransport.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TFramedClientTransport.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/THttpClientTransport.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TMemoryBufferClientTransport.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TNamedPipeClientTransport.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TSocketClientTransport.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TStreamClientTransport.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TTlsSocketClientTransport.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Server/THttpServerTransport.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Server/TNamedPipeServerTransport.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Server/TServerFramedTransport.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Server/TServerSocketTransport.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Server/TTlsServerSocketTransport.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/TClientTransport.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/TServerTransport.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/TTransportException.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/TTransportFactory.cs create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/build.cmd create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/build.sh create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/runtests.cmd create mode 100644 vendor/git.apache.org/thrift.git/lib/netcore/runtests.sh delete mode 100644 vendor/git.apache.org/thrift.git/lib/nodejs/test/browser_client.js create mode 100644 vendor/git.apache.org/thrift.git/lib/nodets/.gitignore create mode 100755 vendor/git.apache.org/thrift.git/lib/nodets/Makefile.am create mode 100644 vendor/git.apache.org/thrift.git/lib/nodets/coding_standards.md create mode 100644 vendor/git.apache.org/thrift.git/lib/nodets/test/client.ts create mode 100755 vendor/git.apache.org/thrift.git/lib/nodets/test/runClient.sh create mode 100755 vendor/git.apache.org/thrift.git/lib/nodets/test/runServer.sh create mode 100644 vendor/git.apache.org/thrift.git/lib/nodets/test/server.ts create mode 100644 vendor/git.apache.org/thrift.git/lib/nodets/test/test-cases.ts create mode 100755 vendor/git.apache.org/thrift.git/lib/nodets/test/testAll.sh create mode 100644 vendor/git.apache.org/thrift.git/lib/nodets/test/test_driver.ts create mode 100644 vendor/git.apache.org/thrift.git/lib/nodets/test/test_handler.ts create mode 100644 vendor/git.apache.org/thrift.git/lib/nodets/test/tsconfig.json create mode 100644 vendor/git.apache.org/thrift.git/lib/ocaml/.gitignore create mode 100644 vendor/git.apache.org/thrift.git/lib/ocaml/DEVELOPMENT delete mode 100644 vendor/git.apache.org/thrift.git/lib/ocaml/OCamlMakefile delete mode 100644 vendor/git.apache.org/thrift.git/lib/ocaml/README-OCamlMakefile create mode 100644 vendor/git.apache.org/thrift.git/lib/ocaml/descr create mode 100644 vendor/git.apache.org/thrift.git/lib/ocaml/opam create mode 100644 vendor/git.apache.org/thrift.git/lib/ocaml/url create mode 100644 vendor/git.apache.org/thrift.git/lib/perl/MANIFEST.SKIP create mode 100755 vendor/git.apache.org/thrift.git/lib/perl/build-cpan-dist.sh create mode 100644 vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Exception.pm create mode 100644 vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Type.pm create mode 100644 vendor/git.apache.org/thrift.git/lib/perl/tools/FixupDist.pl create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Base/TBase.php rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/ClassLoader/ThriftClassLoader.php (78%) create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Exception/TApplicationException.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Exception/TException.php rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Exception/TProtocolException.php (78%) rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Exception/TTransportException.php (79%) rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Factory/TBinaryProtocolFactory.php (72%) rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Factory/TCompactProtocolFactory.php (87%) rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Factory/TJSONProtocolFactory.php (100%) rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Factory/TProtocolFactory.php (85%) rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Factory/TStringFuncFactory.php (83%) create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Factory/TTransportFactory.php rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Protocol/JSON/BaseContext.php (100%) rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Protocol/JSON/ListContext.php (100%) rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Protocol/JSON/LookaheadReader.php (100%) rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Protocol/JSON/PairContext.php (100%) rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Protocol/SimpleJSON/CollectionMapKeyException.php (100%) rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Protocol/SimpleJSON/Context.php (99%) rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Protocol/SimpleJSON/ListContext.php (100%) rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Protocol/SimpleJSON/MapContext.php (96%) rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Protocol/SimpleJSON/StructContext.php (93%) create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TBinaryProtocol.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TBinaryProtocolAccelerated.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TCompactProtocol.php rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Protocol/TJSONProtocol.php (90%) rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Protocol/TMultiplexedProtocol.php (100%) create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TProtocol.php rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Protocol/TProtocolDecorator.php (99%) rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Protocol/TSimpleJSONProtocol.php (98%) create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Serializer/TBinarySerializer.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Server/TForkingServer.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Server/TSSLServerSocket.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Server/TServer.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Server/TServerSocket.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Server/TServerTransport.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Server/TSimpleServer.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/StoredMessageProtocol.php rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/StringFunc/Core.php (100%) rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/StringFunc/Mbstring.php (100%) rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/StringFunc/TStringFunc.php (100%) rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/TMultiplexedProcessor.php (84%) delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Base/TBase.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Exception/TApplicationException.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Exception/TException.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Factory/TTransportFactory.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TBinaryProtocol.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TBinaryProtocolAccelerated.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TCompactProtocol.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TProtocol.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Serializer/TBinarySerializer.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TForkingServer.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TSSLServerSocket.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TServer.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TServerSocket.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TServerTransport.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TSimpleServer.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TBufferedTransport.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TCurlClient.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TFramedTransport.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/THttpClient.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TMemoryBuffer.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TPhpStream.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TSSLSocket.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TSocket.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TSocketPool.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TTransport.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TBufferedTransport.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TCurlClient.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TFramedTransport.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Transport/THttpClient.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TMemoryBuffer.php rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Transport/TNullTransport.php (78%) create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TPhpStream.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TSSLSocket.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TSocket.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TSocketPool.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TTransport.php rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Type/TConstant.php (91%) rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Type/TMessageType.php (91%) rename vendor/git.apache.org/thrift.git/lib/php/lib/{Thrift => }/Type/TType.php (68%) delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/src/ext/thrift_protocol/php_thrift_protocol7.cpp create mode 100644 vendor/git.apache.org/thrift.git/lib/php/test/Fixtures.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/test/JsonSerialize/JsonSerializeTest.php rename vendor/git.apache.org/thrift.git/lib/php/test/{Test/Thrift/Protocol/TestBinarySerializer.php => Protocol/BinarySerializerTest.php} (54%) create mode 100644 vendor/git.apache.org/thrift.git/lib/php/test/Protocol/TJSONProtocolFixtures.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/test/Protocol/TJSONProtocolTest.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/test/Protocol/TSimpleJSONProtocolFixtures.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/test/Protocol/TSimpleJSONProtocolTest.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/Fixtures.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/JsonSerialize/JsonSerializeTest.php delete mode 100755 vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/Protocol/TestTJSONProtocol.php delete mode 100755 vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/Protocol/TestTSimpleJSONProtocol.php delete mode 100644 vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/TestValidators.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/test/Validator/BaseValidatorTest.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/test/Validator/ValidatorTest.php create mode 100644 vendor/git.apache.org/thrift.git/lib/php/test/Validator/ValidatorTestOop.php create mode 100644 vendor/git.apache.org/thrift.git/lib/py/MANIFEST.in create mode 100644 vendor/git.apache.org/thrift.git/lib/py/src/TRecursive.py create mode 100644 vendor/git.apache.org/thrift.git/lib/py/src/protocol/THeaderProtocol.py create mode 100644 vendor/git.apache.org/thrift.git/lib/py/src/transport/THeaderTransport.py create mode 100644 vendor/git.apache.org/thrift.git/lib/rb/spec/ssl_server_socket_spec.rb create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/Cargo.toml create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/Makefile.am create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/README.md create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/src/autogen.rs create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/src/errors.rs create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/src/lib.rs create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/src/protocol/binary.rs create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/src/protocol/compact.rs create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/src/protocol/mod.rs create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/src/protocol/multiplexed.rs create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/src/protocol/stored.rs create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/src/server/mod.rs create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/src/server/multiplexed.rs create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/src/server/threaded.rs create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/src/transport/buffered.rs create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/src/transport/framed.rs create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/src/transport/mem.rs create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/src/transport/mod.rs create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/src/transport/socket.rs create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/test/Cargo.toml create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/test/Makefile.am create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/test/src/bin/kitchen_sink_client.rs create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/test/src/bin/kitchen_sink_server.rs create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/test/src/lib.rs create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/test/thrifts/Base_One.thrift create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/test/thrifts/Base_Two.thrift create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/test/thrifts/Midlayer.thrift create mode 100644 vendor/git.apache.org/thrift.git/lib/rs/test/thrifts/Ultimate.thrift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Package.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/README.md create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/LinuxHelper.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TApplicationError.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TBinary.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TBinaryProtocol.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TClient.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TCompactProtocol.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TEnum.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TError.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TFileHandleTransport.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TFileTransport.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TFramedTransport.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/THTTPSessionTransport.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TList.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TMap.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TMemoryBufferTransport.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TMultiplexedProtocol.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TProcessor.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TProtocol.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TProtocolError.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TSSLSocketTransport.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TSSLSocketTransportError.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TSerializable.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TSet.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TSocketServer.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TSocketTransport.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TStreamTransport.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TStruct.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TTransport.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TTransportError.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/TWrappedProtocol.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Sources/Thrift.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Tests/LinuxMain.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Tests/ThriftTests/TBinaryProtocolTests.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Tests/ThriftTests/TCompactProtocolTests.swift create mode 100644 vendor/git.apache.org/thrift.git/lib/swift/Tests/ThriftTests/ThriftTests.swift create mode 100644 vendor/git.apache.org/thrift.git/package-lock.json create mode 100644 vendor/git.apache.org/thrift.git/phpcs.xml.dist create mode 100644 vendor/git.apache.org/thrift.git/pull_request_template.md create mode 100644 vendor/git.apache.org/thrift.git/test/DoubleConstantsTest.thrift create mode 100644 vendor/git.apache.org/thrift.git/test/EnumContainersTest.thrift create mode 100644 vendor/git.apache.org/thrift.git/test/JavaDeepCopyTest.thrift create mode 100644 vendor/git.apache.org/thrift.git/test/UnsafeTypes.thrift create mode 100644 vendor/git.apache.org/thrift.git/test/c_glib/src/thrift_second_service_handler.c create mode 100644 vendor/git.apache.org/thrift.git/test/c_glib/src/thrift_second_service_handler.h create mode 100755 vendor/git.apache.org/thrift.git/test/cl/Makefile.am create mode 100644 vendor/git.apache.org/thrift.git/test/cl/implementation.lisp create mode 100644 vendor/git.apache.org/thrift.git/test/cl/make-test-client.lisp create mode 100644 vendor/git.apache.org/thrift.git/test/cl/make-test-server.lisp create mode 100644 vendor/git.apache.org/thrift.git/test/cl/tests.lisp delete mode 100644 vendor/git.apache.org/thrift.git/test/cpp/realloc/realloc_test.c create mode 100755 vendor/git.apache.org/thrift.git/test/features/nosslv3.sh create mode 100755 vendor/git.apache.org/thrift.git/test/features/tls.sh create mode 100644 vendor/git.apache.org/thrift.git/test/go/src/common/context_test.go delete mode 100644 vendor/git.apache.org/thrift.git/test/go/src/common/mock_handler.go mode change 100644 => 100755 vendor/git.apache.org/thrift.git/test/haxe/make_all.sh create mode 100644 vendor/git.apache.org/thrift.git/test/netcore/Client/.gitignore create mode 100644 vendor/git.apache.org/thrift.git/test/netcore/Client/Client.csproj create mode 100644 vendor/git.apache.org/thrift.git/test/netcore/Client/Program.cs create mode 100644 vendor/git.apache.org/thrift.git/test/netcore/Client/Properties/AssemblyInfo.cs create mode 100644 vendor/git.apache.org/thrift.git/test/netcore/Client/TestClient.cs create mode 100644 vendor/git.apache.org/thrift.git/test/netcore/Makefile.am create mode 100644 vendor/git.apache.org/thrift.git/test/netcore/README.md create mode 100644 vendor/git.apache.org/thrift.git/test/netcore/Server/.gitignore create mode 100644 vendor/git.apache.org/thrift.git/test/netcore/Server/Program.cs create mode 100644 vendor/git.apache.org/thrift.git/test/netcore/Server/Properties/AssemblyInfo.cs create mode 100644 vendor/git.apache.org/thrift.git/test/netcore/Server/Server.csproj create mode 100644 vendor/git.apache.org/thrift.git/test/netcore/Server/TestServer.cs create mode 100644 vendor/git.apache.org/thrift.git/test/netcore/ThriftTest.sln create mode 100644 vendor/git.apache.org/thrift.git/test/netcore/build.cmd create mode 100755 vendor/git.apache.org/thrift.git/test/netcore/build.sh rename vendor/git.apache.org/thrift.git/test/php/{TestPsr4.php => TestClassmap.php} (96%) create mode 100644 vendor/git.apache.org/thrift.git/test/php/test_php.ini create mode 100644 vendor/git.apache.org/thrift.git/test/py/TestRenderedDoubleConstants.py create mode 100644 vendor/git.apache.org/thrift.git/test/rb/generation/test_recursive.rb create mode 100644 vendor/git.apache.org/thrift.git/test/rs/Cargo.toml create mode 100644 vendor/git.apache.org/thrift.git/test/rs/Makefile.am create mode 100644 vendor/git.apache.org/thrift.git/test/rs/src/bin/test_client.rs create mode 100644 vendor/git.apache.org/thrift.git/test/rs/src/bin/test_server.rs create mode 100644 vendor/git.apache.org/thrift.git/test/rs/src/lib.rs create mode 100755 vendor/git.apache.org/thrift.git/tutorial/cl/Makefile.am create mode 120000 vendor/git.apache.org/thrift.git/tutorial/cl/ensure-externals.sh create mode 100644 vendor/git.apache.org/thrift.git/tutorial/cl/load-locally.lisp create mode 100644 vendor/git.apache.org/thrift.git/tutorial/cl/make-tutorial-client.lisp create mode 100644 vendor/git.apache.org/thrift.git/tutorial/cl/make-tutorial-server.lisp create mode 100644 vendor/git.apache.org/thrift.git/tutorial/cl/shared-implementation.lisp create mode 100644 vendor/git.apache.org/thrift.git/tutorial/cl/thrift-tutorial.asd create mode 100644 vendor/git.apache.org/thrift.git/tutorial/cl/tutorial-implementation.lisp mode change 120000 => 100755 vendor/git.apache.org/thrift.git/tutorial/erl/client.sh mode change 100755 => 120000 vendor/git.apache.org/thrift.git/tutorial/erl/server.sh create mode 100644 vendor/git.apache.org/thrift.git/tutorial/hs/LICENSE create mode 100644 vendor/git.apache.org/thrift.git/tutorial/netcore/.gitignore create mode 100644 vendor/git.apache.org/thrift.git/tutorial/netcore/Client/Client.csproj create mode 100644 vendor/git.apache.org/thrift.git/tutorial/netcore/Client/Program.cs create mode 100644 vendor/git.apache.org/thrift.git/tutorial/netcore/Client/Properties/AssemblyInfo.cs create mode 100644 vendor/git.apache.org/thrift.git/tutorial/netcore/Client/Properties/launchSettings.json create mode 100644 vendor/git.apache.org/thrift.git/tutorial/netcore/Client/ThriftTest.pfx create mode 100644 vendor/git.apache.org/thrift.git/tutorial/netcore/Interfaces/.gitignore create mode 100644 vendor/git.apache.org/thrift.git/tutorial/netcore/Interfaces/Interfaces.csproj create mode 100644 vendor/git.apache.org/thrift.git/tutorial/netcore/Interfaces/Properties/AssemblyInfo.cs create mode 100644 vendor/git.apache.org/thrift.git/tutorial/netcore/Makefile.am create mode 100644 vendor/git.apache.org/thrift.git/tutorial/netcore/README.md create mode 100644 vendor/git.apache.org/thrift.git/tutorial/netcore/Server/Program.cs create mode 100644 vendor/git.apache.org/thrift.git/tutorial/netcore/Server/Properties/AssemblyInfo.cs create mode 100644 vendor/git.apache.org/thrift.git/tutorial/netcore/Server/Properties/launchSettings.json create mode 100644 vendor/git.apache.org/thrift.git/tutorial/netcore/Server/Server.csproj create mode 100644 vendor/git.apache.org/thrift.git/tutorial/netcore/Server/ThriftTest.pfx create mode 100644 vendor/git.apache.org/thrift.git/tutorial/netcore/Tutorial.sln create mode 100644 vendor/git.apache.org/thrift.git/tutorial/netcore/build.cmd create mode 100755 vendor/git.apache.org/thrift.git/tutorial/netcore/build.sh create mode 100644 vendor/git.apache.org/thrift.git/tutorial/rs/Cargo.toml create mode 100644 vendor/git.apache.org/thrift.git/tutorial/rs/Makefile.am create mode 100644 vendor/git.apache.org/thrift.git/tutorial/rs/README.md create mode 100644 vendor/git.apache.org/thrift.git/tutorial/rs/src/bin/tutorial_client.rs create mode 100644 vendor/git.apache.org/thrift.git/tutorial/rs/src/bin/tutorial_server.rs create mode 100644 vendor/git.apache.org/thrift.git/tutorial/rs/src/lib.rs create mode 100644 vendor/github.com/paypal/gorealis/.aurora-config/security.ini create mode 100644 vendor/github.com/paypal/gorealis/.gitattributes create mode 100644 vendor/github.com/paypal/gorealis/gen-go/apache/aurora/GoUnusedProtection__.go create mode 100644 vendor/github.com/paypal/gorealis/gen-go/apache/aurora/auroraAPI-consts.go create mode 100644 vendor/github.com/paypal/gorealis/gen-go/apache/aurora/auroraAPI.go delete mode 100644 vendor/github.com/paypal/gorealis/gen-go/apache/aurora/auroraadmin.go delete mode 100644 vendor/github.com/paypal/gorealis/gen-go/apache/aurora/auroraschedulermanager.go delete mode 100644 vendor/github.com/paypal/gorealis/gen-go/apache/aurora/constants.go delete mode 100644 vendor/github.com/paypal/gorealis/gen-go/apache/aurora/readonlyscheduler.go delete mode 100644 vendor/github.com/paypal/gorealis/gen-go/apache/aurora/ttypes.go create mode 100644 vendor/github.com/paypal/gorealis/go.mod create mode 100644 vendor/github.com/paypal/gorealis/go.sum create mode 100644 vendor/github.com/paypal/gorealis/jobUpdate.go create mode 100644 vendor/github.com/paypal/gorealis/task.go create mode 100644 vendor/github.com/paypal/gorealis/task_test.go delete mode 100644 vendor/github.com/paypal/gorealis/updatejob.go create mode 100644 vendor/github.com/paypal/gorealis/util.go diff --git a/CHANGELOG b/CHANGELOG index 08929c2..64a21a5 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,7 @@ +0.0.7 + +* Initial migration to gorealis v2 + 0.0.6 * Added auto-completion to the deb file. diff --git a/Gopkg.lock b/Gopkg.lock index ff7dc49..b2149da 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -2,13 +2,12 @@ [[projects]] - branch = "0.10.0-http-client-fix" - digest = "1:2b8c4f3c06ddb304a24ba8a625aa9f583c5576743356fa41e48c63e1563021d2" + branch = "0.12.0" + digest = "1:89696c38cec777120b8b1bb5e2d363d655cf2e1e7d8c851919aaa0fd576d9b86" name = "git.apache.org/thrift.git" packages = ["lib/go/thrift"] pruneopts = "" - revision = "cb1afec972a85791e9b24a04b60fc9dbbfc3cda3" - source = "github.com/rdelval/thrift" + revision = "384647d290e2e4a55a14b1b7ef1b7e66293a2c33" [[projects]] digest = "1:eb53021a8aa3f599d29c7102e65026242bdedce998a54837dc67f14b6a97c5fd" @@ -70,8 +69,7 @@ version = "v1.1.2" [[projects]] - branch = "drainSLA" - digest = "1:154e4eb61c4f730b3b5962fc254e7aff9ddb9bab50efd6ab098fcfcad0e1920f" + digest = "1:0a57933aaf17a56940a600fbbe6ede0e0fcc92531d7b85a29f2a6352c12573ca" name = "github.com/paypal/gorealis" packages = [ ".", @@ -79,8 +77,8 @@ "response", ] pruneopts = "" - revision = "f27dc4a6abf5a2ad8675d7a4ba0059309631e473" - source = "github.com/rdelval/gorealis" + revision = "b776bd301d9018b86253711e789eb2376ce60d1c" + version = "v2.0.0" [[projects]] digest = "1:894aef961c056b6d85d12bac890bf60c44e99b46292888bfa66caf529f804457" @@ -210,6 +208,7 @@ "git.apache.org/thrift.git/lib/go/thrift", "github.com/paypal/gorealis", "github.com/paypal/gorealis/gen-go/apache/aurora", + "github.com/pkg/errors", "github.com/sirupsen/logrus", "github.com/spf13/cobra", "github.com/spf13/pflag", diff --git a/Gopkg.toml b/Gopkg.toml index e8d832a..f4d972d 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -2,8 +2,7 @@ required = ["git.apache.org/thrift.git/lib/go/thrift"] [[constraint]] name = "github.com/paypal/gorealis" - branch = "drainSLA" - source = "github.com/rdelval/gorealis" + version = ">=2.0.0" [[constraint]] name = "github.com/spf13/cobra" @@ -14,6 +13,5 @@ required = ["git.apache.org/thrift.git/lib/go/thrift"] revision = "62edee319679b6ceaec16de03b966102d2dea709" [[constraint]] - name = "git.apache.org/thrift.git" - branch = "0.10.0-http-client-fix" - source = "github.com/rdelval/thrift" + name = "git.apache.org/thrift.git" + branch = "0.12.0" diff --git a/cmd/fetch.go b/cmd/fetch.go index 1b9b9fb..b1c69e6 100644 --- a/cmd/fetch.go +++ b/cmd/fetch.go @@ -119,7 +119,7 @@ func fetchTasks(cmd *cobra.Command, args []string) { func fetchStatus(cmd *cobra.Command, args []string) { log.Infof("Fetching maintenance status for %v \n", args) - _, result, err := client.MaintenanceStatus(args...) + result, err := client.MaintenanceStatus(args...) if err != nil { log.Fatalf("error: %+v\n", err) } @@ -127,7 +127,7 @@ func fetchStatus(cmd *cobra.Command, args []string) { if toJson { fmt.Println(toJSON(result.Statuses)) } else { - for k := range result.Statuses { + for _, k := range result.GetStatuses() { fmt.Printf("Result: %s:%s\n", k.Host, k.Mode) } } @@ -162,7 +162,7 @@ func fetchJobs(cmd *cobra.Command, args []string) { *role = "" } - _, result, err := client.GetJobs(*role) + result, err := client.GetJobs(*role) if err != nil { log.Fatalf("error: %+v\n", err) @@ -171,7 +171,7 @@ func fetchJobs(cmd *cobra.Command, args []string) { if toJson { var configSlice []*aurora.JobConfiguration - for config := range result.GetConfigs() { + for _, config := range result.GetConfigs() { configSlice = append(configSlice, config) } diff --git a/cmd/kill.go b/cmd/kill.go index 6a16d84..0b20b00 100644 --- a/cmd/kill.go +++ b/cmd/kill.go @@ -1,8 +1,6 @@ package cmd import ( - "fmt" - "github.com/paypal/gorealis" "github.com/spf13/cobra" @@ -53,20 +51,14 @@ func killJob(cmd *cobra.Command, args []string) { Environment(*env). Role(*role). Name(*name) - resp, err := client.KillJob(job.JobKey()) + err := client.KillJob(job.JobKey()) if err != nil { log.Fatalln(err) } - if ok, err := monitor.Instances(job.JobKey(), 0, 5, 50); !ok || err != nil { + if ok, err := client.InstancesMonitor(job.JobKey(), 0, 5, 50); !ok || err != nil { log.Fatalln("Unable to kill all instances of job") } - - if toJson { - fmt.Println(toJSON(resp.GetResult_())) - } else { - fmt.Println(resp.GetResult_()) - } } func killEntireCluster(cmd *cobra.Command, args []string) { diff --git a/cmd/root.go b/cmd/root.go index 3733419..10e6eb4 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -15,8 +15,7 @@ var username, password, zkAddr, schedAddr string var env, role, name = new(string), new(string), new(string) var ram, disk int64 var cpu float64 -var client realis.Realis -var monitor *realis.Monitor +var client *realis.Client var skipCertVerification bool var caCertsPath string var clientKey, clientCert string @@ -28,7 +27,7 @@ var percent float64 var count int64 var filename string -const australisVer = "v0.0.6" +const australisVer = "v0.0.7" var monitorInterval, monitorTimeout time.Duration @@ -119,7 +118,7 @@ func connect(cmd *cobra.Command, args []string) { realisOptions := []realis.ClientOption{realis.BasicAuth(username, password), realis.ThriftJSON(), - realis.TimeoutMS(20000), + realis.Timeout(20 * time.Second), realis.BackOff(realis.Backoff{ Steps: 2, Duration: 10 * time.Second, @@ -141,16 +140,15 @@ func connect(cmd *cobra.Command, args []string) { // Client certificate configuration if available if clientKey != "" || clientCert != "" || caCertsPath != "" { realisOptions = append(realisOptions, - realis.Certspath(caCertsPath), + realis.CertsPath(caCertsPath), realis.ClientCerts(clientKey, clientCert), realis.InsecureSkipVerify(skipCertVerification)) } // Connect to Aurora Scheduler and create a client object - client, err = realis.NewRealisClient(realisOptions...) + client, err = realis.NewClient(realisOptions...) if err != nil { log.Fatal(err) } - monitor = &realis.Monitor{Client: client} } diff --git a/cmd/set.go b/cmd/set.go index b2a46c4..07d397f 100644 --- a/cmd/set.go +++ b/cmd/set.go @@ -72,15 +72,9 @@ func setQuota(cmd *cobra.Command, args []string) { log.Println("Setting Quota resources for role.") log.Println(args) - resp, err := client.SetQuota(*role, &cpu, &ram, &disk) + err := client.SetQuota(*role, &cpu, &ram, &disk) if err != nil { log.Fatal(err) } - - if toJson{ - fmt.Println(toJSON(resp.GetResult_())) - } else { - fmt.Println(resp.GetResult_()) - } } diff --git a/cmd/start.go b/cmd/start.go index 11dc786..a48a3d1 100644 --- a/cmd/start.go +++ b/cmd/start.go @@ -43,7 +43,7 @@ func init() { // SLA Maintenance specific flags startMaintenanceCmd.Flags().DurationVar(&monitorInterval,"interval", time.Second * 5, "Interval at which to poll scheduler.") - startMaintenanceCmd.Flags().DurationVar(&monitorTimeout,"timeout", time.Minute * 1, "Time after which the monitor will stop polling and throw an error.") + startMaintenanceCmd.Flags().DurationVar(&monitorTimeout,"timeout", time.Minute * 10, "Time after which the monitor will stop polling and throw an error.") } var startCmd = &cobra.Command{ @@ -102,7 +102,7 @@ expects a space separated list of hosts to place into maintenance mode.`, func drain(cmd *cobra.Command, args []string) { log.Infoln("Setting hosts to DRAINING") log.Infoln(args) - _, result, err := client.DrainHosts(args...) + result, err := client.DrainHosts(args...) if err != nil { log.Fatalf("error: %+v\n", err) } @@ -110,16 +110,16 @@ func drain(cmd *cobra.Command, args []string) { log.Debugln(result) // Monitor change to DRAINING and DRAINED mode - hostResult, err := monitor.HostMaintenance( + hostResult, err := client.HostMaintenanceMonitor( args, []aurora.MaintenanceMode{aurora.MaintenanceMode_DRAINED}, - int(monitorInterval.Seconds()), - int(monitorTimeout.Seconds())) + monitorInterval, + monitorTimeout) maintenanceMonitorPrint(hostResult, []aurora.MaintenanceMode{aurora.MaintenanceMode_DRAINED}) if err != nil { - log.Fatalln("error: %+v", err) + log.Fatalln(err) } } @@ -133,11 +133,11 @@ func slaDrain(policy *aurora.SlaPolicy, hosts ...string) { log.Debugln(result) // Monitor change to DRAINING and DRAINED mode - hostResult, err := monitor.HostMaintenance( + hostResult, err := client.HostMaintenanceMonitor( hosts, []aurora.MaintenanceMode{aurora.MaintenanceMode_DRAINED}, - int(monitorInterval.Seconds()), - int(monitorTimeout.Seconds())) + monitorInterval, + monitorTimeout) maintenanceMonitorPrint(hostResult, []aurora.MaintenanceMode{aurora.MaintenanceMode_DRAINED}) @@ -167,7 +167,7 @@ func SLAPercentageDrain(cmd *cobra.Command, args []string) { func maintenance(cmd *cobra.Command, args []string) { log.Infoln("Setting hosts to Maintenance mode") log.Infoln(args) - _, result, err := client.StartMaintenance(args...) + result, err := client.StartMaintenance(args...) if err != nil { log.Fatalf("error: %+v\n", err) } @@ -175,11 +175,11 @@ func maintenance(cmd *cobra.Command, args []string) { log.Debugln(result) // Monitor change to DRAINING and DRAINED mode - hostResult, err := monitor.HostMaintenance( + hostResult, err := client.HostMaintenanceMonitor( args, []aurora.MaintenanceMode{aurora.MaintenanceMode_SCHEDULED}, - int(monitorInterval.Seconds()), - int(monitorTimeout.Seconds())) + monitorInterval, + monitorTimeout) maintenanceMonitorPrint(hostResult, []aurora.MaintenanceMode{aurora.MaintenanceMode_SCHEDULED}) diff --git a/cmd/stop.go b/cmd/stop.go index bcb6624..f66783d 100644 --- a/cmd/stop.go +++ b/cmd/stop.go @@ -1,7 +1,6 @@ package cmd import ( - "fmt" "github.com/paypal/gorealis/gen-go/apache/aurora" "github.com/spf13/cobra" "time" @@ -48,7 +47,7 @@ var stopUpdateCmd = &cobra.Command{ func endMaintenance(cmd *cobra.Command, args []string) { log.Println("Setting hosts to NONE maintenance status.") log.Println(args) - _, result, err := client.EndMaintenance(args...) + result, err := client.EndMaintenance(args...) if err != nil { log.Fatalf("error: %+v\n", err) } @@ -56,12 +55,11 @@ func endMaintenance(cmd *cobra.Command, args []string) { log.Debugln(result) // Monitor change to NONE mode - hostResult, err := monitor.HostMaintenance( + hostResult, err := client.HostMaintenanceMonitor( args, []aurora.MaintenanceMode{aurora.MaintenanceMode_NONE}, - int(monitorInterval.Seconds()), - int(monitorTimeout.Seconds())) - + monitorInterval, + monitorTimeout) maintenanceMonitorPrint(hostResult,[]aurora.MaintenanceMode{aurora.MaintenanceMode_NONE}) @@ -78,7 +76,7 @@ func stopUpdate(cmd *cobra.Command, args []string) { log.Infof("Stopping (aborting) update [%s/%s/%s] %s\n", *env, *role, *name, args[0]) - resp, err := client.AbortJobUpdate(aurora.JobUpdateKey{ + err := client.AbortJobUpdate(aurora.JobUpdateKey{ Job: &aurora.JobKey{Environment: *env, Role: *role, Name: *name}, ID: args[0], }, @@ -87,10 +85,4 @@ func stopUpdate(cmd *cobra.Command, args []string) { if err != nil { log.Fatalln(err) } - - if toJson{ - fmt.Println(toJSON(resp.GetResult_())) - } else { - fmt.Println(resp.GetResult_()) - } } diff --git a/debian/changelog b/debian/changelog index 4cf42eb..d7c9287 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,9 @@ +australis (0.0.7) unstable; urgency=medium + + * Upgraded australis to gorealis v2. + + -- Renan DelValle Wed, 26 Dec 2018 15:10:00 -0700 + australis (0.0.6) unstable; urgency=medium * Added auto-completion to the deb file. diff --git a/vendor/git.apache.org/thrift.git/.eslintignore b/vendor/git.apache.org/thrift.git/.eslintignore new file mode 100644 index 0000000..dde2dba --- /dev/null +++ b/vendor/git.apache.org/thrift.git/.eslintignore @@ -0,0 +1,9 @@ +# TODO: Use eslint on js lib and generated code + +# Ignore lib/js for now, which uses jshint currently +lib/js/* +# Ignore all generated code for now +**/gen-* + +# Don't lint nested node_modules +**/node_modules diff --git a/vendor/git.apache.org/thrift.git/.eslintrc.json b/vendor/git.apache.org/thrift.git/.eslintrc.json new file mode 100644 index 0000000..0aae820 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/.eslintrc.json @@ -0,0 +1,24 @@ +{ + "env": { + "es6": true, + "node": true + }, + "extends": [ + "eslint:recommended", + "plugin:prettier/recommended" + ], + "parserOptions": { + "ecmaVersion": 2017 + }, + "rules": { + "no-console": "off", + "no-var": "error", + "prefer-const": "error", + "no-constant-condition": [ + "error", + { + "checkLoops": false + } + ] + } +} diff --git a/vendor/git.apache.org/thrift.git/.github/stale.yml b/vendor/git.apache.org/thrift.git/.github/stale.yml new file mode 100644 index 0000000..12d4afb --- /dev/null +++ b/vendor/git.apache.org/thrift.git/.github/stale.yml @@ -0,0 +1,59 @@ +# Configuration for probot-stale - https://github.com/probot/stale + +# Number of days of inactivity before an Issue or Pull Request becomes stale +daysUntilStale: 60 + +# Number of days of inactivity before an Issue or Pull Request with the stale label is closed. +# Set to false to disable. If disabled, issues still need to be closed manually, but will remain marked as stale. +daysUntilClose: 7 + +# Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable +exemptLabels: + - Do Not Merge + - blocked + - pinned + - security + - "[Status] Maybe Later" + +# Set to true to ignore issues in a project (defaults to false) +exemptProjects: false + +# Set to true to ignore issues in a milestone (defaults to false) +exemptMilestones: false + +# Label to use when marking as stale +staleLabel: wontfix + +# Comment to post when marking as stale. Set to `false` to disable +markComment: > + This issue has been automatically marked as stale because it has not had + recent activity. It will be closed in 7 days if no further activity occurs. + Thank you for your contributions. + +# Comment to post when removing the stale label. +unmarkComment: > + This issue is no longer stale. + Thank you for your contributions. + +# Comment to post when closing a stale Issue or Pull Request. +closeComment: > + This issue has been automatically closed due to inactivity. + Thank you for your contributions. + +# Limit the number of actions per hour, from 1-30. Default is 30 +limitPerRun: 30 + +# Limit to only `issues` or `pulls` +# only: issues + +# Optionally, specify configuration settings that are specific to just 'issues' or 'pulls': +# pulls: +# daysUntilStale: 30 +# markComment: > +# This pull request has been automatically marked as stale because it has not had +# recent activity. It will be closed if no further activity occurs. Thank you +# for your contributions. + +# issues: +# exemptLabels: +# - confirmed diff --git a/vendor/git.apache.org/thrift.git/.gitignore b/vendor/git.apache.org/thrift.git/.gitignore index 140c93b..b7f7b45 100644 --- a/vendor/git.apache.org/thrift.git/.gitignore +++ b/vendor/git.apache.org/thrift.git/.gitignore @@ -21,28 +21,41 @@ *.swp *.hi *~ +tags .*project +.classpath +.dub +.settings +.checkstyle junit*.properties .idea +*.iml +*.ipr +*.iws gen-* Makefile Makefile.in aclocal.m4 acinclude.m4 +apache-thrift-test-library autom4te.cache cmake-* +dub.selections.json +libapache-thrift.a node_modules compile test-driver erl_crash.dump +project.lock.json .sonar .DS_Store .svn .vagrant +.vscode +.vs -/contrib/.vagrant/ /aclocal/libtool.m4 /aclocal/lt*.m4 /autoscan.log @@ -77,6 +90,7 @@ erl_crash.dump /configure /configure.lineno /configure.scan +/contrib/.vagrant/ /contrib/fb303/config.cache /contrib/fb303/config.log /contrib/fb303/config.status @@ -91,6 +105,13 @@ erl_crash.dump /contrib/fb303/py/fb303/ttypes.py /depcomp /install-sh +/lib/cl/backport-update.zip +/lib/cl/lib +/lib/cl/run-tests +/lib/cl/quicklisp.lisp +/lib/cl/externals/ +/lib/cl/run-tests +/lib/cl/quicklisp/ /lib/cpp/Debug/ /lib/cpp/Debug-mt/ /lib/cpp/Release/ @@ -101,6 +122,7 @@ erl_crash.dump /lib/cpp/src/thrift/stamp-h2 /lib/cpp/test/Benchmark /lib/cpp/test/AllProtocolsTest +/lib/cpp/test/AnnotationTest /lib/cpp/test/DebugProtoTest /lib/cpp/test/DenseProtoTest /lib/cpp/test/EnumTest @@ -108,12 +130,14 @@ erl_crash.dump /lib/cpp/test/OptionalRequiredTest /lib/cpp/test/SecurityTest /lib/cpp/test/SpecializationTest -/lib/cpp/test/ReflectionTest /lib/cpp/test/RecursiveTest +/lib/cpp/test/ReflectionTest +/lib/cpp/test/RenderedDoubleConstantsTest /lib/cpp/test/TFDTransportTest /lib/cpp/test/TFileTransportTest /lib/cpp/test/TInterruptTest /lib/cpp/test/TNonblockingServerTest +/lib/cpp/test/TNonblockingSSLServerTest /lib/cpp/test/TPipedTransportTest /lib/cpp/test/TServerIntegrationTest /lib/cpp/test/TSocketInterruptTest @@ -149,6 +173,7 @@ erl_crash.dump /lib/c_glib/test/testframedtransport /lib/c_glib/test/testmemorybuffer /lib/c_glib/test/testoptionalrequired +/lib/c_glib/test/testtransportsslsocket /lib/c_glib/test/testsimpleserver /lib/c_glib/test/teststruct /lib/c_glib/test/testthrifttest @@ -175,46 +200,35 @@ erl_crash.dump /lib/dart/**/packages /lib/dart/**/.pub/ /lib/dart/**/pubspec.lock -/lib/delphi/src/*.dcu -/lib/delphi/test/*.identcache -/lib/delphi/test/*.local -/lib/delphi/test/*.dcu -/lib/delphi/test/*.2007 -/lib/delphi/test/*.dproj -/lib/delphi/test/*.dproj -/lib/delphi/test/codegen/*.bat -/lib/delphi/test/skip/*.local -/lib/delphi/test/skip/*.identcache -/lib/delphi/test/skip/*.identcache -/lib/delphi/test/skip/*.dproj -/lib/delphi/test/skip/*.dproj -/lib/delphi/test/skip/*.2007 -/lib/delphi/test/serializer/*.identcache -/lib/delphi/test/serializer/*.dproj -/lib/delphi/test/serializer/*.local -/lib/delphi/test/serializer/*.2007 -/lib/delphi/test/serializer/*.dcu -/lib/delphi/test/multiplexed/*.dproj -/lib/delphi/test/multiplexed/*.2007 -/lib/delphi/test/multiplexed/*.local -/lib/delphi/test/multiplexed/*.identcache -/lib/delphi/test/multiplexed/*.dcu -/lib/delphi/test/typeregistry/*.2007 -/lib/delphi/test/typeregistry/*.dproj -/lib/delphi/test/typeregistry/*.identcache -/lib/delphi/test/typeregistry/*.local -/lib/delphi/test/typeregistry/*.dcu -/lib/erl/.generated +/lib/delphi/test/skip/*.request +/lib/delphi/test/skip/*.response +/lib/delphi/**/*.identcache +/lib/delphi/**/*.local +/lib/delphi/**/*.dcu +/lib/delphi/**/*.2007 +/lib/delphi/**/*.dproj +/lib/delphi/**/codegen/*.bat /lib/erl/.eunit -/lib/erl/ebin +/lib/erl/.generated +/lib/erl/.rebar/ /lib/erl/deps/ +/lib/erl/ebin /lib/erl/src/thrift.app.src -/lib/erl/test/*.hrl /lib/erl/test/*.beam +/lib/erl/test/*.hrl +/lib/erl/test/Thrift_omit_without.thrift /lib/haxe/test/bin +/lib/haxe/test/data.tmp /lib/hs/dist +/lib/java/.gradle +/lib/java/android/.gradle /lib/java/build +/lib/java/target +/lib/js/dist +/lib/js/doc /lib/js/test/build +/lib/netcore/**/bin +/lib/netcore/**/obj /lib/nodejs/coverage /lib/nodejs/node_modules/ /lib/perl/MANIFEST @@ -238,6 +252,7 @@ erl_crash.dump /lib/php/src/ext/thrift_protocol/build/ /lib/php/src/ext/thrift_protocol/config.* /lib/php/src/ext/thrift_protocol/configure +/lib/php/src/ext/thrift_protocol/configure.ac /lib/php/src/ext/thrift_protocol/configure.in /lib/php/src/ext/thrift_protocol/install-sh /lib/php/src/ext/thrift_protocol/libtool @@ -254,21 +269,41 @@ erl_crash.dump /lib/php/test/packages/ /lib/py/dist/ /lib/erl/logs/ +/lib/go/pkg +/lib/go/src /lib/go/test/gopath/ /lib/go/test/ThriftTest.thrift +/lib/rs/target/ +/lib/rs/Cargo.lock +/lib/rs/test/Cargo.lock +/lib/rs/test/target/ +/lib/rs/test/bin/ +/lib/rs/test/src/base_one.rs +/lib/rs/test/src/base_two.rs +/lib/rs/test/src/midlayer.rs +/lib/rs/test/src/recursive.rs +/lib/rs/test/src/ultimate.rs +/lib/rs/*.iml +/lib/rs/**/*.iml /libtool /ltmain.sh /missing /node_modules/ +/vendor/ +/composer.lock /stamp-h1 /test/features/results.json /test/results.json /test/c_glib/test_client /test/c_glib/test_server +/test/cl/TestServer +/test/cl/TestClient /test/cpp/StressTest /test/cpp/StressTestNonBlocking /test/cpp/TestClient /test/cpp/TestServer +/test/csharp/obj +/test/csharp/bin /test/dart/**/.packages /test/dart/**/packages /test/dart/**/.pub/ @@ -276,20 +311,45 @@ erl_crash.dump /test/log/ /test/test.log /test/erl/.generated +/test/erl/.rebar /test/erl/ebin /test/go/bin/ /test/go/ThriftTest.thrift /test/go/gopath /test/go/pkg/ /test/go/src/code.google.com/ +/test/go/src/common/mock_handler.go /test/go/src/github.com/golang/ +/test/go/src/golang.org/ /test/go/src/gen/ /test/go/src/thrift /test/haxe/bin /test/hs/TestClient /test/hs/TestServer +/test/php/php_ext_dir/ /test/py.twisted/_trial_temp/ /test/rb/Gemfile.lock +/test/netcore/**/bin +/test/netcore/**/obj +/test/netcore/Thrift +/test/php/php_ext_dir/ +/test/rs/Cargo.lock +/test/rs/src/thrift_test.rs +/test/rs/bin/ +/test/rs/target/ +/test/rs/*.iml +/test/rs/**/*.iml +/lib/cl/backport-update.zip +/lib/cl/lib +/tutorial/cl/quicklisp.lisp +/tutorial/cl/externals/ +/tutorial/cl/quicklisp/ +/tutorial/cl/TutorialClient +/tutorial/cl/TutorialServer +/tutorial/cl/backport-update.zip +/tutorial/cl/lib/ +/tutorial/cl/shared-implementation.fasl +/tutorial/cl/tutorial-implementation.fasl /tutorial/cpp/TutorialClient /tutorial/cpp/TutorialServer /tutorial/c_glib/tutorial_client @@ -305,22 +365,31 @@ erl_crash.dump /tutorial/dart/**/packages /tutorial/dart/**/.pub/ /tutorial/dart/**/pubspec.lock -/tutorial/delphi/*.dsk -/tutorial/delphi/*.local -/tutorial/delphi/*.tvsconfig -/tutorial/delphi/DelphiClient/dcu -/tutorial/delphi/DelphiServer/dcu -/tutorial/delphi/DelphiClient/*.local -/tutorial/delphi/DelphiClient/*.identcache -/tutorial/delphi/DelphiServer/*.identcache -/tutorial/delphi/DelphiServer/*.local +/tutorial/delphi/**/*.dsk +/tutorial/delphi/**/*.local +/tutorial/delphi/**/*.tvsconfig +/tutorial/delphi/**/dcu +/tutorial/delphi/**/*.local +/tutorial/delphi/**/*.identcache +/tutorial/go/gopath /tutorial/go/go-tutorial /tutorial/go/calculator-remote /tutorial/go/src/shared /tutorial/go/src/tutorial /tutorial/go/src/git.apache.org +/tutorial/go/src/golang.org /tutorial/haxe/bin /tutorial/hs/dist/ /tutorial/java/build/ /tutorial/js/build/ +/tutorial/netcore/**/bin +/tutorial/netcore/**/obj +/tutorial/netcore/Thrift +/tutorial/rs/*.iml +/tutorial/rs/src/shared.rs +/tutorial/rs/src/tutorial.rs +/tutorial/rs/bin +/tutorial/rs/target +/tutorial/rs/Cargo.lock /ylwrap + diff --git a/vendor/git.apache.org/thrift.git/.rustfmt.toml b/vendor/git.apache.org/thrift.git/.rustfmt.toml new file mode 100644 index 0000000..dca5afd --- /dev/null +++ b/vendor/git.apache.org/thrift.git/.rustfmt.toml @@ -0,0 +1,64 @@ +max_width = 100 +hard_tabs = false +tab_spaces = 4 +newline_style = "Auto" +use_small_heuristics = "Default" +indent_style = "Block" +wrap_comments = false +format_doc_comments = false +comment_width = 80 +normalize_comments = false +normalize_doc_attributes = false +license_template_path = "" +format_strings = false +format_macro_matchers = false +format_macro_bodies = true +empty_item_single_line = true +struct_lit_single_line = true +fn_single_line = false +where_single_line = false +imports_indent = "Block" +imports_layout = "Mixed" +merge_imports = false +reorder_imports = true +reorder_modules = true +reorder_impl_items = false +type_punctuation_density = "Wide" +space_before_colon = false +space_after_colon = true +spaces_around_ranges = false +binop_separator = "Front" +remove_nested_parens = true +combine_control_expr = true +overflow_delimited_expr = false +struct_field_align_threshold = 0 +enum_discrim_align_threshold = 0 +match_arm_blocks = true +force_multiline_blocks = false +fn_args_density = "Tall" +brace_style = "SameLineWhere" +control_brace_style = "AlwaysSameLine" +trailing_semicolon = true +trailing_comma = "Vertical" +match_block_trailing_comma = false +blank_lines_upper_bound = 1 +blank_lines_lower_bound = 0 +edition = "2015" +merge_derives = true +use_try_shorthand = false +use_field_init_shorthand = false +force_explicit_abi = true +condense_wildcard_suffixes = false +color = "Auto" +required_version = "1.0.0" +unstable_features = false +disable_all_formatting = false +skip_children = false +hide_parse_errors = false +error_on_line_overflow = false +error_on_unformatted = false +report_todo = "Never" +report_fixme = "Never" +ignore = [] +emit_mode = "Files" +make_backup = false diff --git a/vendor/git.apache.org/thrift.git/.travis.yml b/vendor/git.apache.org/thrift.git/.travis.yml index 81a88c3..e09b8a4 100644 --- a/vendor/git.apache.org/thrift.git/.travis.yml +++ b/vendor/git.apache.org/thrift.git/.travis.yml @@ -19,181 +19,163 @@ # build Apache Thrift on Travis CI - https://travis-ci.org/ +# +# Docker Integration +# see: build/docker/README.md +# + sudo: required dist: trusty +language: cpp services: - docker install: - - (travis_wait ./build/docker/check_unmodified.sh $DISTRO && touch .unmodified) || true - - if [ ! -f .unmodified ]; then travis_retry travis_wait docker build -q -t thrift-build:$DISTRO build/docker/$DISTRO; fi + - if [[ `uname` == "Linux" ]]; then build/docker/refresh.sh; fi -script: - - docker run --net=host -e BUILD_LIBS="$BUILD_LIBS" $BUILD_ENV -v $(pwd):/thrift/src -it thrift-build:$DISTRO build/docker/scripts/$SCRIPT $BUILD_ARG +stages: + - docker # docker images + - thrift # thrift build jobs env: global: - - TEST_NAME="" - SCRIPT="cmake.sh" - BUILD_ARG="" - - BUILD_ENV="-e CC=clang -e CXX=clang++" - - DISTRO=ubuntu + - BUILD_ENV="-e CC=gcc -e CXX=g++ -e THRIFT_CROSSTEST_CONCURRENCY=4" + - DISTRO=ubuntu-bionic - BUILD_LIBS="CPP C_GLIB HASKELL JAVA PYTHON TESTING TUTORIALS" # only meaningful for CMake builds + - TRAVIS_BUILD_STAGE=test + # DOCKER_REPO (this works for all builds as a source for docker images - you can override for fork builds in your Travis settings) + - DOCKER_REPO="thrift/thrift-build" + # DOCKER_USER (provide in your Travis settings if you want to build and update docker images once, instead of on every job) + # DOCKER_PASS (same) - matrix: - - TEST_NAME="Cross Language Tests (Binary and Header Protocols)" - SCRIPT="cross-test.sh" - BUILD_ARG="-'(binary|header)'" - BUILD_ENV="-e CC=clang -e CXX=clang++ -e THRIFT_CROSSTEST_CONCURRENCY=4" - - - TEST_NAME="Cross Language Tests (Debian) (Binary and Header Protocols)" - SCRIPT="cross-test.sh" - BUILD_ARG="-'(binary|header)'" - BUILD_ENV="-e CC=clang -e CXX=clang++ -e THRIFT_CROSSTEST_CONCURRENCY=4" - DISTRO=debian - - - TEST_NAME="Cross Language Tests (Compact and JSON Protocols)" - SCRIPT="cross-test.sh" - BUILD_ARG="-'(compact|json)'" - BUILD_ENV="-e CC=clang -e CXX=clang++ -e THRIFT_CROSSTEST_CONCURRENCY=4" - - - TEST_NAME="Cross Language Tests (Debian) (Compact and JSON Protocols)" - SCRIPT="cross-test.sh" - BUILD_ARG="-'(compact|json)'" - BUILD_ENV="-e CC=clang -e CXX=clang++ -e THRIFT_CROSSTEST_CONCURRENCY=4" - DISTRO=debian - - # TODO: Remove them once migrated to CMake - # Autotools builds - - TEST_NAME="C C++ C# D Erlang Haxe Go (automake)" - SCRIPT="autotools.sh" - BUILD_ARG="--without-dart --without-haskell --without-java --without-lua --without-nodejs --without-perl --without-php --without-php_extension --without-python --without-ruby" - - - TEST_NAME="C C++ - GCC (automake)" - SCRIPT="autotools.sh" - BUILD_ARG="--without-csharp --without-java --without-erlang --without-nodejs --without-lua --without-python --without-perl --without-php --without-php_extension --without-dart --without-ruby --without-haskell --without-go --without-haxe --without-d" - BUILD_ENV="-e CC=gcc -e CXX=g++" - - - TEST_NAME="Java Lua PHP Ruby Dart (automake)" - SCRIPT="autotools.sh" - BUILD_ARG="--without-cpp --without-haskell --without-c_glib --without-csharp --without-d --without-erlang --without-go --without-haxe --without-nodejs --without-python --without-perl" - - # These are flaky (due to cabal and npm network/server failures) and also have lengthy output - - TEST_NAME="Haskell Node.js Python Perl (automake)" - SCRIPT="autotools.sh" - BUILD_ARG="--without-cpp --without-c_glib --without-csharp --without-d --without-dart --without-erlang --without-go --without-haxe --without-java --without-lua --without-php --without-php_extension --without-ruby" - - # CMake build - - TEST_NAME="All" - - - TEST_NAME="All (Debian)" - DISTRO=debian - - - TEST_NAME="C C++ - GCC" - BUILD_LIBS="CPP C_GLIB TESTING TUTORIALS" - BUILD_ARG="-DWITH_PYTHON=OFF -DWITH_JAVA=OFF -DWITH_HASKELL=OFF" - BUILD_ENV="-e CC=gcc -e CXX=g++" - - - TEST_NAME="C++ (Boost Thread)" - BUILD_LIBS="CPP TESTING TUTORIALS" - BUILD_ARG="-DWITH_BOOSTTHREADS=ON -DWITH_PYTHON=OFF -DWITH_C_GLIB=OFF -DWITH_JAVA=OFF -DWITH_HASKELL=OFF" - - - TEST_NAME="C++ (Boost Thread - GCC)" - BUILD_LIBS="CPP TESTING TUTORIALS" - BUILD_ARG="-DWITH_BOOSTTHREADS=ON -DWITH_PYTHON=OFF -DWITH_C_GLIB=OFF -DWITH_JAVA=OFF -DWITH_HASKELL=OFF" - BUILD_ENV="-e CC=gcc -e CXX=g++" - - - TEST_NAME="C++ (Std Thread)" - BUILD_LIBS="CPP TESTING TUTORIALS" - BUILD_ARG="-DWITH_STDTHREADS=ON -DCMAKE_CXX_FLAGS='-std=c++11' -DWITH_PYTHON=OFF -DWITH_C_GLIB=OFF -DWITH_JAVA=OFF -DWITH_HASKELL=OFF" - - - TEST_NAME="C++ (Std Thread - GCC)" - BUILD_LIBS="CPP TESTING TUTORIALS" - BUILD_ARG="-DWITH_STDTHREADS=ON -DCMAKE_CXX_FLAGS='-std=c++11' -DWITH_PYTHON=OFF -DWITH_C_GLIB=OFF -DWITH_JAVA=OFF -DWITH_HASKELL=OFF" - BUILD_ENV="-e CC=gcc -e CXX=g++" - - - TEST_NAME="Compiler (mingw)" - BUILD_LIBS="" - BUILD_ARG="-DCMAKE_TOOLCHAIN_FILE=../build/cmake/mingw32-toolchain.cmake -DBUILD_COMPILER=ON -DBUILD_LIBRARIES=OFF -DBUILD_TESTING=OFF -DBUILD_EXAMPLES=OFF" - BUILD_ENV="" - - - TEST_NAME="All - GCC (CentOS)" - BUILD_ENV="-e CC=gcc -e CXX=g++" - DISTRO=centos - - - TEST_NAME="C C++ - Clang (CentOS)" - BUILD_LIBS="CPP C_GLIB TESTING TUTORIALS" - BUILD_ARG="-DWITH_PYTHON=OFF -DWITH_JAVA=OFF -DWITH_HASKELL=OFF" - DISTRO=centos - - - TEST_NAME="Python 2.6 (CentOS 6)" - BUILD_LIBS="PYTHON TESTING TUTORIALS" - BUILD_ARG="-DWITH_PYTHON=ON -DWITH_CPP=OFF -DWITH_JAVA=OFF -DWITH_HASKELL=OFF" - BUILD_ENV="-e CC=gcc -e CXX=g++" - DISTRO=centos6 - - # Distribution - - TEST_NAME="make dist" - SCRIPT="make-dist.sh" - BUILD_ENV="-e CC=gcc -e CXX=g++" - - - TEST_NAME="Debian Packages" - SCRIPT="dpkg.sh" - BUILD_ENV="-e CC=gcc -e CXX=g++" - - - TEST_NAME="make dist (Debian)" - SCRIPT="make-dist.sh" - BUILD_ENV="-e CC=gcc -e CXX=g++" - DISTRO=debian - - - TEST_NAME="Debian Packages (Debian)" - SCRIPT="dpkg.sh" - BUILD_ENV="-e CC=gcc -e CXX=g++" - DISTRO=debian - -matrix: +jobs: include: + # ========================= stage: docker ========================= + - stage: docker + script: true + env: + - JOB="Docker Build ubuntu-xenial 16.04 LTS" + - DISTRO=ubuntu-xenial + - TRAVIS_BUILD_STAGE=docker + - script: true + env: + - JOB="Docker Build ubuntu-bionic 18.04 LTS" + - DISTRO=ubuntu-bionic + - TRAVIS_BUILD_STAGE=docker + + # ========================= stage: thrift ======================= + # ------------------------- phase: cross ------------------------ + # apache/thrift official PR builds can exceed 50 minutes per job so combine all cross tests + - stage: thrift + script: build/docker/run.sh + if: repo = apache/thrift + env: + - JOB="Cross Language Tests" + - SCRIPT="cross-test.sh" + + # fork based PR builds cannot exceed 50 minutes per job + - stage: thrift + script: build/docker/run.sh + if: repo != apache/thrift + env: + - JOB="Cross Language Tests (Binary Protocol)" + - SCRIPT="cross-test.sh" + - BUILD_ARG="-'(binary)'" + + - stage: thrift + script: build/docker/run.sh + if: repo != apache/thrift + env: + - JOB="Cross Language Tests (Header, JSON Protocols)" + - SCRIPT="cross-test.sh" + - BUILD_ARG="-'(header|json)'" + + - stage: thrift + script: build/docker/run.sh + if: repo != apache/thrift + env: + - JOB="Cross Language Tests (Compact and Multiplexed Protocols)" + - SCRIPT="cross-test.sh" + - BUILD_ARG="-'(compact|multiplexed)'" + + # ------------------------- phase: sca -------------------------- # QA jobs for code analytics and metrics - # - # C/C++ static code analysis with cppcheck - # add --error-exitcode=1 to --enable=all as soon as everything is fixed - # - # Python code style check with flake8 - # - # search for TODO etc within source tree - # some statistics about the code base - # some info about the build machine - - env: TEST_NAME="cppcheck, flake8, TODO FIXME HACK, LoC and system info" - install: - - travis_retry sudo apt-get update - - travis_retry sudo apt-get install -ym cppcheck sloccount python-flake8 - script: - # Compiler cppcheck (All) - - cppcheck --force --quiet --inline-suppr --enable=all -j2 compiler/cpp/src - # C++ cppcheck (All) - - cppcheck --force --quiet --inline-suppr --enable=all -j2 lib/cpp/src lib/cpp/test test/cpp tutorial/cpp - # C Glib cppcheck (All) - - cppcheck --force --quiet --inline-suppr --enable=all -j2 lib/c_glib/src lib/c_glib/test test/c_glib/src tutorial/c_glib - # Silent error checks - - cppcheck --force --quiet --inline-suppr --error-exitcode=1 -j2 compiler/cpp/src - - cppcheck --force --quiet --inline-suppr --error-exitcode=1 -j2 lib/cpp/src lib/cpp/test test/cpp tutorial/cpp - - cppcheck --force --quiet --inline-suppr --error-exitcode=1 -j2 lib/c_glib/src lib/c_glib/test test/c_glib/src tutorial/c_glib - # Python code style - - flake8 --ignore=E501 lib/py - - flake8 tutorial/py - - flake8 --ignore=E501 test/py - - flake8 test/py.twisted - - flake8 test/py.tornado - - flake8 --ignore=E501 test/test.py - - flake8 --ignore=E501 test/crossrunner - - flake8 test/features - # TODO etc - - grep -r TODO * - - grep -r FIXME * - - grep -r HACK * - # LoC - - sloccount . - # System Info - - dpkg -l - - uname -a + - stage: thrift + script: build/docker/run.sh + env: + - JOB="Static Code Analysis" + - SCRIPT="sca.sh" + + # C and C++ undefined behavior. + # A binary crashes if undefined behavior occurs and produces a stack trace. + # python is disabled, see: THRIFT-4360 + - script: build/docker/run.sh + env: + - JOB="UBSan" + - SCRIPT="ubsan.sh" + - BUILD_ARG="--without-python --without-py3" + + # ------------------------- phase: autotools -------------------- + # TODO: Remove them once migrated to CMake + - script: build/docker/run.sh + env: + - JOB="Autotools (Ubuntu Bionic)" + - SCRIPT="autotools.sh" + + - script: build/docker/run.sh + env: + - JOB="Autotools (Ubuntu Xenial)" + - DISTRO=ubuntu-xenial + - SCRIPT="autotools.sh" + + # ------------------------- phase: cmake ------------------------ + - script: build/docker/run.sh + env: + - JOB="CMake" + + # C++ specific options: compiler plug-in, threading model + - script: build/docker/run.sh + env: + - JOB="C++98 (Boost Thread)" + - SCRIPT="cmake.sh" + - BUILD_LIBS="CPP TESTING TUTORIALS" + - BUILD_ARG="-DCMAKE_CXX_STANDARD=98 -DCMAKE_CXX_STANDARD_REQUIRED=ON -DCMAKE_CXX_EXTENSIONS=OFF --DWITH_BOOSTTHREADS=ON -DWITH_PYTHON=OFF -DWITH_C_GLIB=OFF -DWITH_JAVA=OFF -DWITH_HASKELL=OFF" + - BUILD_ENV="-e CC=clang -e CXX=clang++" + + - script: build/docker/run.sh + env: + - JOB="C++ (Std Thread) and Plugin" + - SCRIPT="cmake.sh" + - BUILD_LIBS="CPP TESTING TUTORIALS" + - BUILD_ARG="-DWITH_PLUGIN=ON -DWITH_STDTHREADS=ON -DWITH_PYTHON=OFF -DWITH_C_GLIB=OFF -DWITH_JAVA=OFF -DWITH_HASKELL=OFF" + - BUILD_ENV="-e CC=clang -e CXX=clang++" + + # ------------------------- phase: dist ------------------------- + - script: build/docker/run.sh + env: + - JOB="make dist" + - SCRIPT="make-dist.sh" + + - script: build/docker/run.sh + env: + - JOB="Debian Packages" + - SCRIPT="dpkg.sh" + + # ------------------------- phase: coverity --------------------- + # We build the coverity scan build once monthly using a travis cron job + - if: (env(COVERITY_SCAN_NOTIFICATION_EMAIL) IS present) AND (branch IN (master)) AND (type IN (cron)) + script: build/docker/run.sh + env: + - JOB="Coverity Scan" + - SCRIPT="covscan.sh" + + + ### ------------------------- phase: osx -------------------------- + # disabled due to the time delays it imposes on build jobs + # - os: osx + # osx_image: xcode9 + # script: build/docker/scripts/autotools.sh + diff --git a/vendor/git.apache.org/thrift.git/CHANGES b/vendor/git.apache.org/thrift.git/CHANGES index 7b674d6..e3e50b6 100644 --- a/vendor/git.apache.org/thrift.git/CHANGES +++ b/vendor/git.apache.org/thrift.git/CHANGES @@ -1,5 +1,552 @@ Apache Thrift Changelog +================================================================================ +Thrift 0.12.0 +-------------------------------------------------------------------------------- +## New Languages + * Common LISP (cl) + * Swift + * Typescript (nodets) + +## Deprecated Languages + * Cocoa + +## Breaking Changes (since 0.11.0) + * [THRIFT-4529] - Rust enum variants are now camel-cased instead of uppercased to conform to Rust naming conventions + * [THRIFT-4448] - Support for golang 1.6 and earlier has been dropped. + * [THRIFT-4474] - PHP now uses the PSR-4 loader by default instead of class maps. + * [THRIFT-4532] - method signatures changed in the compiler's t_oop_generator. + * [THRIFT-4648] - The C (GLib) compiler's handling of namespaces has been improved. + +## Known Issues (Blocker or Critical) + * [THRIFT-4037] - build: use a single build system for thrift + * [THRIFT-4119] - build: bootstrap.sh is missing from source tarball + * [THRIFT-3289] - csharp: socket exhaustion in csharp implementation + * [THRIFT-3029] - cocoa: Getters for fields defined with uppercase names do not work + * [THRIFT-3325] - cocoa: Extended services aren't subclasses in generated Cocoa + * [THRIFT-4116] - cocoa: Thrift de-capitalizes the name of IsSet property in Cocoa + * [THRIFT-3877] - cpp: the http implementation is not standard; interop with other languages is spotty at best + * [THRIFT-4180] - cpp: Impossible to build Thrift C++ library for Android (NDK) + * [THRIFT-4384] - cpp: Using multiple async services simultaneously is not thread-safe + * [THRIFT-3108] - haskell: Defaulted struct parameters on a service generates invalid Haskell + * [THRIFT-3990] - nodejs: Exception swallowed by deserialization function + * [THRIFT-4214] - nodejs: map key treated as hex value in JavaScript + * [THRIFT-4602] - nodejs: ERROR in ./node_modules/thrift/lib/nodejs/lib/thrift/connection.js Module not found: Error: Can't resolve 'child_process' + * [THRIFT-4639] - nodejs: Sequence numbering for multiplexed protocol broken + * [THRIFT-1310] - php: sequence and reconnection management issues + * [THRIFT-1538] - php: Error during deserialization int64 on 32-bit architecture + * [THRIFT-1580] - php: thrift type i64 java to php serialize/deserealize not working + * [THRIFT-1950] - php: PHP gets stuck in infinite loop + * [THRIFT-2954] - python: sending int or float in a double field breaks the connection + * [THRIFT-4080] - python: unix sockets can get stuck forever + * [THRIFT-4281] - python: generated code is out of order and causes load issues + * [THRIFT-4677] - py3: UnicodeDecideError in Python3 + +## Build Process + * [THRIFT-4308] - D language docker images need demios for libevent and openssl fixed to re-enable make cross on dlang + * [THRIFT-4579] - Use Ubuntu Bionic (18.04 LTS) for CI builds instead of Artful (17.10) + * [THRIFT-4508] - Define CI operating system coverage rules for the project and (hopefully) simplify CI a little more + * [THRIFT-4397] - ubuntu install instructions broken on 16.04 + * [THRIFT-4545] - Appveyor builds are failing due to a haskell / cabal update in chocolatey + * [THRIFT-4452] - optimize Dockerfile (only onetime apt-get update) + * [THRIFT-4440] - rm `build/docker/ubuntu-trusty/Dockerfile.orig` + * [THRIFT-4352] - Ubuntu Artful doesn't appear to be compatible with Thrift and Haxe 3.4.2 + * [THRIFT-4666] - DLang Client Pool Test fails sporadically + * [THRIFT-4676] - CL tutorial build fails sporadically + * [THRIFT-4456] - Make haxelib download quiet so it doesn't blow up the build log + * [THRIFT-4605] - bootstrap.sh fails if automake=1.16.1 + +## c_glib + * [THRIFT-4648] - The C (GLib) compiler's handling of namespaces has been improved. + * [THRIFT-4622] - glibC compilation issue + * [THRIFT-4671] - c glib is unable to handle client close unexpectedly + +## cl (new language support in 0.12.0) + * [THRIFT-82] - Common Lisp support + +## csharp + * [THRIFT-4558] - reserved Csharp keywords are not escaped in some cases + * [THRIFT-4637] - C# async mode generates incorrect code with inherited services + * [THRIFT-4672] - IAsyncResult style methods not being supported by certain transports leads to issues in mixed ISync/IAsync use cases + * [THRIFT-4539] - Allow TBufferedTransport to be used as base class + * [THRIFT-4535] - XML docs; code cleanup (tabs->spaces; String->string) + * [THRIFT-4492] - protected ExceptionType type member of TApplicationException cannot be accessed + * [THRIFT-4446] - JSONProtocol Base64 Encoding Trims Padding + * [THRIFT-4455] - Missing dispose calls in ThreadedServer & ThreadpoolServer + * [THRIFT-4609] - keep InnerException wherever appropriate + * [THRIFT-4673] - IAsyncResult not supported by layered transports (buffered/framed) + +## cpp + * [THRIFT-4476] - Typecasting problem on list items + * [THRIFT-4465] - TNonblockingServer throwing THRIFT LOGGER: TConnection::workSocket(): THRIFT_EAGAIN (unavailable resources) + * [THRIFT-4680] - TBufferTransports.h does not compile under Visual Studio 2017 + * [THRIFT-4618] - TNonblockingServer crash because of limitation of select() + * [THRIFT-4620] - TZlibTransport.cpp doesn't ensure that there is enough space for the zlib flush marker in the buffer. + * [THRIFT-4571] - ZeroMQ contrib library needs a refresh + * [THRIFT-4559] - TSSLServerSocket incorrectly prints errors + * [THRIFT-4578] - Move `TAsyncProtocolProcessor` into main thrift library + * [THRIFT-4418] - evhttp_connection_new is deprecated; use evhttp_connection_base_new + +## compiler + * [THRIFT-4644] - Compiler cannot be compiled on macOS(maybe also on other platforms with clang) + * [THRIFT-4531] - Thrift generates wrong Python code for immutable structures with optional members + * [THRIFT-4513] - thrift generated code is not stable for constants + * [THRIFT-4532] - Avoid updating Thrift compiler generated code if the output has not changed + * [THRIFT-4400] - Visual Studio Compiler project should link runtime statically in release builds + * [THRIFT-4399] - plugin.thrift t_const_value is not used as a union in C++ code -- fix this + * [THRIFT-4496] - Dealing with language keywords in Thrift (e.g. service method names) + * [THRIFT-4393] - repeated runs of compiler produce different binary output at plugin interface + +## dlang + * [THRIFT-4478] - Thrift will not build with dlang 2.078 or later + * [THRIFT-4503] - dlang servers logError on normal client disconnection + * [THRIFT-4308] - D language docker images need demios for libevent and openssl fixed to re-enable make cross on dlang + +## dart + * [THRIFT-4646] - Effective Dart and Exceptions + * [THRIFT-4439] - Shouldn't download dart.deb directly. + +## delphi + * [THRIFT-4562] - Calling wrong exception CTOR leads to "call failed: unknown result" instead of the real exception being thrown + * [THRIFT-4554] - uncompileable code with member names that are also types under specific conditions + * [THRIFT-4422] - Add Async implementation via IFuture + * [THRIFT-4485] - Possible invalid ptr AV with overlapped read/write on pipes + * [THRIFT-4549] - Thrift exceptions should derive from TException + * [THRIFT-4540] - buffered transport broken when trying to re-open a formerly closed transport + * [THRIFT-4473] - Move Thrift.Console.pas out of the Library + * [THRIFT-4490] - Allow a default service as fallback for multiplex processors connected by old clients + * [THRIFT-4454] - Large writes/reads may cause range check errors in debug mode + * [THRIFT-4461] - Compiler directive should match Delphi XE4 + * [THRIFT-4462] - First line in Console duplicated + * [THRIFT-4642] - FPU ctrl word settings may cause an unexpected "denormalized" error + +## erlang + * [THRIFT-4497] - Erlang records should use map() for map type + * [THRIFT-4495] - Erlang records should allow 'undefined' for non-required fields + * [THRIFT-4580] - Fix erlang tutorial unpack on Windows + * [THRIFT-4582] - Ubuntu Xenial erlang 18.3 "make check" fails + +## golang + * [THRIFT-4448] - Support for golang 1.6 and earlier has been dropped. + * [THRIFT-4253] - Go generator assigns strings to field in const instead of pointers. + * [THRIFT-4573] - Unions Field Count Does Not Consider Binary + * [THRIFT-4447] - Golang: Panic on p.c.Call when using deprecated initializers + * [THRIFT-4650] - Required field incorrectly marked as set when fieldType does not match + * [THRIFT-4486] - Golang: -remote.go client cleanup + * [THRIFT-4537] - TSimpleServer can exit Accept loop with lock still acquired + * [THRIFT-4516] - Add support for go 1.10 + * [THRIFT-4421] - golang tests rely on gomock, which has change behaviour, causing tests to fail + * [THRIFT-4626] - Communication crash when using binary/compact protocol and zlib transport + * [THRIFT-4659] - golang race detected when closing listener socket + +## haskell + * [THRIFT-4634] - Haskell builds with older cabal cannot reconcile complex version requirements + +## java + * [THRIFT-4259] - Thrift does not compile due to Ant Maven task errors + * [THRIFT-1418] - Compiling Thrift from source: Class org.apache.tools.ant.taskdefs.ConditionTask doesn't support the nested "typefound" element + * [THRIFT-4530] - proposal: add nullability annotations to generated Java code + * [THRIFT-4614] - Generate missing @Nullable annotations for Java iterator getters + * [THRIFT-4555] - Getter of binary field in Java creates unnecessary copy + * [THRIFT-3983] - libthrift is deployed on central with pom packaging instead of jar + * [THRIFT-4294] - Java Configure Fails for Ant >= 1.10 + * [THRIFT-4178] - Java libraries missing from package when using cmake + * [THRIFT-4120] - pom files are not generated or provided in the build + * [THRIFT-1507] - Maven can't download resource from central when behind a proxy and won't use local repository + * [THRIFT-4556] - Optional rethrow of unhandled exceptions in java processor + * [THRIFT-4337] - Able to set keyStore and trustStore as InputStream in the TSSLTransportFactory.TSSLTransportParameters + * [THRIFT-4566] - Pass message of unhandled exception to optional rethrow. + * [THRIFT-4506] - Remove assertion in Java SASL code that would be ignored in release builds + * [THRIFT-4470] - Include popular IDE file templates to gitignore + * [THRIFT-4429] - Make TThreadPoolServer.executorService_ available in inherited classes and refactor methods to be able customization + * [THRIFT-3769] - Fix logic of THRIFT-2268 + * [THRIFT-4494] - Increase Java Socket Buffer Size + * [THRIFT-4499] - Remove Magic Number In TFIleTransport + +## js + * [THRIFT-4406] - JavaScript: Use modern Promise implementations + * [THRIFT-4625] - let / const variable decorators for es6 compiler + * [THRIFT-4653] - ES6 Classes + * [THRIFT-4592] - JS: readI32 performance on large arrays is very poor in Chrome + * [THRIFT-4509] - js and nodejs libraries need to be refreshed with current libraries + * [THRIFT-4403] - thrift.js: Incorrect usage of 'this' in TWebSocketTransport.__onOpen + * [THRIFT-4436] - Deserialization of nested list discards content + * [THRIFT-4437] - JS WebSocket client callbacks invoked twice on parallel requests + * [THRIFT-4679] - Duplicate declaration of InputBufferUnderrunError in lib/nodejs/lib/thrift/json_protocol.js + * [THRIFT-4551] - Add prettier for consistent JS code formatting + +## lua + * [THRIFT-4591] - lua client uses two write() calls per framed message send + * [THRIFT-3863] - Can't "make install" Lua Library + +## netcore + * [THRIFT-4524] - .NET Core Server doesn't close properly when cancelled + * [THRIFT-4434] - Update .NET Core components, add tests for .Net Core library and .Net Core compiler, fix bugs and build process + * [THRIFT-4446] - JSONProtocol Base64 Encoding Trims Padding + +## node.js + * [THRIFT-4225] - Error handling malformed arguments leaks memory, corrupts transport buffers causing next RPC to fail + * [THRIFT-3950] - Memory leak while calling oneway method + * [THRIFT-3143] - add typescript directory support + * [THRIFT-4564] - TBufferedTransport can leave corrupt data in the buffer + * [THRIFT-4647] - Node.js Fileserver webroot path + * [THRIFT-4489] - Unix domain socket support for NodeJS client + * [THRIFT-4443] - node.js json_protocol throws error in skip function + * [THRIFT-4604] - NodeJS: Expose Int64 from browser.js for consumption by browser + * [THRIFT-4480] - NodeJS warning on binary_protocol writeMessageEnd when seqid = 0 + +## perl + * [THRIFT-4382] - Replace the use of Perl Indirect Object Syntax calls to new() + * [THRIFT-4471] - Thrift CPAN release is missing Makefile.PL and the clients are unable to build the module + * [THRIFT-4416] - Perl CPAN Packaging Improvements + +## php + * [THRIFT-4474] - PHP generator use PSR-4 default + * [THRIFT-4463] - PHP generated code match PSR-2 + * [THRIFT-4373] - Extending Thrift class results in "Attempt serialize from non-Thrift object" + * [THRIFT-4354] - TSocket block on read + * [THRIFT-4423] - migrate php library to psr-4 + * [THRIFT-4656] - infinite loop in latest PHP library + * [THRIFT-4477] - TBufferedTransport must have underlying transport + * [THRIFT-4475] - lib/php/test should be checked for PSR-2 + * [THRIFT-4498] - add phpcs back + * [THRIFT-4460] - php library use PSR-2 + * [THRIFT-4641] - TCurlClient doesn't check for HTTP status code + * [THRIFT-4645] - TCurlClient: show actual error message when throwing TTransportException + * [THRIFT-4674] - Add stream context support into PHP/THttpClient + * [THRIFT-4459] - reduce php library directory depth + +## python + * [THRIFT-4670] - Twisted, slots, and void method fails with "object has no attribute 'success'" + * [THRIFT-4464] - Potentially server-crashing typo in Python TNonblockingServer + * [THRIFT-4548] - Supporting TBinaryProtocolAccelerated protocol when using TMultiplexedProcessor in Python + * [THRIFT-4577] - Outdated cipher string in python unit test + * [THRIFT-4505] - python build on Vagrant Windows boxes fails + * [THRIFT-4621] - THeader for Python + * [THRIFT-4668] - make socket backlog configurable for python + * [THRIFT-4561] - Python: cleanup socket timeout settings + +## ruby + * [THRIFT-4289] - Thrift RSpec test suite fails with Ruby 2.4.x due to Fixnum deprecation + * [THRIFT-4342] - Support ruby rspec 3 + * [THRIFT-4525] - Add ssl socket option to ruby cross tests + * [THRIFT-4450] - Add seek support to TCompactInputProtocol in Rust + * [THRIFT-4631] - Codegen Creates Invalid Ruby for Recursive Structs + * [THRIFT-4472] - Fix the genspec for ruby so it does not complain about an invalid license + +## rust + * [THRIFT-4662] - Rust const string calls function at compile time + * [THRIFT-4661] - Rust enum name wrong case in generated structs + * [THRIFT-4617] - Avoid generating conflicting struct names in Rust code + * [THRIFT-4529] - Rust generation should include #![allow(non_snake_case)] or force conform to Rust style guidelines + * [THRIFT-4390] - Rust binary protocol and buffered transport cannot handle writes above 4096 bytes + * [THRIFT-4419] - Rust framed transport cannot handle writes above 4096 bytes + * [THRIFT-4658] - Rust's TBinaryInputProtocol fails when strict is false + * [THRIFT-4187] - Dart -> Rust Framed cross tests fail + * [THRIFT-4664] - Rust cannot create ReadHalf/WriteHalf to implement custom tranports + +## swift (new language support in 0.12.0) + * [THRIFT-3773] - Swift Library + +## test suite + * [THRIFT-4515] - Gracefully shutdown cross-test servers to fully test teardown + * [THRIFT-4085] - Add .NET Core to the make cross standard test suite + * [THRIFT-4358] - Add unix domain sockets in ruby to cross test - code exists + +## typescript (new language support in 0.12.0) + * [THRIFT-3143] - add typescript directory support + +================================================================================ +Thrift 0.11.0 +-------------------------------------------------------------------------------- +## Sub-task + * [THRIFT-2733] - Erlang coding standards + * [THRIFT-2740] - Perl coding standards + * [THRIFT-3610] - Streamline exception handling in Python server handler + * [THRIFT-3686] - Java processor should report internal error on uncaught exception + * [THRIFT-4049] - Skip() should throw TProtocolException.INVALID_DATA on unknown data types + * [THRIFT-4053] - Skip() should throw TProtocolException.INVALID_DATA on unknown data types + * [THRIFT-4136] - Align is_binary() method with is_string() to simplify those checks + * [THRIFT-4137] - Fix remaining undefined behavior invalid vptr casts in Thrift Compiler + * [THRIFT-4138] - Fix remaining undefined behavior invalid vptr casts in C++ library + * [THRIFT-4296] - Fix Ubuntu Xenial build environment for the python language + * [THRIFT-4298] - Fix Ubuntu Xenial build environment for the go 1.6 language + * [THRIFT-4299] - Fix Ubuntu Xenial build environment for the D language + * [THRIFT-4300] - Fix make cross in Ubuntu Xenial docker environment, once all language support issues are fixed + * [THRIFT-4302] - Fix Ubuntu Xenial make cross testing for lua and php7 + * [THRIFT-4398] - Update EXTRA_DIST for "make dist" + +## Bug + * [THRIFT-381] - Fail fast if configure detects C++ problems + * [THRIFT-1677] - MinGW support broken + * [THRIFT-1805] - Thrift should not swallow ALL exceptions + * [THRIFT-2026] - Fix TCompactProtocol 64 bit builds + * [THRIFT-2642] - Recursive structs don't work in python + * [THRIFT-2889] - stable release 0.9.2, erlang tutorial broken + * [THRIFT-2913] - Ruby Server Thrift::ThreadPoolServer should serve inside a thread + * [THRIFT-2998] - Node.js: Missing header from http request + * [THRIFT-3000] - .NET implementation has trouble with mixed IP modes + * [THRIFT-3281] - Travis CI build passed but the log says BUILD FAILED + * [THRIFT-3358] - Makefile:1362: *** missing separator. Stop. + * [THRIFT-3600] - Make TTwisted server send exception on unexpected handler error + * [THRIFT-3602] - Make Tornado server send exception on unexpected handler error + * [THRIFT-3657] - D TFileWriterTransport close should use non-priority send + * [THRIFT-3700] - Go Map has wrong default value when optional + * [THRIFT-3703] - Unions Field Count Does Not Consider Map/Set/List Fields + * [THRIFT-3730] - server log error twice + * [THRIFT-3778] - go client can not pass method parameter to server of other language if no field_id is given + * [THRIFT-3784] - thrift-maven-plugin generates invalid include directories for IDL in dependency JARs + * [THRIFT-3801] - Node Thrift client throws exception with multiplexer and responses that are bigger than a single buffer + * [THRIFT-3821] - TMemoryBuffer buffer may overflow when resizing + * [THRIFT-3832] - Thrift version 0.9.3 example on Windows, Visual Studio, linking errors during compiling + * [THRIFT-3847] - thrift/config.h includes a #define for VERSION which will likely conflict with existing user environment or code + * [THRIFT-3873] - Fix various build warnings when using Visual Studio + * [THRIFT-3891] - TNonblockingServer configured with more than one IO threads does not always return from serve() upon stop() + * [THRIFT-3892] - Thrift uses TLS SNI extension provided by OpenSSL library. Older version of OpenSSL(< 0.9.8f) may create problem because they do not support 'SSL_set_tlsext_host_name()'. + * [THRIFT-3895] - Build fails using Java 1.8 with Ant < 1.9 + * [THRIFT-3896] - map data with number string key cannot access that deserialized by php extension + * [THRIFT-3938] - Python TNonblockingServer does not work with SSL + * [THRIFT-3944] - TSSLSocket has dead code in checkHandshake + * [THRIFT-3946] - Java 1.5 compatibility broken for binary fields (java5 option) + * [THRIFT-3960] - Inherited services in Lua generator are not named correctly + * [THRIFT-3962] - Ant build.xml broken on Windows for Java library + * [THRIFT-3963] - Thrift.cabal filename does not match module name + * [THRIFT-3967] - gobject/gparam.h:166:33: warning: enumerator value for ‘G_PARAM_DEPRECATED’ is not an integer constant expression + * [THRIFT-3968] - Deserializing empty string/binary fields + * [THRIFT-3974] - Using clang-3.8 and ThreadSanitizer on the concurrency_test claims bad PThread behavior + * [THRIFT-3984] - PHP7 extension causes segfault + * [THRIFT-4008] - broken ci due to upstream dependency versioning break + * [THRIFT-4009] - Use @implementer instead of implements in TTwisted.py + * [THRIFT-4010] - Q.fcall messing up with *this* pointer inside called function + * [THRIFT-4011] - Sets of Thrift structs generate Go code that can't be serialized to JSON + * [THRIFT-4012] - Python Twisted implementation uses implements, not compatible with Py3 + * [THRIFT-4014] - align C# meta data in AssemblyInfo.cs + * [THRIFT-4015] - Fix wrongly spelled "Thirft"s + * [THRIFT-4016] - testInsanity() impl does not conform to test spec in ThriftTest.thrift + * [THRIFT-4023] - Skip unexpected field types on read/write + * [THRIFT-4024] - Skip() should throw on unknown data types + * [THRIFT-4026] - TSSLSocket doesn't work with Python < 2.7.9 + * [THRIFT-4029] - Accelerated protocols do not build from thrift-py 0.10.0 on PyPI + * [THRIFT-4031] - Go plugin generates invalid code for lists of typedef'ed built-in types + * [THRIFT-4033] - Default build WITH_PLUGIN=ON for all builds results in packaging errors + * [THRIFT-4034] - CMake doesn't work to build compiler on MacOS + * [THRIFT-4036] - Add .NET Core environment/build support to the docker image + * [THRIFT-4038] - socket check: checking an unsigned number against >= 0 never fails + * [THRIFT-4042] - ExtractionError when using accelerated thrift in a multiprocess test + * [THRIFT-4043] - thrift perl debian package is placing files in the wrong place + * [THRIFT-4044] - Build job 17 failing on every pull request; hspec core (haskell) 2.4 issue + * [THRIFT-4046] - MinGW with gcc 6.2 does not compile on Windows + * [THRIFT-4060] - Thrift printTo ostream overload mechanism breaks down when types are nested + * [THRIFT-4062] - Remove debug print from TServiceClient + * [THRIFT-4065] - Document Perl ForkingServer signal restriction imposed by THRIFT-3848 and remove unnecessary code + * [THRIFT-4068] - A code comment in Java ServerSocket is wrong around accept() + * [THRIFT-4073] - enum files are still being generated with unused imports + * [THRIFT-4076] - Appveyor builds failing because ant 1.9.8 was removed from apache servers + * [THRIFT-4077] - AI_ADDRCONFIG redefined after recent change to PlatformSocket header + * [THRIFT-4079] - Generated perl code that returns structures from included thrift files is missing a necessary use clause + * [THRIFT-4087] - Spurious exception destroying TThreadedServer because of incorrect join() call + * [THRIFT-4102] - TBufferedTransport performance issue since 0.10.0 + * [THRIFT-4106] - concurrency_test fails randomly + * [THRIFT-4108] - c_glib thrift ssl has multiple bugs and deprecated functions + * [THRIFT-4109] - Configure Script uses string comparison for versions + * [THRIFT-4129] - C++ TNonblockingServer fd leak when failing to dispatch new connections + * [THRIFT-4131] - Javascript with WebSocket handles oneway methods wrong + * [THRIFT-4134] - Fix remaining undefined behavior invalid vptr casts + * [THRIFT-4140] - Use of non-thread-safe function gmtime() + * [THRIFT-4141] - Installation of haxe in docker files refers to a redirect link and fails + * [THRIFT-4147] - Rust: protocol should accept transports with non-static lifetime + * [THRIFT-4148] - [maven-thrift-plugin] compile error while import a thrift in dependency jar file. + * [THRIFT-4149] - System.out pollutes log files + * [THRIFT-4154] - PHP close() of a TSocket needs to close any type of socket + * [THRIFT-4158] - minor issue in README-MSYS2.md + * [THRIFT-4159] - Building tests fails on MSYS2 (MinGW64) due to a (small?) linker error + * [THRIFT-4160] - TNonblocking server fix use of closed/freed connections + * [THRIFT-4161] - TNonBlocking server using uninitialized event in error paths + * [THRIFT-4162] - TNonBlocking handling of TSockets in error state is incorrect after fd is closed + * [THRIFT-4164] - Core in TSSLSocket cleanupOpenSSL when destroying a mutex used by openssl + * [THRIFT-4165] - C++ build has many warnings under c++03 due to recent changes, cmake needs better platform-independent language level control + * [THRIFT-4166] - Recent fix to remove boost::lexical_cast usage broke VS2010 + * [THRIFT-4167] - Missing compile flag + * [THRIFT-4170] - Support lua 5.1 or earlier properly for object length determination + * [THRIFT-4172] - node.js tutorial client does not import assert, connection issues are not handled properly + * [THRIFT-4177] - Java compiler produces deep copy constructor that could make shallow copy instead + * [THRIFT-4184] - Building on Appveyor: invalid escape sequence \L + * [THRIFT-4185] - fb303 counter encoding fix + * [THRIFT-4189] - Framed/buffered transport Dispose() does not dispose the nested transport + * [THRIFT-4193] - Lower the default maxReadBufferBytes for non-blocking servers + * [THRIFT-4195] - Compilation to GO produces broken code + * [THRIFT-4196] - Cannot generate recursive Rust types + * [THRIFT-4204] - typo in compact spec + * [THRIFT-4206] - Strings in container fields are not decoded properly with py:dynamic and py:utf8strings + * [THRIFT-4208] - C# NamedPipesServer not really working in some scenarios + * [THRIFT-4211] - Fix GError glib management under Thrift + * [THRIFT-4212] - c_glib flush tries to close SSL even if socket is invalid + * [THRIFT-4213] - Travis build fails at curl -sSL https://www.npmjs.com/install.sh | sh + * [THRIFT-4215] - Golang TTransportFactory Pattern Squelches Errors + * [THRIFT-4216] - Golang Http Clients Do Not Respect User Options + * [THRIFT-4218] - Set TCP_NODELAY for PHP client socket + * [THRIFT-4219] - Golang HTTP clients created with Nil buffer + * [THRIFT-4231] - TJSONProtocol throws unexpected non-Thrift-exception on null strings + * [THRIFT-4232] - ./configure does bad ant version check + * [THRIFT-4234] - Travis build fails cross language tests with "Unsupported security protocol type" + * [THRIFT-4237] - Go TServerSocket Race Conditions + * [THRIFT-4240] - Go TSimpleServer does not close properly + * [THRIFT-4243] - Go TSimpleServer race on wait in Stop() method + * [THRIFT-4245] - Golang TFramedTransport's writeBuffer increases if writes to transport failed + * [THRIFT-4246] - Sequence number mismatch on multiplexed clients + * [THRIFT-4247] - Compile fails with openssl 1.1 + * [THRIFT-4248] - Compile fails - strncpy, memcmp, memset not declared in src/thrift/transport/TSSLSocket.cpp + * [THRIFT-4251] - Java Epoll Selector Bug + * [THRIFT-4257] - Typescript async callbacks do not provide the correct types + * [THRIFT-4258] - Boost/std thread wrapping faultiness + * [THRIFT-4260] - Go context generation issue. Context is parameter in Interface not in implementation + * [THRIFT-4261] - Go context generation issue: breaking change in generated code regarding thrift.TProcessorFunction interface + * [THRIFT-4262] - Invalid binding to InterlockedCompareExchange64() with 64-bit targets + * [THRIFT-4263] - Fix use after free bug for thrown exceptions + * [THRIFT-4266] - Erlang library throws during skipping fields of composite type (maps, lists, structs, sets) + * [THRIFT-4268] - Erlang library emits debugging output in transport layer + * [THRIFT-4273] - erlang:now/0: Deprecated BIF. + * [THRIFT-4274] - Python feature tests for SSL/TLS failing + * [THRIFT-4279] - Wrong path in include directive in generated Thrift sources + * [THRIFT-4283] - TNamedPipeServer race condition in interrupt + * [THRIFT-4284] - File contains a NBSP: lib/nodejs/lib/thrift/web_server.js + * [THRIFT-4290] - C# nullable option generates invalid code for non-required enum field with default value + * [THRIFT-4292] - TimerManager::remove() is not implemented + * [THRIFT-4307] - Make ssl-open timeout effective in golang client + * [THRIFT-4312] - Erlang client cannot connect to Python server: exception error: econnrefused + * [THRIFT-4313] - Program code of the Erlang tutorial files contain syntax errors + * [THRIFT-4316] - TByteBuffer.java will read too much data if a previous read returns fewer bytes than requested + * [THRIFT-4319] - command line switch for "evhttp" incorrectly resolved to anon pipes + * [THRIFT-4323] - range check errors or NPE in edge cases + * [THRIFT-4324] - field names can conflict with local vars in generated code + * [THRIFT-4328] - Travis CI builds are timing out (job 1) and haxe builds are failing since 9/11 + * [THRIFT-4329] - c_glib Doesn't have a multiplexed processor + * [THRIFT-4331] - C++: TSSLSockets bug in handling huge messages, bug in handling polling + * [THRIFT-4332] - Binary protocol has memory leaks + * [THRIFT-4334] - Perl indentation incorrect when defaulting field attribute to a struct + * [THRIFT-4339] - Thrift Framed Transport in Erlang crashes server when client disconnects + * [THRIFT-4340] - Erlang fix a crash on client close + * [THRIFT-4355] - Javascript indentation incorrect when defaulting field attribute to a struct + * [THRIFT-4356] - thrift_protocol call Transport cause Segmentation fault + * [THRIFT-4359] - Haxe compiler looks like it is producing incorrect code for map or set key that is binary type + * [THRIFT-4362] - Missing size-check can lead to huge memory allocation + * [THRIFT-4364] - Website contributing guide erroneously recommends submitting patches in JIRA + * [THRIFT-4365] - Perl generated code uses indirect object syntax, which occasionally causes compilation errors. + * [THRIFT-4367] - python TProcessor.process is missing "self" + * [THRIFT-4370] - Ubuntu Artful cppcheck and flake8 are more stringent and causing SCA build job failures + * [THRIFT-4372] - Pipe write operations across a network are limited to 65,535 bytes per write. + * [THRIFT-4374] - cannot load thrift_protocol due to undefined symbol: _ZTVN10__cxxabiv120__si_class_type_infoE + * [THRIFT-4376] - Coverity high impact issue resolution + * [THRIFT-4377] - haxe. socket handles leak in TSimpleServer + * [THRIFT-4381] - Wrong isset bitfield value after transmission + * [THRIFT-4385] - Go remote client -u flag is broken + * [THRIFT-4392] - compiler/..../plugin.thrift structs mis-ordered blows up ocaml generator + * [THRIFT-4395] - Unable to build in the ubuntu-xenial docker image: clap 2.28 requires Rust 1.20 + * [THRIFT-4396] - inconsistent (or plain wrong) version numbers in master/trunk + +## Documentation + * [THRIFT-4157] - outdated readme about Haxe installation on Linux + +## Improvement + * [THRIFT-105] - make a thrift_spec for a structures with negative tags + * [THRIFT-281] - Cocoa library code needs comments, badly + * [THRIFT-775] - performance improvements for Perl + * [THRIFT-2221] - Generate c++ code with std::shared_ptr instead of boost::shared_ptr. + * [THRIFT-2364] - OCaml: Use Oasis exclusively for build process + * [THRIFT-2504] - TMultiplexedProcessor should allow registering default processor called if no service name is present + * [THRIFT-3207] - Enable build with OpenSSL 1.1.0 series + * [THRIFT-3272] - Perl SSL Authentication Support + * [THRIFT-3357] - Generate EnumSet/EnumMap where elements/keys are enums + * [THRIFT-3369] - Implement SSL/TLS support on C with c_glib + * [THRIFT-3467] - Go Maps for Thrift Sets Should Have Values of Type struct{} + * [THRIFT-3580] - THeader for Haskell + * [THRIFT-3627] - Missing basic code style consistency of JavaScript. + * [THRIFT-3706] - There's no support for Multiplexed protocol on c_glib library + * [THRIFT-3766] - Add getUnderlyingTransport() to TZlibTransport + * [THRIFT-3776] - Go code from multiple thrift files with the same namespace + * [THRIFT-3823] - Escape documentation while generating non escaped documetation + * [THRIFT-3854] - allow users to clear read buffers + * [THRIFT-3859] - Unix Domain Socket Support in Objective-C + * [THRIFT-3921] - C++ code should print enums as strings + * [THRIFT-3926] - There should be an error emitted when http status code is not 200 + * [THRIFT-4007] - Micro-optimization of TTransport.py + * [THRIFT-4040] - Add real cause of TNonblockingServerSocket error to exception + * [THRIFT-4064] - Update node library dependencies + * [THRIFT-4069] - All perl packages should have proper namespace, version syntax, and use proper thrift exceptions + * [THRIFT-4071] - Consolidate the Travis CI jobs where possible to put less stress on the Apache Foundation's allocation of CI build slaves + * [THRIFT-4072] - Add the possibility to send custom headers in TCurlClient + * [THRIFT-4075] - Better MinGW support for headers-only boost (without thread library) + * [THRIFT-4081] - Provide a MinGW 64-bit Appveyor CI build for better pull request validation + * [THRIFT-4084] - Improve SSL security in thrift by adding a make cross client that checks to make sure SSLv3 protocol cannot be negotiated + * [THRIFT-4095] - Add multiplexed protocol to Travis CI for make cross + * [THRIFT-4099] - Auto-derive Hash for generated Rust structs + * [THRIFT-4110] - The debian build files do not produce a "-dbg" package for debug symbols of libthrift0 + * [THRIFT-4114] - Space after '///' in doc comments + * [THRIFT-4126] - Validate objects in php extension + * [THRIFT-4130] - Ensure Apache Http connection is released back to pool after use + * [THRIFT-4151] - Thrift Mutex Contention Profiling (pthreads) should be disabled by default + * [THRIFT-4176] - Implement a threaded and threadpool server type for Rust + * [THRIFT-4183] - Named pipe client blocks forever on Open() when there is no server at the other end + * [THRIFT-4190] - improve C# TThreadPoolServer defaults + * [THRIFT-4197] - Implement transparent gzip compression for HTTP transport + * [THRIFT-4198] - Ruby should log Thrift internal errors to global logger + * [THRIFT-4203] - thrift server stop gracefully + * [THRIFT-4205] - c_glib is not linking against glib + gobject + * [THRIFT-4209] - warning CS0414 in T[TLS]ServerSocket.cs + * [THRIFT-4210] - include Thrift.45.csproj into CI runs + * [THRIFT-4217] - HttpClient should support gzip and deflate + * [THRIFT-4222] - Support Unix Domain Sockets in Golang TServerSocket + * [THRIFT-4233] - Make THsHaServer.invoker available (get method only) in inherited classes + * [THRIFT-4236] - Support context in go generated code. + * [THRIFT-4238] - JSON generator: make annotation-aware + * [THRIFT-4269] - Don't append '.' to Erlang namespace if it ends in '_'. + * [THRIFT-4270] - Generate Erlang mapping functions for const maps and lists + * [THRIFT-4275] - Add support for zope.interface only, apart from twisted support. + * [THRIFT-4285] - Pull generated send/recv into library to allow behaviour to be customised + * [THRIFT-4287] - Add c++ compiler "no_skeleton" flag option + * [THRIFT-4288] - Implement logging levels properly for node.js + * [THRIFT-4295] - Refresh the Docker image file suite for Ubuntu, Debian, and CentOS + * [THRIFT-4305] - Emit ddoc for generated items + * [THRIFT-4306] - Thrift imports not replicated to D service output + * [THRIFT-4315] - Add default message for TApplicationException + * [THRIFT-4318] - Delphi performance improvements + * [THRIFT-4325] - Simplify automake cross compilation by relying on one global THRIFT compiler path + * [THRIFT-4327] - Improve TimerManager API to allow removing specific task + * [THRIFT-4330] - Allow unused crates in Rust files + * [THRIFT-4333] - Erlang tutorial examples are using a different port (9999) + * [THRIFT-4343] - Change CI builds to use node.js 8.x LTS once available + * [THRIFT-4345] - Create a docker build environment that uses the minimum supported language levels + * [THRIFT-4346] - Allow Zlib transport factory to wrap other transports + * [THRIFT-4348] - Perl HTTP Client custom HTTP headers + * [THRIFT-4350] - Update netcore build for dotnet 2.0 sdk and make cross validation + * [THRIFT-4351] - Use Travis CI Build Stages to optimize the CI build + * [THRIFT-4353] - cannot read via thrift_protocol at server side + * [THRIFT-4378] - add set stopTimeoutUnit method to TThreadPoolServer + +## New Feature + * [THRIFT-750] - C++ Compiler Virtual Function Option + * [THRIFT-2945] - Implement support for Rust language + * [THRIFT-3857] - thrift js:node complier support an object as parameter not an instance of struct + * [THRIFT-3933] - Port official C# .NET library for Thrift to C# .NET Core libary + * [THRIFT-4039] - Update of Apache Thrift .Net Core lib + * [THRIFT-4113] - Provide a buffer transport for reading/writing in memory byte stream + +## Question + * [THRIFT-2956] - autoconf - possibly undefined macro - AC_PROG_BISON + * [THRIFT-4223] - Add support to the isServing() method for the C++ library + +## Task + * [THRIFT-3622] - Fix deprecated uses of std::auto_ptr + * [THRIFT-4028] - Please remove System.out.format from the source code + * [THRIFT-4186] - Build and test rust client in Travis + +## Test + * [THRIFT-4264] - PHP - Support both shared & static linking of sockets library + +## Wish + * [THRIFT-4344] - Define and maintain the minimum language level for all languages in one place + + Thrift 0.10.0 -------------------------------------------------------------------------------- ## Bug diff --git a/vendor/git.apache.org/thrift.git/CMakeLists.txt b/vendor/git.apache.org/thrift.git/CMakeLists.txt index 93ed8d2..9f57a66 100644 --- a/vendor/git.apache.org/thrift.git/CMakeLists.txt +++ b/vendor/git.apache.org/thrift.git/CMakeLists.txt @@ -17,7 +17,14 @@ # under the License. # -cmake_minimum_required(VERSION 2.8.12) +cmake_minimum_required(VERSION 3.1) + +# CMake 3.1 supports C++ standards selection with CMAKE_CXX_STANDARD +# If you need CMake 3.1+ for Ubuntu 14.04, try +# https://launchpad.net/~george-edison55/+archive/ubuntu/cmake-3.x +# If you need CMake 3.1+ for debian "jessie", get it from jessie-backports +# Otherwise +# http://cmake.org project("Apache Thrift") diff --git a/vendor/git.apache.org/thrift.git/CONTRIBUTING.md b/vendor/git.apache.org/thrift.git/CONTRIBUTING.md index 316da9a..7a1d710 100644 --- a/vendor/git.apache.org/thrift.git/CONTRIBUTING.md +++ b/vendor/git.apache.org/thrift.git/CONTRIBUTING.md @@ -1,49 +1,116 @@ -## How to contribute - 1. Help to review and verify existing patches - 1. Make sure your issue is not all ready in the [Jira issue tracker](http://issues.apache.org/jira/browse/THRIFT) - 1. If not, create a ticket describing the change you're proposing in the [Jira issue tracker](http://issues.apache.org/jira/browse/THRIFT) - 1. Contribute your patch using one of the two methods below +# How to Contribute # -### Contributing via a patch - -1. Check out the latest version of the source code - - * git clone https://git-wip-us.apache.org/repos/asf/thrift.git thrift - -1. Modify the source to include the improvement/bugfix - - * Remember to provide *tests* for all submited changes - * When bugfixing: add test that will isolate bug *before* applying change that fixes it - * Verify that you follow [Thrift Coding Standards](/docs/coding_standards) (you can run 'make style', which ensures proper format for some languages) - -1. Create a patch from project root directory (e.g. you@dev:~/thrift $ ): - - * git diff > ../thrift-XXX-my-new-feature.patch - -1. Attach the newly generated patch to the issue -1. Wait for other contributors or committers to review your new addition -1. Wait for a committer to commit your patch - -### Contributing via GitHub pull requests - -1. Create a fork for http://github.com/apache/thrift -1. Create a branch for your changes(best practice is issue as branch name, e.g. THRIFT-9999) -1. Modify the source to include the improvement/bugfix - - * Remember to provide *tests* for all submited changes - * When bugfixing: add test that will isolate bug *before* applying change that fixes it - * Verify that you follow [Thrift Coding Standards](/docs/coding_standards) (you can run 'make style', which ensures proper format for some languages) - * Verify that your change works on other platforms by adding a GitHub service hook to [Travis CI](http://docs.travis-ci.com/user/getting-started/#Step-one%3A-Sign-in) and [AppVeyor](http://www.appveyor.com/docs) - -1. Commit and push changes to your branch (please use issue name and description as commit title, e.g. THRIFT-9999 make it perfect) -1. Issue a pull request with the jira ticket number you are working on in it's name -1. Wait for other contributors or committers to review your new addition -1. Wait for a committer to commit your patch - -### More info - - Plenty of information on why and how to contribute is available on the Apache Software Foundation (ASF) web site. In particular, we recommend the following: +Thank you for your interest in contributing to the Apache Thrift project! Information on why and how to contribute is available on the Apache Software Foundation (ASF) web site. In particular, we recommend the following to become acquainted with Apache Contributions: * [Contributors Tech Guide](http://www.apache.org/dev/contributors) * [Get involved!](http://www.apache.org/foundation/getinvolved.html) * [Legal aspects on Submission of Contributions (Patches)](http://www.apache.org/licenses/LICENSE-2.0.html#contributions) + +## GitHub pull requests ## + +This is the preferred method of submitting changes. When you submit a pull request through github, +it activates the continuous integration (CI) build systems at Appveyor and Travis to build your changesxi +on a variety of Linux and Windows configurations and run all the test suites. Follow these requirements +for a successful pull request: + + 1. All code changes require an [Apache Jira THRIFT Issue](http://issues.apache.org/jira/browse/THRIFT) ticket. + + 1. All pull requests should contain a single commit per issue, or we will ask you to squash it. + 1. The pull request title must begin with the Jira THRIFT ticket identifier, for example: + + THRIFT-9999: an example pull request title + + 1. Commit messages must follow this pattern for code changes (deviations will not be merged): + + THRIFT-9999: [summary of fix, one line if possible] + Client: [language(s) affected, comma separated, use lib/ directory names please] + +Instructions: + + 1. Create a fork in your GitHub account of http://github.com/apache/thrift + 1. Clone the fork to your development system. + 1. Create a branch for your changes (best practice is issue as branch name, e.g. THRIFT-9999). + 1. Modify the source to include the improvement/bugfix, and: + + * Remember to provide *tests* for all submitted changes! + * Use test-driven development (TDD): add a test that will isolate the bug *before* applying the change that fixes it. + * Verify that you follow [Thrift Coding Standards](/docs/coding_standards) (you can run 'make style', which ensures proper format for some languages). + * [*optional*] Verify that your change works on other platforms by adding a GitHub service hook to [Travis CI](http://docs.travis-ci.com/user/getting-started/#Step-one%3A-Sign-in) and [AppVeyor](http://www.appveyor.com/docs). You can use this technique to run the Thrift CI jobs in your account to check your changes before they are made public. Every GitHub pull request into Thrift will run the full CI build and test suite on your changes. + + 1. Squash your changes to a single commit. This maintains clean change history. + 1. Commit and push changes to your branch (please use issue name and description as commit title, e.g. "THRIFT-9999: make it perfect"), with the affected languages on the next line of the description. + 1. Use GitHub to create a pull request going from your branch to apache:master. Ensure that the Jira ticket number is at the beginning of the title of your pull request, same as the commit title. + 1. Wait for other contributors or committers to review your new addition, and for a CI build to complete. + 1. Wait for a committer to commit your patch. You can nudge the committers if necessary by sending a message to the [Apache Thrift mailing list](https://thrift.apache.org/mailing). + +## If you want to build the project locally ## + +For Windows systems, see our detailed instructions on the [CMake README](/build/cmake/README.md). + +For Windows Native C++ builds, see our detailed instructions on the [WinCPP README](/build/wincpp/README.md). + +For unix systems, see our detailed instructions on the [Docker README](/build/docker/README.md). + +## If you want to review open issues... ## + + 1. Review the [GitHub Pull Request Backlog](https://github.com/apache/thrift/pulls). Code reviews are open to all. + 2. Review the [Jira issue tracker](http://issues.apache.org/jira/browse/THRIFT). You can search for tickets relating to languages you are interested in or currently using with thrift, for example a Jira search (Issues -> Search For Issues) query of ``project = THRIFT AND component in ("Erlang - Library") and status not in (resolved, closed)`` will locate all the open Erlang Library issues. + +## If you discovered a defect... ## + + 1. Check to see if the issue is already in the [Jira issue tracker](http://issues.apache.org/jira/browse/THRIFT). + 1. If not, create a ticket describing the change you're proposing in the Jira issue tracker. + 1. Contribute your code changes using the GitHub pull request method: + +## Contributing via Patch ## + +Some changes do not require a build, for example in documentation. For changes that are not code or build related, you can submit a patch on Jira for review. To create a patch from changes in your local directory: + + git diff > ../THRIFT-NNNN.patch + +then wait for contributors or committers to review your changes, and then for a committer to apply your patch. + +## GitHub recipes for Pull Requests ## + +Sometimes commmitters may ask you to take actions in your pull requests. Here are some recipes that will help you accomplish those requests. These examples assume you are working on Jira issue THRIFT-9999. You should also be familiar with the [upstream](https://help.github.com/articles/syncing-a-fork/) repository concept. + +### Squash your changes ### + +If you have not submitted a pull request yet, or if you have not yet rebased your existing pull request, you can squash all your commits down to a single commit. This makes life easier for the committers. If your pull request on GitHub has more than one commit, you should do this. + +1. Use the command ``git log`` to identify how many commits you made since you began. +2. Use the command ``git rebase -i HEAD~N`` where N is the number of commits. +3. Leave "pull" in the first line. +4. Change all other lines from "pull" to "fixup". +5. All your changes are now in a single commit. + +If you already have a pull request outstanding, you will need to do a "force push" to overwrite it since you changed your commit history: + + git push -u origin THRIFT-9999 --force + +A more detailed walkthrough of a squash can be found at [Git Ready](http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html). + +### Rebase your pull request ### + +If your pull request has a conflict with master, it needs to be rebased: + + git checkout THRIFT-9999 + git rebase upstream master + (resolve any conflicts, make sure it builds) + git push -u origin THRIFT-9999 --force + +### Fix a bad merge ### + +If your pull request contains commits that are not yours, then you should use the following technique to fix the bad merge in your branch: + + git checkout master + git pull upstream master + git checkout -b THRIFT-9999-take-2 + git cherry-pick ... + (pick only your commits from your original pull request in ascending chronological order) + squash your changes to a single commit if there is more than one (see above) + git push -u origin THRIFT-9999-take-2:THRIFT-9999 + +This procedure will apply only your commits in order to the current master, then you will squash them to a single commit, and then you force push your local THRIFT-9999-take-2 into remote THRIFT-9999 which represents your pull request, replacing all the commits with the new one. + + diff --git a/vendor/git.apache.org/thrift.git/Dockerfile b/vendor/git.apache.org/thrift.git/Dockerfile deleted file mode 100644 index 0d7ad21..0000000 --- a/vendor/git.apache.org/thrift.git/Dockerfile +++ /dev/null @@ -1,61 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you 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. -# - -# Goal: provide a thrift-compiler Docker image -# -# Usage: -# docker run -v "${PWD}:/data" thrift/thrift-compiler -gen cpp -o /data/ /data/test/ThriftTest.thrift -# -# further details on docker for thrift is here build/docker/ -# -# TODO: push to apache/thrift-compiler instead of thrift/thrift-compiler - -FROM debian:jessie -MAINTAINER Apache Thrift - -ENV DEBIAN_FRONTEND noninteractive - -ADD . /thrift - -RUN buildDeps=" \ - flex \ - bison \ - g++ \ - make \ - cmake \ - curl \ - "; \ - apt-get update && apt-get install -y --no-install-recommends $buildDeps \ - && mkdir /tmp/cmake-build && cd /tmp/cmake-build \ - && cmake \ - -DBUILD_COMPILER=ON \ - -DBUILD_LIBRARIES=OFF \ - -DBUILD_TESTING=OFF \ - -DBUILD_EXAMPLES=OFF \ - /thrift \ - && cmake --build . --config Release \ - && make install \ - && curl -k -sSL "https://storage.googleapis.com/golang/go1.5.2.linux-amd64.tar.gz" -o /tmp/go.tar.gz \ - && tar xzf /tmp/go.tar.gz -C /tmp \ - && cp /tmp/go/bin/gofmt /usr/bin/gofmt \ - && apt-get purge -y --auto-remove $buildDeps \ - && apt-get clean \ - && rm -rf /tmp/* \ - && rm -rf /var/lib/apt/lists/* - -ENTRYPOINT ["thrift"] diff --git a/vendor/git.apache.org/thrift.git/LANGUAGES.md b/vendor/git.apache.org/thrift.git/LANGUAGES.md new file mode 100644 index 0000000..acf9083 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/LANGUAGES.md @@ -0,0 +1,355 @@ +# Apache Thrift Language Support # + +Last Modified: 2018-12-17 + +Guidance For: 0.12.0 or later + +Thrift supports many programming languages and has an impressive test suite that exercises most of the languages, protocols, and transports that represents a matrix of thousands of possible combinations. Each language typically has a minimum required version as well as support libraries - some mandatory and some optional. All of this information is provided below to help you assess whether you can use Apache Thrift with your project. Obviously this is a complex matrix to maintain and may not be correct in all cases - if you spot an error please inform the developers using the mailing list. + +Apache Thrift has a choice of two build systems. The `autoconf` build system is the most complete build and is used to build all supported languages. The `cmake` build system has been designated by the project to replace `autoconf` however this transition will take quite some time to complete. + +The Language/Library Levels indicate the minimum and maximum versions that are used in the [continuous integration environments](build/docker/README.md) (Appveyor, Travis) for Apache Thrift. Other language levels may be supported for each language, however tested less thoroughly; check the README file inside each lib directory for additional details. Note that while a language may contain support for protocols, transports, and servers, the extent to which each is tested as part of the overall build process varies. The definitive integration test for the project is called the "cross" test which executes a test matrix with clients and servers communicating across languages. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
LanguageSinceBuild SystemsLang/Lib Levels (Tested)Low-Level TransportsTransport WrappersProtocolsServersOpen Issues
autoconfcmakeMinMaxDomain File Memory Pipe Socket TLS Framed http  zlib BinaryCompact JSON MultiplexForkingNonblockingSimpleThreadedThreadPool
ActionScript0.3.0ActionScript 3YesYesYesActionScript
C (glib)0.6.0YesYes2.48.22.54.0YesYesYesYesYesYesYesYesYesC (glib)
C++0.2.0YesYesC++98YesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesC++
C#0.2.0Yes.NET 3.5 / mono 3.2.8.0.NET 4.6.1 / mono 4.6.2.7YesYesYesYesYesYesYesYesYesYesYesYesYesC# (.NET)
Cocoa0.2.0unknownYesYesYesYesYesYesYesYesYesYesCocoa
Common Lisp0.12.0YesSBCL 1.4.5SBCL 1.4.9YesYesYesYesYesYesYesCommon Lisp
Dlang0.9.0Yes2.075.12.081.0YesYesYesYesYesYesYesYesYesYesYesYesYesYesYesD
Dart0.10.0Yes1.22.11.24.3YesYesYesYesYesYesYesDart
Delphi0.8.02010unknownYesYesYesYesYesYesYesYesDelphi
.NET Core0.11.0Yes2.1.4YesYesYesYesYesYesYesYesYesYesYes.NET Core
Erlang0.3.0Yes18.320.0.4YesYesYesYesYesYesYesYesYesYesYesErlang
Go0.7.0Yes1.7.61.10.3YesYesYesYesYesYesYesYesYesYesYesGo
Haskell0.5.0YesYes7.10.38.0.2YesYesYesYesYesYesYesYesYesYesYesHaskell
Haxe0.9.3Yes3.2.13.4.4YesYesYesYesYesYesYesYesYesHaxe
Java (SE)0.2.0YesYes1.8.0_151YesYesYesYesYesYesYesYesYesYesYesYesYesYesYesJava SE
Java (ME)0.5.0unknownYesYesYesYesYesYesJava ME
Javascript0.3.0YesunknownYesYesYesYesYesJavascript
Lua0.9.2Yes5.1.55.2.4YesYesYesYesYesYesYesYesLua
node.js0.6.0Yes6.x8.11.3YesYesYesYesYesYesYesYesYesYesnode.js
node.ts0.12.0Yes3.1.6YesYesYesYesnode.ts
OCaml0.2.04.04.0YesYesYesYesYesOCaml
Perl0.2.0Yes5.22.15.26.0YesYesYesYesYesYesYesYesYesYesYesPerl
PHP0.2.0Yes7.0.227.1.8YesYesYesYesYesYesYesYesYesYesYesPHP
Python0.2.0YesYes2.7.12, 3.5.22.7.14, 3.6.3YesYesYesYesYesYesYesYesYesYesYesPython
Ruby0.2.0Yes2.3.1p1122.3.3p222YesYesYesYesYesYesYesYesYesYesYesYesYesYesRuby
Rust0.11.0Yes1.17.01.21.0YesYesYesYesYesYesYesRust
Smalltalk0.2.0unknownYesYesSmalltalk
LanguageSinceautoconfcmakeMinMaxDomain File Memory Pipe Socket TLS Framed http  zlib BinaryCompact JSON MultiplexForkingNonblockingSimpleThreadedThreadPoolOpen Issues
Build SystemsLang/Lib Levels (Tested)Low-Level TransportsTransport WrappersProtocolsServers
diff --git a/vendor/git.apache.org/thrift.git/Makefile.am b/vendor/git.apache.org/thrift.git/Makefile.am index ed58265..511452d 100755 --- a/vendor/git.apache.org/thrift.git/Makefile.am +++ b/vendor/git.apache.org/thrift.git/Makefile.am @@ -43,7 +43,7 @@ dist-hook: find $(distdir) -type d \( -iname ".svn" -or -iname ".git" \) | xargs rm -rf print-version: - @echo $(VERSION) + @echo $(PACKAGE_VERSION) .PHONY: precross cross precross-%: all @@ -54,7 +54,7 @@ empty := space := $(empty) $(empty) comma := , -CROSS_LANGS = @MAYBE_CPP@ @MAYBE_C_GLIB@ @MAYBE_D@ @MAYBE_JAVA@ @MAYBE_CSHARP@ @MAYBE_PYTHON@ @MAYBE_PY3@ @MAYBE_RUBY@ @MAYBE_HASKELL@ @MAYBE_PERL@ @MAYBE_PHP@ @MAYBE_GO@ @MAYBE_NODEJS@ @MAYBE_DART@ @MAYBE_ERLANG@ @MAYBE_LUA@ +CROSS_LANGS = @MAYBE_CPP@ @MAYBE_C_GLIB@ @MAYBE_CL@ @MAYBE_D@ @MAYBE_JAVA@ @MAYBE_CSHARP@ @MAYBE_PYTHON@ @MAYBE_PY3@ @MAYBE_RUBY@ @MAYBE_HASKELL@ @MAYBE_PERL@ @MAYBE_PHP@ @MAYBE_GO@ @MAYBE_NODEJS@ @MAYBE_DART@ @MAYBE_ERLANG@ @MAYBE_LUA@ @MAYBE_RS@ @MAYBE_DOTNETCORE@ @MAYBE_NODETS@ CROSS_LANGS_COMMA_SEPARATED = $(subst $(space),$(comma),$(CROSS_LANGS)) if WITH_PY3 @@ -65,14 +65,14 @@ endif if WITH_PYTHON crossfeature: precross - $(CROSS_PY) test/test.py --retry-count 3 --features .* --skip-known-failures --server $(CROSS_LANGS_COMMA_SEPARATED) + $(CROSS_PY) test/test.py --retry-count 5 --features .* --skip-known-failures --server $(CROSS_LANGS_COMMA_SEPARATED) else # feature test needs python build crossfeature: endif cross-%: precross crossfeature - $(CROSS_PY) test/test.py --retry-count 3 --skip-known-failures --server $(CROSS_LANGS_COMMA_SEPARATED) --client $(CROSS_LANGS_COMMA_SEPARATED) --regex "$*" + $(CROSS_PY) test/test.py --retry-count 5 --skip-known-failures --server $(CROSS_LANGS_COMMA_SEPARATED) --client $(CROSS_LANGS_COMMA_SEPARATED) --regex "$*" cross: cross-.* @@ -111,9 +111,13 @@ EXTRA_DIST = \ .clang-format \ .editorconfig \ .travis.yml \ + .rustfmt.toml \ + .dockerignore \ appveyor.yml \ bower.json \ build \ + bootstrap.sh \ + cleanup.sh \ CMakeLists.txt \ composer.json \ contrib \ @@ -123,7 +127,7 @@ EXTRA_DIST = \ doap.rdf \ package.json \ sonar-project.properties \ - Dockerfile \ + LANGUAGES.md \ LICENSE \ CHANGES \ NOTICE \ diff --git a/vendor/git.apache.org/thrift.git/NOTICE b/vendor/git.apache.org/thrift.git/NOTICE index c23995a..902dc8d 100644 --- a/vendor/git.apache.org/thrift.git/NOTICE +++ b/vendor/git.apache.org/thrift.git/NOTICE @@ -1,5 +1,5 @@ Apache Thrift -Copyright 2006-2010 The Apache Software Foundation. +Copyright 2006-2017 The Apache Software Foundation. This product includes software developed at -The Apache Software Foundation (http://www.apache.org/). \ No newline at end of file +The Apache Software Foundation (http://www.apache.org/). diff --git a/vendor/git.apache.org/thrift.git/README.md b/vendor/git.apache.org/thrift.git/README.md index 07cd32f..d09e6e1 100644 --- a/vendor/git.apache.org/thrift.git/README.md +++ b/vendor/git.apache.org/thrift.git/README.md @@ -1,29 +1,66 @@ Apache Thrift ============= -+[![Build Status](https://travis-ci.org/apache/thrift.svg?branch=master)](https://travis-ci.org/apache/thrift) -- +[![AppVeyor Build status](https://ci.appveyor.com/api/projects/status/e2qks7enyp9gw7ma?svg=true)](https://ci.appveyor.com/project/apache/thrift) - - Introduction ============ Thrift is a lightweight, language-independent software stack with an -associated code generation mechanism for RPC. Thrift provides clean -abstractions for data transport, data serialization, and application +associated code generation mechanism for point-to-point RPC. Thrift provides +clean abstractions for data transport, data serialization, and application level processing. The code generation system takes a simple definition -language as its input and generates code across programming languages that +language as input and generates code across programming languages that uses the abstracted stack to build interoperable RPC clients and servers. +![Apache Thrift Layered Architecture](doc/images/thrift-layers.png) + +Thrift makes it easy for programs written in different programming +languages to share data and call remote procedures. With support +for [25 programming languages](LANGUAGES.md), chances are Thrift +supports the languages that you currently use. + Thrift is specifically designed to support non-atomic version changes across client and server code. -For more details on Thrift's design and implementation, take a gander at -the Thrift whitepaper included in this distribution or at the README.md files +For more details on Thrift's design and implementation, see the Thrift +whitepaper included in this distribution, or at the README.md file in your particular subdirectory of interest. -Hierarchy -========= +Status +====== + +| Branch | Travis | Appveyor | Coverity Scan | codecov.io | Website | +| :----- | :----- | :------- | :------------ | :--------- | :------ | +| [`master`](https://github.com/apache/thrift/tree/master) | [![Build Status](https://travis-ci.org/apache/thrift.svg?branch=master)](https://travis-ci.org/apache/thrift) | [![Build status](https://ci.appveyor.com/api/projects/status/github/apache/thrift?branch=master&svg=true)](https://ci.appveyor.com/project/ApacheSoftwareFoundation/thrift/history) | [![Coverity Scan Build Status](https://scan.coverity.com/projects/1345/badge.svg)](https://scan.coverity.com/projects/thrift) | | [![Website](https://img.shields.io/badge/official-website-brightgreen.svg)](https://thrift.apache.org/) | + +Releases +======== + +Thrift does not maintain a specific release calendar at this time. + +We strive to release twice yearly. Download the [current release](http://thrift.apache.org/download). + +License +======= + +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you 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. + +Project Hierarchy +================= thrift/ @@ -42,6 +79,7 @@ thrift/ php/ py/ rb/ + ... test/ @@ -53,10 +91,16 @@ thrift/ Contains a basic tutorial that will teach you how to develop software using Thrift. +Development +=========== + +To build the same way Travis CI builds the project you should use docker. +We have [comprehensive building instructions for docker](build/docker/README.md). + Requirements ============ -See http://thrift.apache.org/docs/install for an up-to-date list of build requirements. +See http://thrift.apache.org/docs/install for a list of build requirements (may be stale). Alternatively see the docker build environments for a list of prerequisites. Resources ========= @@ -145,22 +189,4 @@ To run the cross-language test suite, please run: This will run a set of tests that use different language clients and servers. -License -======= -Licensed to the Apache Software Foundation (ASF) under one -or more contributor license agreements. See the NOTICE file -distributed with this work for additional information -regarding copyright ownership. The ASF licenses this file -to you 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. diff --git a/vendor/git.apache.org/thrift.git/Thrift-swift3.podspec b/vendor/git.apache.org/thrift.git/Thrift-swift3.podspec new file mode 100644 index 0000000..542d810 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/Thrift-swift3.podspec @@ -0,0 +1,16 @@ +Pod::Spec.new do |s| + s.name = "Thrift-swift3" + s.version = "0.12.0" + s.summary = "Apache Thrift is a lightweight, language-independent software stack with an associated code generation mechanism for RPC." + s.description = <<-DESC +The Apache Thrift software framework, for scalable cross-language services development, combines a software stack with a code generation engine to build services that work efficiently and seamlessly between C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, OCaml and Delphi and other languages. + DESC + s.homepage = "http://thrift.apache.org" + s.license = { :type => 'Apache License, Version 2.0', :url => 'https://www.apache.org/licenses/LICENSE-2.0' } + s.author = { "Apache Thrift Developers" => "dev@thrift.apache.org" } + s.ios.deployment_target = '9.0' + s.osx.deployment_target = '10.10' + s.requires_arc = true + s.source = { :git => "https://github.com/apache/thrift.git", :tag => "0.12.0" } + s.source_files = "lib/swift/Sources/*.swift" +end diff --git a/vendor/git.apache.org/thrift.git/Thrift.podspec b/vendor/git.apache.org/thrift.git/Thrift.podspec index 2ead0e9..e5b8149 100644 --- a/vendor/git.apache.org/thrift.git/Thrift.podspec +++ b/vendor/git.apache.org/thrift.git/Thrift.podspec @@ -1,18 +1,18 @@ Pod::Spec.new do |s| s.name = "Thrift" - s.version = "0.10.0" + s.version = "0.12.0" s.summary = "Apache Thrift is a lightweight, language-independent software stack with an associated code generation mechanism for RPC." s.description = <<-DESC The Apache Thrift software framework, for scalable cross-language services development, combines a software stack with a code generation engine to build services that work efficiently and seamlessly between C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, OCaml and Delphi and other languages. DESC s.homepage = "http://thrift.apache.org" - s.license = { :type => 'Apache License, Version 2.0', :url => 'https://raw.github.com/apache/thrift/thrift-0.9.0/LICENSE' } - s.author = { "The Apache Software Foundation" => "apache@apache.org" } + s.license = { :type => 'Apache License, Version 2.0', :url => 'https://www.apache.org/licenses/LICENSE-2.0' } + s.author = { "Apache Thrift Developers" => "dev@thrift.apache.org" } s.requires_arc = true s.ios.deployment_target = '7.0' s.osx.deployment_target = '10.8' s.ios.framework = 'CFNetwork' s.osx.framework = 'CoreServices' - s.source = { :git => "https://github.com/apache/thrift.git", :tag => "thrift-0.10.0" } + s.source = { :git => "https://github.com/apache/thrift.git", :tag => "0.12.0" } s.source_files = 'lib/cocoa/src/**/*.{h,m,swift}' -end \ No newline at end of file +end diff --git a/vendor/git.apache.org/thrift.git/aclocal/ax_boost_base.m4 b/vendor/git.apache.org/thrift.git/aclocal/ax_boost_base.m4 index b496020..d540395 100644 --- a/vendor/git.apache.org/thrift.git/aclocal/ax_boost_base.m4 +++ b/vendor/git.apache.org/thrift.git/aclocal/ax_boost_base.m4 @@ -1,5 +1,5 @@ # =========================================================================== -# http://www.gnu.org/software/autoconf-archive/ax_boost_base.html +# https://www.gnu.org/software/autoconf-archive/ax_boost_base.html # =========================================================================== # # SYNOPSIS @@ -33,7 +33,15 @@ # and this notice are preserved. This file is offered as-is, without any # warranty. -#serial 23 +#serial 45 + +# example boost program (need to pass version) +m4_define([_AX_BOOST_BASE_PROGRAM], + [AC_LANG_PROGRAM([[ +#include +]],[[ +(void) ((void)sizeof(char[1 - 2*!!((BOOST_VERSION) < ($1))])); +]])]) AC_DEFUN([AX_BOOST_BASE], [ @@ -44,101 +52,121 @@ AC_ARG_WITH([boost], or disable it (ARG=no) @<:@ARG=yes@:>@ ])], [ - if test "$withval" = "no"; then - want_boost="no" - elif test "$withval" = "yes"; then - want_boost="yes" - ac_boost_path="" - else - want_boost="yes" - ac_boost_path="$withval" - fi + AS_CASE([$withval], + [no],[want_boost="no";_AX_BOOST_BASE_boost_path=""], + [yes],[want_boost="yes";_AX_BOOST_BASE_boost_path=""], + [want_boost="yes";_AX_BOOST_BASE_boost_path="$withval"]) ], [want_boost="yes"]) AC_ARG_WITH([boost-libdir], - AS_HELP_STRING([--with-boost-libdir=LIB_DIR], - [Force given directory for boost libraries. Note that this will override library path detection, so use this parameter only if default library detection fails and you know exactly where your boost libraries are located.]), - [ - if test -d "$withval" - then - ac_boost_lib_path="$withval" - else - AC_MSG_ERROR(--with-boost-libdir expected directory name) - fi - ], - [ac_boost_lib_path=""] -) + [AS_HELP_STRING([--with-boost-libdir=LIB_DIR], + [Force given directory for boost libraries. + Note that this will override library path detection, + so use this parameter only if default library detection fails + and you know exactly where your boost libraries are located.])], + [ + AS_IF([test -d "$withval"], + [_AX_BOOST_BASE_boost_lib_path="$withval"], + [AC_MSG_ERROR([--with-boost-libdir expected directory name])]) + ], + [_AX_BOOST_BASE_boost_lib_path=""]) -if test "x$want_boost" = "xyes"; then - boost_lib_version_req=ifelse([$1], ,1.20.0,$1) - boost_lib_version_req_shorten=`expr $boost_lib_version_req : '\([[0-9]]*\.[[0-9]]*\)'` - boost_lib_version_req_major=`expr $boost_lib_version_req : '\([[0-9]]*\)'` - boost_lib_version_req_minor=`expr $boost_lib_version_req : '[[0-9]]*\.\([[0-9]]*\)'` - boost_lib_version_req_sub_minor=`expr $boost_lib_version_req : '[[0-9]]*\.[[0-9]]*\.\([[0-9]]*\)'` - if test "x$boost_lib_version_req_sub_minor" = "x" ; then - boost_lib_version_req_sub_minor="0" - fi - WANT_BOOST_VERSION=`expr $boost_lib_version_req_major \* 100000 \+ $boost_lib_version_req_minor \* 100 \+ $boost_lib_version_req_sub_minor` - AC_MSG_CHECKING(for boostlib >= $boost_lib_version_req) +BOOST_LDFLAGS="" +BOOST_CPPFLAGS="" +AS_IF([test "x$want_boost" = "xyes"], + [_AX_BOOST_BASE_RUNDETECT([$1],[$2],[$3])]) +AC_SUBST(BOOST_CPPFLAGS) +AC_SUBST(BOOST_LDFLAGS) +]) + + +# convert a version string in $2 to numeric and affect to polymorphic var $1 +AC_DEFUN([_AX_BOOST_BASE_TONUMERICVERSION],[ + AS_IF([test "x$2" = "x"],[_AX_BOOST_BASE_TONUMERICVERSION_req="1.20.0"],[_AX_BOOST_BASE_TONUMERICVERSION_req="$2"]) + _AX_BOOST_BASE_TONUMERICVERSION_req_shorten=`expr $_AX_BOOST_BASE_TONUMERICVERSION_req : '\([[0-9]]*\.[[0-9]]*\)'` + _AX_BOOST_BASE_TONUMERICVERSION_req_major=`expr $_AX_BOOST_BASE_TONUMERICVERSION_req : '\([[0-9]]*\)'` + AS_IF([test "x$_AX_BOOST_BASE_TONUMERICVERSION_req_major" = "x"], + [AC_MSG_ERROR([You should at least specify libboost major version])]) + _AX_BOOST_BASE_TONUMERICVERSION_req_minor=`expr $_AX_BOOST_BASE_TONUMERICVERSION_req : '[[0-9]]*\.\([[0-9]]*\)'` + AS_IF([test "x$_AX_BOOST_BASE_TONUMERICVERSION_req_minor" = "x"], + [_AX_BOOST_BASE_TONUMERICVERSION_req_minor="0"]) + _AX_BOOST_BASE_TONUMERICVERSION_req_sub_minor=`expr $_AX_BOOST_BASE_TONUMERICVERSION_req : '[[0-9]]*\.[[0-9]]*\.\([[0-9]]*\)'` + AS_IF([test "X$_AX_BOOST_BASE_TONUMERICVERSION_req_sub_minor" = "X"], + [_AX_BOOST_BASE_TONUMERICVERSION_req_sub_minor="0"]) + _AX_BOOST_BASE_TONUMERICVERSION_RET=`expr $_AX_BOOST_BASE_TONUMERICVERSION_req_major \* 100000 \+ $_AX_BOOST_BASE_TONUMERICVERSION_req_minor \* 100 \+ $_AX_BOOST_BASE_TONUMERICVERSION_req_sub_minor` + AS_VAR_SET($1,$_AX_BOOST_BASE_TONUMERICVERSION_RET) +]) + +dnl Run the detection of boost should be run only if $want_boost +AC_DEFUN([_AX_BOOST_BASE_RUNDETECT],[ + _AX_BOOST_BASE_TONUMERICVERSION(WANT_BOOST_VERSION,[$1]) succeeded=no + + AC_REQUIRE([AC_CANONICAL_HOST]) dnl On 64-bit systems check for system libraries in both lib64 and lib. dnl The former is specified by FHS, but e.g. Debian does not adhere to dnl this (as it rises problems for generic multi-arch support). dnl The last entry in the list is chosen by default when no libraries dnl are found, e.g. when only header-only libraries are installed! - libsubdirs="lib" - ax_arch=`uname -m` - case $ax_arch in - x86_64|ppc64|s390x|sparc64|aarch64) - libsubdirs="lib64 lib lib64" - ;; - esac + AS_CASE([${host_cpu}], + [x86_64],[libsubdirs="lib64 libx32 lib lib64"], + [ppc64|powerpc64|s390x|sparc64|aarch64|ppc64le|powerpc64le|riscv64],[libsubdirs="lib64 lib lib64"], + [libsubdirs="lib"] + ) dnl allow for real multi-arch paths e.g. /usr/lib/x86_64-linux-gnu. Give dnl them priority over the other paths since, if libs are found there, they dnl are almost assuredly the ones desired. - AC_REQUIRE([AC_CANONICAL_HOST]) - libsubdirs="lib/${host_cpu}-${host_os} $libsubdirs" - - case ${host_cpu} in - i?86) - libsubdirs="lib/i386-${host_os} $libsubdirs" - ;; - esac + AS_CASE([${host_cpu}], + [i?86],[multiarch_libsubdir="lib/i386-${host_os}"], + [multiarch_libsubdir="lib/${host_cpu}-${host_os}"] + ) dnl first we check the system location for boost libraries dnl this location ist chosen if boost libraries are installed with the --layout=system option dnl or if you install boost with RPM - if test "$ac_boost_path" != ""; then - BOOST_CPPFLAGS="-I$ac_boost_path/include" - for ac_boost_path_tmp in $libsubdirs; do - if test -d "$ac_boost_path"/"$ac_boost_path_tmp" ; then - BOOST_LDFLAGS="-L$ac_boost_path/$ac_boost_path_tmp" - break - fi - done - elif test "$cross_compiling" != yes; then - for ac_boost_path_tmp in $lt_sysroot/usr $lt_sysroot/usr/local $lt_sysroot/opt $lt_sysroot/opt/local ; do - if test -d "$ac_boost_path_tmp/include/boost" && test -r "$ac_boost_path_tmp/include/boost"; then - for libsubdir in $libsubdirs ; do - if ls "$ac_boost_path_tmp/$libsubdir/libboost_"* >/dev/null 2>&1 ; then break; fi + AS_IF([test "x$_AX_BOOST_BASE_boost_path" != "x"],[ + AC_MSG_CHECKING([for boostlib >= $1 ($WANT_BOOST_VERSION) includes in "$_AX_BOOST_BASE_boost_path/include"]) + AS_IF([test -d "$_AX_BOOST_BASE_boost_path/include" && test -r "$_AX_BOOST_BASE_boost_path/include"],[ + AC_MSG_RESULT([yes]) + BOOST_CPPFLAGS="-I$_AX_BOOST_BASE_boost_path/include" + for _AX_BOOST_BASE_boost_path_tmp in $multiarch_libsubdir $libsubdirs; do + AC_MSG_CHECKING([for boostlib >= $1 ($WANT_BOOST_VERSION) lib path in "$_AX_BOOST_BASE_boost_path/$_AX_BOOST_BASE_boost_path_tmp"]) + AS_IF([test -d "$_AX_BOOST_BASE_boost_path/$_AX_BOOST_BASE_boost_path_tmp" && test -r "$_AX_BOOST_BASE_boost_path/$_AX_BOOST_BASE_boost_path_tmp" ],[ + AC_MSG_RESULT([yes]) + BOOST_LDFLAGS="-L$_AX_BOOST_BASE_boost_path/$_AX_BOOST_BASE_boost_path_tmp"; + break; + ], + [AC_MSG_RESULT([no])]) + done],[ + AC_MSG_RESULT([no])]) + ],[ + if test X"$cross_compiling" = Xyes; then + search_libsubdirs=$multiarch_libsubdir + else + search_libsubdirs="$multiarch_libsubdir $libsubdirs" + fi + for _AX_BOOST_BASE_boost_path_tmp in /usr /usr/local /opt /opt/local ; do + if test -d "$_AX_BOOST_BASE_boost_path_tmp/include/boost" && test -r "$_AX_BOOST_BASE_boost_path_tmp/include/boost" ; then + for libsubdir in $search_libsubdirs ; do + if ls "$_AX_BOOST_BASE_boost_path_tmp/$libsubdir/libboost_"* >/dev/null 2>&1 ; then break; fi done - BOOST_LDFLAGS="-L$ac_boost_path_tmp/$libsubdir" - BOOST_CPPFLAGS="-I$ac_boost_path_tmp/include" + BOOST_LDFLAGS="-L$_AX_BOOST_BASE_boost_path_tmp/$libsubdir" + BOOST_CPPFLAGS="-I$_AX_BOOST_BASE_boost_path_tmp/include" break; fi done - fi + ]) dnl overwrite ld flags if we have required special directory with dnl --with-boost-libdir parameter - if test "$ac_boost_lib_path" != ""; then - BOOST_LDFLAGS="-L$ac_boost_lib_path" - fi + AS_IF([test "x$_AX_BOOST_BASE_boost_lib_path" != "x"], + [BOOST_LDFLAGS="-L$_AX_BOOST_BASE_boost_lib_path"]) + AC_MSG_CHECKING([for boostlib >= $1 ($WANT_BOOST_VERSION)]) CPPFLAGS_SAVED="$CPPFLAGS" CPPFLAGS="$CPPFLAGS $BOOST_CPPFLAGS" export CPPFLAGS @@ -149,15 +177,7 @@ if test "x$want_boost" = "xyes"; then AC_REQUIRE([AC_PROG_CXX]) AC_LANG_PUSH(C++) - AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ - @%:@include - ]], [[ - #if BOOST_VERSION >= $WANT_BOOST_VERSION - // Everything is okay - #else - # error Boost version is too old - #endif - ]])],[ + AC_COMPILE_IFELSE([_AX_BOOST_BASE_PROGRAM($WANT_BOOST_VERSION)],[ AC_MSG_RESULT(yes) succeeded=yes found_system=yes @@ -169,30 +189,50 @@ if test "x$want_boost" = "xyes"; then dnl if we found no boost with system layout we search for boost libraries dnl built and installed without the --layout=system option or for a staged(not installed) version - if test "x$succeeded" != "xyes"; then + if test "x$succeeded" != "xyes" ; then + CPPFLAGS="$CPPFLAGS_SAVED" + LDFLAGS="$LDFLAGS_SAVED" + BOOST_CPPFLAGS= + if test -z "$_AX_BOOST_BASE_boost_lib_path" ; then + BOOST_LDFLAGS= + fi _version=0 - if test "$ac_boost_path" != ""; then - if test -d "$ac_boost_path" && test -r "$ac_boost_path"; then - for i in `ls -d $ac_boost_path/include/boost-* 2>/dev/null`; do - _version_tmp=`echo $i | sed "s#$ac_boost_path##" | sed 's/\/include\/boost-//' | sed 's/_/./'` + if test -n "$_AX_BOOST_BASE_boost_path" ; then + if test -d "$_AX_BOOST_BASE_boost_path" && test -r "$_AX_BOOST_BASE_boost_path"; then + for i in `ls -d $_AX_BOOST_BASE_boost_path/include/boost-* 2>/dev/null`; do + _version_tmp=`echo $i | sed "s#$_AX_BOOST_BASE_boost_path##" | sed 's/\/include\/boost-//' | sed 's/_/./'` V_CHECK=`expr $_version_tmp \> $_version` - if test "$V_CHECK" = "1" ; then + if test "x$V_CHECK" = "x1" ; then _version=$_version_tmp fi VERSION_UNDERSCORE=`echo $_version | sed 's/\./_/'` - BOOST_CPPFLAGS="-I$ac_boost_path/include/boost-$VERSION_UNDERSCORE" + BOOST_CPPFLAGS="-I$_AX_BOOST_BASE_boost_path/include/boost-$VERSION_UNDERSCORE" done + dnl if nothing found search for layout used in Windows distributions + if test -z "$BOOST_CPPFLAGS"; then + if test -d "$_AX_BOOST_BASE_boost_path/boost" && test -r "$_AX_BOOST_BASE_boost_path/boost"; then + BOOST_CPPFLAGS="-I$_AX_BOOST_BASE_boost_path" + fi + fi + dnl if we found something and BOOST_LDFLAGS was unset before + dnl (because "$_AX_BOOST_BASE_boost_lib_path" = ""), set it here. + if test -n "$BOOST_CPPFLAGS" && test -z "$BOOST_LDFLAGS"; then + for libsubdir in $libsubdirs ; do + if ls "$_AX_BOOST_BASE_boost_path/$libsubdir/libboost_"* >/dev/null 2>&1 ; then break; fi + done + BOOST_LDFLAGS="-L$_AX_BOOST_BASE_boost_path/$libsubdir" + fi fi else - if test "$cross_compiling" != yes; then - for ac_boost_path in $lt_sysroot/usr $lt_sysroot/usr/local $lt_sysroot/opt $lt_sysroot/opt/local ; do - if test -d "$ac_boost_path" && test -r "$ac_boost_path"; then - for i in `ls -d $ac_boost_path/include/boost-* 2>/dev/null`; do - _version_tmp=`echo $i | sed "s#$ac_boost_path##" | sed 's/\/include\/boost-//' | sed 's/_/./'` + if test "x$cross_compiling" != "xyes" ; then + for _AX_BOOST_BASE_boost_path in /usr /usr/local /opt /opt/local ; do + if test -d "$_AX_BOOST_BASE_boost_path" && test -r "$_AX_BOOST_BASE_boost_path" ; then + for i in `ls -d $_AX_BOOST_BASE_boost_path/include/boost-* 2>/dev/null`; do + _version_tmp=`echo $i | sed "s#$_AX_BOOST_BASE_boost_path##" | sed 's/\/include\/boost-//' | sed 's/_/./'` V_CHECK=`expr $_version_tmp \> $_version` - if test "$V_CHECK" = "1" ; then + if test "x$V_CHECK" = "x1" ; then _version=$_version_tmp - best_path=$ac_boost_path + best_path=$_AX_BOOST_BASE_boost_path fi done fi @@ -200,7 +240,7 @@ if test "x$want_boost" = "xyes"; then VERSION_UNDERSCORE=`echo $_version | sed 's/\./_/'` BOOST_CPPFLAGS="-I$best_path/include/boost-$VERSION_UNDERSCORE" - if test "$ac_boost_lib_path" = ""; then + if test -z "$_AX_BOOST_BASE_boost_lib_path" ; then for libsubdir in $libsubdirs ; do if ls "$best_path/$libsubdir/libboost_"* >/dev/null 2>&1 ; then break; fi done @@ -208,7 +248,7 @@ if test "x$want_boost" = "xyes"; then fi fi - if test "x$BOOST_ROOT" != "x"; then + if test -n "$BOOST_ROOT" ; then for libsubdir in $libsubdirs ; do if ls "$BOOST_ROOT/stage/$libsubdir/libboost_"* >/dev/null 2>&1 ; then break; fi done @@ -217,7 +257,7 @@ if test "x$want_boost" = "xyes"; then stage_version=`echo $version_dir | sed 's/boost_//' | sed 's/_/./g'` stage_version_shorten=`expr $stage_version : '\([[0-9]]*\.[[0-9]]*\)'` V_CHECK=`expr $stage_version_shorten \>\= $_version` - if test "$V_CHECK" = "1" -a "$ac_boost_lib_path" = "" ; then + if test "x$V_CHECK" = "x1" && test -z "$_AX_BOOST_BASE_boost_lib_path" ; then AC_MSG_NOTICE(We will use a staged boost library from $BOOST_ROOT) BOOST_CPPFLAGS="-I$BOOST_ROOT" BOOST_LDFLAGS="-L$BOOST_ROOT/stage/$libsubdir" @@ -232,15 +272,7 @@ if test "x$want_boost" = "xyes"; then export LDFLAGS AC_LANG_PUSH(C++) - AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ - @%:@include - ]], [[ - #if BOOST_VERSION >= $WANT_BOOST_VERSION - // Everything is okay - #else - # error Boost version is too old - #endif - ]])],[ + AC_COMPILE_IFELSE([_AX_BOOST_BASE_PROGRAM($WANT_BOOST_VERSION)],[ AC_MSG_RESULT(yes) succeeded=yes found_system=yes @@ -249,17 +281,15 @@ if test "x$want_boost" = "xyes"; then AC_LANG_POP([C++]) fi - if test "$succeeded" != "yes" ; then - if test "$_version" = "0" ; then - AC_MSG_NOTICE([[We could not detect the boost libraries (version $boost_lib_version_req_shorten or higher). If you have a staged boost library (still not installed) please specify \$BOOST_ROOT in your environment and do not give a PATH to --with-boost option. If you are sure you have boost installed, then check your version number looking in . See http://randspringer.de/boost for more documentation.]]) + if test "x$succeeded" != "xyes" ; then + if test "x$_version" = "x0" ; then + AC_MSG_NOTICE([[We could not detect the boost libraries (version $1 or higher). If you have a staged boost library (still not installed) please specify \$BOOST_ROOT in your environment and do not give a PATH to --with-boost option. If you are sure you have boost installed, then check your version number looking in . See http://randspringer.de/boost for more documentation.]]) else AC_MSG_NOTICE([Your boost libraries seems to old (version $_version).]) fi # execute ACTION-IF-NOT-FOUND (if present): ifelse([$3], , :, [$3]) else - AC_SUBST(BOOST_CPPFLAGS) - AC_SUBST(BOOST_LDFLAGS) AC_DEFINE(HAVE_BOOST,,[define if the Boost library is available]) # execute ACTION-IF-FOUND (if present): ifelse([$2], , :, [$2]) @@ -267,6 +297,5 @@ if test "x$want_boost" = "xyes"; then CPPFLAGS="$CPPFLAGS_SAVED" LDFLAGS="$LDFLAGS_SAVED" -fi ]) diff --git a/vendor/git.apache.org/thrift.git/aclocal/ax_check_openssl.m4 b/vendor/git.apache.org/thrift.git/aclocal/ax_check_openssl.m4 index a87c5a6..28e48cb 100644 --- a/vendor/git.apache.org/thrift.git/aclocal/ax_check_openssl.m4 +++ b/vendor/git.apache.org/thrift.git/aclocal/ax_check_openssl.m4 @@ -1,5 +1,5 @@ # =========================================================================== -# http://www.gnu.org/software/autoconf-archive/ax_check_openssl.html +# https://www.gnu.org/software/autoconf-archive/ax_check_openssl.html # =========================================================================== # # SYNOPSIS @@ -32,7 +32,7 @@ # and this notice are preserved. This file is offered as-is, without any # warranty. -#serial 8 +#serial 10 AU_ALIAS([CHECK_SSL], [AX_CHECK_OPENSSL]) AC_DEFUN([AX_CHECK_OPENSSL], [ @@ -51,7 +51,7 @@ AC_DEFUN([AX_CHECK_OPENSSL], [ ], [ # if pkg-config is installed and openssl has installed a .pc file, # then use that information and don't search ssldirs - AC_PATH_PROG([PKG_CONFIG], [pkg-config]) + AC_CHECK_TOOL([PKG_CONFIG], [pkg-config]) if test x"$PKG_CONFIG" != x""; then OPENSSL_LDFLAGS=`$PKG_CONFIG openssl --libs-only-L 2>/dev/null` if test $? = 0; then diff --git a/vendor/git.apache.org/thrift.git/aclocal/m4_ax_compare_version.m4 b/vendor/git.apache.org/thrift.git/aclocal/ax_compare_version.m4 similarity index 98% rename from vendor/git.apache.org/thrift.git/aclocal/m4_ax_compare_version.m4 rename to vendor/git.apache.org/thrift.git/aclocal/ax_compare_version.m4 index 74dc0fd..9c8e208 100644 --- a/vendor/git.apache.org/thrift.git/aclocal/m4_ax_compare_version.m4 +++ b/vendor/git.apache.org/thrift.git/aclocal/ax_compare_version.m4 @@ -1,5 +1,5 @@ # =========================================================================== -# http://www.gnu.org/software/autoconf-archive/ax_compare_version.html +# https://www.gnu.org/software/autoconf-archive/ax_compare_version.html # =========================================================================== # # SYNOPSIS @@ -79,7 +79,7 @@ # and this notice are preserved. This file is offered as-is, without any # warranty. -#serial 11 +#serial 12 dnl ######################################################################### AC_DEFUN([AX_COMPARE_VERSION], [ diff --git a/vendor/git.apache.org/thrift.git/aclocal/ax_cxx_compile_stdcxx.m4 b/vendor/git.apache.org/thrift.git/aclocal/ax_cxx_compile_stdcxx.m4 new file mode 100644 index 0000000..9e9eaed --- /dev/null +++ b/vendor/git.apache.org/thrift.git/aclocal/ax_cxx_compile_stdcxx.m4 @@ -0,0 +1,948 @@ +# =========================================================================== +# https://www.gnu.org/software/autoconf-archive/ax_cxx_compile_stdcxx.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_CXX_COMPILE_STDCXX(VERSION, [ext|noext], [mandatory|optional]) +# +# DESCRIPTION +# +# Check for baseline language coverage in the compiler for the specified +# version of the C++ standard. If necessary, add switches to CXX and +# CXXCPP to enable support. VERSION may be '11' (for the C++11 standard) +# or '14' (for the C++14 standard). +# +# The second argument, if specified, indicates whether you insist on an +# extended mode (e.g. -std=gnu++11) or a strict conformance mode (e.g. +# -std=c++11). If neither is specified, you get whatever works, with +# preference for an extended mode. +# +# The third argument, if specified 'mandatory' or if left unspecified, +# indicates that baseline support for the specified C++ standard is +# required and that the macro should error out if no mode with that +# support is found. If specified 'optional', then configuration proceeds +# regardless, after defining HAVE_CXX${VERSION} if and only if a +# supporting mode is found. +# +# LICENSE +# +# Copyright (c) 2008 Benjamin Kosnik +# Copyright (c) 2012 Zack Weinberg +# Copyright (c) 2013 Roy Stogner +# Copyright (c) 2014, 2015 Google Inc.; contributed by Alexey Sokolov +# Copyright (c) 2015 Paul Norman +# Copyright (c) 2015 Moritz Klammler +# Copyright (c) 2016, 2018 Krzesimir Nowak +# +# Copying and distribution of this file, with or without modification, are +# permitted in any medium without royalty provided the copyright notice +# and this notice are preserved. This file is offered as-is, without any +# warranty. + +#serial 10 + +dnl This macro is based on the code from the AX_CXX_COMPILE_STDCXX_11 macro +dnl (serial version number 13). + +AC_DEFUN([AX_CXX_COMPILE_STDCXX], [dnl + m4_if([$1], [11], [ax_cxx_compile_alternatives="11 0x"], + [$1], [14], [ax_cxx_compile_alternatives="14 1y"], + [$1], [17], [ax_cxx_compile_alternatives="17 1z"], + [m4_fatal([invalid first argument `$1' to AX_CXX_COMPILE_STDCXX])])dnl + m4_if([$2], [], [], + [$2], [ext], [], + [$2], [noext], [], + [m4_fatal([invalid second argument `$2' to AX_CXX_COMPILE_STDCXX])])dnl + m4_if([$3], [], [ax_cxx_compile_cxx$1_required=true], + [$3], [mandatory], [ax_cxx_compile_cxx$1_required=true], + [$3], [optional], [ax_cxx_compile_cxx$1_required=false], + [m4_fatal([invalid third argument `$3' to AX_CXX_COMPILE_STDCXX])]) + AC_LANG_PUSH([C++])dnl + ac_success=no + + m4_if([$2], [noext], [], [dnl + if test x$ac_success = xno; then + for alternative in ${ax_cxx_compile_alternatives}; do + switch="-std=gnu++${alternative}" + cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx$1_$switch]) + AC_CACHE_CHECK(whether $CXX supports C++$1 features with $switch, + $cachevar, + [ac_save_CXX="$CXX" + CXX="$CXX $switch" + AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])], + [eval $cachevar=yes], + [eval $cachevar=no]) + CXX="$ac_save_CXX"]) + if eval test x\$$cachevar = xyes; then + CXX="$CXX $switch" + if test -n "$CXXCPP" ; then + CXXCPP="$CXXCPP $switch" + fi + ac_success=yes + break + fi + done + fi]) + + m4_if([$2], [ext], [], [dnl + if test x$ac_success = xno; then + dnl HP's aCC needs +std=c++11 according to: + dnl http://h21007.www2.hp.com/portal/download/files/unprot/aCxx/PDF_Release_Notes/769149-001.pdf + dnl Cray's crayCC needs "-h std=c++11" + for alternative in ${ax_cxx_compile_alternatives}; do + for switch in -std=c++${alternative} +std=c++${alternative} "-h std=c++${alternative}"; do + cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx$1_$switch]) + AC_CACHE_CHECK(whether $CXX supports C++$1 features with $switch, + $cachevar, + [ac_save_CXX="$CXX" + CXX="$CXX $switch" + AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])], + [eval $cachevar=yes], + [eval $cachevar=no]) + CXX="$ac_save_CXX"]) + if eval test x\$$cachevar = xyes; then + CXX="$CXX $switch" + if test -n "$CXXCPP" ; then + CXXCPP="$CXXCPP $switch" + fi + ac_success=yes + break + fi + done + if test x$ac_success = xyes; then + break + fi + done + fi]) + AC_LANG_POP([C++]) + if test x$ax_cxx_compile_cxx$1_required = xtrue; then + if test x$ac_success = xno; then + AC_MSG_ERROR([*** A compiler with support for C++$1 language features is required.]) + fi + fi + if test x$ac_success = xno; then + HAVE_CXX$1=0 + AC_MSG_NOTICE([No compiler with C++$1 support was found]) + else + HAVE_CXX$1=1 + AC_DEFINE(HAVE_CXX$1,1, + [define if the compiler supports basic C++$1 syntax]) + fi + AC_SUBST(HAVE_CXX$1) +]) + + +dnl Test body for checking C++11 support + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_11], + _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 +) + + +dnl Test body for checking C++14 support + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_14], + _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 +) + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_17], + _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_17 +) + +dnl Tests for new features in C++11 + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_11], [[ + +// If the compiler admits that it is not ready for C++11, why torture it? +// Hopefully, this will speed up the test. + +#ifndef __cplusplus + +#error "This is not a C++ compiler" + +#elif __cplusplus < 201103L + +#error "This is not a C++11 compiler" + +#else + +namespace cxx11 +{ + + namespace test_static_assert + { + + template + struct check + { + static_assert(sizeof(int) <= sizeof(T), "not big enough"); + }; + + } + + namespace test_final_override + { + + struct Base + { + virtual void f() {} + }; + + struct Derived : public Base + { + virtual void f() override {} + }; + + } + + namespace test_double_right_angle_brackets + { + + template < typename T > + struct check {}; + + typedef check single_type; + typedef check> double_type; + typedef check>> triple_type; + typedef check>>> quadruple_type; + + } + + namespace test_decltype + { + + int + f() + { + int a = 1; + decltype(a) b = 2; + return a + b; + } + + } + + namespace test_type_deduction + { + + template < typename T1, typename T2 > + struct is_same + { + static const bool value = false; + }; + + template < typename T > + struct is_same + { + static const bool value = true; + }; + + template < typename T1, typename T2 > + auto + add(T1 a1, T2 a2) -> decltype(a1 + a2) + { + return a1 + a2; + } + + int + test(const int c, volatile int v) + { + static_assert(is_same::value == true, ""); + static_assert(is_same::value == false, ""); + static_assert(is_same::value == false, ""); + auto ac = c; + auto av = v; + auto sumi = ac + av + 'x'; + auto sumf = ac + av + 1.0; + static_assert(is_same::value == true, ""); + static_assert(is_same::value == true, ""); + static_assert(is_same::value == true, ""); + static_assert(is_same::value == false, ""); + static_assert(is_same::value == true, ""); + return (sumf > 0.0) ? sumi : add(c, v); + } + + } + + namespace test_noexcept + { + + int f() { return 0; } + int g() noexcept { return 0; } + + static_assert(noexcept(f()) == false, ""); + static_assert(noexcept(g()) == true, ""); + + } + + namespace test_constexpr + { + + template < typename CharT > + unsigned long constexpr + strlen_c_r(const CharT *const s, const unsigned long acc) noexcept + { + return *s ? strlen_c_r(s + 1, acc + 1) : acc; + } + + template < typename CharT > + unsigned long constexpr + strlen_c(const CharT *const s) noexcept + { + return strlen_c_r(s, 0UL); + } + + static_assert(strlen_c("") == 0UL, ""); + static_assert(strlen_c("1") == 1UL, ""); + static_assert(strlen_c("example") == 7UL, ""); + static_assert(strlen_c("another\0example") == 7UL, ""); + + } + + namespace test_rvalue_references + { + + template < int N > + struct answer + { + static constexpr int value = N; + }; + + answer<1> f(int&) { return answer<1>(); } + answer<2> f(const int&) { return answer<2>(); } + answer<3> f(int&&) { return answer<3>(); } + + void + test() + { + int i = 0; + const int c = 0; + static_assert(decltype(f(i))::value == 1, ""); + static_assert(decltype(f(c))::value == 2, ""); + static_assert(decltype(f(0))::value == 3, ""); + } + + } + + namespace test_uniform_initialization + { + + struct test + { + static const int zero {}; + static const int one {1}; + }; + + static_assert(test::zero == 0, ""); + static_assert(test::one == 1, ""); + + } + + namespace test_lambdas + { + + void + test1() + { + auto lambda1 = [](){}; + auto lambda2 = lambda1; + lambda1(); + lambda2(); + } + + int + test2() + { + auto a = [](int i, int j){ return i + j; }(1, 2); + auto b = []() -> int { return '0'; }(); + auto c = [=](){ return a + b; }(); + auto d = [&](){ return c; }(); + auto e = [a, &b](int x) mutable { + const auto identity = [](int y){ return y; }; + for (auto i = 0; i < a; ++i) + a += b--; + return x + identity(a + b); + }(0); + return a + b + c + d + e; + } + + int + test3() + { + const auto nullary = [](){ return 0; }; + const auto unary = [](int x){ return x; }; + using nullary_t = decltype(nullary); + using unary_t = decltype(unary); + const auto higher1st = [](nullary_t f){ return f(); }; + const auto higher2nd = [unary](nullary_t f1){ + return [unary, f1](unary_t f2){ return f2(unary(f1())); }; + }; + return higher1st(nullary) + higher2nd(nullary)(unary); + } + + } + + namespace test_variadic_templates + { + + template + struct sum; + + template + struct sum + { + static constexpr auto value = N0 + sum::value; + }; + + template <> + struct sum<> + { + static constexpr auto value = 0; + }; + + static_assert(sum<>::value == 0, ""); + static_assert(sum<1>::value == 1, ""); + static_assert(sum<23>::value == 23, ""); + static_assert(sum<1, 2>::value == 3, ""); + static_assert(sum<5, 5, 11>::value == 21, ""); + static_assert(sum<2, 3, 5, 7, 11, 13>::value == 41, ""); + + } + + // http://stackoverflow.com/questions/13728184/template-aliases-and-sfinae + // Clang 3.1 fails with headers of libstd++ 4.8.3 when using std::function + // because of this. + namespace test_template_alias_sfinae + { + + struct foo {}; + + template + using member = typename T::member_type; + + template + void func(...) {} + + template + void func(member*) {} + + void test(); + + void test() { func(0); } + + } + +} // namespace cxx11 + +#endif // __cplusplus >= 201103L + +]]) + + +dnl Tests for new features in C++14 + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_14], [[ + +// If the compiler admits that it is not ready for C++14, why torture it? +// Hopefully, this will speed up the test. + +#ifndef __cplusplus + +#error "This is not a C++ compiler" + +#elif __cplusplus < 201402L + +#error "This is not a C++14 compiler" + +#else + +namespace cxx14 +{ + + namespace test_polymorphic_lambdas + { + + int + test() + { + const auto lambda = [](auto&&... args){ + const auto istiny = [](auto x){ + return (sizeof(x) == 1UL) ? 1 : 0; + }; + const int aretiny[] = { istiny(args)... }; + return aretiny[0]; + }; + return lambda(1, 1L, 1.0f, '1'); + } + + } + + namespace test_binary_literals + { + + constexpr auto ivii = 0b0000000000101010; + static_assert(ivii == 42, "wrong value"); + + } + + namespace test_generalized_constexpr + { + + template < typename CharT > + constexpr unsigned long + strlen_c(const CharT *const s) noexcept + { + auto length = 0UL; + for (auto p = s; *p; ++p) + ++length; + return length; + } + + static_assert(strlen_c("") == 0UL, ""); + static_assert(strlen_c("x") == 1UL, ""); + static_assert(strlen_c("test") == 4UL, ""); + static_assert(strlen_c("another\0test") == 7UL, ""); + + } + + namespace test_lambda_init_capture + { + + int + test() + { + auto x = 0; + const auto lambda1 = [a = x](int b){ return a + b; }; + const auto lambda2 = [a = lambda1(x)](){ return a; }; + return lambda2(); + } + + } + + namespace test_digit_separators + { + + constexpr auto ten_million = 100'000'000; + static_assert(ten_million == 100000000, ""); + + } + + namespace test_return_type_deduction + { + + auto f(int& x) { return x; } + decltype(auto) g(int& x) { return x; } + + template < typename T1, typename T2 > + struct is_same + { + static constexpr auto value = false; + }; + + template < typename T > + struct is_same + { + static constexpr auto value = true; + }; + + int + test() + { + auto x = 0; + static_assert(is_same::value, ""); + static_assert(is_same::value, ""); + return x; + } + + } + +} // namespace cxx14 + +#endif // __cplusplus >= 201402L + +]]) + + +dnl Tests for new features in C++17 + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_17], [[ + +// If the compiler admits that it is not ready for C++17, why torture it? +// Hopefully, this will speed up the test. + +#ifndef __cplusplus + +#error "This is not a C++ compiler" + +#elif __cplusplus < 201703L + +#error "This is not a C++17 compiler" + +#else + +#include +#include +#include + +namespace cxx17 +{ + + namespace test_constexpr_lambdas + { + + constexpr int foo = [](){return 42;}(); + + } + + namespace test::nested_namespace::definitions + { + + } + + namespace test_fold_expression + { + + template + int multiply(Args... args) + { + return (args * ... * 1); + } + + template + bool all(Args... args) + { + return (args && ...); + } + + } + + namespace test_extended_static_assert + { + + static_assert (true); + + } + + namespace test_auto_brace_init_list + { + + auto foo = {5}; + auto bar {5}; + + static_assert(std::is_same, decltype(foo)>::value); + static_assert(std::is_same::value); + } + + namespace test_typename_in_template_template_parameter + { + + template typename X> struct D; + + } + + namespace test_fallthrough_nodiscard_maybe_unused_attributes + { + + int f1() + { + return 42; + } + + [[nodiscard]] int f2() + { + [[maybe_unused]] auto unused = f1(); + + switch (f1()) + { + case 17: + f1(); + [[fallthrough]]; + case 42: + f1(); + } + return f1(); + } + + } + + namespace test_extended_aggregate_initialization + { + + struct base1 + { + int b1, b2 = 42; + }; + + struct base2 + { + base2() { + b3 = 42; + } + int b3; + }; + + struct derived : base1, base2 + { + int d; + }; + + derived d1 {{1, 2}, {}, 4}; // full initialization + derived d2 {{}, {}, 4}; // value-initialized bases + + } + + namespace test_general_range_based_for_loop + { + + struct iter + { + int i; + + int& operator* () + { + return i; + } + + const int& operator* () const + { + return i; + } + + iter& operator++() + { + ++i; + return *this; + } + }; + + struct sentinel + { + int i; + }; + + bool operator== (const iter& i, const sentinel& s) + { + return i.i == s.i; + } + + bool operator!= (const iter& i, const sentinel& s) + { + return !(i == s); + } + + struct range + { + iter begin() const + { + return {0}; + } + + sentinel end() const + { + return {5}; + } + }; + + void f() + { + range r {}; + + for (auto i : r) + { + [[maybe_unused]] auto v = i; + } + } + + } + + namespace test_lambda_capture_asterisk_this_by_value + { + + struct t + { + int i; + int foo() + { + return [*this]() + { + return i; + }(); + } + }; + + } + + namespace test_enum_class_construction + { + + enum class byte : unsigned char + {}; + + byte foo {42}; + + } + + namespace test_constexpr_if + { + + template + int f () + { + if constexpr(cond) + { + return 13; + } + else + { + return 42; + } + } + + } + + namespace test_selection_statement_with_initializer + { + + int f() + { + return 13; + } + + int f2() + { + if (auto i = f(); i > 0) + { + return 3; + } + + switch (auto i = f(); i + 4) + { + case 17: + return 2; + + default: + return 1; + } + } + + } + + namespace test_template_argument_deduction_for_class_templates + { + + template + struct pair + { + pair (T1 p1, T2 p2) + : m1 {p1}, + m2 {p2} + {} + + T1 m1; + T2 m2; + }; + + void f() + { + [[maybe_unused]] auto p = pair{13, 42u}; + } + + } + + namespace test_non_type_auto_template_parameters + { + + template + struct B + {}; + + B<5> b1; + B<'a'> b2; + + } + + namespace test_structured_bindings + { + + int arr[2] = { 1, 2 }; + std::pair pr = { 1, 2 }; + + auto f1() -> int(&)[2] + { + return arr; + } + + auto f2() -> std::pair& + { + return pr; + } + + struct S + { + int x1 : 2; + volatile double y1; + }; + + S f3() + { + return {}; + } + + auto [ x1, y1 ] = f1(); + auto& [ xr1, yr1 ] = f1(); + auto [ x2, y2 ] = f2(); + auto& [ xr2, yr2 ] = f2(); + const auto [ x3, y3 ] = f3(); + + } + + namespace test_exception_spec_type_system + { + + struct Good {}; + struct Bad {}; + + void g1() noexcept; + void g2(); + + template + Bad + f(T*, T*); + + template + Good + f(T1*, T2*); + + static_assert (std::is_same_v); + + } + + namespace test_inline_variables + { + + template void f(T) + {} + + template inline T g(T) + { + return T{}; + } + + template<> inline void f<>(int) + {} + + template<> int g<>(int) + { + return 5; + } + + } + +} // namespace cxx17 + +#endif // __cplusplus < 201703L + +]]) diff --git a/vendor/git.apache.org/thrift.git/aclocal/ax_cxx_compile_stdcxx_11.m4 b/vendor/git.apache.org/thrift.git/aclocal/ax_cxx_compile_stdcxx_11.m4 index a9a8f58..1733fd8 100644 --- a/vendor/git.apache.org/thrift.git/aclocal/ax_cxx_compile_stdcxx_11.m4 +++ b/vendor/git.apache.org/thrift.git/aclocal/ax_cxx_compile_stdcxx_11.m4 @@ -1,26 +1,23 @@ -# ============================================================================ -# http://www.gnu.org/software/autoconf-archive/ax_cxx_compile_stdcxx_11.html -# ============================================================================ +# ============================================================================= +# https://www.gnu.org/software/autoconf-archive/ax_cxx_compile_stdcxx_11.html +# ============================================================================= # # SYNOPSIS # -# AX_CXX_COMPILE_STDCXX_11([ext|noext],[mandatory|optional]) +# AX_CXX_COMPILE_STDCXX_11([ext|noext], [mandatory|optional]) # # DESCRIPTION # # Check for baseline language coverage in the compiler for the C++11 -# standard; if necessary, add switches to CXXFLAGS to enable support. +# standard; if necessary, add switches to CXX and CXXCPP to enable +# support. # -# The first argument, if specified, indicates whether you insist on an -# extended mode (e.g. -std=gnu++11) or a strict conformance mode (e.g. -# -std=c++11). If neither is specified, you get whatever works, with -# preference for an extended mode. -# -# The second argument, if specified 'mandatory' or if left unspecified, -# indicates that baseline C++11 support is required and that the macro -# should error out if no mode with that support is found. If specified -# 'optional', then configuration proceeds regardless, after defining -# HAVE_CXX11 if and only if a supporting mode is found. +# This macro is a convenience alias for calling the AX_CXX_COMPILE_STDCXX +# macro with the version set to C++11. The two optional arguments are +# forwarded literally as the second and third argument respectively. +# Please see the documentation for the AX_CXX_COMPILE_STDCXX macro for +# more information. If you want to use this macro, you also need to +# download the ax_cxx_compile_stdcxx.m4 file. # # LICENSE # @@ -28,138 +25,15 @@ # Copyright (c) 2012 Zack Weinberg # Copyright (c) 2013 Roy Stogner # Copyright (c) 2014, 2015 Google Inc.; contributed by Alexey Sokolov +# Copyright (c) 2015 Paul Norman +# Copyright (c) 2015 Moritz Klammler # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice # and this notice are preserved. This file is offered as-is, without any # warranty. -#serial 10 +#serial 18 -m4_define([_AX_CXX_COMPILE_STDCXX_11_testbody], [[ - template - struct check - { - static_assert(sizeof(int) <= sizeof(T), "not big enough"); - }; - - struct Base { - virtual void f() {} - }; - struct Child : public Base { - virtual void f() override {} - }; - - typedef check> right_angle_brackets; - - int a; - decltype(a) b; - - typedef check check_type; - check_type c; - check_type&& cr = static_cast(c); - - auto d = a; - auto l = [](){}; - // Prevent Clang error: unused variable 'l' [-Werror,-Wunused-variable] - struct use_l { use_l() { l(); } }; - - // http://stackoverflow.com/questions/13728184/template-aliases-and-sfinae - // Clang 3.1 fails with headers of libstd++ 4.8.3 when using std::function because of this - namespace test_template_alias_sfinae { - struct foo {}; - - template - using member = typename T::member_type; - - template - void func(...) {} - - template - void func(member*) {} - - void test(); - - void test() { - func(0); - } - } -]]) - -AC_DEFUN([AX_CXX_COMPILE_STDCXX_11], [dnl - m4_if([$1], [], [], - [$1], [ext], [], - [$1], [noext], [], - [m4_fatal([invalid argument `$1' to AX_CXX_COMPILE_STDCXX_11])])dnl - m4_if([$2], [], [ax_cxx_compile_cxx11_required=true], - [$2], [mandatory], [ax_cxx_compile_cxx11_required=true], - [$2], [optional], [ax_cxx_compile_cxx11_required=false], - [m4_fatal([invalid second argument `$2' to AX_CXX_COMPILE_STDCXX_11])]) - AC_LANG_PUSH([C++])dnl - ac_success=no - AC_CACHE_CHECK(whether $CXX supports C++11 features by default, - ax_cv_cxx_compile_cxx11, - [AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_11_testbody])], - [ax_cv_cxx_compile_cxx11=yes], - [ax_cv_cxx_compile_cxx11=no])]) - if test x$ax_cv_cxx_compile_cxx11 = xyes; then - ac_success=yes - fi - - m4_if([$1], [noext], [], [dnl - if test x$ac_success = xno; then - for switch in -std=gnu++11 -std=gnu++0x; do - cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx11_$switch]) - AC_CACHE_CHECK(whether $CXX supports C++11 features with $switch, - $cachevar, - [ac_save_CXXFLAGS="$CXXFLAGS" - CXXFLAGS="$CXXFLAGS $switch" - AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_11_testbody])], - [eval $cachevar=yes], - [eval $cachevar=no]) - CXXFLAGS="$ac_save_CXXFLAGS"]) - if eval test x\$$cachevar = xyes; then - CXXFLAGS="$CXXFLAGS $switch" - ac_success=yes - break - fi - done - fi]) - - m4_if([$1], [ext], [], [dnl - if test x$ac_success = xno; then - for switch in -std=c++11 -std=c++0x; do - cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx11_$switch]) - AC_CACHE_CHECK(whether $CXX supports C++11 features with $switch, - $cachevar, - [ac_save_CXXFLAGS="$CXXFLAGS" - CXXFLAGS="$CXXFLAGS $switch" - AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_11_testbody])], - [eval $cachevar=yes], - [eval $cachevar=no]) - CXXFLAGS="$ac_save_CXXFLAGS"]) - if eval test x\$$cachevar = xyes; then - CXXFLAGS="$CXXFLAGS $switch" - ac_success=yes - break - fi - done - fi]) - AC_LANG_POP([C++]) - if test x$ax_cxx_compile_cxx11_required = xtrue; then - if test x$ac_success = xno; then - AC_MSG_ERROR([*** A compiler with support for C++11 language features is required.]) - fi - else - if test x$ac_success = xno; then - HAVE_CXX11=0 - AC_MSG_NOTICE([No compiler with C++11 support was found]) - else - HAVE_CXX11=1 - AC_DEFINE(HAVE_CXX11,1, - [define if the compiler supports basic C++11 syntax]) - fi - - AC_SUBST(HAVE_CXX11) - fi -]) +AX_REQUIRE_DEFINED([AX_CXX_COMPILE_STDCXX]) +AC_DEFUN([AX_CXX_COMPILE_STDCXX_11], [AX_CXX_COMPILE_STDCXX([11], [$1], [$2])]) diff --git a/vendor/git.apache.org/thrift.git/aclocal/ax_javac_and_java.m4 b/vendor/git.apache.org/thrift.git/aclocal/ax_javac_and_java.m4 index f341f50..0203960 100644 --- a/vendor/git.apache.org/thrift.git/aclocal/ax_javac_and_java.m4 +++ b/vendor/git.apache.org/thrift.git/aclocal/ax_javac_and_java.m4 @@ -118,7 +118,7 @@ AC_DEFUN([AX_CHECK_JAVA_CLASS], AC_DEFUN([AX_CHECK_ANT_VERSION], [ AC_MSG_CHECKING(for ant version > $2) - ANT_VALID=`expr $($1 -version 2>/dev/null | sed -n 's/.*version \(@<:@0-9\.@:>@*\).*/\1/p') \>= $2` + ANT_VALID=`expr "x$(printf "$2\n$($1 -version 2>/dev/null | sed -n 's/.*version \(@<:@0-9\.@:>@*\).*/\1/p')" | sort -t '.' -k 1,1 -k 2,2 -k 3,3 -g | sed -n 1p)" = "x$2"` if test "x$ANT_VALID" = "x1" ; then AC_MSG_RESULT(yes) else diff --git a/vendor/git.apache.org/thrift.git/aclocal/ax_lua.m4 b/vendor/git.apache.org/thrift.git/aclocal/ax_lua.m4 index 9feb352..5920167 100644 --- a/vendor/git.apache.org/thrift.git/aclocal/ax_lua.m4 +++ b/vendor/git.apache.org/thrift.git/aclocal/ax_lua.m4 @@ -1,5 +1,5 @@ # =========================================================================== -# http://www.gnu.org/software/autoconf-archive/ax_lua.html +# https://www.gnu.org/software/autoconf-archive/ax_lua.html # =========================================================================== # # SYNOPSIS @@ -166,7 +166,7 @@ # Public License for more details. # # You should have received a copy of the GNU General Public License along -# with this program. If not, see . +# with this program. If not, see . # # As a special exception, the respective Autoconf Macro's copyright owner # gives unlimited permission to copy, distribute and modify the configure @@ -181,7 +181,7 @@ # modified version of the Autoconf Macro, you may extend this special # exception to the GPL to apply to your modified version as well. -#serial 39 +#serial 40 dnl ========================================================================= dnl AX_PROG_LUA([MINIMUM-VERSION], [TOO-BIG-VERSION], diff --git a/vendor/git.apache.org/thrift.git/aclocal/ax_prog_dotnetcore_version.m4 b/vendor/git.apache.org/thrift.git/aclocal/ax_prog_dotnetcore_version.m4 new file mode 100644 index 0000000..92c7495 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/aclocal/ax_prog_dotnetcore_version.m4 @@ -0,0 +1,61 @@ +# =============================================================================== +# https://www.gnu.org/software/autoconf-archive/ax_prog_dotnetcore_version.html +# =============================================================================== +# +# SYNOPSIS +# +# AX_PROG_DOTNETCORE_VERSION([VERSION],[ACTION-IF-TRUE],[ACTION-IF-FALSE]) +# +# DESCRIPTION +# +# Makes sure that .NET Core supports the version indicated. If true the +# shell commands in ACTION-IF-TRUE are executed. If not the shell commands +# in ACTION-IF-FALSE are run. The $dotnetcore_version variable will be +# filled with the detected version. +# +# This macro uses the $DOTNETCORE variable to perform the check. If +# $DOTNETCORE is not set prior to calling this macro, the macro will fail. +# +# Example: +# +# AC_PATH_PROG([DOTNETCORE],[dotnet]) +# AC_PROG_DOTNETCORE_VERSION([1.0.2],[ ... ],[ ... ]) +# +# Searches for .NET Core, then checks if at least version 1.0.2 is +# present. +# +# LICENSE +# +# Copyright (c) 2016 Jens Geyer +# +# Copying and distribution of this file, with or without modification, are +# permitted in any medium without royalty provided the copyright notice +# and this notice are preserved. This file is offered as-is, without any +# warranty. + +#serial 2 + +AC_DEFUN([AX_PROG_DOTNETCORE_VERSION],[ + AC_REQUIRE([AC_PROG_SED]) + + AS_IF([test -n "$DOTNETCORE"],[ + ax_dotnetcore_version="$1" + + AC_MSG_CHECKING([for .NET Core version]) + dotnetcore_version=`$DOTNETCORE --version 2>&1 | $SED -e 's/\(@<:@0-9@:>@*\.@<:@0-9@:>@*\.@<:@0-9@:>@*\)\(.*\)/\1/'` + AC_MSG_RESULT($dotnetcore_version) + + AC_SUBST([DOTNETCORE_VERSION],[$dotnetcore_version]) + + AX_COMPARE_VERSION([$ax_dotnetcore_version],[le],[$dotnetcore_version],[ + : + $2 + ],[ + : + $3 + ]) + ],[ + AC_MSG_WARN([could not find .NET Core]) + $3 + ]) +]) diff --git a/vendor/git.apache.org/thrift.git/aclocal/ax_prog_haxe_version.m4 b/vendor/git.apache.org/thrift.git/aclocal/ax_prog_haxe_version.m4 index 3dee430..fcacc67 100644 --- a/vendor/git.apache.org/thrift.git/aclocal/ax_prog_haxe_version.m4 +++ b/vendor/git.apache.org/thrift.git/aclocal/ax_prog_haxe_version.m4 @@ -1,5 +1,5 @@ # =========================================================================== -# http://www.gnu.org/software/autoconf-archive/ax_prog_haxe_version.html +# https://www.gnu.org/software/autoconf-archive/ax_prog_haxe_version.html # =========================================================================== # # SYNOPSIS @@ -32,7 +32,7 @@ # and this notice are preserved. This file is offered as-is, without any # warranty. -#serial 1 +#serial 2 AC_DEFUN([AX_PROG_HAXE_VERSION],[ AC_REQUIRE([AC_PROG_SED]) diff --git a/vendor/git.apache.org/thrift.git/aclocal/ax_prog_perl_modules.m4 b/vendor/git.apache.org/thrift.git/aclocal/ax_prog_perl_modules.m4 index 11a326c..70b3230 100644 --- a/vendor/git.apache.org/thrift.git/aclocal/ax_prog_perl_modules.m4 +++ b/vendor/git.apache.org/thrift.git/aclocal/ax_prog_perl_modules.m4 @@ -1,5 +1,5 @@ # =========================================================================== -# http://www.gnu.org/software/autoconf-archive/ax_prog_perl_modules.html +# https://www.gnu.org/software/autoconf-archive/ax_prog_perl_modules.html # =========================================================================== # # SYNOPSIS @@ -32,7 +32,7 @@ # and this notice are preserved. This file is offered as-is, without any # warranty. -#serial 7 +#serial 8 AU_ALIAS([AC_PROG_PERL_MODULES], [AX_PROG_PERL_MODULES]) AC_DEFUN([AX_PROG_PERL_MODULES],[dnl diff --git a/vendor/git.apache.org/thrift.git/appveyor.yml b/vendor/git.apache.org/thrift.git/appveyor.yml index 03ee295..b126dc9 100755 --- a/vendor/git.apache.org/thrift.git/appveyor.yml +++ b/vendor/git.apache.org/thrift.git/appveyor.yml @@ -1,3 +1,4 @@ +# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information @@ -18,76 +19,92 @@ # build Apache Thrift on AppVeyor - https://ci.appveyor.com -shallow_clone: true -clone_depth: 10 +version: '0.12.0.{build}' + +shallow_clone: true -version: '{build}' os: -# - Windows Server 2012 R2 -- Visual Studio 2015 + - Visual Studio 2017 + +matrix: + allow_failures: + - PROFILE: CYGWIN + fast_finish: true environment: - BOOST_ROOT: C:\Libraries\boost_1_59_0 - BOOST_LIBRARYDIR: C:\Libraries\boost_1_59_0\lib64-msvc-14.0 - # Unfurtunately, this version needs manual update because old versions are quickly deleted. - ANT_VERSION: 1.9.7 + matrix: + - PROFILE: MSVC2017 + PLATFORM: x64 + CONFIGURATION: Release + BOOST_VERSION: 1.65.1 + LIBEVENT_VERSION: 2.1.8 + PYTHON_VERSION: 3.6 + QT_VERSION: 5.10 + ZLIB_VERSION: 1.2.11 + DISABLED_TESTS: StressTestNonBlocking + + - PROFILE: MSVC2013 + PLATFORM: x86 + CONFIGURATION: Release + BOOST_VERSION: 1.58.0 + LIBEVENT_VERSION: 2.0.22 + PYTHON_VERSION: 3.5 + QT_VERSION: 5.8 + ZLIB_VERSION: 1.2.8 + DISABLED_TESTS: StressTestNonBlocking + APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015 + + - PROFILE: MINGW + PLATFORM: x64 + CONFIGURATION: RelWithDebInfo + DISABLED_TESTS: StressTestNonBlocking + + - PROFILE: CYGWIN + PLATFORM: x86 + CONFIGURATION: RelWithDebInfo + DISABLED_TESTS: (ZlibTest|OpenSSLManualInitTest|TNonblockingServerTest|StressTestNonBlocking) + +# - PROFILE: CYGWIN +# PLATFORM: x64 +# CONFIGURATION: RelWithDebInfo +# DISABLED_TESTS: (ZlibTest|OpenSSLManualInitTest|TNonblockingServerTest|StressTestNonBlocking) install: -- '"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x64' -- cd \ - # Zlib -- appveyor DownloadFile https://github.com/madler/zlib/archive/v1.2.8.tar.gz -- 7z x v1.2.8.tar.gz -so | 7z x -si -ttar > nul -- cd zlib-1.2.8 -- cmake -G "Visual Studio 14 2015 Win64" . -- cmake --build . --config release -- cd .. - # OpenSSL -- C:\Python35-x64\python %APPVEYOR_BUILD_FOLDER%\build\appveyor\download_openssl.py -- ps: Start-Process "Win64OpenSSL.exe" -ArgumentList "/silent /verysilent /sp- /suppressmsgboxes" -Wait - # Libevent -- appveyor DownloadFile https://github.com/libevent/libevent/releases/download/release-2.0.22-stable/libevent-2.0.22-stable.tar.gz -- 7z x libevent-2.0.22-stable.tar.gz -so | 7z x -si -ttar > nul -- cd libevent-2.0.22-stable -- nmake -f Makefile.nmake -- mkdir lib -- move *.lib lib\ -- move WIN32-Code\event2\* include\event2\ -- move *.h include\ -- cd .. -- appveyor-retry cinst -y winflexbison -- appveyor DownloadFile http://www.us.apache.org/dist/ant/binaries/apache-ant-%ANT_VERSION%-bin.zip -- 7z x apache-ant-%ANT_VERSION%-bin.zip > nul -- cd %APPVEYOR_BUILD_FOLDER% -# TODO: Enable Haskell build -# - cinst HaskellPlatform -version 2014.2.0.0 - + - cd %APPVEYOR_BUILD_FOLDER% + - call build\appveyor\%PROFILE:~0,4%-appveyor-install.bat + - refreshenv build_script: -- set PATH=C:\ProgramData\chocolatey\bin;C:\apache-ant-%ANT_VERSION%\bin;%PATH% -- set JAVA_HOME=C:\Program Files\Java\jdk1.7.0 -- set PATH=%JAVA_HOME%\bin;%PATH% -# - set PATH=%PATH%;C:\Program Files (x86)\Haskell Platform\2014.2.0.0\bin -# - set PATH=%PATH%;C:\Program Files (x86)\Haskell Platform\2014.2.0.0\lib\extralibs\bin -- set PATH=C:\Python27-x64\scripts;C:\Python27-x64;%PATH% -- pip install ipaddress backports.ssl_match_hostname tornado twisted -- mkdir cmake-build -- cd cmake-build -- cmake -G "Visual Studio 14 2015 Win64" -DWITH_SHARED_LIB=OFF -DLIBEVENT_ROOT=C:\libevent-2.0.22-stable -DZLIB_INCLUDE_DIR=C:\zlib-1.2.8 -DZLIB_LIBRARY=C:\zlib-1.2.8\release\zlibstatic.lib -DBOOST_ROOT="%BOOST_ROOT%" -DBOOST_LIBRARYDIR="%BOOST_LIBRARYDIR%" .. -- findstr /b /e BUILD_COMPILER:BOOL=ON CMakeCache.txt -- findstr /b /e BUILD_CPP:BOOL=ON CMakeCache.txt -- findstr /b /e BUILD_JAVA:BOOL=ON CMakeCache.txt -- findstr /b /e BUILD_PYTHON:BOOL=ON CMakeCache.txt -# - findstr /b /e BUILD_C_GLIB:BOOL=ON CMakeCache.txt -# - findstr /b /e BUILD_HASKELL:BOOL=ON CMakeCache.txt -- findstr /b /e BUILD_TESTING:BOOL=ON CMakeCache.txt -# - cmake --build . -- cmake --build . --config Release -# TODO: Fix cpack -# - cpack -# TODO: Run more tests -# CTest fails to invoke ant seemingly due to "ant.bat" v.s. "ant" (shell script) conflict. -# Currently, everything that involves OpenSSL seems to hang forever on our Appveyor setup. -# Also a few C++ tests hang (on Appveyor or on Windows in general). -- ctest -C Release --timeout 600 -VV -E "(StressTestNonBlocking|PythonTestSSLSocket|python_test$|^Java)" -# TODO make it perfect ;-r + - cd %APPVEYOR_BUILD_FOLDER% + - call build\appveyor\%PROFILE:~0,4%-appveyor-build.bat + +test_script: + - cd %APPVEYOR_BUILD_FOLDER% + - call build\appveyor\%PROFILE:~0,4%-appveyor-test.bat + + +# artifact capture disabled as it might increase service cost for little gain: +# +# artifacts: +# - path: local-thrift-inst +# name: cmake installed content +# type: zip +# +# - path: local-thrift-build\Testing +# name: ctest output +# type: zip + +# RDP support: use one or the other... +# +# enables RDP for each build job so you can inspect the environment at the beginning of the job: +# init: +# - ps: iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1')) +# +# enables RDP at the end of the build job so you can login and re-run +# commands to see why something failed... +#on_finish: +# - ps: $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1')) +# +# also need: +# environment: +# APPVEYOR_RDP_PASSWORD: thr1FT2345$xyzZ diff --git a/vendor/git.apache.org/thrift.git/bootstrap.sh b/vendor/git.apache.org/thrift.git/bootstrap.sh index 52ecda4..2452eea 100755 --- a/vendor/git.apache.org/thrift.git/bootstrap.sh +++ b/vendor/git.apache.org/thrift.git/bootstrap.sh @@ -38,17 +38,24 @@ else exit 1 fi +format_version () { + printf "%03d%03d%03d%03d" $(echo $1 | tr '.' ' '); +} + # we require automake 1.13 or later # check must happen externally due to use of newer macro AUTOMAKE_VERSION=`automake --version | grep automake | egrep -o '([0-9]{1,}\.)+[0-9]{1,}'` -if [ "$AUTOMAKE_VERSION" \< "1.13" ]; then +if [ $(format_version $AUTOMAKE_VERSION) -lt $(format_version 1.13) ]; then echo >&2 "automake version $AUTOMAKE_VERSION is too old (need 1.13 or later)" exit 1 fi +set -e autoscan $LIBTOOLIZE --copy --automake aclocal -I ./aclocal autoheader +sed '/undef VERSION/d' config.hin > config.hin2 +mv config.hin2 config.hin autoconf automake --copy --add-missing --foreign diff --git a/vendor/git.apache.org/thrift.git/bower.json b/vendor/git.apache.org/thrift.git/bower.json index 9ec59fc..5f40760 100644 --- a/vendor/git.apache.org/thrift.git/bower.json +++ b/vendor/git.apache.org/thrift.git/bower.json @@ -1,6 +1,6 @@ { "name": "thrift", - "version": "0.10.0", + "version": "0.12.0", "homepage": "https://git-wip-us.apache.org/repos/asf/thrift.git", "authors": [ "Apache Thrift " diff --git a/vendor/git.apache.org/thrift.git/build/appveyor/download_openssl.py b/vendor/git.apache.org/thrift.git/build/appveyor/download_openssl.py deleted file mode 100644 index fcb72e5..0000000 --- a/vendor/git.apache.org/thrift.git/build/appveyor/download_openssl.py +++ /dev/null @@ -1,41 +0,0 @@ -import urllib.request -import sys - -OUT = 'Win64OpenSSL.exe' - -URL_STR = 'https://slproweb.com/download/Win64OpenSSL-%s.exe' - -VERSION_MAJOR = 1 -VERSION_MINOR = 0 -VERSION_PATCH = 2 -VERSION_SUFFIX = 'j' -VERSION_STR = '%d_%d_%d%s' - -TRY_COUNT = 4 - - -def main(): - for patch in range(VERSION_PATCH, TRY_COUNT): - for suffix in range(TRY_COUNT): - if patch == VERSION_PATCH: - s = VERSION_SUFFIX - else: - s = 'a' - s = chr(ord(s) + suffix) - ver = VERSION_STR % (VERSION_MAJOR, VERSION_MINOR, patch, s) - url = URL_STR % ver - try: - with urllib.request.urlopen(url) as res: - if res.getcode() == 200: - with open(OUT, 'wb') as out: - out.write(res.read()) - print('successfully downloaded from ' + url) - return 0 - except urllib.error.HTTPError: - pass - print('failed to download from ' + url, file=sys.stderr) - print('could not download openssl', file=sys.stderr) - return 1 - -if __name__ == '__main__': - sys.exit(main()) diff --git a/vendor/git.apache.org/thrift.git/build/cmake/ConfigureChecks.cmake b/vendor/git.apache.org/thrift.git/build/cmake/ConfigureChecks.cmake index f650544..457bfe0 100644 --- a/vendor/git.apache.org/thrift.git/build/cmake/ConfigureChecks.cmake +++ b/vendor/git.apache.org/thrift.git/build/cmake/ConfigureChecks.cmake @@ -17,17 +17,16 @@ # under the License. # - -include(CheckSymbolExists) +include(CheckFunctionExists) include(CheckIncludeFile) include(CheckIncludeFiles) -include(CheckFunctionExists) +include(CheckSymbolExists) -# If AI_ADDRCONFIG is not defined we define it as 0 -check_symbol_exists(AI_ADDRCONFIG "sys/types.h;sys/socket.h;netdb.h" HAVE_AI_ADDRCONFIG) -if(NOT HAVE_AI_ADDRCONFIG) -set(AI_ADDRCONFIG 1) -endif(NOT HAVE_AI_ADDRCONFIG) +if (Inttypes_FOUND) + # This allows the inttypes.h and stdint.h checks to succeed on platforms that + # do not natively provide there. + set (CMAKE_REQUIRED_INCLUDES ${INTTYPES_INCLUDE_DIRS}) +endif () check_include_file(arpa/inet.h HAVE_ARPA_INET_H) check_include_file(fcntl.h HAVE_FCNTL_H) @@ -35,18 +34,22 @@ check_include_file(getopt.h HAVE_GETOPT_H) check_include_file(inttypes.h HAVE_INTTYPES_H) check_include_file(netdb.h HAVE_NETDB_H) check_include_file(netinet/in.h HAVE_NETINET_IN_H) +check_include_file(signal.h HAVE_SIGNAL_H) check_include_file(stdint.h HAVE_STDINT_H) check_include_file(unistd.h HAVE_UNISTD_H) check_include_file(pthread.h HAVE_PTHREAD_H) -check_include_file(sys/time.h HAVE_SYS_TIME_H) +check_include_file(sys/ioctl.h HAVE_SYS_IOCTL_H) check_include_file(sys/param.h HAVE_SYS_PARAM_H) check_include_file(sys/resource.h HAVE_SYS_RESOURCE_H) check_include_file(sys/socket.h HAVE_SYS_SOCKET_H) check_include_file(sys/stat.h HAVE_SYS_STAT_H) +check_include_file(sys/time.h HAVE_SYS_TIME_H) check_include_file(sys/un.h HAVE_SYS_UN_H) +check_include_file(poll.h HAVE_POLL_H) check_include_file(sys/poll.h HAVE_SYS_POLL_H) check_include_file(sys/select.h HAVE_SYS_SELECT_H) check_include_file(sched.h HAVE_SCHED_H) +check_include_file(string.h HAVE_STRING_H) check_include_file(strings.h HAVE_STRINGS_H) check_function_exists(gethostbyname HAVE_GETHOSTBYNAME) @@ -72,5 +75,5 @@ set(VERSION ${thrift_VERSION}) # generate a config.h file configure_file("${CMAKE_CURRENT_SOURCE_DIR}/build/cmake/config.h.in" "${CMAKE_CURRENT_BINARY_DIR}/thrift/config.h") -# HACK: Some files include thrift/config.h and some config.h so we include both. This should be cleaned up. -include_directories("${CMAKE_CURRENT_BINARY_DIR}/thrift" "${CMAKE_CURRENT_BINARY_DIR}") + +include_directories("${CMAKE_CURRENT_BINARY_DIR}") diff --git a/vendor/git.apache.org/thrift.git/build/cmake/DefineCMakeDefaults.cmake b/vendor/git.apache.org/thrift.git/build/cmake/DefineCMakeDefaults.cmake index 8125de9..dc2cc29 100644 --- a/vendor/git.apache.org/thrift.git/build/cmake/DefineCMakeDefaults.cmake +++ b/vendor/git.apache.org/thrift.git/build/cmake/DefineCMakeDefaults.cmake @@ -35,7 +35,7 @@ set(CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE ON) set(CMAKE_COLOR_MAKEFILE ON) # Define the generic version of the libraries here -set(GENERIC_LIB_VERSION "0.10.0") +set(GENERIC_LIB_VERSION "0.12.0") set(GENERIC_LIB_SOVERSION "0") # Set the default build type to release with debug info @@ -68,3 +68,26 @@ set(CMAKE_MACOSX_RPATH TRUE) # locations and running the executables without LD_PRELOAD or similar. # This requires the library to be built with rpath support. set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) + +# +# C++ Language Level Defaults - this depends on the compiler capabilities +# +if (NOT DEFINED CMAKE_CXX_STANDARD) + if (MSVC AND MSVC_VERSION LESS 1800) + # MSVC 2012 and earlier don't support template aliases so you have to use C++98 + set(CMAKE_CXX_STANDARD 98) + message(STATUS "Setting C++98 as the default language level (for an older MSVC compiler).") + else() + set(CMAKE_CXX_STANDARD 11) # C++11 + message(STATUS "Setting C++11 as the default language level.") + endif() + message(STATUS "To specify a different C++ language level, set CMAKE_CXX_STANDARD") +endif() + +if (NOT DEFINED CMAKE_CXX_STANDARD_REQUIRED) + set(CMAKE_CXX_STANDARD_REQUIRED OFF) # can degrade to C++98 if compiler does not support C++11 +endif() + +if (NOT DEFINED CMAKE_CXX_EXTENSIONS) + set(CMAKE_CXX_EXTENSIONS OFF) # use standards compliant language level for portability +endif() diff --git a/vendor/git.apache.org/thrift.git/build/cmake/DefineOptions.cmake b/vendor/git.apache.org/thrift.git/build/cmake/DefineOptions.cmake index 0c853b1..f419229 100644 --- a/vendor/git.apache.org/thrift.git/build/cmake/DefineOptions.cmake +++ b/vendor/git.apache.org/thrift.git/build/cmake/DefineOptions.cmake @@ -40,7 +40,17 @@ option(BUILD_LIBRARIES "Build Thrift libraries" ON) # and enables the library if all are found. This means the default is to build as # much as possible but leaving out libraries if their dependencies are not met. -CMAKE_DEPENDENT_OPTION(WITH_BOOST_STATIC "Build with Boost static link library" OFF "NOT MSVC" ON) +option(WITH_BOOST_FUNCTIONAL "Use boost/tr1/functional.hpp even under C++11 or later" OFF) +if (WITH_BOOST_FUNCTIONAL) + add_definitions(-DFORCE_BOOST_FUNCTIONAL) +endif() + +option(WITH_BOOST_SMART_PTR "Use boost/smart_ptr.hpp even under C++11 or later" OFF) +if (WITH_BOOST_SMART_PTR) + add_definitions(-DFORCE_BOOST_SMART_PTR) +endif() + +option(WITH_BOOST_STATIC "Build with Boost static link library" OFF) set(Boost_USE_STATIC_LIBS ${WITH_BOOST_STATIC}) if (NOT WITH_BOOST_STATIC) add_definitions(-DBOOST_ALL_DYN_LINK) @@ -84,7 +94,7 @@ if(WITH_CPP) endif() CMAKE_DEPENDENT_OPTION(BUILD_CPP "Build C++ library" ON "BUILD_LIBRARIES;WITH_CPP;Boost_FOUND" OFF) -CMAKE_DEPENDENT_OPTION(WITH_PLUGIN "Build compiler plugin support" ON +CMAKE_DEPENDENT_OPTION(WITH_PLUGIN "Build compiler plugin support" OFF "BUILD_COMPILER;BUILD_CPP" OFF) # C GLib @@ -117,10 +127,10 @@ if(ANDROID) CMAKE_DEPENDENT_OPTION(BUILD_JAVA "Build Java library" ON "BUILD_LIBRARIES;WITH_JAVA;GRADLE_FOUND" OFF) else() + find_package(Gradlew QUIET) find_package(Java QUIET) - find_package(Ant QUIET) CMAKE_DEPENDENT_OPTION(BUILD_JAVA "Build Java library" ON - "BUILD_LIBRARIES;WITH_JAVA;JAVA_FOUND;ANT_FOUND" OFF) + "BUILD_LIBRARIES;WITH_JAVA;JAVA_FOUND;GRADLEW_FOUND" OFF) endif() # Python @@ -164,7 +174,6 @@ message(STATUS "Thrift package version: ${PACKAGE_VERSION} message(STATUS "Build configuration Summary") message(STATUS " Build Thrift compiler: ${BUILD_COMPILER}") message(STATUS " Build compiler plugin support: ${WITH_PLUGIN}") -MESSAGE_DEP(PLUGIN_COMPILER_NOT_TOO_OLD "Disabled due to older compiler") message(STATUS " Build with unit tests: ${BUILD_TESTING}") MESSAGE_DEP(HAVE_COMPILER "Disabled because BUILD_THRIFT=OFF and no valid THRIFT_COMPILER is given") message(STATUS " Build examples: ${BUILD_EXAMPLES}") @@ -174,6 +183,7 @@ message(STATUS " Language libraries:") message(STATUS " Build C++ library: ${BUILD_CPP}") MESSAGE_DEP(WITH_CPP "Disabled by WITH_CPP=OFF") MESSAGE_DEP(Boost_FOUND "Boost headers missing") +message(STATUS " C++ Language Level: ${CXX_LANGUAGE_LEVEL}") message(STATUS " Build C (GLib) library: ${BUILD_C_GLIB}") MESSAGE_DEP(WITH_C_GLIB "Disabled by WITH_C_GLIB=OFF") MESSAGE_DEP(GLIB_FOUND "GLib missing") @@ -183,7 +193,7 @@ if(ANDROID) MESSAGE_DEP(GRADLE_FOUND "Gradle missing") else() MESSAGE_DEP(JAVA_FOUND "Java Runtime missing") - MESSAGE_DEP(ANT_FOUND "Ant missing") + MESSAGE_DEP(GRADLEW_FOUND "Gradle Wrapper missing") endif() message(STATUS " Build Python library: ${BUILD_PYTHON}") MESSAGE_DEP(WITH_PYTHON "Disabled by WITH_PYTHON=OFF") @@ -195,16 +205,15 @@ MESSAGE_DEP(CABAL_FOUND "Cabal missing") message(STATUS " Library features:") message(STATUS " Build shared libraries: ${WITH_SHARED_LIB}") message(STATUS " Build static libraries: ${WITH_STATIC_LIB}") -message(STATUS " Build with ZLIB support: ${WITH_ZLIB}") +message(STATUS " Build with Boost static link library: ${WITH_BOOST_STATIC}") +message(STATUS " Build with Boost thread support: ${WITH_BOOSTTHREADS}") +message(STATUS " Build with boost/tr1/functional (forced) ${WITH_BOOST_FUNCTIONAL}") +message(STATUS " Build with boost/smart_ptr (forced) ${WITH_BOOST_SMART_PTR}") +message(STATUS " Build with C++ std::thread support: ${WITH_STDTHREADS}") message(STATUS " Build with libevent support: ${WITH_LIBEVENT}") +message(STATUS " Build with OpenSSL support: ${WITH_OPENSSL}") message(STATUS " Build with Qt4 support: ${WITH_QT4}") message(STATUS " Build with Qt5 support: ${WITH_QT5}") -message(STATUS " Build with OpenSSL support: ${WITH_OPENSSL}") -message(STATUS " Build with Boost thread support: ${WITH_BOOSTTHREADS}") -message(STATUS " Build with C++ std::thread support: ${WITH_STDTHREADS}") -message(STATUS " Build with Boost static link library: ${WITH_BOOST_STATIC}") -if(MSVC) - message(STATUS " - Enabled for Visual C++") -endif() +message(STATUS " Build with ZLIB support: ${WITH_ZLIB}") message(STATUS "----------------------------------------------------------") endmacro(PRINT_CONFIG_SUMMARY) diff --git a/vendor/git.apache.org/thrift.git/build/cmake/DefinePlatformSpecifc.cmake b/vendor/git.apache.org/thrift.git/build/cmake/DefinePlatformSpecifc.cmake index e57ecc2..a809c07 100644 --- a/vendor/git.apache.org/thrift.git/build/cmake/DefinePlatformSpecifc.cmake +++ b/vendor/git.apache.org/thrift.git/build/cmake/DefinePlatformSpecifc.cmake @@ -17,6 +17,8 @@ # under the License. # +# Uncomment this to show some basic cmake variables about platforms +# include (NewPlatformDebug) # Visual Studio specific options if(MSVC) @@ -59,9 +61,6 @@ if(MSVC) set(STATIC_POSTFIX "md" CACHE STRING "Set static library postfix" FORCE) endif(WITH_MT) - # Disable Windows.h definition of macros for min and max - add_definitions("-DNOMINMAX") - # Disable boost auto linking pragmas - cmake includes the right files add_definitions("-DBOOST_ALL_NO_LIB") @@ -71,12 +70,25 @@ if(MSVC) message (FATAL_ERROR "Windows build does not support shared library output yet, please set -DWITH_SHARED_LIB=off") endif() + add_definitions("/MP") # parallel build + add_definitions("/W3") # warning level 3 + + # VS2010 does not provide inttypes which we need for "PRId64" used in many places + find_package(Inttypes) + if (Inttypes_FOUND) + include_directories(${INTTYPES_INCLUDE_DIRS}) + # OpenSSL conflicts with the definition of PRId64 unless it is defined first + add_definitions("/FIinttypes.h") + endif () elseif(UNIX) find_program( MEMORYCHECK_COMMAND valgrind ) set( MEMORYCHECK_COMMAND_OPTIONS "--gen-suppressions=all --leak-check=full" ) set( MEMORYCHECK_SUPPRESSIONS_FILE "${PROJECT_SOURCE_DIR}/test/valgrind.suppress" ) endif() +add_definitions("-D__STDC_FORMAT_MACROS") +add_definitions("-D__STDC_LIMIT_MACROS") + # WITH_*THREADS selects which threading library to use if(WITH_BOOSTTHREADS) add_definitions("-DUSE_BOOST_THREAD=1") @@ -84,23 +96,34 @@ elseif(WITH_STDTHREADS) add_definitions("-DUSE_STD_THREAD=1") endif() -# GCC and Clang. -if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") - # FIXME -pedantic can not be used at the moment because of: https://issues.apache.org/jira/browse/THRIFT-2784 - #set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -O2 -Wall -Wextra -pedantic") - # FIXME enabling c++11 breaks some Linux builds on Travis by triggering a g++ bug, see - # https://travis-ci.org/apache/thrift/jobs/58017022 - # on the other hand, both MacOSX and FreeBSD need c++11 - if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin" OR ${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -O2 -Wall -Wextra") +# C++ Language Level +set(CXX_LANGUAGE_LEVEL "C++${CMAKE_CXX_STANDARD}") +if (CMAKE_CXX_STANDARD_REQUIRED) + string(CONCAT CXX_LANGUAGE_LEVEL "${CXX_LANGUAGE_LEVEL} [compiler must support it]") +else() + string(CONCAT CXX_LANGUAGE_LEVEL "${CXX_LANGUAGE_LEVEL} [fallback to earlier if compiler does not support it]") +endif() +if (CMAKE_CXX_EXTENSIONS) + string(CONCAT CXX_LANGUAGE_LEVEL "${CXX_LANGUAGE_LEVEL} [with compiler-specific extensions]") +else() + if ((CMAKE_CXX_COMPILER_ID MATCHES "GNU" OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") AND NOT MINGW) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-variadic-macros -Wno-long-long") + endif() + if ((CMAKE_CXX_COMPILER_ID MATCHES "Clang") AND NOT MINGW) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-c++11-long-long") endif() endif() -# If gcc older than 4.8 is detected, disable new compiler plug-in support (see THRIFT-3937) -set(PLUGIN_COMPILER_NOT_TOO_OLD ON) # simplifies messaging in DefineOptions summary -if (CMAKE_CXX_COMPILER_ID MATCHES "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.8" AND WITH_PLUGIN) - message(STATUS "Disabling compiler plug-in support to work with older gcc compiler") - set(WITH_PLUGIN OFF) - set(PLUGIN_COMPILER_NOT_TOO_OLD OFF) +if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-deprecated-register") +endif() + +# Building WITH_PLUGIN requires boost memory operations, for now, and gcc >= 4.8 +if (WITH_PLUGIN) + if (CMAKE_CXX_COMPILER_ID MATCHES "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.8") + message(SEND_ERROR "Thrift compiler plug-in support is not possible with older gcc ( < 4.8 ) compiler") + endif() + message(STATUS "Forcing use of boost::smart_ptr to build WITH_PLUGIN") + add_definitions("-DFORCE_BOOST_SMART_PTR=1") endif() diff --git a/vendor/git.apache.org/thrift.git/build/cmake/FindLibevent.cmake b/vendor/git.apache.org/thrift.git/build/cmake/FindLibevent.cmake index 2bcd709..ac6a078 100644 --- a/vendor/git.apache.org/thrift.git/build/cmake/FindLibevent.cmake +++ b/vendor/git.apache.org/thrift.git/build/cmake/FindLibevent.cmake @@ -13,9 +13,13 @@ foreach(prefix ${LibEvent_EXTRA_PREFIXES}) list(APPEND LibEvent_LIBRARIES_PATHS "${prefix}/lib") endforeach() -find_path(LIBEVENT_INCLUDE_DIRS event.h PATHS ${LibEvent_INCLUDE_PATHS}) -# "lib" prefix is needed on Windows -find_library(LIBEVENT_LIBRARIES NAMES event libevent PATHS ${LibEvent_LIBRARIES_PATHS}) +# Looking for "event.h" will find the Platform SDK include dir on windows +# so we also look for a peer header like evhttp.h to get the right path +find_path(LIBEVENT_INCLUDE_DIRS evhttp.h event.h PATHS ${LibEvent_INCLUDE_PATHS}) + +# "lib" prefix is needed on Windows in some cases +# newer versions of libevent use three libraries +find_library(LIBEVENT_LIBRARIES NAMES event event_core event_extra libevent PATHS ${LibEvent_LIBRARIES_PATHS}) if (LIBEVENT_LIBRARIES AND LIBEVENT_INCLUDE_DIRS) set(Libevent_FOUND TRUE) diff --git a/vendor/git.apache.org/thrift.git/build/cmake/config.h.in b/vendor/git.apache.org/thrift.git/build/cmake/config.h.in index 181ea18..39d8270 100644 --- a/vendor/git.apache.org/thrift.git/build/cmake/config.h.in +++ b/vendor/git.apache.org/thrift.git/build/cmake/config.h.in @@ -44,9 +44,6 @@ /* Define to the full name and version of this package. */ #define PACKAGE_STRING "${PACKAGE_STRING}" -/* Version number of package */ -#define VERSION "${VERSION}" - /************************** DEFINES *************************/ /* Define if the AI_ADDRCONFIG symbol is unavailable */ @@ -94,6 +91,9 @@ /* Define to 1 if you have the header file. */ #cmakedefine HAVE_NETINET_IN_H 1 +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SIGNAL_H 1 + /* Define to 1 if you have the header file. */ #cmakedefine HAVE_STDINT_H 1 @@ -103,8 +103,8 @@ /* Define to 1 if you have the header file. */ #cmakedefine HAVE_PTHREAD_H 1 -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_SYS_TIME_H 1 +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_IOCTL_H 1 /* Define to 1 if you have the header file. */ #cmakedefine HAVE_SYS_PARAM_H 1 @@ -121,12 +121,18 @@ /* Define to 1 if you have the header file. */ #cmakedefine HAVE_SYS_UN_H 1 +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_POLL_H 1 + /* Define to 1 if you have the header file. */ #cmakedefine HAVE_SYS_POLL_H 1 /* Define to 1 if you have the header file. */ #cmakedefine HAVE_SYS_SELECT_H 1 +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_TIME_H 1 + /* Define to 1 if you have the header file. */ #cmakedefine HAVE_SCHED_H 1 @@ -154,4 +160,4 @@ /* Define to 1 if strerror_r returns char *. */ #cmakedefine STRERROR_R_CHAR_P 1 -#endif \ No newline at end of file +#endif diff --git a/vendor/git.apache.org/thrift.git/build/docker/README.md b/vendor/git.apache.org/thrift.git/build/docker/README.md index 85cb3b2..d0a8388 100644 --- a/vendor/git.apache.org/thrift.git/build/docker/README.md +++ b/vendor/git.apache.org/thrift.git/build/docker/README.md @@ -1,27 +1,198 @@ -# Apache Thrift Docker containers -A set of docker containers used to build and test Apache Thrift +# Docker Integration # -### Available Containers +Due to the large number of languages supported by Apache Thrift, +docker containers are used to build and test the project on a +variety of platforms to provide maximum test coverage. -* Ubuntu - based on ubuntu:trusty (14.04) -* Centos - based on centos:6.6 +## Appveyor Integration ## -## Dependencies +At this time the Appveyor scripts do not use docker containers. +Once Microsoft supports Visual Studio Build Tools running inside +nano containers (instead of Core, which is huge) then we will +consider using containers for the Windows builds as well. -* A working Docker environment. A Vagrantfile is provided which will setup an Ubuntu host and working Docker environment as well as build the Apache Thrift Docker container for testing and development +## Travis CI Integration ## -## Usage -From the Apache Thrift code base root +The Travis CI scripts use the following environment variables and +logic to determine their behavior: -* Build +### Environment Variables ### - docker build -t thrift build/docker/ubuntu +| Variable | Default | Usage | +| -------- | ----- | ------- | +| `DISTRO` | `ubuntu-bionic` | Set by various build jobs in `.travis.yml` to run builds in different containers. Not intended to be set externally.| +| `DOCKER_REPO` | `thrift/thrift-build` | The name of the Docker Hub repository to obtain and store docker images. | +| `DOCKER_USER` | `` | The Docker Hub account name containing the repository. | +| `DOCKER_PASS` | `` | The Docker Hub account password to use when pushing new tags. | - or +For example, the default docker image that is used in builds if no overrides are specified would be: `thrift/thrift-build:ubuntu-bionic` - docker build -t thrift build/docker/centos +### Forks ### -* Run +If you have forked the Apache Thrift repository and you would like +to use your own Docker Hub account to store thrift build images, +you can use the Travis CI web interface to set the `DOCKER_USER`, +`DOCKER_PASS`, and `DOCKER_REPO` variables in a secure manner. +Your fork builds will then pull, push, and tag the docker images +in your account. - docker run -v $(pwd):/thrift/src -it thrift /bin/bash +### Logic ### +The Travis CI build runs in two phases - first the docker images are rebuilt +for each of the supported containers if they do not match the Dockerfile that +was used to build the most recent tag. If a `DOCKER_PASS` environment +variable is specified, the docker stage builds will attempt to log into +Docker Hub and push the resulting tags. + +## Supported Containers ## + +The Travis CI (continuous integration) builds use the Ubuntu Bionic +(18.04 LTS) and Xenial (16.04 LTS) images to maximize language level +coverage. + +### Ubuntu ### + +* bionic (stable, current) +* artful (previous stable) +* xenial (legacy) + +## Unsupported Containers ## + +These containers may be in various states, and may not build everything. +They can be found in the `old/` subdirectory. + +### CentOS ### +* 7.3 + * make check in lib/py may hang in test_sslsocket - root cause unknown + +### Debian ### + +* jessie +* stretch + * make check in lib/cpp fails due to https://svn.boost.org/trac10/ticket/12507 + +## Building like Travis CI does, locally ## + +We recommend you build locally the same way Travis CI does, so that when you +submit your pull request you will run into fewer surprises. To make it a +little easier, put the following into your `~/.bash_aliases` file: + + # Kill all running containers. + alias dockerkillall='docker kill $(docker ps -q)' + + # Delete all stopped containers. + alias dockercleanc='printf "\n>>> Deleting stopped containers\n\n" && docker rm $(docker ps -a -q)' + + # Delete all untagged images. + alias dockercleani='printf "\n>>> Deleting untagged images\n\n" && docker rmi $(docker images -q -f dangling=true)' + + # Delete all stopped containers and untagged images. + alias dockerclean='dockercleanc || true && dockercleani' + + # Build a thrift docker image (run from top level of git repo): argument #1 is image type (ubuntu, centos, etc). + function dockerbuild + { + docker build -t $1 build/docker/$1 + } + + # Run a thrift docker image: argument #1 is image type (ubuntu, centos, etc). + function dockerrun + { + docker run -v $(pwd):/thrift/src -it $1 /bin/bash + } + +Then, to pull down the current image being used to build (the same way +Travis CI does it) - if it is out of date in any way it will build a +new one for you: + + thrift$ DOCKER_REPO=thrift/thrift-build DISTRO=ubuntu-bionic build/docker/refresh.sh + +To run all unit tests (just like Travis CI does): + + thrift$ dockerrun ubuntu-bionic + root@8caf56b0ce7b:/thrift/src# build/docker/scripts/autotools.sh + +To run the cross tests (just like Travis CI does): + + thrift$ dockerrun ubuntu-bionic + root@8caf56b0ce7b:/thrift/src# build/docker/scripts/cross-test.sh + +When you are done, you want to clean up occasionally so that docker isn't using lots of extra disk space: + + thrift$ dockerclean + +You need to run the docker commands from the root of the local clone of the +thrift git repository for them to work. + +When you are done in the root docker shell you can `exit` to go back to +your user host shell. Once the unit tests and cross test passes locally, +submit the changes, and if desired squash the pull request to one commit +to make it easier to merge (the committers can squash at commit time now +that GitHub is the master repository). Now you are building like Travis CI does! + +## Raw Commands for Building with Docker ## + +If you do not want to use the same scripts Travis CI does, you can do it manually: + +Build the image: + + thrift$ docker build -t thrift build/docker/ubuntu-bionic + +Open a command prompt in the image: + + thrift$ docker run -v $(pwd):/thrift/src -it thrift /bin/bash + +## Core Tool Versions per Dockerfile ## + +Last updated: October 1, 2017 + +| Tool | ubuntu-xenial | ubuntu-bionic | Notes | +| :-------- | :------------ | :------------ | :---- | +| ant | 1.9.6 | 1.10.3 | | +| autoconf | 2.69 | 2.69 | | +| automake | 1.15 | 1.15.1 | | +| bison | 3.0.4 | 3.0.4 | | +| boost | 1.58.0 | 1.65.1 | | +| cmake | 3.5.1 | 3.10.2 | | +| cppcheck | 1.72 | 1.82 | | +| flex | 2.6.0 | 2.6.4 | | +| libc6 | 2.23 | 2.27 | glibc | +| libevent | 2.0.21 | 2.1.8 | | +| libstdc++ | 5.4.0 | 7.3.0 | | +| make | 4.1 | 4.1 | | +| openssl | 1.0.2g | 1.1.0g | | +| qt5 | 5.5.1 | 5.9.5 | | + +## Compiler/Language Versions per Dockerfile ## + +| Language | ubuntu-xenial | ubuntu-bionic | Notes | +| :-------- | :------------ | :------------ | :---- | +| as of | Mar 06, 2018 | Jul 6, 2018 | | +| as3 | | | Not in CI | +| C++ gcc | 5.4.0 | 7.3.0 | | +| C++ clang | 3.8 | 6.0 | | +| C# (mono) | 4.2.1.0 | 4.6.2.7 | | +| c_glib | 2.48.2 | 2.56.0 | | +| cl (sbcl) | | 1.4.9 | | +| cocoa | | | Not in CI | +| d | 2.075.1 | 2.081.0 | | +| dart | 1.22.1 | 1.24.3 | | +| delphi | | | Not in CI | +| dotnet | 2.1.4 | 2.1.301 | | +| erlang | 18.3 | 20.2.2 | | +| go | 1.7.6 | 1.10.3 | | +| haskell | 7.10.3 | 8.0.2 | | +| haxe | 3.2.1 | 3.4.4 | THRIFT-4352: avoid 3.4.2 | +| java | 1.8.0_151 | 1.8.0_171 | | +| js | | | Unsure how to look for version info? | +| lua | 5.2.4 | 5.2.4 | Lua 5.3: see THRIFT-4386 | +| nodejs | 6.13.0 | 8.11.3 | | +| ocaml | | 4.05.0 | THRIFT-4517: ocaml 4.02.3 on xenial appears broken | +| perl | 5.22.1 | 5.26.1 | | +| php | 7.0.22 | 7.2.5 | | +| python | 2.7.12 | 2.7.15rc1 | | +| python3 | 3.5.2 | 3.6.5 | | +| ruby | 2.3.1p112 | 2.5.1p57 | | +| rust | 1.17.0 | 1.24.1 | | +| smalltalk | | | Not in CI | +| swift | | | Not in CI | diff --git a/vendor/git.apache.org/thrift.git/build/docker/Vagrantfile b/vendor/git.apache.org/thrift.git/build/docker/Vagrantfile deleted file mode 100644 index 5eac6e6..0000000 --- a/vendor/git.apache.org/thrift.git/build/docker/Vagrantfile +++ /dev/null @@ -1,59 +0,0 @@ -# -*- mode: ruby -*- -# vi: set ft=ruby : -# -# 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. - -# Base system bootstrap script -$bootstrap_script = <<__BOOTSTRAP__ -echo "Provisioning defaults" - -sudo apt-get update -y -sudo apt-get upgrade -y - -# Install default packages -sudo apt-get install -y build-essential curl git - -# Install latest Docker version -sudo curl -sSL https://get.docker.io/gpg | sudo apt-key add - -sudo echo "deb http://get.docker.io/ubuntu docker main" > /etc/apt/sources.list.d/docker.list -sudo apt-get update -y -sudo apt-get install -y linux-image-extra-`uname -r` aufs-tools -sudo apt-get install -y lxc-docker - -echo "Finished provisioning defaults" -__BOOTSTRAP__ - -Vagrant.configure("2") do |config| - config.vm.box = "trusty64" - config.vm.box_url = "https://cloud-images.ubuntu.com/vagrant/trusty/current/trusty-server-cloudimg-amd64-vagrant-disk1.box" - config.ssh.forward_agent = true - - config.vm.provider :virtualbox do |vbox| - vbox.customize ["modifyvm", :id, "--memory", "1024"] - vbox.customize ["modifyvm", :id, "--cpus", "2"] - end - - # Setup the default bootstrap script for our ubuntu base box image - config.vm.provision "shell", inline: $bootstrap_script - - # Setup the custom docker image from our Ubuntu Dockerfile - config.vm.provision "docker" do |d| - d.build_image "/vagrant/ubuntu", args: "-t thrift" - end - - # Setup the custom docker image from our Centos Dockerfile - #config.vm.provision "docker" do |d| - # d.build_image "/vagrant/centos", args: "-t thrift-centos" - #end - -end diff --git a/vendor/git.apache.org/thrift.git/build/docker/centos/Dockerfile b/vendor/git.apache.org/thrift.git/build/docker/centos/Dockerfile deleted file mode 100644 index 59bbfd6..0000000 --- a/vendor/git.apache.org/thrift.git/build/docker/centos/Dockerfile +++ /dev/null @@ -1,142 +0,0 @@ -# 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. - -# Apache Thrift Docker build environment for Centos -# -# Known missing client libraries: -# - D -# - Haxe -# - Lua -# - -FROM centos:7 -MAINTAINER Apache Thrift - -RUN yum install -y epel-release - -# General dependencies -RUN yum install -y \ - tar \ - m4 \ - perl \ - clang \ - gcc \ - gcc-c++ \ - git \ - libtool \ - autoconf \ - make \ - bison \ - bison-devel \ - flex - -# C++ dependencies -RUN yum install -y \ - boost-devel-static \ - zlib-devel \ - openssl-devel \ - libevent-devel - -# Java Dependencies -RUN yum install -y \ - ant \ - junit \ - ant-junit \ - java-1.7.0-openjdk-devel - -# Python Dependencies -RUN yum install -y \ - python-devel \ - python-pip \ - python-setuptools \ - python-six \ - python-twisted-web && \ - pip install -U backports.ssl_match_hostname ipaddress tornado - -# Ruby Dependencies -RUN yum install -y \ - ruby \ - ruby-devel \ - rubygems && \ - gem install bundler rake - -# Perl Dependencies -RUN yum install -y \ - perl-Bit-Vector \ - perl-Class-Accessor \ - perl-ExtUtils-MakeMaker \ - perl-Test-Simple \ - perl-IO-Socket-SSL \ - perl-Net-SSLeay \ - perl-Crypt-SSLeay - -# PHP Dependencies -RUN yum install -y \ - php \ - php-devel \ - php-pear \ - re2c \ - php-phpunit-PHPUnit \ - bzip2 - -# GLibC Dependencies -RUN yum install -y glib2-devel - -# Erlang Dependencies -RUN curl -sSL http://packages.erlang-solutions.com/rpm/centos/erlang_solutions.repo -o /etc/yum.repos.d/erlang_solutions.repo && \ - yum install -y \ - erlang-kernel \ - erlang-erts \ - erlang-stdlib \ - erlang-eunit \ - erlang-rebar \ - erlang-tools - -# Go Dependencies -RUN curl -sSL https://storage.googleapis.com/golang/go1.4.3.linux-amd64.tar.gz | tar -C /usr/local/ -xz -ENV PATH /usr/local/go/bin:$PATH - -# Haskell Dependencies -RUN yum -y install haskell-platform - -# Node.js Dependencies -RUN yum install -y \ - nodejs \ - nodejs-devel \ - npm - -# C# Dependencies -RUN yum install -y \ - mono-core \ - mono-devel \ - mono-web-devel \ - mono-extras \ - -# MinGW Dependencies -RUN yum install -y \ - mingw32-binutils \ - mingw32-crt \ - mingw32-nsis - -# CMake -RUN curl -sSL https://cmake.org/files/v3.4/cmake-3.4.0.tar.gz | tar -xz && \ - cd cmake-3.4.0 && ./bootstrap && make -j4 && make install && \ - cd .. && rm -rf cmake-3.4.0 - -# Clean up -RUN rm -rf /tmp/* && \ - yum clean all - -ENV THRIFT_ROOT /thrift -RUN mkdir -p $THRIFT_ROOT/src -COPY Dockerfile $THRIFT_ROOT/ -WORKDIR $THRIFT_ROOT/src diff --git a/vendor/git.apache.org/thrift.git/build/docker/centos6/Dockerfile b/vendor/git.apache.org/thrift.git/build/docker/centos6/Dockerfile deleted file mode 100644 index aa19731..0000000 --- a/vendor/git.apache.org/thrift.git/build/docker/centos6/Dockerfile +++ /dev/null @@ -1,54 +0,0 @@ -# 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. - -# Apache Thrift Docker build environment for Centos 6 -# -# This file is intended for testing old packages that are not available for -# latest Ubuntu LTS/Debian/CentOS. Currently, it is only used for Python 2.6. -# - -FROM centos:6 -MAINTAINER Apache Thrift - -RUN yum install -y epel-release && \ - yum install -y \ - autoconf \ - bison \ - bison-devel \ - clang \ - flex \ - gcc \ - gcc-c++ \ - git \ - libtool \ - m4 \ - make \ - perl \ - tar \ - python-devel \ - python-setuptools \ - python-twisted-web \ - python-pip \ - && yum clean all - -# optional dependencies -RUN pip install ipaddress backports.ssl_match_hostname tornado - -# CMake -RUN curl -sSL https://cmake.org/files/v3.4/cmake-3.4.1.tar.gz | tar -xz && \ - cd cmake-3.4.1 && ./bootstrap && make -j4 && make install && \ - cd .. && rm -rf cmake-3.4.1 - -ENV THRIFT_ROOT /thrift -RUN mkdir -p $THRIFT_ROOT/src -COPY Dockerfile $THRIFT_ROOT/ -WORKDIR $THRIFT_ROOT/src diff --git a/vendor/git.apache.org/thrift.git/build/docker/debian/Dockerfile b/vendor/git.apache.org/thrift.git/build/docker/debian/Dockerfile deleted file mode 100644 index 29b7804..0000000 --- a/vendor/git.apache.org/thrift.git/build/docker/debian/Dockerfile +++ /dev/null @@ -1,192 +0,0 @@ -# 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. - -# Apache Thrift Docker build environment for Centos -# -# Known missing client libraries: -# - None - -FROM buildpack-deps:jessie-scm -MAINTAINER Apache Thrift - -ENV DEBIAN_FRONTEND noninteractive - -# Add apt sources -# Dart -RUN curl https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - && \ - curl https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_stable.list > /etc/apt/sources.list.d/dart_stable.list && \ - sed -i /etc/apt/sources.list.d/dart_stable.list -e 's/https:/http:/g' - -RUN apt-get update && apt-get install -y --no-install-recommends \ -`# General dependencies` \ - bison \ - build-essential \ - clang \ - cmake \ - debhelper \ - flex \ - pkg-config - -RUN apt-get update && apt-get install -y --no-install-recommends \ -`# C++ dependencies` \ - libboost-dev \ - libboost-filesystem-dev \ - libboost-program-options-dev \ - libboost-system-dev \ - libboost-test-dev \ - libboost-thread-dev \ - libevent-dev \ - libssl-dev \ - qt5-default \ - qtbase5-dev \ - qtbase5-dev-tools - -RUN apt-get update && apt-get install -y --no-install-recommends \ -`# Java dependencies` \ - ant \ - ant-optional \ - openjdk-7-jdk \ - maven - -RUN apt-get update && apt-get install -y --no-install-recommends \ -`# Python dependencies` \ - python-all \ - python-all-dbg \ - python-all-dev \ - python-pip \ - python-setuptools \ - python-twisted \ - python-zope.interface \ - python3-all \ - python3-all-dbg \ - python3-all-dev \ - python3-setuptools \ - python3-pip - -RUN echo 'deb http://deb.debian.org/debian jessie-backports main' >> /etc/apt/sources.list \ - && apt-get update && apt-get install -y --no-install-recommends \ -`# Ruby dependencies` \ - ruby \ - ruby-bundler \ - ruby-dev \ -`# Perl dependencies` \ - libbit-vector-perl \ - libclass-accessor-class-perl \ - libcrypt-ssleay-perl \ - libio-socket-ssl-perl \ - libnet-ssleay-perl - -RUN apt-get update && apt-get install -y --no-install-recommends \ -`# Php dependencies` \ - php5 \ - php5-dev \ - php5-cli \ - php-pear \ - re2c \ - phpunit \ -`# GlibC dependencies` \ - libglib2.0-dev - -RUN apt-get update && apt-get install -y --no-install-recommends \ -`# Erlang dependencies` \ - erlang-base \ - erlang-eunit \ - erlang-dev \ - erlang-tools \ - rebar - -RUN apt-get update && apt-get install -y --no-install-recommends \ -`# Haskell dependencies` \ - ghc \ - cabal-install \ -`# Haxe dependencies` \ - neko \ - neko-dev \ - libneko0 - -RUN apt-get update && apt-get install -y --no-install-recommends \ -`# Node.js dependencies` \ - nodejs \ - nodejs-dev \ - nodejs-legacy \ - npm - -RUN apt-get update && apt-get install -y --no-install-recommends \ -`# CSharp dependencies` \ - libmono-system-web2.0-cil \ - mono-devel - -RUN apt-get update && apt-get install -y --no-install-recommends \ -`# D dependencies` \ - xdg-utils \ -`# Dart dependencies` \ - dart \ -`# Lua dependencies` \ - lua5.2 \ - lua5.2-dev \ -`# MinGW dependencies` \ - mingw32 \ - mingw32-binutils \ -`# mingw32-runtime` \ - nsis \ -`# Clean up` \ - && rm -rf /var/cache/apt/* && \ - rm -rf /var/lib/apt/lists/* && \ - rm -rf /tmp/* && \ - rm -rf /var/tmp/* - -# Ruby -RUN gem install bundler --no-ri --no-rdoc - -# Python optional dependencies -RUN pip2 install -U ipaddress backports.ssl_match_hostname tornado -RUN pip3 install -U backports.ssl_match_hostname tornado - -# Go -RUN curl -sSL https://storage.googleapis.com/golang/go1.4.3.linux-amd64.tar.gz | tar -C /usr/local/ -xz -ENV PATH /usr/local/go/bin:$PATH - -# Haxe -RUN mkdir -p /usr/lib/haxe && \ - curl http://haxe.org/website-content/downloads/3.2.0/downloads/haxe-3.2.0-linux64.tar.gz | \ - tar -C /usr/lib/haxe --strip-components=1 -xz && \ - ln -s /usr/lib/haxe/haxe /usr/bin/haxe && \ - ln -s /usr/lib/haxe/haxelib /usr/bin/haxelib && \ - mkdir -p /usr/lib/haxe/lib && \ - chmod -R 777 /usr/lib/haxe/lib && \ - haxelib setup /usr/lib/haxe/lib && \ - haxelib install hxcpp - -# D -RUN curl -sSL http://downloads.dlang.org/releases/2.x/2.070.0/dmd_2.070.0-0_amd64.deb -o /tmp/dmd_2.070.0-0_amd64.deb && \ - dpkg -i /tmp/dmd_2.070.0-0_amd64.deb && \ - rm /tmp/dmd_2.070.0-0_amd64.deb && \ - curl -sSL https://github.com/D-Programming-Deimos/openssl/archive/master.tar.gz| tar xz && \ - curl -sSL https://github.com/D-Programming-Deimos/libevent/archive/master.tar.gz| tar xz && \ - mkdir -p /usr/include/dmd/druntime/import/deimos /usr/include/dmd/druntime/import/C && \ - mv libevent-master/deimos/* openssl-master/deimos/* /usr/include/dmd/druntime/import/deimos/ && \ - mv libevent-master/C/* openssl-master/C/* /usr/include/dmd/druntime/import/C/ && \ - rm -rf libevent-master openssl-master && \ - echo 'gcc -Wl,--no-as-needed $*' > /usr/local/bin/gcc-dmd && \ - chmod 755 /usr/local/bin/gcc-dmd && \ - echo 'CC=/usr/local/bin/gcc-dmd' >> /etc/dmd.conf - -# Dart -ENV PATH /usr/lib/dart/bin:$PATH - -# Force utf8 locale to successfully build Haskell tf-random -ENV LC_ALL C.UTF-8 - -ENV THRIFT_ROOT /thrift -RUN mkdir -p $THRIFT_ROOT/src -COPY Dockerfile $THRIFT_ROOT/ -WORKDIR $THRIFT_ROOT/src diff --git a/vendor/git.apache.org/thrift.git/build/docker/scripts/cmake.sh b/vendor/git.apache.org/thrift.git/build/docker/scripts/cmake.sh index 6508e71..ccc311e 100755 --- a/vendor/git.apache.org/thrift.git/build/docker/scripts/cmake.sh +++ b/vendor/git.apache.org/thrift.git/build/docker/scripts/cmake.sh @@ -19,5 +19,5 @@ for LIB in $BUILD_LIBS; do done $MAKEPROG -j3 cpack -ctest -VV -# was: -E "(concurrency_test|processor_test)" +ctest -VV -E "(python_test)" +# disabled cmake python_test for now since it fails in travis under centos diff --git a/vendor/git.apache.org/thrift.git/build/docker/ubuntu/Dockerfile b/vendor/git.apache.org/thrift.git/build/docker/ubuntu/Dockerfile deleted file mode 100644 index 7d245e8..0000000 --- a/vendor/git.apache.org/thrift.git/build/docker/ubuntu/Dockerfile +++ /dev/null @@ -1,209 +0,0 @@ -# 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. - -# Apache Thrift Docker build environment for Centos -# -# Known missing client libraries: -# - None - -FROM buildpack-deps:trusty-scm -MAINTAINER Apache Thrift - -ENV DEBIAN_FRONTEND noninteractive - -# Add apt sources -# Erlang -RUN echo 'deb http://packages.erlang-solutions.com/debian trusty contrib' > /etc/apt/sources.list.d/erlang_solutions.list && \ - curl -sSL https://packages.erlang-solutions.com/debian/erlang_solutions.asc | apt-key add - -# Dart -RUN curl https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - && \ - curl https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_stable.list > /etc/apt/sources.list.d/dart_stable.list && \ - sed -i /etc/apt/sources.list.d/dart_stable.list -e 's/https:/http:/g' - -# Consider using mirror nearby when building locally -# TODO: Provide option via --build-arg=... -# RUN sed -i /etc/apt/sources.list -e 's!http://archive.ubuntu.com/ubuntu/!http://your/mirror/!g' - -RUN apt-get update && apt-get install -y --no-install-recommends \ -`# General dependencies` \ - bison \ - build-essential \ - clang \ - cmake \ - debhelper \ - flex \ - ninja-build \ - pkg-config \ -`# Included in buildpack-deps` \ -`# autoconf` \ -`# automake` \ -`# g++` \ -`# git` \ -`# libtool` \ -`# make` - -RUN apt-get update && apt-get install -y --no-install-recommends \ -`# C++ dependencies` \ -`# libevent and OpenSSL are needed by D too` \ - libboost-dev \ - libboost-filesystem-dev \ - libboost-program-options-dev \ - libboost-system-dev \ - libboost-test-dev \ - libboost-thread-dev \ - libevent-dev \ - libssl-dev \ - qt5-default \ - qtbase5-dev \ - qtbase5-dev-tools - -RUN apt-get update && apt-get install -y --no-install-recommends \ -`# Java dependencies` \ - ant \ - ant-optional \ - openjdk-7-jdk \ - maven - -RUN apt-get update && apt-get install -y --no-install-recommends \ -`# Python dependencies` \ -`# TODO:` \ -`# Install twisted and zope.interface via pip. we need twisted at ./configure time, otherwise` \ -`# py.twisted tests are skipped.` \ - python-all \ - python-all-dbg \ - python-all-dev \ - python-pip \ - python-setuptools \ - python-twisted \ - python-zope.interface \ - python3-all \ - python3-all-dbg \ - python3-all-dev \ - python3-setuptools \ - python3-pip - -RUN apt-get update && apt-get install -y --no-install-recommends \ -`# Ruby dependencies` \ - ruby \ - ruby-bundler \ - ruby-dev \ -`# Perl dependencies` \ - libbit-vector-perl \ - libclass-accessor-class-perl \ - libcrypt-ssleay-perl \ - libio-socket-ssl-perl \ - libnet-ssleay-perl - -RUN apt-get update && apt-get install -y --no-install-recommends \ -`# Php dependencies` \ - php5 \ - php5-dev \ - php5-cli \ - php-pear \ - re2c \ - phpunit \ -`# GlibC dependencies` \ - libglib2.0-dev - -RUN apt-get update && apt-get install -y --no-install-recommends \ -`# Erlang dependencies` \ - erlang-base \ - erlang-eunit \ - erlang-dev \ - erlang-tools \ - rebar - -RUN apt-get update && apt-get install -y --no-install-recommends \ -`# Haskell dependencies` \ - ghc \ - cabal-install \ -`# Haxe dependencies` \ - neko \ - neko-dev \ - libneko0 - -RUN apt-get update && apt-get install -y --no-install-recommends \ -`# Node.js dependencies` \ - nodejs \ - nodejs-dev \ - nodejs-legacy - -RUN apt-get update && apt-get install -y --no-install-recommends \ -`# CSharp dependencies` \ - libmono-system-web2.0-cil \ - mono-devel - -RUN apt-get update && apt-get install -y --no-install-recommends \ -`# D dependencies` \ - xdg-utils \ -`# Dart dependencies` \ - dart \ -`# Lua dependencies` \ - lua5.2 \ - lua5.2-dev \ -`# MinGW dependencies` \ - mingw32 \ - mingw32-binutils \ - mingw32-runtime \ - nsis \ -`# Clean up` \ - && rm -rf /var/cache/apt/* && \ - rm -rf /var/lib/apt/lists/* && \ - rm -rf /tmp/* && \ - rm -rf /var/tmp/* - -# Ruby -RUN gem install bundler --no-ri --no-rdoc - -# Python optional dependencies -RUN pip2 install -U ipaddress backports.ssl_match_hostname tornado -RUN pip3 install -U backports.ssl_match_hostname tornado - -# Go -RUN curl -sSL https://storage.googleapis.com/golang/go1.4.3.linux-amd64.tar.gz | tar -C /usr/local/ -xz -ENV PATH /usr/local/go/bin:$PATH - -# Haxe -RUN mkdir -p /usr/lib/haxe && \ - curl http://haxe.org/website-content/downloads/3.2.0/downloads/haxe-3.2.0-linux64.tar.gz | \ - tar -C /usr/lib/haxe --strip-components=1 -xz && \ - ln -s /usr/lib/haxe/haxe /usr/bin/haxe && \ - ln -s /usr/lib/haxe/haxelib /usr/bin/haxelib && \ - mkdir -p /usr/lib/haxe/lib && \ - chmod -R 777 /usr/lib/haxe/lib && \ - haxelib setup /usr/lib/haxe/lib && \ - haxelib install hxcpp - -# Node.js -RUN curl -sSL https://www.npmjs.com/install.sh | sh - -# D -RUN curl -sSL http://downloads.dlang.org/releases/2.x/2.070.0/dmd_2.070.0-0_amd64.deb -o /tmp/dmd_2.070.0-0_amd64.deb && \ - dpkg -i /tmp/dmd_2.070.0-0_amd64.deb && \ - rm /tmp/dmd_2.070.0-0_amd64.deb && \ - curl -sSL https://github.com/D-Programming-Deimos/openssl/archive/master.tar.gz| tar xz && \ - curl -sSL https://github.com/D-Programming-Deimos/libevent/archive/master.tar.gz| tar xz && \ - mkdir -p /usr/include/dmd/druntime/import/deimos /usr/include/dmd/druntime/import/C && \ - mv libevent-master/deimos/* openssl-master/deimos/* /usr/include/dmd/druntime/import/deimos/ && \ - mv libevent-master/C/* openssl-master/C/* /usr/include/dmd/druntime/import/C/ && \ - rm -rf libevent-master openssl-master && \ - echo 'gcc -Wl,--no-as-needed $*' > /usr/local/bin/gcc-dmd && \ - chmod 755 /usr/local/bin/gcc-dmd && \ - echo 'CC=/usr/local/bin/gcc-dmd' >> /etc/dmd.conf - -# Dart -ENV PATH /usr/lib/dart/bin:$PATH - -ENV THRIFT_ROOT /thrift -RUN mkdir -p $THRIFT_ROOT/src -COPY Dockerfile $THRIFT_ROOT/ -WORKDIR $THRIFT_ROOT/src diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/CMakeLists.txt b/vendor/git.apache.org/thrift.git/compiler/cpp/CMakeLists.txt index 02ed78c..0df790e 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/CMakeLists.txt +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/CMakeLists.txt @@ -16,30 +16,37 @@ # specific language governing permissions and limitations # under the License. # +cmake_minimum_required(VERSION 2.8.12) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/src/thrift/version.h.in ${CMAKE_CURRENT_BINARY_DIR}/thrift/version.h) +if(MSVC) + # The winflexbison generator outputs some macros that conflict with the Visual Studio 2010 copy of stdint.h + # This might be fixed in later versions of Visual Studio, but an easy solution is to include stdint.h first + if(HAVE_STDINT_H) + add_definitions(-D__STDC_FORMAT_MACROS) + add_definitions(-D__STDC_LIMIT_MACROS) + add_definitions(/FI"stdint.h") + endif(HAVE_STDINT_H) +endif() find_package(FLEX REQUIRED) find_package(BISON REQUIRED) +# create directory for thrifty and thriftl +file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/thrift/) + # Create flex and bison files and build the lib parse static library BISON_TARGET(thrifty ${CMAKE_CURRENT_SOURCE_DIR}/src/thrift/thrifty.yy ${CMAKE_CURRENT_BINARY_DIR}/thrift/thrifty.cc) FLEX_TARGET(thriftl ${CMAKE_CURRENT_SOURCE_DIR}/src/thrift/thriftl.ll ${CMAKE_CURRENT_BINARY_DIR}/thrift/thriftl.cc) ADD_FLEX_BISON_DEPENDENCY(thriftl thrifty) -# HACK: Work around the fact that bison crates a .hh file but we need a .h file -add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/thrift/thrifty.h - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/thrift/thrifty.hh ${CMAKE_CURRENT_BINARY_DIR}/thrift/thrifty.h - DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/thrift/thrifty.hh - ) - -set(libparse_SOURCES +set(parse_SOURCES ${CMAKE_CURRENT_BINARY_DIR}/thrift/thrifty.cc ${CMAKE_CURRENT_BINARY_DIR}/thrift/thriftl.cc - ${CMAKE_CURRENT_BINARY_DIR}/thrift/thrifty.h + ${CMAKE_CURRENT_BINARY_DIR}/thrift/thrifty.hh ) -add_library(libparse STATIC ${libparse_SOURCES}) +add_library(parse STATIC ${parse_SOURCES}) # Create the thrift compiler set(compiler_core @@ -55,6 +62,9 @@ set(thrift-compiler_SOURCES src/thrift/audit/t_audit.cpp ) +set(thrift_compiler_LANGS +) + # This macro adds an option THRIFT_COMPILER_${NAME} # that allows enabling or disabling certain languages macro(THRIFT_ADD_COMPILER name description initial) @@ -63,6 +73,7 @@ macro(THRIFT_ADD_COMPILER name description initial) option(${enabler} ${description} ${initial}) if(${enabler}) list(APPEND thrift-compiler_SOURCES ${src}) + list(APPEND thrift_compiler_LANGS ${name}) endif() endmacro() @@ -74,6 +85,7 @@ THRIFT_ADD_COMPILER(as3 "Enable compiler for ActionScript 3" ON) THRIFT_ADD_COMPILER(dart "Enable compiler for Dart" ON) THRIFT_ADD_COMPILER(haxe "Enable compiler for Haxe" ON) THRIFT_ADD_COMPILER(csharp "Enable compiler for C#" ON) +THRIFT_ADD_COMPILER(netcore "Enable compiler for .NET Core" ON) THRIFT_ADD_COMPILER(py "Enable compiler for Python 2.0" ON) THRIFT_ADD_COMPILER(rb "Enable compiler for Ruby" ON) THRIFT_ADD_COMPILER(perl "Enable compiler for Perl" ON) @@ -94,15 +106,17 @@ THRIFT_ADD_COMPILER(go "Enable compiler for Go" ON) THRIFT_ADD_COMPILER(d "Enable compiler for D" ON) THRIFT_ADD_COMPILER(lua "Enable compiler for Lua" ON) THRIFT_ADD_COMPILER(gv "Enable compiler for GraphViz" ON) +THRIFT_ADD_COMPILER(rs "Enable compiler for Rust" ON) THRIFT_ADD_COMPILER(xml "Enable compiler for XML" ON) # Thrift is looking for include files in the src directory # we also add the current binary directory for generated files include_directories(${CMAKE_CURRENT_BINARY_DIR} src) -if(NOT ${WITH_PLUGIN}) +if(NOT DEFINED WITH_PLUGIN OR NOT ${WITH_PLUGIN}) list(APPEND thrift-compiler_SOURCES ${compiler_core}) endif() + add_executable(thrift-compiler ${thrift-compiler_SOURCES}) if(${WITH_PLUGIN}) @@ -111,7 +125,7 @@ if(${WITH_PLUGIN}) src/thrift/audit/t_audit.cpp src/thrift/generate/t_cpp_generator.cc ) - target_link_libraries(thrift-bootstrap libparse) + target_link_libraries(thrift-bootstrap parse) set(PLUGIN_GEN_SOURCES ${CMAKE_CURRENT_BINARY_DIR}/thrift/plugin/plugin_types.h @@ -144,11 +158,12 @@ if(${WITH_PLUGIN}) LINK_AGAINST_THRIFT_LIBRARY(thrift-compiler thriftc) endif() +set_target_properties(thrift-compiler PROPERTIES RUNTIME_OUTPUT_DIRECTORY bin/) set_target_properties(thrift-compiler PROPERTIES OUTPUT_NAME thrift) -target_link_libraries(thrift-compiler libparse) +target_link_libraries(thrift-compiler parse) -install(TARGETS thrift-compiler DESTINATION "${BIN_INSTALL_DIR}") +install(TARGETS thrift-compiler DESTINATION bin) if(${WITH_PLUGIN}) # Install the headers diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/Makefile.am b/vendor/git.apache.org/thrift.git/compiler/cpp/Makefile.am index a239391..0b8ef2e 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/Makefile.am +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/Makefile.am @@ -71,7 +71,7 @@ compiler_core = src/thrift/common.h \ src/thrift/parse/parse.cc \ src/thrift/generate/t_generator.h \ src/thrift/generate/t_oop_generator.h \ - src/thrift/generate/t_html_generator.h + src/thrift/generate/t_html_generator.h thrift_SOURCES = src/thrift/main.h \ src/thrift/main.cc \ @@ -87,6 +87,8 @@ thrift_SOURCES += src/thrift/generate/t_c_glib_generator.cc \ src/thrift/generate/t_dart_generator.cc \ src/thrift/generate/t_haxe_generator.cc \ src/thrift/generate/t_csharp_generator.cc \ + src/thrift/generate/t_netcore_generator.cc \ + src/thrift/generate/t_netcore_generator.h \ src/thrift/generate/t_py_generator.cc \ src/thrift/generate/t_rb_generator.cc \ src/thrift/generate/t_perl_generator.cc \ @@ -106,10 +108,12 @@ thrift_SOURCES += src/thrift/generate/t_c_glib_generator.cc \ src/thrift/generate/t_go_generator.cc \ src/thrift/generate/t_gv_generator.cc \ src/thrift/generate/t_d_generator.cc \ - src/thrift/generate/t_lua_generator.cc + src/thrift/generate/t_lua_generator.cc \ + src/thrift/generate/t_rs_generator.cc \ + src/thrift/generate/t_cl_generator.cc thrift_CPPFLAGS = -I$(srcdir)/src -thrift_CXXFLAGS = -Wall -Wextra -pedantic +thrift_CXXFLAGS = -Wall -Wextra -pedantic -Werror thrift_LDADD = @LEXLIB@ src/thrift/libparse.a if !WITH_PLUGIN @@ -151,7 +155,7 @@ include_generatedir = $(include_thriftdir)/generate include_generate_HEADERS = src/thrift/generate/t_generator.h \ src/thrift/generate/t_generator_registry.h \ src/thrift/generate/t_oop_generator.h \ - src/thrift/generate/t_html_generator.h + src/thrift/generate/t_html_generator.h include_parsedir = $(include_thriftdir)/parse include_parse_HEADERS = src/thrift/parse/t_service.h \ diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/README.md b/vendor/git.apache.org/thrift.git/compiler/cpp/README.md index 90300ac..32eac9f 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/README.md +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/README.md @@ -1,83 +1,175 @@ -# Build compiler using CMake +# Build Thrift IDL compiler using CMake -Use the following steps to build using cmake: + - mkdir cmake-build - cd cmake-build - cmake .. - make +- [Build Thrift IDL compiler using CMake](#build-thrift-idl-compiler-using-cmake) + - [Build on Unix-like System](#build-on-unix-like-system) + - [Prerequisites](#prerequisites) + - [Build using CMake](#build-using-cmake) + - [Build with Eclipse IDE](#build-with-eclipse-ide) + - [Build with XCode IDE in MacOS](#build-with-xcode-ide-in-macos) + - [Usage of other IDEs](#usage-of-other-ides) + - [Build on Windows](#build-on-windows) + - [Prerequisites](#prerequisites-1) + - [Build using Git Bash](#build-using-git-bash) + - [Using Visual Studio and Win flex-bison](#using-visual-studio-and-win-flex-bison) + - [Cross compile using mingw32 and generate a Windows Installer with CPack](#cross-compile-using-mingw32-and-generate-a-windows-installer-with-cpack) +- [Other cases](#other-cases) + - [Building the Thrift IDL compiler in Windows without CMake](#building-the-thrift-idl-compiler-in-windows-without-cmake) +- [Unit tests for compiler](#unit-tests-for-compiler) + - [Using boost test](#using-boost-test) + - [Using Catch C++ test library](#using-catch-c-test-library) +- [Have a Happy free time and holidays](#have-a-happy-free-time-and-holidays) + -### Create an eclipse project +## Build on Unix-like System - mkdir cmake-ec && cd cmake-ec - cmake -G "Eclipse CDT4 - Unix Makefiles" .. - make +### Prerequisites +- Install CMake +- Install flex and bison + +### Build using CMake + +- Go to **thrift\compiler\cpp** +- Use the following steps to build using cmake: + +``` +mkdir cmake-build && cd cmake-build +cmake .. +make +``` + +#### Build with Eclipse IDE + +- Go to **thrift\compiler\cpp** +- Use the following steps to build using cmake: + +``` +mkdir cmake-ec && cd cmake-ec +cmake -G "Eclipse CDT4 - Unix Makefiles" .. +make +``` Now open the folder cmake-ec using eclipse. +#### Build with XCode IDE in MacOS + +- Install/update flex, bison and cmake with brew + +``` +brew install cmake +brew install bison +``` + +- Go to **thrift\compiler\cpp** +- Run commands in command line: + +``` +mkdir cmake-build && cd cmake-build +cmake -G "Xcode" -DWITH_PLUGIN=OFF .. +cmake --build . +``` + +#### Usage of other IDEs + +Please check list of supported IDE + +``` +cmake --help +``` + +## Build on Windows + +### Prerequisites +- Install CMake - https://cmake.org/download/ +- In case if you want to build without Git Bash - install winflexbison - https://sourceforge.net/projects/winflexbison/ +- In case if you want to build with Visual Studio - install Visual Studio + - Better to use the latest stable Visual Studio Community Edition - https://www.visualstudio.com/vs/whatsnew/ (ensure that you installed workload "Desktop Development with C++" for VS2017) - Microsoft added some support for CMake and improving it in Visual Studio + +### Build using Git Bash + +Git Bash provides flex and bison + +- Go to **thrift\compiler\cpp** +- Use the following steps to build using cmake: + +``` +mkdir cmake-vs && cd cmake-vs +cmake -DWITH_SHARED_LIB=off .. +cmake --build . +``` + +### Using Visual Studio and Win flex-bison + +- Generate a Visual Studio project for version of Visual Studio which you have (**cmake --help** can show list of supportable VS versions): +- Run commands in command line: +``` +mkdir cmake-vs +cd cmake-vs +cmake -G "Visual Studio 15 2017" -DWITH_PLUGIN=OFF .. +``` +- Now open the folder cmake-vs using Visual Studio. ### Cross compile using mingw32 and generate a Windows Installer with CPack - mkdir cmake-mingw32 && cd cmake-mingw32 - cmake -DCMAKE_TOOLCHAIN_FILE=../build/cmake/mingw32-toolchain.cmake -DBUILD_COMPILER=ON -DBUILD_LIBRARIES=OFF -DBUILD_TESTING=OFF -DBUILD_EXAMPLES=OFF .. - cpack - -## Build on windows - -### using Git Bash -Git Bash provides flex and bison, so you just need to do this: - - mkdir cmake-vs && cd cmake-vs - cmake -DWITH_SHARED_LIB=off .. - -### using Win flex-bison - -In order to build on windows with winflexbison a few additional steps are necessary: - -1. Download winflexbison from http://sourceforge.net/projects/winflexbison/ -2. Extract the winflex bison files to for e.g. C:\winflexbison -3. Make the CMake variables point to the correct binaries. - * FLEX_EXECUTABLE = C:/winbuild/win_flex.exe - * BISON_EXECUTABLE = C:/winbuild/win_bison.exe -4. Generate a Visual Studio project: ``` -mkdir cmake-vs && cd cmake-vs -cmake -G "Visual Studio 12" -DWITH_SHARED_LIB=off .. +mkdir cmake-mingw32 && cd cmake-mingw32 +cmake -DCMAKE_TOOLCHAIN_FILE=../build/cmake/mingw32-toolchain.cmake -DBUILD_COMPILER=ON -DBUILD_LIBRARIES=OFF -DBUILD_TESTING=OFF -DBUILD_EXAMPLES=OFF .. +cpack ``` -5. Now open the folder build_vs using Visual Studio 2013. -# Building the Thrift IDL compiler in Windows +# Other cases -If you don't want to use CMake you can use the already available Visual Studio -2010 solution. -The Visual Studio project contains pre-build commands to generate the -thriftl.cc, thrifty.cc and thrifty.hh files which are necessary to build -the compiler. These depend on bison, flex and their dependencies to -work properly. -Download flex & bison as described above. -Place these binaries somewhere in the path and -rename win_flex.exe and win_bison.exe to flex.exe and bison.exe respectively. +## Building the Thrift IDL compiler in Windows without CMake + +If you don't want to use CMake you can use the already available Visual Studio 2010 solution. + +The Visual Studio project contains pre-build commands to generate the thriftl.cc, thrifty.cc and thrifty.hh files which are necessary to build the compiler. + +These depend on bison, flex and their dependencies to work properly. + +Download flex & bison as described above. + +Place these binaries somewhere in the path and rename win_flex.exe and win_bison.exe to flex.exe and bison.exe respectively. If this doesn't work on a system, try these manual pre-build steps. -Open compiler.sln and remove the Pre-build commands under the project's - Properties -> Build Events -> Pre-Build Events. +Open compiler.sln and remove the Pre-build commands under the project's: Properties -> Build Events -> Pre-Build Events. From a command prompt: -> cd thrift/compiler/cpp -> flex -osrc\thrift\thriftl.cc src\thrift\thriftl.ll +``` +cd thrift/compiler/cpp +flex -o src\thrift\thriftl.cc src\thrift\thriftl.ll +``` In the generated thriftl.cc, comment out #include Place a copy of bison.simple in thrift/compiler/cpp -> bison -y -o "src/thrift/thrifty.cc" --defines src/thrift/thrifty.yy -> move src\thrift\thrifty.cc.hh src\thrift\thrifty.hh +``` +bison -y -o "src/thrift/thrifty.cc" --defines src/thrift/thrifty.yy +move src\thrift\thrifty.cc.hh src\thrift\thrifty.hh +``` Bison might generate the yacc header file "thrifty.cc.h" with just one h ".h" extension; in this case you'll have to rename to "thrifty.h". -> move src\thrift\version.h.in src\thrift\version.h +``` +move src\thrift\version.h.in src\thrift\version.h +``` Download inttypes.h from the interwebs and place it in an include path location (e.g. thrift/compiler/cpp/src). Build the compiler in Visual Studio. + +# Unit tests for compiler + +## Using boost test +- pls check **test** folder + +## Using Catch C++ test library + +Added generic way to cover code by tests for many languages (you just need to make a correct header file for generator for your language - example in **netcore** implementation) + +- pls check **tests** folder + +# Have a Happy free time and holidays \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/compiler.vcxproj b/vendor/git.apache.org/thrift.git/compiler/cpp/compiler.vcxproj index 878e219..0628b54 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/compiler.vcxproj +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/compiler.vcxproj @@ -51,12 +51,13 @@ - + + @@ -78,6 +79,7 @@ + @@ -194,7 +196,6 @@ flex -o "src\\thrift\\thriftl.cc" src/thrift/thriftl.ll && bison -y -o "src\\thrift\\thrifty.cc" --defines="src\\thrift\\thrifty.hh" src/thrift/thrifty.yy - @@ -208,6 +209,7 @@ WIN32;MINGW;YY_NO_UNISTD_H;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) thrift\windows\config.h CompileAsCpp + MultiThreaded Console @@ -217,7 +219,6 @@ flex -o "src\\thrift\\thriftl.cc" src/thrift/thriftl.ll && bison -y -o "src\\thrift\\thrifty.cc" --defines="src\\thrift\\thrifty.hh" src/thrift/thrifty.yy - @@ -231,6 +232,7 @@ WIN32;MINGW;YY_NO_UNISTD_H;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) thrift\windows\config.h CompileAsCpp + MultiThreaded Console @@ -240,10 +242,9 @@ flex -o "src\\thrift\\thriftl.cc" src/thrift/thriftl.ll && bison -y -o "src\\thrift\\thrifty.cc" --defines="src\\thrift\\thrifty.hh" src/thrift/thrifty.yy - - + \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/compiler.vcxproj.filters b/vendor/git.apache.org/thrift.git/compiler/cpp/compiler.vcxproj.filters index 9b14bbf..b96865b 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/compiler.vcxproj.filters +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/compiler.vcxproj.filters @@ -161,6 +161,9 @@ generate + + generate + generate @@ -193,4 +196,4 @@ - \ No newline at end of file + diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/audit/t_audit.cpp b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/audit/t_audit.cpp index 1386f3b..ef39d60 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/audit/t_audit.cpp +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/audit/t_audit.cpp @@ -202,8 +202,8 @@ bool compare_defaults(t_const_value* newStructDefault, t_const_value* oldStructD } case t_const_value::CV_MAP: { - const std::map newMap = newStructDefault->get_map(); - const std::map oldMap = oldStructDefault->get_map(); + const std::map newMap = newStructDefault->get_map(); + const std::map oldMap = oldStructDefault->get_map(); bool defaultValuesCompare = (oldMap.size() == newMap.size()); diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_as3_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_as3_generator.cc index 5ae3f91..41724fe 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_as3_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_as3_generator.cc @@ -31,7 +31,7 @@ #include "thrift/generate/t_oop_generator.h" using std::map; -using std::ofstream; +using std::ostream; using std::ostringstream; using std::string; using std::stringstream; @@ -83,13 +83,13 @@ public: void generate_xception(t_struct* txception); void generate_service(t_service* tservice); - void print_const_value(std::ofstream& out, + void print_const_value(std::ostream& out, std::string name, t_type* type, t_const_value* value, bool in_static, bool defval = false); - std::string render_const_value(ofstream& out, + std::string render_const_value(ostream& out, std::string name, t_type* type, t_const_value* value); @@ -100,19 +100,19 @@ public: void generate_as3_struct(t_struct* tstruct, bool is_exception); - void generate_as3_struct_definition(std::ofstream& out, + void generate_as3_struct_definition(std::ostream& out, t_struct* tstruct, bool is_xception = false, bool in_class = false, bool is_result = false); // removed -- equality,compare_to - void generate_as3_struct_reader(std::ofstream& out, t_struct* tstruct); - void generate_as3_validator(std::ofstream& out, t_struct* tstruct); - void generate_as3_struct_result_writer(std::ofstream& out, t_struct* tstruct); - void generate_as3_struct_writer(std::ofstream& out, t_struct* tstruct); - void generate_as3_struct_tostring(std::ofstream& out, t_struct* tstruct, bool bindable); - void generate_as3_meta_data_map(std::ofstream& out, t_struct* tstruct); - void generate_field_value_meta_data(std::ofstream& out, t_type* type); + void generate_as3_struct_reader(std::ostream& out, t_struct* tstruct); + void generate_as3_validator(std::ostream& out, t_struct* tstruct); + void generate_as3_struct_result_writer(std::ostream& out, t_struct* tstruct); + void generate_as3_struct_writer(std::ostream& out, t_struct* tstruct); + void generate_as3_struct_tostring(std::ostream& out, t_struct* tstruct, bool bindable); + void generate_as3_meta_data_map(std::ostream& out, t_struct* tstruct); + void generate_field_value_meta_data(std::ostream& out, t_type* type); std::string get_as3_type_string(t_type* type); void generate_reflection_setters(std::ostringstream& out, t_type* type, @@ -122,15 +122,15 @@ public: t_type* type, std::string field_name, std::string cap_name); - void generate_generic_field_getters_setters(std::ofstream& out, t_struct* tstruct); - void generate_generic_isset_method(std::ofstream& out, t_struct* tstruct); - void generate_as3_bean_boilerplate(std::ofstream& out, t_struct* tstruct, bool bindable); + void generate_generic_field_getters_setters(std::ostream& out, t_struct* tstruct); + void generate_generic_isset_method(std::ostream& out, t_struct* tstruct); + void generate_as3_bean_boilerplate(std::ostream& out, t_struct* tstruct, bool bindable); void generate_function_helpers(t_function* tfunction); std::string get_cap_name(std::string name); std::string generate_isset_check(t_field* field); std::string generate_isset_check(std::string field); - void generate_isset_set(ofstream& out, t_field* field); + void generate_isset_set(ostream& out, t_field* field); // removed std::string isset_field_id(t_field* field); void generate_service_interface(t_service* tservice); @@ -143,38 +143,38 @@ public: * Serialization constructs */ - void generate_deserialize_field(std::ofstream& out, t_field* tfield, std::string prefix = ""); + void generate_deserialize_field(std::ostream& out, t_field* tfield, std::string prefix = ""); - void generate_deserialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); + void generate_deserialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); - void generate_deserialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); + void generate_deserialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); - void generate_deserialize_set_element(std::ofstream& out, t_set* tset, std::string prefix = ""); + void generate_deserialize_set_element(std::ostream& out, t_set* tset, std::string prefix = ""); - void generate_deserialize_map_element(std::ofstream& out, t_map* tmap, std::string prefix = ""); + void generate_deserialize_map_element(std::ostream& out, t_map* tmap, std::string prefix = ""); - void generate_deserialize_list_element(std::ofstream& out, + void generate_deserialize_list_element(std::ostream& out, t_list* tlist, std::string prefix = ""); - void generate_serialize_field(std::ofstream& out, t_field* tfield, std::string prefix = ""); + void generate_serialize_field(std::ostream& out, t_field* tfield, std::string prefix = ""); - void generate_serialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); + void generate_serialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); - void generate_serialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); + void generate_serialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); - void generate_serialize_map_element(std::ofstream& out, + void generate_serialize_map_element(std::ostream& out, t_map* tmap, std::string iter, std::string map); - void generate_serialize_set_element(std::ofstream& out, t_set* tmap, std::string iter); + void generate_serialize_set_element(std::ostream& out, t_set* tmap, std::string iter); - void generate_serialize_list_element(std::ofstream& out, t_list* tlist, std::string iter); + void generate_serialize_list_element(std::ostream& out, t_list* tlist, std::string iter); - void generate_as3_doc(std::ofstream& out, t_doc* tdoc); + void generate_as3_doc(std::ostream& out, t_doc* tdoc); - void generate_as3_doc(std::ofstream& out, t_function* tdoc); + void generate_as3_doc(std::ostream& out, t_function* tdoc); /** * Helper rendering functions @@ -208,7 +208,7 @@ private: */ std::string package_name_; - std::ofstream f_service_; + ofstream_with_content_based_conditional_update f_service_; std::string package_dir_; bool bindable_; @@ -353,8 +353,8 @@ void t_as3_generator::generate_typedef(t_typedef* ttypedef) { void t_as3_generator::generate_enum(t_enum* tenum) { // Make output file string f_enum_name = package_dir_ + "/" + (tenum->get_name()) + ".as"; - ofstream f_enum; - f_enum.open(f_enum_name.c_str()); + ofstream_with_content_based_conditional_update f_enum; + f_enum.open(f_enum_name); // Comment and package it f_enum << autogen_comment() << as3_package() << endl; @@ -416,8 +416,8 @@ void t_as3_generator::generate_consts(std::vector consts) { } string f_consts_name = package_dir_ + "/" + program_name_ + "Constants.as"; - ofstream f_consts; - f_consts.open(f_consts_name.c_str()); + ofstream_with_content_based_conditional_update f_consts; + f_consts.open(f_consts_name); // Print header f_consts << autogen_comment() << as3_package(); @@ -443,7 +443,7 @@ void t_as3_generator::generate_consts(std::vector consts) { f_consts.close(); } -void t_as3_generator::print_const_value(std::ofstream& out, +void t_as3_generator::print_const_value(std::ostream& out, string name, t_type* type, t_const_value* value, @@ -471,8 +471,8 @@ void t_as3_generator::print_const_value(std::ofstream& out, } else if (type->is_struct() || type->is_xception()) { const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; out << name << ":" << type_name(type) << " = new " << type_name(type, false, true) << "();" << endl; if (!in_static) { @@ -516,8 +516,8 @@ void t_as3_generator::print_const_value(std::ofstream& out, } t_type* ktype = ((t_map*)type)->get_key_type(); t_type* vtype = ((t_map*)type)->get_val_type(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { string key = render_const_value(out, name, ktype, v_iter->first); string val = render_const_value(out, name, vtype, v_iter->second); @@ -567,7 +567,7 @@ void t_as3_generator::print_const_value(std::ofstream& out, } } -string t_as3_generator::render_const_value(ofstream& out, +string t_as3_generator::render_const_value(ostream& out, string name, t_type* type, t_const_value* value) { @@ -644,7 +644,7 @@ void t_as3_generator::generate_xception(t_struct* txception) { void t_as3_generator::generate_as3_struct(t_struct* tstruct, bool is_exception) { // Make output file string f_struct_name = package_dir_ + "/" + (tstruct->get_name()) + ".as"; - ofstream f_struct; + ofstream_with_content_based_conditional_update f_struct; f_struct.open(f_struct_name.c_str()); f_struct << autogen_comment() << as3_package(); @@ -678,7 +678,7 @@ void t_as3_generator::generate_as3_struct(t_struct* tstruct, bool is_exception) * @param in_class If inside a class, needs to be static class * @param is_result If this is a result it needs a different writer */ -void t_as3_generator::generate_as3_struct_definition(ofstream& out, +void t_as3_generator::generate_as3_struct_definition(ostream& out, t_struct* tstruct, bool is_exception, bool in_class, @@ -782,7 +782,7 @@ void t_as3_generator::generate_as3_struct_definition(ofstream& out, * * @param tstruct The struct definition */ -void t_as3_generator::generate_as3_struct_reader(ofstream& out, t_struct* tstruct) { +void t_as3_generator::generate_as3_struct_reader(ostream& out, t_struct* tstruct) { out << indent() << "public function read(iprot:TProtocol):void {" << endl; indent_up(); @@ -862,7 +862,7 @@ void t_as3_generator::generate_as3_struct_reader(ofstream& out, t_struct* tstruc // generates as3 method to perform various checks // (e.g. check that all required fields are set) -void t_as3_generator::generate_as3_validator(ofstream& out, t_struct* tstruct) { +void t_as3_generator::generate_as3_validator(ostream& out, t_struct* tstruct) { indent(out) << "public function validate():void {" << endl; indent_up(); @@ -912,7 +912,7 @@ void t_as3_generator::generate_as3_validator(ofstream& out, t_struct* tstruct) { * * @param tstruct The struct definition */ -void t_as3_generator::generate_as3_struct_writer(ofstream& out, t_struct* tstruct) { +void t_as3_generator::generate_as3_struct_writer(ostream& out, t_struct* tstruct) { out << indent() << "public function write(oprot:TProtocol):void {" << endl; indent_up(); @@ -971,7 +971,7 @@ void t_as3_generator::generate_as3_struct_writer(ofstream& out, t_struct* tstruc * * @param tstruct The struct definition */ -void t_as3_generator::generate_as3_struct_result_writer(ofstream& out, t_struct* tstruct) { +void t_as3_generator::generate_as3_struct_result_writer(ostream& out, t_struct* tstruct) { out << indent() << "public function write(oprot:TProtocol):void {" << endl; indent_up(); @@ -1044,7 +1044,7 @@ void t_as3_generator::generate_reflection_setters(ostringstream& out, indent_down(); } -void t_as3_generator::generate_generic_field_getters_setters(std::ofstream& out, +void t_as3_generator::generate_generic_field_getters_setters(std::ostream& out, t_struct* tstruct) { std::ostringstream getter_stream; @@ -1100,7 +1100,7 @@ void t_as3_generator::generate_generic_field_getters_setters(std::ofstream& out, } // Creates a generic isSet method that takes the field number as argument -void t_as3_generator::generate_generic_isset_method(std::ofstream& out, t_struct* tstruct) { +void t_as3_generator::generate_generic_isset_method(std::ostream& out, t_struct* tstruct) { const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; @@ -1134,7 +1134,7 @@ void t_as3_generator::generate_generic_isset_method(std::ofstream& out, t_struct * * @param tstruct The struct definition */ -void t_as3_generator::generate_as3_bean_boilerplate(ofstream& out, +void t_as3_generator::generate_as3_bean_boilerplate(ostream& out, t_struct* tstruct, bool bindable) { const vector& fields = tstruct->get_members(); @@ -1216,7 +1216,7 @@ void t_as3_generator::generate_as3_bean_boilerplate(ofstream& out, * * @param tstruct The struct definition */ -void t_as3_generator::generate_as3_struct_tostring(ofstream& out, +void t_as3_generator::generate_as3_struct_tostring(ostream& out, t_struct* tstruct, bool bindable) { // If it's bindable, it extends EventDispatcher so toString is an override. @@ -1251,7 +1251,7 @@ void t_as3_generator::generate_as3_struct_tostring(ofstream& out, indent_up(); } - if (field->get_type()->is_base_type() && ((t_base_type*)(field->get_type()))->is_binary()) { + if (field->get_type()->is_binary()) { indent(out) << " ret += \"BINARY\";" << endl; } else if (field->get_type()->is_enum()) { indent(out) << "var " << field->get_name() @@ -1293,7 +1293,7 @@ void t_as3_generator::generate_as3_struct_tostring(ofstream& out, * * @param tstruct The struct definition */ -void t_as3_generator::generate_as3_meta_data_map(ofstream& out, t_struct* tstruct) { +void t_as3_generator::generate_as3_meta_data_map(ostream& out, t_struct* tstruct) { const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; @@ -1381,7 +1381,7 @@ std::string t_as3_generator::get_as3_type_string(t_type* type) { } } -void t_as3_generator::generate_field_value_meta_data(std::ofstream& out, t_type* type) { +void t_as3_generator::generate_field_value_meta_data(std::ostream& out, t_type* type) { out << endl; indent_up(); indent_up(); @@ -1960,7 +1960,7 @@ void t_as3_generator::generate_process_function(t_service* tservice, t_function* * @param tfield The field * @param prefix The variable name or container for this field */ -void t_as3_generator::generate_deserialize_field(ofstream& out, t_field* tfield, string prefix) { +void t_as3_generator::generate_deserialize_field(ostream& out, t_field* tfield, string prefix) { t_type* type = get_true_type(tfield->get_type()); if (type->is_void()) { @@ -1984,7 +1984,7 @@ void t_as3_generator::generate_deserialize_field(ofstream& out, t_field* tfield, throw "compiler error: cannot serialize void field in a struct: " + name; break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { out << "readBinary();"; } else { out << "readString();"; @@ -2025,7 +2025,7 @@ void t_as3_generator::generate_deserialize_field(ofstream& out, t_field* tfield, /** * Generates an unserializer for a struct, invokes read() */ -void t_as3_generator::generate_deserialize_struct(ofstream& out, t_struct* tstruct, string prefix) { +void t_as3_generator::generate_deserialize_struct(ostream& out, t_struct* tstruct, string prefix) { out << indent() << prefix << " = new " << type_name(tstruct) << "();" << endl << indent() << prefix << ".read(iprot);" << endl; } @@ -2033,7 +2033,7 @@ void t_as3_generator::generate_deserialize_struct(ofstream& out, t_struct* tstru /** * Deserializes a container by reading its size and then iterating */ -void t_as3_generator::generate_deserialize_container(ofstream& out, t_type* ttype, string prefix) { +void t_as3_generator::generate_deserialize_container(ostream& out, t_type* ttype, string prefix) { scope_up(out); string obj; @@ -2093,7 +2093,7 @@ void t_as3_generator::generate_deserialize_container(ofstream& out, t_type* ttyp /** * Generates code to deserialize a map */ -void t_as3_generator::generate_deserialize_map_element(ofstream& out, t_map* tmap, string prefix) { +void t_as3_generator::generate_deserialize_map_element(ostream& out, t_map* tmap, string prefix) { string key = tmp("_key"); string val = tmp("_val"); t_field fkey(tmap->get_key_type(), key); @@ -2111,7 +2111,7 @@ void t_as3_generator::generate_deserialize_map_element(ofstream& out, t_map* tma /** * Deserializes a set element */ -void t_as3_generator::generate_deserialize_set_element(ofstream& out, t_set* tset, string prefix) { +void t_as3_generator::generate_deserialize_set_element(ostream& out, t_set* tset, string prefix) { string elem = tmp("_elem"); t_field felem(tset->get_elem_type(), elem); @@ -2125,7 +2125,7 @@ void t_as3_generator::generate_deserialize_set_element(ofstream& out, t_set* tse /** * Deserializes a list element */ -void t_as3_generator::generate_deserialize_list_element(ofstream& out, +void t_as3_generator::generate_deserialize_list_element(ostream& out, t_list* tlist, string prefix) { string elem = tmp("_elem"); @@ -2144,7 +2144,7 @@ void t_as3_generator::generate_deserialize_list_element(ofstream& out, * @param tfield The field to serialize * @param prefix Name to prepend to field name */ -void t_as3_generator::generate_serialize_field(ofstream& out, t_field* tfield, string prefix) { +void t_as3_generator::generate_serialize_field(ostream& out, t_field* tfield, string prefix) { t_type* type = get_true_type(tfield->get_type()); // Do nothing for void types @@ -2168,7 +2168,7 @@ void t_as3_generator::generate_serialize_field(ofstream& out, t_field* tfield, s throw "compiler error: cannot serialize void field in a struct: " + name; break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { out << "writeBinary(" << name << ");"; } else { out << "writeString(" << name << ");"; @@ -2213,7 +2213,7 @@ void t_as3_generator::generate_serialize_field(ofstream& out, t_field* tfield, s * @param tstruct The struct to serialize * @param prefix String prefix to attach to all fields */ -void t_as3_generator::generate_serialize_struct(ofstream& out, t_struct* tstruct, string prefix) { +void t_as3_generator::generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix) { (void)tstruct; out << indent() << prefix << ".write(oprot);" << endl; } @@ -2224,7 +2224,7 @@ void t_as3_generator::generate_serialize_struct(ofstream& out, t_struct* tstruct * @param ttype The type of container * @param prefix String prefix for fields */ -void t_as3_generator::generate_serialize_container(ofstream& out, t_type* ttype, string prefix) { +void t_as3_generator::generate_serialize_container(ostream& out, t_type* ttype, string prefix) { scope_up(out); if (ttype->is_map()) { @@ -2282,7 +2282,7 @@ void t_as3_generator::generate_serialize_container(ofstream& out, t_type* ttype, /** * Serializes the members of a map. */ -void t_as3_generator::generate_serialize_map_element(ofstream& out, +void t_as3_generator::generate_serialize_map_element(ostream& out, t_map* tmap, string iter, string map) { @@ -2295,7 +2295,7 @@ void t_as3_generator::generate_serialize_map_element(ofstream& out, /** * Serializes the members of a set. */ -void t_as3_generator::generate_serialize_set_element(ofstream& out, t_set* tset, string iter) { +void t_as3_generator::generate_serialize_set_element(ostream& out, t_set* tset, string iter) { t_field efield(tset->get_elem_type(), iter); generate_serialize_field(out, &efield, ""); } @@ -2303,7 +2303,7 @@ void t_as3_generator::generate_serialize_set_element(ofstream& out, t_set* tset, /** * Serializes the members of a list. */ -void t_as3_generator::generate_serialize_list_element(ofstream& out, t_list* tlist, string iter) { +void t_as3_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string iter) { t_field efield(tlist->get_elem_type(), iter); generate_serialize_field(out, &efield, ""); } @@ -2390,7 +2390,7 @@ string t_as3_generator::declare_field(t_field* tfield, bool init) { if (init) { t_type* ttype = get_true_type(tfield->get_type()); if (ttype->is_base_type() && tfield->get_value() != NULL) { - ofstream dummy; + std::ofstream dummy; result += " = " + render_const_value(dummy, tfield->get_name(), ttype, tfield->get_value()); } else if (ttype->is_base_type()) { t_base_type::t_base tbase = ((t_base_type*)ttype)->get_base(); @@ -2539,7 +2539,7 @@ string t_as3_generator::constant_name(string name) { /** * Emits a As3Doc comment if the provided object has a doc in Thrift */ -void t_as3_generator::generate_as3_doc(ofstream& out, t_doc* tdoc) { +void t_as3_generator::generate_as3_doc(ostream& out, t_doc* tdoc) { if (tdoc->has_doc()) { generate_docstring_comment(out, "/**\n", " * ", tdoc->get_doc(), " */\n"); } @@ -2548,7 +2548,7 @@ void t_as3_generator::generate_as3_doc(ofstream& out, t_doc* tdoc) { /** * Emits a As3Doc comment if the provided function object has a doc in Thrift */ -void t_as3_generator::generate_as3_doc(ofstream& out, t_function* tfunction) { +void t_as3_generator::generate_as3_doc(ostream& out, t_function* tfunction) { if (tfunction->has_doc()) { stringstream ss; ss << tfunction->get_doc(); @@ -2573,7 +2573,7 @@ std::string t_as3_generator::generate_isset_check(std::string field_name) { return "is" + get_cap_name("set") + get_cap_name(field_name) + "()"; } -void t_as3_generator::generate_isset_set(ofstream& out, t_field* field) { +void t_as3_generator::generate_isset_set(ostream& out, t_field* field) { if (!type_can_be_null(field->get_type())) { indent(out) << "this.__isset_" << field->get_name() << " = true;" << endl; } diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_c_glib_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_c_glib_generator.cc index 7d4e4f0..be3bad1 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_c_glib_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_c_glib_generator.cc @@ -33,7 +33,7 @@ #include "thrift/generate/t_oop_generator.h" using std::map; -using std::ofstream; +using std::ostream; using std::ostringstream; using std::string; using std::stringstream; @@ -116,10 +116,10 @@ public: private: /* file streams */ - ofstream f_types_; - ofstream f_types_impl_; - ofstream f_header_; - ofstream f_service_; + ofstream_with_content_based_conditional_update f_types_; + ofstream_with_content_based_conditional_update f_types_impl_; + ofstream_with_content_based_conditional_update f_header_; + ofstream_with_content_based_conditional_update f_service_; /* namespace variables */ string nspace; @@ -145,8 +145,8 @@ private: bool pointer = false, bool constant = false, bool reference = false); - void declare_local_variable(ofstream& out, t_type* ttype, string& base_name, bool for_hash_table); - void declore_local_variable_for_write(ofstream& out, t_type* ttype, string& base_name); + void declare_local_variable(ostream& out, t_type* ttype, string& base_name, bool for_hash_table); + void declore_local_variable_for_write(ostream& out, t_type* ttype, string& base_name); /* generation functions */ void generate_const_initializer(string name, @@ -159,51 +159,51 @@ private: void generate_service_processor(t_service* tservice); void generate_service_server(t_service* tservice); void generate_object(t_struct* tstruct); - void generate_struct_writer(ofstream& out, + void generate_struct_writer(ostream& out, t_struct* tstruct, string this_name, string this_get = "", bool is_function = true); - void generate_struct_reader(ofstream& out, + void generate_struct_reader(ostream& out, t_struct* tstruct, string this_name, string this_get = "", bool is_function = true); - void generate_serialize_field(ofstream& out, + void generate_serialize_field(ostream& out, t_field* tfield, string prefix, string suffix, int error_ret); - void generate_serialize_struct(ofstream& out, t_struct* tstruct, string prefix, int error_ret); - void generate_serialize_container(ofstream& out, t_type* ttype, string prefix, int error_ret); - void generate_serialize_map_element(ofstream& out, + void generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix, int error_ret); + void generate_serialize_container(ostream& out, t_type* ttype, string prefix, int error_ret); + void generate_serialize_map_element(ostream& out, t_map* tmap, string key, string value, int error_ret); - void generate_serialize_set_element(ofstream& out, t_set* tset, string element, int error_ret); - void generate_serialize_list_element(ofstream& out, + void generate_serialize_set_element(ostream& out, t_set* tset, string element, int error_ret); + void generate_serialize_list_element(ostream& out, t_list* tlist, string list, string index, int error_ret); - void generate_deserialize_field(ofstream& out, + void generate_deserialize_field(ostream& out, t_field* tfield, string prefix, string suffix, int error_ret, bool allocate = true); - void generate_deserialize_struct(ofstream& out, + void generate_deserialize_struct(ostream& out, t_struct* tstruct, string prefix, int error_ret, bool allocate = true); - void generate_deserialize_container(ofstream& out, t_type* ttype, string prefix, int error_ret); - void generate_deserialize_map_element(ofstream& out, t_map* tmap, string prefix, int error_ret); - void generate_deserialize_set_element(ofstream& out, t_set* tset, string prefix, int error_ret); - void generate_deserialize_list_element(ofstream& out, + void generate_deserialize_container(ostream& out, t_type* ttype, string prefix, int error_ret); + void generate_deserialize_map_element(ostream& out, t_map* tmap, string prefix, int error_ret); + void generate_deserialize_set_element(ostream& out, t_set* tset, string prefix, int error_ret); + void generate_deserialize_list_element(ostream& out, t_list* tlist, string prefix, string index, @@ -250,11 +250,21 @@ void t_c_glib_generator::init_generator() { /* include other thrift includes */ const vector& includes = program_->get_includes(); - for (size_t i = 0; i < includes.size(); ++i) { - f_types_ << "/* other thrift includes */" << endl << "#include \"" << this->nspace_lc - << initial_caps_to_underscores(includes[i]->get_name()) << "_types.h\"" << endl; + if (!includes.empty()) { + f_types_ << "/* other thrift includes */" << endl; + + for (vector::const_iterator iter = includes.begin(); + iter != includes.end(); + ++iter) { + const std::string& include_nspace = (*iter)->get_namespace("c_glib"); + std::string include_nspace_prefix = + include_nspace.empty() ? "" : initial_caps_to_underscores(include_nspace) + "_"; + + f_types_ << "#include \"" << include_nspace_prefix + << initial_caps_to_underscores((*iter)->get_name()) << "_types.h\"" << endl; + } + f_types_ << endl; } - f_types_ << endl; /* include custom headers */ const vector& c_includes = program_->get_c_includes(); @@ -579,7 +589,7 @@ string t_c_glib_generator::type_name(t_type* ttype, bool in_typedef, bool is_con // TODO: discuss whether or not to implement TSet, THashSet or GHashSet cname = "GHashTable"; } else if (ttype->is_list()) { - t_type* etype = ((t_list*)ttype)->get_elem_type(); + t_type* etype = get_true_type(((t_list*)ttype)->get_elem_type()); if (etype->is_void()) { throw std::runtime_error("compiler error: list element type cannot be void"); } @@ -602,7 +612,8 @@ string t_c_glib_generator::type_name(t_type* ttype, bool in_typedef, bool is_con } // check for a namespace - string pname = this->nspace + ttype->get_name(); + t_program* tprogram = ttype->get_program(); + string pname = (tprogram ? tprogram->get_namespace("c_glib") : "") + ttype->get_name(); if (is_complex_type(ttype)) { pname += " *"; @@ -997,8 +1008,8 @@ void t_c_glib_generator::generate_const_initializer(string name, if (type->is_struct() || type->is_xception()) { const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; ostringstream initializers; // initialize any constants that may be referenced by this initializer @@ -1171,8 +1182,8 @@ void t_c_glib_generator::generate_const_initializer(string name, } else if (type->is_map()) { t_type* ktype = ((t_map*)type)->get_key_type(); t_type* vtype = ((t_map*)type)->get_val_type(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; ostringstream initializers; ostringstream appenders; @@ -1831,8 +1842,10 @@ void t_c_glib_generator::generate_service_handler(t_service* tservice) { string service_name_lc = to_lower_case(initial_caps_to_underscores(service_name_)); string service_name_uc = to_upper_case(service_name_lc); - string class_name = this->nspace + service_name_ + "Handler"; - string class_name_lc = to_lower_case(initial_caps_to_underscores(class_name)); + string service_handler_name = service_name_ + "Handler"; + + string class_name = this->nspace + service_handler_name; + string class_name_lc = this->nspace_lc + initial_caps_to_underscores(service_handler_name); string class_name_uc = to_upper_case(class_name_lc); string parent_class_name; @@ -2051,8 +2064,10 @@ void t_c_glib_generator::generate_service_processor(t_service* tservice) { string service_name_lc = to_lower_case(initial_caps_to_underscores(service_name_)); string service_name_uc = to_upper_case(service_name_lc); - string class_name = this->nspace + service_name_ + "Processor"; - string class_name_lc = to_lower_case(initial_caps_to_underscores(class_name)); + string service_processor_name = service_name_ + "Processor"; + + string class_name = this->nspace + service_processor_name; + string class_name_lc = this->nspace_lc + initial_caps_to_underscores(service_processor_name); string class_name_uc = to_upper_case(class_name_lc); string parent_class_name; @@ -2784,7 +2799,7 @@ void t_c_glib_generator::generate_object(t_struct* tstruct) { string name_uc = to_upper_case(name_u); string class_name = this->nspace + name; - string class_name_lc = to_lower_case(initial_caps_to_underscores(class_name)); + string class_name_lc = this->nspace_lc + initial_caps_to_underscores(name); string class_name_uc = to_upper_case(class_name_lc); string function_name; @@ -3124,7 +3139,8 @@ void t_c_glib_generator::generate_object(t_struct* tstruct) { << "THRIFT_UNUSED_VAR (object);" << endl; for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { - t_type* t = get_true_type((*m_iter)->get_type()); + t_type* member_type = (*m_iter)->get_type(); + t_type* t = get_true_type(member_type); if (t->is_base_type()) { string dval = " = "; if (t->is_enum()) { @@ -3139,10 +3155,14 @@ void t_c_glib_generator::generate_object(t_struct* tstruct) { indent(f_types_impl_) << "object->" << (*m_iter)->get_name() << dval << ";" << endl; } else if (t->is_struct()) { string name = (*m_iter)->get_name(); - string type_name_uc - = to_upper_case(initial_caps_to_underscores((*m_iter)->get_type()->get_name())); - indent(f_types_impl_) << "object->" << name << " = g_object_new (" << this->nspace_uc - << "TYPE_" << type_name_uc << ", NULL);" << endl; + t_program* type_program = member_type->get_program(); + string type_nspace = type_program ? type_program->get_namespace("c_glib") : ""; + string type_nspace_prefix = + type_nspace.empty() ? "" : initial_caps_to_underscores(type_nspace) + "_"; + string type_name_uc = to_upper_case(initial_caps_to_underscores(member_type->get_name())); + indent(f_types_impl_) << "object->" << name << " = g_object_new (" + << to_upper_case(type_nspace_prefix) << "TYPE_" << type_name_uc + << ", NULL);" << endl; } else if (t->is_xception()) { string name = (*m_iter)->get_name(); indent(f_types_impl_) << "object->" << name << " = NULL;" << endl; @@ -3424,7 +3444,12 @@ void t_c_glib_generator::generate_object(t_struct* tstruct) { << "G_PARAM_READWRITE));" << endl; indent_down(); } else if (member_type->is_struct() || member_type->is_xception()) { - string param_type = this->nspace_uc + "TYPE_" + t_program* type_program = member_type->get_program(); + string type_nspace = type_program ? type_program->get_namespace("c_glib") : ""; + string type_nspace_prefix = + type_nspace.empty() ? "" : initial_caps_to_underscores(type_nspace) + "_"; + + string param_type = to_upper_case(type_nspace_prefix) + "TYPE_" + to_upper_case(initial_caps_to_underscores(member_type->get_name())); args_indent += string(20, ' '); @@ -3480,7 +3505,7 @@ void t_c_glib_generator::generate_object(t_struct* tstruct) { /** * Generates functions to write Thrift structures to a stream. */ -void t_c_glib_generator::generate_struct_writer(ofstream& out, +void t_c_glib_generator::generate_struct_writer(ostream& out, t_struct* tstruct, string this_name, string this_get, @@ -3553,7 +3578,7 @@ void t_c_glib_generator::generate_struct_writer(ofstream& out, /** * Generates code to read Thrift structures from a stream. */ -void t_c_glib_generator::generate_struct_reader(ofstream& out, +void t_c_glib_generator::generate_struct_reader(ostream& out, t_struct* tstruct, string this_name, string this_get, @@ -3690,7 +3715,7 @@ void t_c_glib_generator::generate_struct_reader(ofstream& out, indent(out) << "}" << endl << endl; } -void t_c_glib_generator::generate_serialize_field(ofstream& out, +void t_c_glib_generator::generate_serialize_field(ostream& out, t_field* tfield, string prefix, string suffix, @@ -3734,7 +3759,7 @@ void t_c_glib_generator::generate_serialize_field(ofstream& out, out << "double (protocol, " << name; break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { out << "binary (protocol, " << name << " ? ((GByteArray *) " << name << ")->data : NULL, " << name << " ? ((GByteArray *) " << name << ")->len : 0"; } else { @@ -3756,7 +3781,7 @@ void t_c_glib_generator::generate_serialize_field(ofstream& out, } } -void t_c_glib_generator::generate_serialize_struct(ofstream& out, +void t_c_glib_generator::generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix, int error_ret) { @@ -3766,7 +3791,7 @@ void t_c_glib_generator::generate_serialize_struct(ofstream& out, << indent() << "xfer += ret;" << endl << endl; } -void t_c_glib_generator::generate_serialize_container(ofstream& out, +void t_c_glib_generator::generate_serialize_container(ostream& out, t_type* ttype, string prefix, int error_ret) { @@ -3923,7 +3948,7 @@ void t_c_glib_generator::generate_serialize_container(ofstream& out, scope_down(out); } -void t_c_glib_generator::generate_serialize_map_element(ofstream& out, +void t_c_glib_generator::generate_serialize_map_element(ostream& out, t_map* tmap, string key, string value, @@ -3935,7 +3960,7 @@ void t_c_glib_generator::generate_serialize_map_element(ofstream& out, generate_serialize_field(out, &vfield, "", "", error_ret); } -void t_c_glib_generator::generate_serialize_set_element(ofstream& out, +void t_c_glib_generator::generate_serialize_set_element(ostream& out, t_set* tset, string element, int error_ret) { @@ -3943,7 +3968,7 @@ void t_c_glib_generator::generate_serialize_set_element(ofstream& out, generate_serialize_field(out, &efield, "", "", error_ret); } -void t_c_glib_generator::generate_serialize_list_element(ofstream& out, +void t_c_glib_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string list, string index, @@ -3975,7 +4000,7 @@ void t_c_glib_generator::generate_serialize_list_element(ofstream& out, } /* deserializes a field of any type. */ -void t_c_glib_generator::generate_deserialize_field(ofstream& out, +void t_c_glib_generator::generate_deserialize_field(ostream& out, t_field* tfield, string prefix, string suffix, @@ -4010,7 +4035,7 @@ void t_c_glib_generator::generate_deserialize_field(ofstream& out, throw "compiler error: cannot serialize void field in a struct: " + name; break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { out << "binary (protocol, &data, &len"; } else { out << "string (protocol, &" << name; @@ -4042,7 +4067,7 @@ void t_c_glib_generator::generate_deserialize_field(ofstream& out, << endl; // load the byte array with the data - if (tbase == t_base_type::TYPE_STRING && ((t_base_type*)type)->is_binary()) { + if (tbase == t_base_type::TYPE_STRING && type->is_binary()) { indent(out) << name << " = g_byte_array_new();" << endl; indent(out) << "g_byte_array_append (" << name << ", (guint8 *) data, (guint) len);" << endl; indent(out) << "g_free (data);" << endl; @@ -4061,14 +4086,14 @@ void t_c_glib_generator::generate_deserialize_field(ofstream& out, // if the type is not required and this is a thrift struct (no prefix), // set the isset variable. if the type is required, then set the // local variable indicating the value was set, so that we can do // validation later. - if (tfield->get_req() != t_field::T_REQUIRED && prefix != "") { + if (prefix != "" && tfield->get_req() != t_field::T_REQUIRED) { indent(out) << prefix << "__isset_" << tfield->get_name() << suffix << " = TRUE;" << endl; - } else if (tfield->get_req() == t_field::T_REQUIRED && prefix != "") { + } else if (prefix != "" && tfield->get_req() == t_field::T_REQUIRED) { indent(out) << "isset_" << tfield->get_name() << " = TRUE;" << endl; } } -void t_c_glib_generator::generate_deserialize_struct(ofstream& out, +void t_c_glib_generator::generate_deserialize_struct(ostream& out, t_struct* tstruct, string prefix, int error_ret, @@ -4101,7 +4126,7 @@ void t_c_glib_generator::generate_deserialize_struct(ofstream& out, out << indent() << "}" << endl << indent() << "xfer += ret;" << endl; } -void t_c_glib_generator::generate_deserialize_container(ofstream& out, +void t_c_glib_generator::generate_deserialize_container(ostream& out, t_type* ttype, string prefix, int error_ret) { @@ -4202,7 +4227,7 @@ void t_c_glib_generator::generate_deserialize_container(ofstream& out, scope_down(out); } -void t_c_glib_generator::declare_local_variable(ofstream& out, t_type* ttype, string& name, bool for_hash_table) { +void t_c_glib_generator::declare_local_variable(ostream& out, t_type* ttype, string& name, bool for_hash_table) { string tname = type_name(ttype); /* If the given type is a typedef, find its underlying type so we @@ -4226,7 +4251,7 @@ void t_c_glib_generator::declare_local_variable(ofstream& out, t_type* ttype, st } } -void t_c_glib_generator::declore_local_variable_for_write(ofstream& out, +void t_c_glib_generator::declore_local_variable_for_write(ostream& out, t_type* ttype, string& name) { string tname = type_name(ttype); @@ -4236,7 +4261,7 @@ void t_c_glib_generator::declore_local_variable_for_write(ofstream& out, out << indent() << tname << ptr << name << init_val << ";" << endl; } -void t_c_glib_generator::generate_deserialize_map_element(ofstream& out, +void t_c_glib_generator::generate_deserialize_map_element(ostream& out, t_map* tmap, string prefix, int error_ret) { @@ -4270,7 +4295,7 @@ void t_c_glib_generator::generate_deserialize_map_element(ofstream& out, indent_down(); } -void t_c_glib_generator::generate_deserialize_set_element(ofstream& out, +void t_c_glib_generator::generate_deserialize_set_element(ostream& out, t_set* tset, string prefix, int error_ret) { @@ -4290,7 +4315,7 @@ void t_c_glib_generator::generate_deserialize_set_element(ofstream& out, indent_down(); } -void t_c_glib_generator::generate_deserialize_list_element(ofstream& out, +void t_c_glib_generator::generate_deserialize_list_element(ostream& out, t_list* tlist, string prefix, string index, diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_cl_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_cl_generator.cc new file mode 100644 index 0000000..628d0d8 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_cl_generator.cc @@ -0,0 +1,558 @@ +/* + * Copyright (c) 2008- Patrick Collison + * Copyright (c) 2006- Facebook + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "thrift/platform.h" +#include "t_oop_generator.h" +using namespace std; + + +/** + * Common Lisp code generator. + * + * @author Patrick Collison + */ +class t_cl_generator : public t_oop_generator { + public: + t_cl_generator( + t_program* program, + const std::map& parsed_options, + const std::string& option_string) + : t_oop_generator(program) + { + no_asd = false; + system_prefix = "thrift-gen-"; + + std::map::const_iterator iter; + + for(iter = parsed_options.begin(); iter != parsed_options.end(); ++iter) { + if(iter->first.compare("no_asd") == 0) { + no_asd = true; + } else if (iter->first.compare("sys_pref") == 0) { + system_prefix = iter->second; + } else { + throw "unknown option cl:" + iter->first; + } + } + + out_dir_base_ = "gen-cl"; + copy_options_ = option_string; + } + + void init_generator(); + void close_generator(); + + void generate_typedef (t_typedef* ttypedef); + void generate_enum (t_enum* tenum); + void generate_const (t_const* tconst); + void generate_struct (t_struct* tstruct); + void generate_xception (t_struct* txception); + void generate_service (t_service* tservice); + void generate_cl_struct (std::ostream& out, t_struct* tstruct, bool is_exception); + void generate_cl_struct_internal (std::ostream& out, t_struct* tstruct, bool is_exception); + void generate_exception_sig(std::ostream& out, t_function* f); + std::string render_const_value(t_type* type, t_const_value* value); + + std::string cl_autogen_comment(); + void asdf_def(std::ostream &out); + void package_def(std::ostream &out); + void package_in(std::ostream &out); + std::string generated_package(); + std::string prefix(std::string name); + std::string package_of(t_program* program); + std::string package(); + std::string render_includes(); + + std::string type_name(t_type* ttype); + std::string typespec (t_type *t); + std::string function_signature(t_function* tfunction); + std::string argument_list(t_struct* tstruct); + + std::string cl_docstring(std::string raw); + + private: + + int temporary_var; + /** + * Isolate the variable definitions, as they can require structure definitions + */ + ofstream_with_content_based_conditional_update f_asd_; + ofstream_with_content_based_conditional_update f_types_; + ofstream_with_content_based_conditional_update f_vars_; + + std::string copy_options_; + + bool no_asd; + std::string system_prefix; +}; + + +void t_cl_generator::init_generator() { + MKDIR(get_out_dir().c_str()); + string program_dir = get_out_dir() + "/" + program_name_; + MKDIR(program_dir.c_str()); + + temporary_var = 0; + + string f_types_name = program_dir + "/" + program_name_ + "-types.lisp"; + string f_vars_name = program_dir + "/" + program_name_ + "-vars.lisp"; + + f_types_.open(f_types_name.c_str()); + f_types_ << cl_autogen_comment() << endl; + f_vars_.open(f_vars_name.c_str()); + f_vars_ << cl_autogen_comment() << endl; + + package_def(f_types_); + package_in(f_types_); + package_in(f_vars_); + + if (!no_asd) { + string f_asd_name = program_dir + "/" + system_prefix + program_name_ + ".asd"; + f_asd_.open(f_asd_name.c_str()); + f_asd_ << cl_autogen_comment() << endl; + asdf_def(f_asd_); + } +} + +/** + * Renders all the imports necessary for including another Thrift program + */ +string t_cl_generator::render_includes() { + const vector& includes = program_->get_includes(); + string result = ""; + result += ":depends-on (:thrift"; + for (size_t i = 0; i < includes.size(); ++i) { + result += " :" + system_prefix + underscore(includes[i]->get_name()); + } + result += ")\n"; + return result; +} + +string t_cl_generator::package_of(t_program* program) { + string prefix = program->get_namespace("cl"); + return prefix.empty() ? "thrift-generated" : prefix; +} + +string t_cl_generator::package() { + return package_of(program_); +} + +string t_cl_generator::prefix(string symbol) { + return "\"" + symbol + "\""; +} + +string t_cl_generator::cl_autogen_comment() { + return + std::string(";;; ") + "Autogenerated by Thrift\n" + + ";;; DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING\n" + + ";;; options string: " + copy_options_ + "\n"; +} + +string t_cl_generator::cl_docstring(string raw) { + replace(raw.begin(), raw.end(), '"', '\''); + return raw; +} + + +void t_cl_generator::close_generator() { + f_asd_.close(); + f_types_.close(); + f_vars_.close(); +} + +string t_cl_generator::generated_package() { + return program_->get_namespace("cpp"); +} + +void t_cl_generator::asdf_def(std::ostream &out) { + out << "(asdf:defsystem #:" << system_prefix << program_name_ << endl; + indent_up(); + out << indent() << render_includes() + << indent() << ":serial t" << endl + << indent() << ":components (" + << "(:file \"" << program_name_ << "-types\") " + << "(:file \"" << program_name_ << "-vars\")))" << endl; + indent_down(); +} + +/*** + * Generate a package definition. Add use references equivalent to the idl file's include statements. + */ +void t_cl_generator::package_def(std::ostream &out) { + const vector& includes = program_->get_includes(); + + out << "(thrift:def-package :" << package(); + if ( includes.size() > 0 ) { + out << " :use ("; + for (size_t i = 0; i < includes.size(); ++i) { + out << " :" << includes[i]->get_name(); + } + out << ")"; + } + out << ")" << endl << endl; +} + +void t_cl_generator::package_in(std::ostream &out) { + out << "(cl:in-package :" << package() << ")" << endl << endl; +} + +/** + * Generates a typedef. This is not done in Common Lisp, types are all implicit. + * + * @param ttypedef The type definition + */ +void t_cl_generator::generate_typedef(t_typedef* ttypedef) { + (void)ttypedef; +} + +void t_cl_generator::generate_enum(t_enum* tenum) { + f_types_ << "(thrift:def-enum " << prefix(tenum->get_name()) << endl; + + vector constants = tenum->get_constants(); + vector::iterator c_iter; + int value = -1; + + indent_up(); + f_types_ << indent() << "("; + for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) { + value = (*c_iter)->get_value(); + + if(c_iter != constants.begin()) f_types_ << endl << indent() << " "; + + f_types_ << "(\"" << (*c_iter)->get_name() << "\" . " << value << ")"; + } + indent_down(); + f_types_ << "))" << endl << endl; +} + +/** + * Generate a constant value + */ +void t_cl_generator::generate_const(t_const* tconst) { + t_type* type = tconst->get_type(); + string name = tconst->get_name(); + t_const_value* value = tconst->get_value(); + + f_vars_ << "(thrift:def-constant " << prefix(name) << " " << render_const_value(type, value) << ")" + << endl << endl; +} + +/** + * Prints the value of a constant with the given type. Note that type checking + * is NOT performed in this function as it is always run beforehand using the + * validate_types method in main.cc + */ +string t_cl_generator::render_const_value(t_type* type, t_const_value* value) { + type = get_true_type(type); + std::ostringstream out; + if (type->is_base_type()) { + t_base_type::t_base tbase = ((t_base_type*)type)->get_base(); + switch (tbase) { + case t_base_type::TYPE_STRING: + out << "\"" << value->get_string() << "\""; + break; + case t_base_type::TYPE_BOOL: + out << (value->get_integer() > 0 ? "t" : "nil"); + break; + case t_base_type::TYPE_I8: + case t_base_type::TYPE_I16: + case t_base_type::TYPE_I32: + case t_base_type::TYPE_I64: + out << value->get_integer(); + break; + case t_base_type::TYPE_DOUBLE: + if (value->get_type() == t_const_value::CV_INTEGER) { + out << value->get_integer(); + } else { + out << value->get_double(); + } + break; + default: + throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase); + } + } else if (type->is_enum()) { + indent(out) << value->get_integer(); + } else if (type->is_struct() || type->is_xception()) { + out << (type->is_struct() ? "(make-instance '" : "(make-exception '") << + lowercase(type->get_name()) << " " << endl; + indent_up(); + + const vector& fields = ((t_struct*)type)->get_members(); + vector::const_iterator f_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; + + for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { + t_type* field_type = NULL; + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { + if ((*f_iter)->get_name() == v_iter->first->get_string()) { + field_type = (*f_iter)->get_type(); + } + } + if (field_type == NULL) { + throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string(); + } + + out << indent() << ":" << v_iter->first->get_string() << " " << + render_const_value(field_type, v_iter->second) << endl; + } + out << indent() << ")"; + + indent_down(); + } else if (type->is_map()) { + // emit an hash form with both keys and values to be evaluated + t_type* ktype = ((t_map*)type)->get_key_type(); + t_type* vtype = ((t_map*)type)->get_val_type(); + out << "(thrift:map "; + indent_up(); + const map& val = value->get_map(); + map::const_iterator v_iter; + for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { + out << endl << indent() + << "(cl:cons " << render_const_value(ktype, v_iter->first) << " " + << render_const_value(vtype, v_iter->second) << ")"; + } + indent_down(); + out << indent() << ")"; + } else if (type->is_list() || type->is_set()) { + t_type* etype; + if (type->is_list()) { + etype = ((t_list*)type)->get_elem_type(); + } else { + etype = ((t_set*)type)->get_elem_type(); + } + if (type->is_set()) { + out << "(thrift:set" << endl; + } else { + out << "(thrift:list" << endl; + } + indent_up(); + indent_up(); + const vector& val = value->get_list(); + vector::const_iterator v_iter; + for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { + out << indent() << render_const_value(etype, *v_iter) << endl; + } + out << indent() << ")"; + indent_down(); + indent_down(); + } else { + throw "CANNOT GENERATE CONSTANT FOR TYPE: " + type->get_name(); + } + return out.str(); +} + +void t_cl_generator::generate_struct(t_struct* tstruct) { + generate_cl_struct(f_types_, tstruct, false); +} + +void t_cl_generator::generate_xception(t_struct* txception) { + generate_cl_struct(f_types_, txception, true); +} + +void t_cl_generator::generate_cl_struct_internal(std::ostream& out, t_struct* tstruct, bool is_exception) { + (void)is_exception; + const vector& members = tstruct->get_members(); + vector::const_iterator m_iter; + + out << "("; + + for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { + t_const_value* value = (*m_iter)->get_value(); + t_type* type = (*m_iter)->get_type(); + + if (m_iter != members.begin()) { + out << endl << indent() << " "; + } + out << "(" << prefix((*m_iter)->get_name()) << " " << + ( (NULL != value) ? render_const_value(type, value) : "nil" ) << + " :id " << (*m_iter)->get_key(); + if ( type->is_base_type() && "string" == typespec(type) ) + if ( ((t_base_type*)type)->is_binary() ) + out << " :type binary"; + else + out << " :type string"; + else + out << " :type " << typespec(type); + if ( (*m_iter)->get_req() == t_field::T_OPTIONAL ) { + out << " :optional t"; + } + if ( (*m_iter)->has_doc()) { + out << " :documentation \"" << cl_docstring((*m_iter)->get_doc()) << "\""; + } + out <<")"; + } + + out << ")"; +} + +void t_cl_generator::generate_cl_struct(std::ostream& out, t_struct* tstruct, bool is_exception = false) { + std::string name = type_name(tstruct); + out << (is_exception ? "(thrift:def-exception " : "(thrift:def-struct ") << + prefix(name) << endl; + indent_up(); + if ( tstruct->has_doc() ) { + out << indent() ; + out << "\"" << cl_docstring(tstruct->get_doc()) << "\"" << endl; + } + out << indent() ; + generate_cl_struct_internal(out, tstruct, is_exception); + indent_down(); + out << ")" << endl << endl; +} + +void t_cl_generator::generate_exception_sig(std::ostream& out, t_function* f) { + generate_cl_struct_internal(out, f->get_xceptions(), true); +} + +void t_cl_generator::generate_service(t_service* tservice) { + string extends_client; + vector functions = tservice->get_functions(); + vector::iterator f_iter; + + if (tservice->get_extends() != NULL) { + extends_client = type_name(tservice->get_extends()); + } + + extends_client = extends_client.empty() ? "nil" : prefix(extends_client); + + f_types_ << "(thrift:def-service " << prefix(service_name_) << " " + << extends_client; + + indent_up(); + + if ( tservice->has_doc()) { + f_types_ << endl << indent() + << "(:documentation \"" << cl_docstring(tservice->get_doc()) << "\")"; + } + + for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { + t_function* function = *f_iter; + string fname = function->get_name(); + string signature = function_signature(function); + t_struct* exceptions = function->get_xceptions(); + const vector& xmembers = exceptions->get_members(); + + f_types_ << endl << indent() << "(:method " << prefix(fname); + f_types_ << " (" << signature << " " << typespec((*f_iter)->get_returntype()) << ")"; + if (xmembers.size() > 0) { + f_types_ << endl << indent() << " :exceptions " ; + generate_exception_sig(f_types_, function); + } + if ( (*f_iter)->is_oneway() ) { + f_types_ << endl << indent() << " :oneway t"; + } + if ( (*f_iter)->has_doc() ) { + f_types_ << endl << indent() << " :documentation \"" + << cl_docstring((*f_iter)->get_doc()) << "\""; + } + f_types_ << ")"; + } + + f_types_ << ")" << endl << endl; + + indent_down(); +} + +string t_cl_generator::typespec(t_type *t) { + t = get_true_type(t); + + if (t -> is_binary()){ + return "binary"; + } else if (t->is_base_type()) { + return type_name(t); + } else if (t->is_map()) { + t_map *m = (t_map*) t; + return "(thrift:map " + typespec(m->get_key_type()) + " " + + typespec(m->get_val_type()) + ")"; + } else if (t->is_struct() || t->is_xception()) { + return "(struct " + prefix(type_name(t)) + ")"; + } else if (t->is_list()) { + return "(thrift:list " + typespec(((t_list*) t)->get_elem_type()) + ")"; + } else if (t->is_set()) { + return "(thrift:set " + typespec(((t_set*) t)->get_elem_type()) + ")"; + } else if (t->is_enum()) { + return "(enum \"" + ((t_enum*) t)->get_name() + "\")"; + } else { + throw "Sorry, I don't know how to generate this: " + type_name(t); + } +} + +string t_cl_generator::function_signature(t_function* tfunction) { + return argument_list(tfunction->get_arglist()); +} + +string t_cl_generator::argument_list(t_struct* tstruct) { + stringstream res; + res << "("; + + const vector& fields = tstruct->get_members(); + vector::const_iterator f_iter; + bool first = true; + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { + if (first) { + first = false; + } else { + res << " "; + } + res << "(" + prefix((*f_iter)->get_name()) << " " << + typespec((*f_iter)->get_type()) << " " << + (*f_iter)->get_key() << ")"; + + + } + res << ")"; + return res.str(); +} + +string t_cl_generator::type_name(t_type* ttype) { + string prefix = ""; + t_program* program = ttype->get_program(); + + if (program != NULL && program != program_) + prefix = package_of(program) == package() ? "" : package_of(program) + ":"; + + string name = ttype->get_name(); + + if (ttype->is_struct() || ttype->is_xception()) + name = lowercase(ttype->get_name()); + + return prefix + name; +} + +THRIFT_REGISTER_GENERATOR( + cl, + "Common Lisp", + " no_asd: Do not define ASDF systems for each generated Thrift program.\n" + " sys_pref= The prefix to give ASDF system names. Default: thrift-gen-\n") diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_cocoa_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_cocoa_generator.cc index eba94c0..ac644f5 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_cocoa_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_cocoa_generator.cc @@ -109,35 +109,35 @@ public: bool box_it = false); void generate_cocoa_struct(t_struct* tstruct, bool is_exception); - void generate_cocoa_struct_interface(std::ofstream& out, + void generate_cocoa_struct_interface(std::ostream& out, t_struct* tstruct, bool is_xception = false); - void generate_cocoa_struct_implementation(std::ofstream& out, + void generate_cocoa_struct_implementation(std::ostream& out, t_struct* tstruct, bool is_xception = false, bool is_result = false); - void generate_cocoa_struct_initializer_signature(std::ofstream& out, t_struct* tstruct); - void generate_cocoa_struct_init_with_coder_method(ofstream& out, + void generate_cocoa_struct_initializer_signature(std::ostream& out, t_struct* tstruct); + void generate_cocoa_struct_init_with_coder_method(ostream& out, t_struct* tstruct, bool is_exception); - void generate_cocoa_struct_encode_with_coder_method(ofstream& out, + void generate_cocoa_struct_encode_with_coder_method(ostream& out, t_struct* tstruct, bool is_exception); - void generate_cocoa_struct_copy_method(ofstream& out, + void generate_cocoa_struct_copy_method(ostream& out, t_struct* tstruct, bool is_exception); - void generate_cocoa_struct_hash_method(ofstream& out, t_struct* tstruct); - void generate_cocoa_struct_is_equal_method(ofstream& out, + void generate_cocoa_struct_hash_method(ostream& out, t_struct* tstruct); + void generate_cocoa_struct_is_equal_method(ostream& out, t_struct* tstruct, bool is_exception); - void generate_cocoa_struct_field_accessor_implementations(std::ofstream& out, + void generate_cocoa_struct_field_accessor_implementations(std::ostream& out, t_struct* tstruct, bool is_exception); - void generate_cocoa_struct_reader(std::ofstream& out, t_struct* tstruct); - void generate_cocoa_struct_result_writer(std::ofstream& out, t_struct* tstruct); - void generate_cocoa_struct_writer(std::ofstream& out, t_struct* tstruct); - void generate_cocoa_struct_validator(std::ofstream& out, t_struct* tstruct); - void generate_cocoa_struct_description(std::ofstream& out, t_struct* tstruct); + void generate_cocoa_struct_reader(std::ostream& out, t_struct* tstruct); + void generate_cocoa_struct_result_writer(std::ostream& out, t_struct* tstruct); + void generate_cocoa_struct_writer(std::ostream& out, t_struct* tstruct); + void generate_cocoa_struct_validator(std::ostream& out, t_struct* tstruct); + void generate_cocoa_struct_description(std::ostream& out, t_struct* tstruct); std::string function_result_helper_struct_type(t_service *tservice, t_function* tfunction); std::string function_args_helper_struct_type(t_service* tservice, t_function* tfunction); @@ -147,29 +147,29 @@ public: * Service-level generation functions */ - void generate_cocoa_service_protocol(std::ofstream& out, t_service* tservice); - void generate_cocoa_service_async_protocol(std::ofstream& out, t_service* tservice); + void generate_cocoa_service_protocol(std::ostream& out, t_service* tservice); + void generate_cocoa_service_async_protocol(std::ostream& out, t_service* tservice); - void generate_cocoa_service_client_interface(std::ofstream& out, t_service* tservice); - void generate_cocoa_service_client_async_interface(std::ofstream& out, t_service* tservice); + void generate_cocoa_service_client_interface(std::ostream& out, t_service* tservice); + void generate_cocoa_service_client_async_interface(std::ostream& out, t_service* tservice); - void generate_cocoa_service_client_send_function_implementation(ofstream& out, + void generate_cocoa_service_client_send_function_implementation(ostream& out, t_service* tservice, t_function* tfunction, bool needs_protocol); - void generate_cocoa_service_client_send_function_invocation(ofstream& out, t_function* tfunction); - void generate_cocoa_service_client_send_async_function_invocation(ofstream& out, + void generate_cocoa_service_client_send_function_invocation(ostream& out, t_function* tfunction); + void generate_cocoa_service_client_send_async_function_invocation(ostream& out, t_function* tfunction, string failureBlockName); - void generate_cocoa_service_client_recv_function_implementation(ofstream& out, + void generate_cocoa_service_client_recv_function_implementation(ostream& out, t_service* tservice, t_function* tfunction, bool needs_protocol); - void generate_cocoa_service_client_implementation(std::ofstream& out, t_service* tservice); - void generate_cocoa_service_client_async_implementation(std::ofstream& out, t_service* tservice); + void generate_cocoa_service_client_implementation(std::ostream& out, t_service* tservice); + void generate_cocoa_service_client_async_implementation(std::ostream& out, t_service* tservice); - void generate_cocoa_service_server_interface(std::ofstream& out, t_service* tservice); - void generate_cocoa_service_server_implementation(std::ofstream& out, t_service* tservice); + void generate_cocoa_service_server_interface(std::ostream& out, t_service* tservice); + void generate_cocoa_service_server_implementation(std::ostream& out, t_service* tservice); void generate_cocoa_service_helpers(t_service* tservice); void generate_service_client(t_service* tservice); void generate_service_server(t_service* tservice); @@ -179,34 +179,34 @@ public: * Serialization constructs */ - void generate_deserialize_field(std::ofstream& out, t_field* tfield, std::string fieldName); + void generate_deserialize_field(std::ostream& out, t_field* tfield, std::string fieldName); - void generate_deserialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); + void generate_deserialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); - void generate_deserialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); + void generate_deserialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); - void generate_deserialize_set_element(std::ofstream& out, t_set* tset, std::string prefix = ""); + void generate_deserialize_set_element(std::ostream& out, t_set* tset, std::string prefix = ""); - void generate_deserialize_map_element(std::ofstream& out, t_map* tmap, std::string prefix = ""); + void generate_deserialize_map_element(std::ostream& out, t_map* tmap, std::string prefix = ""); - void generate_deserialize_list_element(std::ofstream& out, + void generate_deserialize_list_element(std::ostream& out, t_list* tlist, std::string prefix = ""); - void generate_serialize_field(std::ofstream& out, t_field* tfield, std::string prefix = ""); + void generate_serialize_field(std::ostream& out, t_field* tfield, std::string prefix = ""); - void generate_serialize_struct(std::ofstream& out, t_struct* tstruct, std::string fieldName = ""); + void generate_serialize_struct(std::ostream& out, t_struct* tstruct, std::string fieldName = ""); - void generate_serialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); + void generate_serialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); - void generate_serialize_map_element(std::ofstream& out, + void generate_serialize_map_element(std::ostream& out, t_map* tmap, std::string iter, std::string map); - void generate_serialize_set_element(std::ofstream& out, t_set* tmap, std::string iter); + void generate_serialize_set_element(std::ostream& out, t_set* tmap, std::string iter); - void generate_serialize_list_element(std::ofstream& out, + void generate_serialize_list_element(std::ostream& out, t_list* tlist, std::string index, std::string listName); @@ -238,6 +238,12 @@ public: std::string getter_name(string field_name); std::string setter_name(string field_name); + bool type_can_be_copy(t_type* ttype) { + ttype = get_true_type(ttype); + + return ttype->is_string(); + } + bool type_can_be_null(t_type* ttype) { ttype = get_true_type(ttype); @@ -254,8 +260,8 @@ private: * File streams */ - std::ofstream f_header_; - std::ofstream f_impl_; + ofstream_with_content_based_conditional_update f_header_; + ofstream_with_content_based_conditional_update f_impl_; bool log_unexpected_; bool validate_required_; @@ -568,7 +574,7 @@ void t_cocoa_generator::generate_xception(t_struct* txception) { * * @param tstruct The struct definition */ -void t_cocoa_generator::generate_cocoa_struct_interface(ofstream& out, +void t_cocoa_generator::generate_cocoa_struct_interface(ostream& out, t_struct* tstruct, bool is_exception) { @@ -618,7 +624,7 @@ void t_cocoa_generator::generate_cocoa_struct_interface(ofstream& out, * Generate signature for initializer of struct with a parameter for * each field. */ -void t_cocoa_generator::generate_cocoa_struct_initializer_signature(ofstream& out, +void t_cocoa_generator::generate_cocoa_struct_initializer_signature(ostream& out, t_struct* tstruct) { const vector& members = tstruct->get_members(); vector::const_iterator m_iter; @@ -641,7 +647,7 @@ void t_cocoa_generator::generate_cocoa_struct_initializer_signature(ofstream& ou * Generate the initWithCoder method for this struct so it's compatible with * the NSCoding protocol */ -void t_cocoa_generator::generate_cocoa_struct_init_with_coder_method(ofstream& out, +void t_cocoa_generator::generate_cocoa_struct_init_with_coder_method(ostream& out, t_struct* tstruct, bool is_exception) { @@ -713,7 +719,7 @@ void t_cocoa_generator::generate_cocoa_struct_init_with_coder_method(ofstream& o * Generate the encodeWithCoder method for this struct so it's compatible with * the NSCoding protocol */ -void t_cocoa_generator::generate_cocoa_struct_encode_with_coder_method(ofstream& out, +void t_cocoa_generator::generate_cocoa_struct_encode_with_coder_method(ostream& out, t_struct* tstruct, bool is_exception) { @@ -780,7 +786,7 @@ void t_cocoa_generator::generate_cocoa_struct_encode_with_coder_method(ofstream& /** * Generate the copy method for this struct */ -void t_cocoa_generator::generate_cocoa_struct_copy_method(ofstream& out, t_struct* tstruct, bool is_exception) { +void t_cocoa_generator::generate_cocoa_struct_copy_method(ostream& out, t_struct* tstruct, bool is_exception) { out << indent() << "- (instancetype) copyWithZone:(NSZone *)zone" << endl; scope_up(out); @@ -815,7 +821,7 @@ void t_cocoa_generator::generate_cocoa_struct_copy_method(ofstream& out, t_struc /** * Generate the hash method for this struct */ -void t_cocoa_generator::generate_cocoa_struct_hash_method(ofstream& out, t_struct* tstruct) { +void t_cocoa_generator::generate_cocoa_struct_hash_method(ostream& out, t_struct* tstruct) { indent(out) << "- (NSUInteger) hash" << endl; scope_up(out); out << indent() << "NSUInteger hash = 17;" << endl; @@ -846,7 +852,7 @@ void t_cocoa_generator::generate_cocoa_struct_hash_method(ofstream& out, t_struc /** * Generate the isEqual method for this struct */ -void t_cocoa_generator::generate_cocoa_struct_is_equal_method(ofstream& out, t_struct* tstruct, bool is_exception) { +void t_cocoa_generator::generate_cocoa_struct_is_equal_method(ostream& out, t_struct* tstruct, bool is_exception) { indent(out) << "- (BOOL) isEqual: (id) anObject" << endl; scope_up(out); @@ -913,7 +919,7 @@ void t_cocoa_generator::generate_cocoa_struct_is_equal_method(ofstream& out, t_s * @param is_exception Is this an exception? * @param is_result If this is a result it needs a different writer */ -void t_cocoa_generator::generate_cocoa_struct_implementation(ofstream& out, +void t_cocoa_generator::generate_cocoa_struct_implementation(ostream& out, t_struct* tstruct, bool is_exception, bool is_result) { @@ -1017,7 +1023,7 @@ void t_cocoa_generator::generate_cocoa_struct_implementation(ofstream& out, * * @param tstruct The struct definition */ -void t_cocoa_generator::generate_cocoa_struct_reader(ofstream& out, t_struct* tstruct) { +void t_cocoa_generator::generate_cocoa_struct_reader(ostream& out, t_struct* tstruct) { out << "- (BOOL) read: (id ) inProtocol error: (NSError *__autoreleasing *)__thriftError" << endl; scope_up(out); @@ -1111,7 +1117,7 @@ void t_cocoa_generator::generate_cocoa_struct_reader(ofstream& out, t_struct* ts * * @param tstruct The struct definition */ -void t_cocoa_generator::generate_cocoa_struct_writer(ofstream& out, t_struct* tstruct) { +void t_cocoa_generator::generate_cocoa_struct_writer(ostream& out, t_struct* tstruct) { out << indent() << "- (BOOL) write: (id ) outProtocol error: (NSError *__autoreleasing *)__thriftError {" << endl; indent_up(); @@ -1162,7 +1168,7 @@ void t_cocoa_generator::generate_cocoa_struct_writer(ofstream& out, t_struct* ts * * @param tstruct The struct definition */ -void t_cocoa_generator::generate_cocoa_struct_result_writer(ofstream& out, t_struct* tstruct) { +void t_cocoa_generator::generate_cocoa_struct_result_writer(ostream& out, t_struct* tstruct) { out << indent() << "- (BOOL) write: (id ) outProtocol error: (NSError *__autoreleasing *)__thriftError {" << endl; indent_up(); @@ -1225,7 +1231,7 @@ void t_cocoa_generator::generate_cocoa_struct_result_writer(ofstream& out, t_str * * @param tstruct The struct definition */ -void t_cocoa_generator::generate_cocoa_struct_validator(ofstream& out, t_struct* tstruct) { +void t_cocoa_generator::generate_cocoa_struct_validator(ostream& out, t_struct* tstruct) { out << indent() << "- (BOOL) validate: (NSError *__autoreleasing *)__thriftError {" << endl; indent_up(); @@ -1259,7 +1265,7 @@ void t_cocoa_generator::generate_cocoa_struct_validator(ofstream& out, t_struct* * * @param tstruct The struct definition */ -void t_cocoa_generator::generate_cocoa_struct_field_accessor_implementations(ofstream& out, +void t_cocoa_generator::generate_cocoa_struct_field_accessor_implementations(ostream& out, t_struct* tstruct, bool is_exception) { (void)is_exception; @@ -1298,7 +1304,7 @@ void t_cocoa_generator::generate_cocoa_struct_field_accessor_implementations(ofs * * @param tstruct The struct definition */ -void t_cocoa_generator::generate_cocoa_struct_description(ofstream& out, t_struct* tstruct) { +void t_cocoa_generator::generate_cocoa_struct_description(ostream& out, t_struct* tstruct) { // Allow use of debugDescription so the app can add description via a cateogory/extension if (debug_descriptions_) { @@ -1428,7 +1434,7 @@ void t_cocoa_generator::generate_function_helpers(t_service *tservice, t_functio * * @param tservice The service to generate a protocol definition for */ -void t_cocoa_generator::generate_cocoa_service_protocol(ofstream& out, t_service* tservice) { +void t_cocoa_generator::generate_cocoa_service_protocol(ostream& out, t_service* tservice) { out << "@protocol " << cocoa_prefix_ << tservice->get_name() << " " << endl; vector functions = tservice->get_functions(); @@ -1452,7 +1458,7 @@ void t_cocoa_generator::generate_cocoa_service_protocol(ofstream& out, t_service * * @param tservice The service to generate a protocol definition for */ -void t_cocoa_generator::generate_cocoa_service_async_protocol(ofstream& out, t_service* tservice) { +void t_cocoa_generator::generate_cocoa_service_async_protocol(ostream& out, t_service* tservice) { out << "@protocol " << cocoa_prefix_ << tservice->get_name() << "Async" << " " << endl; @@ -1472,7 +1478,7 @@ void t_cocoa_generator::generate_cocoa_service_async_protocol(ofstream& out, t_s * * @param tservice The service to generate a client interface definition for */ -void t_cocoa_generator::generate_cocoa_service_client_interface(ofstream& out, +void t_cocoa_generator::generate_cocoa_service_client_interface(ostream& out, t_service* tservice) { out << "@interface " << cocoa_prefix_ << tservice->get_name() << "Client : TBaseClient <" << cocoa_prefix_ << tservice->get_name() << "> " << endl; @@ -1488,7 +1494,7 @@ void t_cocoa_generator::generate_cocoa_service_client_interface(ofstream& out, * * @param tservice The service to generate a client interface definition for */ -void t_cocoa_generator::generate_cocoa_service_client_async_interface(ofstream& out, +void t_cocoa_generator::generate_cocoa_service_client_async_interface(ostream& out, t_service* tservice) { out << "@interface " << cocoa_prefix_ << tservice->get_name() << "ClientAsync : TBaseClient <" << cocoa_prefix_ << tservice->get_name() << "Async> " << endl @@ -1506,7 +1512,7 @@ void t_cocoa_generator::generate_cocoa_service_client_async_interface(ofstream& * * @param tservice The service to generate a client interface definition for */ -void t_cocoa_generator::generate_cocoa_service_server_interface(ofstream& out, +void t_cocoa_generator::generate_cocoa_service_server_interface(ostream& out, t_service* tservice) { out << "@interface " << cocoa_prefix_ << tservice->get_name() << "Processor : NSObject " << endl; @@ -1519,7 +1525,7 @@ void t_cocoa_generator::generate_cocoa_service_server_interface(ofstream& out, } void t_cocoa_generator::generate_cocoa_service_client_send_function_implementation( - ofstream& out, + ostream& out, t_service *tservice, t_function* tfunction, bool needs_protocol) { @@ -1577,7 +1583,7 @@ void t_cocoa_generator::generate_cocoa_service_client_send_function_implementati } void t_cocoa_generator::generate_cocoa_service_client_recv_function_implementation( - ofstream& out, + ostream& out, t_service* tservice, t_function* tfunction, bool needs_protocol) { @@ -1666,7 +1672,7 @@ void t_cocoa_generator::generate_cocoa_service_client_recv_function_implementati * @param tfunction The service to generate an implementation for */ void t_cocoa_generator::generate_cocoa_service_client_send_function_invocation( - ofstream& out, + ostream& out, t_function* tfunction) { t_struct* arg_struct = tfunction->get_arglist(); @@ -1696,7 +1702,7 @@ void t_cocoa_generator::generate_cocoa_service_client_send_function_invocation( * @param tfunction The service to generate an implementation for */ void t_cocoa_generator::generate_cocoa_service_client_send_async_function_invocation( - ofstream& out, + ostream& out, t_function* tfunction, string failureBlockName) { @@ -1730,7 +1736,7 @@ void t_cocoa_generator::generate_cocoa_service_client_send_async_function_invoca * * @param tservice The service to generate an implementation for */ -void t_cocoa_generator::generate_cocoa_service_client_implementation(ofstream& out, +void t_cocoa_generator::generate_cocoa_service_client_implementation(ostream& out, t_service* tservice) { string name = cocoa_prefix_ + tservice->get_name() + "Client"; @@ -1814,7 +1820,7 @@ void t_cocoa_generator::generate_cocoa_service_client_implementation(ofstream& o * * @param tservice The service to generate an implementation for */ -void t_cocoa_generator::generate_cocoa_service_client_async_implementation(ofstream& out, +void t_cocoa_generator::generate_cocoa_service_client_async_implementation(ostream& out, t_service* tservice) { string name = cocoa_prefix_ + tservice->get_name() + "ClientAsync"; @@ -1974,7 +1980,7 @@ void t_cocoa_generator::generate_cocoa_service_client_async_implementation(ofstr * * @param tservice The service to generate an implementation for */ -void t_cocoa_generator::generate_cocoa_service_server_implementation(ofstream& out, +void t_cocoa_generator::generate_cocoa_service_server_implementation(ostream& out, t_service* tservice) { string name = cocoa_prefix_ + tservice->get_name() + "Processor"; @@ -2150,7 +2156,7 @@ void t_cocoa_generator::generate_cocoa_service_server_implementation(ofstream& o * @param tfield The field * @param fieldName The variable name for this field */ -void t_cocoa_generator::generate_deserialize_field(ofstream& out, +void t_cocoa_generator::generate_deserialize_field(ostream& out, t_field* tfield, string fieldName) { t_type* type = get_true_type(tfield->get_type()); @@ -2174,7 +2180,7 @@ void t_cocoa_generator::generate_deserialize_field(ofstream& out, throw "compiler error: cannot serialize void field in a struct: " + tfield->get_name(); break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { out << "readBinary:&" << fieldName << " error: __thriftError]"; } else { out << "readString:&" << fieldName << " error: __thriftError]"; @@ -2216,7 +2222,7 @@ void t_cocoa_generator::generate_deserialize_field(ofstream& out, /** * Generates an unserializer for a struct, allocates the struct and invokes read: */ -void t_cocoa_generator::generate_deserialize_struct(ofstream& out, +void t_cocoa_generator::generate_deserialize_struct(ostream& out, t_struct* tstruct, string fieldName) { indent(out) << type_name(tstruct) << fieldName << " = [[" << type_name(tstruct, true) @@ -2227,7 +2233,7 @@ void t_cocoa_generator::generate_deserialize_struct(ofstream& out, /** * Deserializes a container by reading its size and then iterating */ -void t_cocoa_generator::generate_deserialize_container(ofstream& out, +void t_cocoa_generator::generate_deserialize_container(ostream& out, t_type* ttype, string fieldName) { string size = tmp("_size"); @@ -2348,7 +2354,7 @@ string t_cocoa_generator::unbox(t_type* ttype, string field_name) { /** * Generates code to deserialize a map element */ -void t_cocoa_generator::generate_deserialize_map_element(ofstream& out, +void t_cocoa_generator::generate_deserialize_map_element(ostream& out, t_map* tmap, string fieldName) { string key = tmp("_key"); @@ -2368,7 +2374,7 @@ void t_cocoa_generator::generate_deserialize_map_element(ofstream& out, /** * Deserializes a set element */ -void t_cocoa_generator::generate_deserialize_set_element(ofstream& out, +void t_cocoa_generator::generate_deserialize_set_element(ostream& out, t_set* tset, string fieldName) { string elem = tmp("_elem"); @@ -2383,7 +2389,7 @@ void t_cocoa_generator::generate_deserialize_set_element(ofstream& out, /** * Deserializes a list element */ -void t_cocoa_generator::generate_deserialize_list_element(ofstream& out, +void t_cocoa_generator::generate_deserialize_list_element(ostream& out, t_list* tlist, string fieldName) { string elem = tmp("_elem"); @@ -2401,7 +2407,7 @@ void t_cocoa_generator::generate_deserialize_list_element(ofstream& out, * @param tfield The field to serialize * @param fieldName Name to of the variable holding the field */ -void t_cocoa_generator::generate_serialize_field(ofstream& out, t_field* tfield, string fieldName) { +void t_cocoa_generator::generate_serialize_field(ostream& out, t_field* tfield, string fieldName) { t_type* type = get_true_type(tfield->get_type()); // Do nothing for void types @@ -2423,7 +2429,7 @@ void t_cocoa_generator::generate_serialize_field(ofstream& out, t_field* tfield, throw "compiler error: cannot serialize void field in a struct: " + fieldName; break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { out << "writeBinary: " << fieldName << " error: __thriftError]"; } else { out << "writeString: " << fieldName << " error: __thriftError]"; @@ -2468,7 +2474,7 @@ void t_cocoa_generator::generate_serialize_field(ofstream& out, t_field* tfield, * @param tstruct The struct to serialize * @param fieldName Name of variable holding struct */ -void t_cocoa_generator::generate_serialize_struct(ofstream& out, +void t_cocoa_generator::generate_serialize_struct(ostream& out, t_struct* tstruct, string fieldName) { (void)tstruct; @@ -2481,7 +2487,7 @@ void t_cocoa_generator::generate_serialize_struct(ofstream& out, * @param ttype The type of container * @param fieldName Name of variable holding container */ -void t_cocoa_generator::generate_serialize_container(ofstream& out, +void t_cocoa_generator::generate_serialize_container(ostream& out, t_type* ttype, string fieldName) { scope_up(out); @@ -2547,7 +2553,7 @@ void t_cocoa_generator::generate_serialize_container(ofstream& out, /** * Serializes the members of a map. */ -void t_cocoa_generator::generate_serialize_map_element(ofstream& out, +void t_cocoa_generator::generate_serialize_map_element(ostream& out, t_map* tmap, string key, string mapName) { @@ -2560,7 +2566,7 @@ void t_cocoa_generator::generate_serialize_map_element(ofstream& out, /** * Serializes the members of a set. */ -void t_cocoa_generator::generate_serialize_set_element(ofstream& out, +void t_cocoa_generator::generate_serialize_set_element(ostream& out, t_set* tset, string elementName) { t_field efield(tset->get_elem_type(), elementName); @@ -2570,7 +2576,7 @@ void t_cocoa_generator::generate_serialize_set_element(ofstream& out, /** * Serializes the members of a list. */ -void t_cocoa_generator::generate_serialize_list_element(ofstream& out, +void t_cocoa_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string index, string listName) { @@ -2733,8 +2739,8 @@ void t_cocoa_generator::print_const_value(ostream& out, indent(out); const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; if (defval) out << type_name(type) << " "; out << name << " = [" << type_name(type, true) << " new];" @@ -2758,8 +2764,8 @@ void t_cocoa_generator::print_const_value(ostream& out, indent(mapout); t_type* ktype = ((t_map*)type)->get_key_type(); t_type* vtype = ((t_map*)type)->get_val_type(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; if (defval) mapout << type_name(type) << " "; mapout << name << " = @{"; @@ -2824,7 +2830,7 @@ string t_cocoa_generator::render_const_value(ostream& out, case t_base_type::TYPE_STRING: // We must handle binary constant but the syntax of IDL defines // nothing about binary constant. - // if ((t_base_type*)type)->is_binary()) + // if type->is_binary()) // // binary code render << "@\"" << get_escaped_string(value) << '"'; break; @@ -2904,8 +2910,8 @@ string t_cocoa_generator::render_const_value(string name, } else if (type->is_struct() || type->is_xception()) { const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; if (val.size() > 0) render << "[[" << type_name(type, true) << " alloc] initWith"; else @@ -2937,8 +2943,8 @@ string t_cocoa_generator::render_const_value(string name, render << "[[NSDictionary alloc] initWithObjectsAndKeys: "; t_type* ktype = ((t_map*)type)->get_key_type(); t_type* vtype = ((t_map*)type)->get_val_type(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; bool first = true; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { string key = render_const_value(name, ktype, v_iter->first, true); @@ -3011,7 +3017,9 @@ string t_cocoa_generator::declare_property(t_field* tfield) { std::ostringstream render; render << "@property ("; - if (type_can_be_null(tfield->get_type())) { + if (type_can_be_copy(tfield->get_type())) { + render << "copy, "; + } else if (type_can_be_null(tfield->get_type())) { render << "strong, "; } else { render << "assign, "; diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_cpp_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_cpp_generator.cc index cbe8da2..3e8f728 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_cpp_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_cpp_generator.cc @@ -24,7 +24,9 @@ #include #include +#include #include +#include #include #include #include @@ -64,6 +66,9 @@ public: gen_templates_ = false; gen_templates_only_ = false; gen_moveable_ = false; + gen_no_ostream_operators_ = false; + gen_no_skeleton_ = false; + for( iter = parsed_options.begin(); iter != parsed_options.end(); ++iter) { if( iter->first.compare("pure_enums") == 0) { gen_pure_enums_ = true; @@ -80,6 +85,10 @@ public: gen_templates_only_ = (iter->second == "only"); } else if( iter->first.compare("moveable_types") == 0) { gen_moveable_ = true; + } else if ( iter->first.compare("no_ostream_operators") == 0) { + gen_no_ostream_operators_ = true; + } else if ( iter->first.compare("no_skeleton") == 0) { + gen_no_skeleton_ = true; } else { throw "unknown option cpp:" + iter->first; } @@ -103,6 +112,8 @@ public: void generate_typedef(t_typedef* ttypedef); void generate_enum(t_enum* tenum); + void generate_enum_ostream_operator_decl(std::ostream& out, t_enum* tenum); + void generate_enum_ostream_operator(std::ostream& out, t_enum* tenum); void generate_forward_declaration(t_struct* tstruct); void generate_struct(t_struct* tstruct) { generate_cpp_struct(tstruct, false); } void generate_xception(t_struct* txception) { generate_cpp_struct(txception, true); } @@ -110,13 +121,13 @@ public: void generate_service(t_service* tservice); - void print_const_value(std::ofstream& out, std::string name, t_type* type, t_const_value* value); - std::string render_const_value(std::ofstream& out, + void print_const_value(std::ostream& out, std::string name, t_type* type, t_const_value* value); + std::string render_const_value(std::ostream& out, std::string name, t_type* type, t_const_value* value); - void generate_struct_declaration(std::ofstream& out, + void generate_struct_declaration(std::ostream& out, t_struct* tstruct, bool is_exception = false, bool pointers = false, @@ -124,25 +135,26 @@ public: bool write = true, bool swap = false, bool is_user_struct = false); - void generate_struct_definition(std::ofstream& out, - std::ofstream& force_cpp_out, + void generate_struct_definition(std::ostream& out, + std::ostream& force_cpp_out, t_struct* tstruct, - bool setters = true); - void generate_copy_constructor(std::ofstream& out, t_struct* tstruct, bool is_exception); - void generate_move_constructor(std::ofstream& out, t_struct* tstruct, bool is_exception); - void generate_constructor_helper(std::ofstream& out, + bool setters = true, + bool is_user_struct = false); + void generate_copy_constructor(std::ostream& out, t_struct* tstruct, bool is_exception); + void generate_move_constructor(std::ostream& out, t_struct* tstruct, bool is_exception); + void generate_constructor_helper(std::ostream& out, t_struct* tstruct, bool is_excpetion, bool is_move); - void generate_assignment_operator(std::ofstream& out, t_struct* tstruct); - void generate_move_assignment_operator(std::ofstream& out, t_struct* tstruct); - void generate_assignment_helper(std::ofstream& out, t_struct* tstruct, bool is_move); - void generate_struct_reader(std::ofstream& out, t_struct* tstruct, bool pointers = false); - void generate_struct_writer(std::ofstream& out, t_struct* tstruct, bool pointers = false); - void generate_struct_result_writer(std::ofstream& out, t_struct* tstruct, bool pointers = false); - void generate_struct_swap(std::ofstream& out, t_struct* tstruct); - void generate_struct_print_method(std::ofstream& out, t_struct* tstruct); - void generate_exception_what_method(std::ofstream& out, t_struct* tstruct); + void generate_assignment_operator(std::ostream& out, t_struct* tstruct); + void generate_move_assignment_operator(std::ostream& out, t_struct* tstruct); + void generate_assignment_helper(std::ostream& out, t_struct* tstruct, bool is_move); + void generate_struct_reader(std::ostream& out, t_struct* tstruct, bool pointers = false); + void generate_struct_writer(std::ostream& out, t_struct* tstruct, bool pointers = false); + void generate_struct_result_writer(std::ostream& out, t_struct* tstruct, bool pointers = false); + void generate_struct_swap(std::ostream& out, t_struct* tstruct); + void generate_struct_print_method(std::ostream& out, t_struct* tstruct); + void generate_exception_what_method(std::ostream& out, t_struct* tstruct); /** * Service-level generation functions @@ -167,45 +179,45 @@ public: * Serialization constructs */ - void generate_deserialize_field(std::ofstream& out, + void generate_deserialize_field(std::ostream& out, t_field* tfield, std::string prefix = "", std::string suffix = ""); - void generate_deserialize_struct(std::ofstream& out, + void generate_deserialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = "", bool pointer = false); - void generate_deserialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); + void generate_deserialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); - void generate_deserialize_set_element(std::ofstream& out, t_set* tset, std::string prefix = ""); + void generate_deserialize_set_element(std::ostream& out, t_set* tset, std::string prefix = ""); - void generate_deserialize_map_element(std::ofstream& out, t_map* tmap, std::string prefix = ""); + void generate_deserialize_map_element(std::ostream& out, t_map* tmap, std::string prefix = ""); - void generate_deserialize_list_element(std::ofstream& out, + void generate_deserialize_list_element(std::ostream& out, t_list* tlist, std::string prefix, bool push_back, std::string index); - void generate_serialize_field(std::ofstream& out, + void generate_serialize_field(std::ostream& out, t_field* tfield, std::string prefix = "", std::string suffix = ""); - void generate_serialize_struct(std::ofstream& out, + void generate_serialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = "", bool pointer = false); - void generate_serialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); + void generate_serialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); - void generate_serialize_map_element(std::ofstream& out, t_map* tmap, std::string iter); + void generate_serialize_map_element(std::ostream& out, t_map* tmap, std::string iter); - void generate_serialize_set_element(std::ofstream& out, t_set* tmap, std::string iter); + void generate_serialize_set_element(std::ostream& out, t_set* tmap, std::string iter); - void generate_serialize_list_element(std::ofstream& out, t_list* tlist, std::string iter); + void generate_serialize_list_element(std::ostream& out, t_list* tlist, std::string iter); void generate_function_call(ostream& out, t_function* tfunction, @@ -236,15 +248,16 @@ public: std::string argument_list(t_struct* tstruct, bool name_params = true, bool start_comma = false); std::string type_to_enum(t_type* ttype); - void generate_enum_constant_list(std::ofstream& f, + void generate_enum_constant_list(std::ostream& f, const vector& constants, const char* prefix, const char* suffix, bool include_values); - void generate_struct_ostream_operator(std::ofstream& f, t_struct* tstruct); - void generate_struct_print_method_decl(std::ofstream& f, t_struct* tstruct); - void generate_exception_what_method_decl(std::ofstream& f, + void generate_struct_ostream_operator_decl(std::ostream& f, t_struct* tstruct); + void generate_struct_ostream_operator(std::ostream& f, t_struct* tstruct); + void generate_struct_print_method_decl(std::ostream& f, t_struct* tstruct); + void generate_exception_what_method_decl(std::ostream& f, t_struct* tstruct, bool external = false); @@ -260,6 +273,22 @@ public: void set_use_include_prefix(bool use_include_prefix) { use_include_prefix_ = use_include_prefix; } + /** + * The compiler option "no_thrift_ostream_impl" can be used to prevent + * the compiler from emitting implementations for operator <<. In this + * case the consuming application must provide any needed to build. + * + * To disable this on a per structure bases, one can alternatively set + * the annotation "cpp.customostream" to prevent thrift from emitting an + * operator << (std::ostream&). + * + * See AnnotationTest for validation of this annotation feature. + */ + bool has_custom_ostream(t_type* ttype) const { + return (gen_no_ostream_operators_) || + (ttype->annotations_.find("cpp.customostream") != ttype->annotations_.end()); + } + private: /** * Returns the include prefix to use for a file generated by program, or the @@ -288,6 +317,11 @@ private: */ bool gen_moveable_; + /** + * True if we should generate ostream definitions + */ + bool gen_no_ostream_operators_; + /** * True iff we should use a path prefix in our #include statements for other * thrift-generated header files. @@ -309,6 +343,11 @@ private: */ bool gen_no_default_operators_; + /** + * True if we should generate skeleton. + */ + bool gen_no_skeleton_; + /** * Strings for namespace, computed once up front then used directly */ @@ -321,12 +360,12 @@ private: * function. */ - std::ofstream f_types_; - std::ofstream f_types_impl_; - std::ofstream f_types_tcc_; - std::ofstream f_header_; - std::ofstream f_service_; - std::ofstream f_service_tcc_; + ofstream_with_content_based_conditional_update f_types_; + ofstream_with_content_based_conditional_update f_types_impl_; + ofstream_with_content_based_conditional_update f_types_tcc_; + ofstream_with_content_based_conditional_update f_header_; + ofstream_with_content_based_conditional_update f_service_; + ofstream_with_content_based_conditional_update f_service_tcc_; // The ProcessorGenerator is used to generate parts of the code, // so it needs access to many of our protected members and methods. @@ -347,7 +386,7 @@ void t_cpp_generator::init_generator() { // Make output file string f_types_name = get_out_dir() + program_name_ + "_types.h"; - f_types_.open(f_types_name.c_str()); + f_types_.open(f_types_name); string f_types_impl_name = get_out_dir() + program_name_ + "_types.cpp"; f_types_impl_.open(f_types_impl_name.c_str()); @@ -380,7 +419,7 @@ void t_cpp_generator::init_generator() { << "#include " << endl << endl; // Include C++xx compatibility header - f_types_ << "#include " << endl; + f_types_ << "#include " << endl; // Include other Thrift includes const vector& includes = program_->get_includes(); @@ -466,7 +505,7 @@ void t_cpp_generator::generate_typedef(t_typedef* ttypedef) { << ttypedef->get_symbolic() << ";" << endl << endl; } -void t_cpp_generator::generate_enum_constant_list(std::ofstream& f, +void t_cpp_generator::generate_enum_constant_list(std::ostream& f, const vector& constants, const char* prefix, const char* suffix, @@ -541,6 +580,54 @@ void t_cpp_generator::generate_enum(t_enum* tenum) { << tenum->get_name() << "Values" << ", _k" << tenum->get_name() << "Names), " << "::apache::thrift::TEnumIterator(-1, NULL, NULL));" << endl << endl; + + generate_enum_ostream_operator_decl(f_types_, tenum); + generate_enum_ostream_operator(f_types_impl_, tenum); +} + +void t_cpp_generator::generate_enum_ostream_operator_decl(std::ostream& out, t_enum* tenum) { + + out << "std::ostream& operator<<(std::ostream& out, const "; + if (gen_pure_enums_) { + out << tenum->get_name(); + } else { + out << tenum->get_name() << "::type&"; + } + out << " val);" << endl; + out << endl; +} + +void t_cpp_generator::generate_enum_ostream_operator(std::ostream& out, t_enum* tenum) { + + // If we've been told the consuming application will provide an ostream + // operator definition then we only make a declaration: + + if (!has_custom_ostream(tenum)) { + out << "std::ostream& operator<<(std::ostream& out, const "; + if (gen_pure_enums_) { + out << tenum->get_name(); + } else { + out << tenum->get_name() << "::type&"; + } + out << " val) "; + scope_up(out); + + out << indent() << "std::map::const_iterator it = _" + << tenum->get_name() << "_VALUES_TO_NAMES.find(val);" << endl; + out << indent() << "if (it != _" << tenum->get_name() << "_VALUES_TO_NAMES.end()) {" << endl; + indent_up(); + out << indent() << "out << it->second;" << endl; + indent_down(); + out << indent() << "} else {" << endl; + indent_up(); + out << indent() << "out << static_cast(val);" << endl; + indent_down(); + out << indent() << "}" << endl; + + out << indent() << "return out;" << endl; + scope_down(out); + out << endl; + } } /** @@ -548,12 +635,12 @@ void t_cpp_generator::generate_enum(t_enum* tenum) { */ void t_cpp_generator::generate_consts(std::vector consts) { string f_consts_name = get_out_dir() + program_name_ + "_constants.h"; - ofstream f_consts; - f_consts.open(f_consts_name.c_str()); + ofstream_with_content_based_conditional_update f_consts; + f_consts.open(f_consts_name); string f_consts_impl_name = get_out_dir() + program_name_ + "_constants.cpp"; - ofstream f_consts_impl; - f_consts_impl.open(f_consts_impl_name.c_str()); + ofstream_with_content_based_conditional_update f_consts_impl; + f_consts_impl.open(f_consts_impl_name); // Print header f_consts << autogen_comment(); @@ -597,6 +684,7 @@ void t_cpp_generator::generate_consts(std::vector consts) { f_consts.close(); f_consts_impl << endl << ns_close_ << endl << endl; + f_consts_impl.close(); } /** @@ -604,7 +692,7 @@ void t_cpp_generator::generate_consts(std::vector consts) { * is NOT performed in this function as it is always run beforehand using the * validate_types method in main.cc */ -void t_cpp_generator::print_const_value(ofstream& out, +void t_cpp_generator::print_const_value(ostream& out, string name, t_type* type, t_const_value* value) { @@ -618,8 +706,8 @@ void t_cpp_generator::print_const_value(ofstream& out, } else if (type->is_struct() || type->is_xception()) { const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; bool is_nonrequired_field = false; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { t_type* field_type = NULL; @@ -643,8 +731,8 @@ void t_cpp_generator::print_const_value(ofstream& out, } else if (type->is_map()) { t_type* ktype = ((t_map*)type)->get_key_type(); t_type* vtype = ((t_map*)type)->get_val_type(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { string key = render_const_value(out, name, ktype, v_iter->first); string val = render_const_value(out, name, vtype, v_iter->second); @@ -677,7 +765,7 @@ void t_cpp_generator::print_const_value(ofstream& out, /** * */ -string t_cpp_generator::render_const_value(ofstream& out, +string t_cpp_generator::render_const_value(ostream& out, string name, t_type* type, t_const_value* value) { @@ -703,9 +791,9 @@ string t_cpp_generator::render_const_value(ofstream& out, break; case t_base_type::TYPE_DOUBLE: if (value->get_type() == t_const_value::CV_INTEGER) { - render << value->get_integer(); + render << "static_cast(" << value->get_integer() << ")"; } else { - render << value->get_double(); + render << emit_double_as_string(value->get_double()); } break; default: @@ -737,9 +825,9 @@ void t_cpp_generator::generate_forward_declaration(t_struct* tstruct) { */ void t_cpp_generator::generate_cpp_struct(t_struct* tstruct, bool is_exception) { generate_struct_declaration(f_types_, tstruct, is_exception, false, true, true, true, true); - generate_struct_definition(f_types_impl_, f_types_impl_, tstruct); + generate_struct_definition(f_types_impl_, f_types_impl_, tstruct, true, true); - std::ofstream& out = (gen_templates_ ? f_types_tcc_ : f_types_impl_); + std::ostream& out = (gen_templates_ ? f_types_tcc_ : f_types_impl_); generate_struct_reader(out, tstruct); generate_struct_writer(out, tstruct); generate_struct_swap(f_types_impl_, tstruct); @@ -751,19 +839,23 @@ void t_cpp_generator::generate_cpp_struct(t_struct* tstruct, bool is_exception) if (gen_moveable_) { generate_move_assignment_operator(f_types_impl_, tstruct); } - generate_struct_print_method(f_types_impl_, tstruct); + + if (!has_custom_ostream(tstruct)) { + generate_struct_print_method(f_types_impl_, tstruct); + } + if (is_exception) { generate_exception_what_method(f_types_impl_, tstruct); } } -void t_cpp_generator::generate_copy_constructor(ofstream& out, +void t_cpp_generator::generate_copy_constructor(ostream& out, t_struct* tstruct, bool is_exception) { generate_constructor_helper(out, tstruct, is_exception, /*is_move=*/false); } -void t_cpp_generator::generate_move_constructor(ofstream& out, +void t_cpp_generator::generate_move_constructor(ostream& out, t_struct* tstruct, bool is_exception) { generate_constructor_helper(out, tstruct, is_exception, /*is_move=*/true); @@ -779,7 +871,7 @@ std::string maybeMove(std::string const& other, bool move) { } } -void t_cpp_generator::generate_constructor_helper(ofstream& out, +void t_cpp_generator::generate_constructor_helper(ostream& out, t_struct* tstruct, bool is_exception, bool is_move) { @@ -822,15 +914,15 @@ void t_cpp_generator::generate_constructor_helper(ofstream& out, indent(out) << "}" << endl; } -void t_cpp_generator::generate_assignment_operator(ofstream& out, t_struct* tstruct) { +void t_cpp_generator::generate_assignment_operator(ostream& out, t_struct* tstruct) { generate_assignment_helper(out, tstruct, /*is_move=*/false); } -void t_cpp_generator::generate_move_assignment_operator(ofstream& out, t_struct* tstruct) { +void t_cpp_generator::generate_move_assignment_operator(ostream& out, t_struct* tstruct) { generate_assignment_helper(out, tstruct, /*is_move=*/true); } -void t_cpp_generator::generate_assignment_helper(ofstream& out, t_struct* tstruct, bool is_move) { +void t_cpp_generator::generate_assignment_helper(ostream& out, t_struct* tstruct, bool is_move) { std::string tmp_name = tmp("other"); indent(out) << tstruct->get_name() << "& " << tstruct->get_name() << "::operator=("; @@ -873,7 +965,7 @@ void t_cpp_generator::generate_assignment_helper(ofstream& out, t_struct* tstruc * @param out Output stream * @param tstruct The struct */ -void t_cpp_generator::generate_struct_declaration(ofstream& out, +void t_cpp_generator::generate_struct_declaration(ostream& out, t_struct* tstruct, bool is_exception, bool pointers, @@ -1027,7 +1119,7 @@ void t_cpp_generator::generate_struct_declaration(ofstream& out, continue; } if (is_reference((*m_iter))) { - out << endl << indent() << "void __set_" << (*m_iter)->get_name() << "(boost::shared_ptr<" + out << endl << indent() << "void __set_" << (*m_iter)->get_name() << "(::apache::thrift::stdcxx::shared_ptr<" << type_name((*m_iter)->get_type(), false, false) << ">"; out << " val);" << endl; } else { @@ -1094,7 +1186,7 @@ void t_cpp_generator::generate_struct_declaration(ofstream& out, } out << endl; - if (is_user_struct) { + if (is_user_struct && !has_custom_ostream(tstruct)) { out << indent() << "virtual "; generate_struct_print_method_decl(out, NULL); out << ";" << endl; @@ -1118,14 +1210,15 @@ void t_cpp_generator::generate_struct_declaration(ofstream& out, } if (is_user_struct) { - generate_struct_ostream_operator(out, tstruct); + generate_struct_ostream_operator_decl(out, tstruct); } } -void t_cpp_generator::generate_struct_definition(ofstream& out, - ofstream& force_cpp_out, +void t_cpp_generator::generate_struct_definition(ostream& out, + ostream& force_cpp_out, t_struct* tstruct, - bool setters) { + bool setters, + bool is_user_struct) { // Get members vector::const_iterator m_iter; const vector& members = tstruct->get_members(); @@ -1146,7 +1239,7 @@ void t_cpp_generator::generate_struct_definition(ofstream& out, if (is_reference((*m_iter))) { std::string type = type_name((*m_iter)->get_type()); out << endl << indent() << "void " << tstruct->get_name() << "::__set_" - << (*m_iter)->get_name() << "(boost::shared_ptr<" + << (*m_iter)->get_name() << "(::apache::thrift::stdcxx::shared_ptr<" << type_name((*m_iter)->get_type(), false, false) << ">"; out << " val) {" << endl; } else { @@ -1167,6 +1260,9 @@ void t_cpp_generator::generate_struct_definition(ofstream& out, out << indent() << "}" << endl; } } + if (is_user_struct) { + generate_struct_ostream_operator(out, tstruct); + } out << endl; } @@ -1176,7 +1272,7 @@ void t_cpp_generator::generate_struct_definition(ofstream& out, * @param out Stream to write to * @param tstruct The struct */ -void t_cpp_generator::generate_struct_reader(ofstream& out, t_struct* tstruct, bool pointers) { +void t_cpp_generator::generate_struct_reader(ostream& out, t_struct* tstruct, bool pointers) { if (gen_templates_) { out << indent() << "template " << endl << indent() << "uint32_t " << tstruct->get_name() << "::read(Protocol_* iprot) {" << endl; @@ -1191,7 +1287,7 @@ void t_cpp_generator::generate_struct_reader(ofstream& out, t_struct* tstruct, b // Declare stack tmp variables out << endl - << indent() << "apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);" << endl + << indent() << "::apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);" << endl << indent() << "uint32_t xfer = 0;" << endl << indent() << "std::string fname;" << endl << indent() << "::apache::thrift::protocol::TType ftype;" << endl @@ -1299,7 +1395,7 @@ void t_cpp_generator::generate_struct_reader(ofstream& out, t_struct* tstruct, b * @param out Stream to write to * @param tstruct The struct */ -void t_cpp_generator::generate_struct_writer(ofstream& out, t_struct* tstruct, bool pointers) { +void t_cpp_generator::generate_struct_writer(ostream& out, t_struct* tstruct, bool pointers) { string name = tstruct->get_name(); const vector& fields = tstruct->get_sorted_members(); vector::const_iterator f_iter; @@ -1315,7 +1411,7 @@ void t_cpp_generator::generate_struct_writer(ofstream& out, t_struct* tstruct, b out << indent() << "uint32_t xfer = 0;" << endl; - indent(out) << "apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot);" << endl; + indent(out) << "::apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot);" << endl; indent(out) << "xfer += oprot->writeStructBegin(\"" << name << "\");" << endl; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { @@ -1365,7 +1461,7 @@ void t_cpp_generator::generate_struct_writer(ofstream& out, t_struct* tstruct, b * @param out Output stream * @param tstruct The result struct */ -void t_cpp_generator::generate_struct_result_writer(ofstream& out, +void t_cpp_generator::generate_struct_result_writer(ostream& out, t_struct* tstruct, bool pointers) { string name = tstruct->get_name(); @@ -1429,7 +1525,7 @@ void t_cpp_generator::generate_struct_result_writer(ofstream& out, * @param out Stream to write to * @param tstruct The struct */ -void t_cpp_generator::generate_struct_swap(ofstream& out, t_struct* tstruct) { +void t_cpp_generator::generate_struct_swap(ostream& out, t_struct* tstruct) { out << indent() << "void swap(" << tstruct->get_name() << " &a, " << tstruct->get_name() << " &b) {" << endl; indent_up(); @@ -1466,18 +1562,28 @@ void t_cpp_generator::generate_struct_swap(ofstream& out, t_struct* tstruct) { out << endl; } -void t_cpp_generator::generate_struct_ostream_operator(std::ofstream& out, t_struct* tstruct) { - out << "inline std::ostream& operator<<(std::ostream& out, const " +void t_cpp_generator::generate_struct_ostream_operator_decl(std::ostream& out, t_struct* tstruct) { + out << "std::ostream& operator<<(std::ostream& out, const " << tstruct->get_name() - << "& obj)" << endl; - scope_up(out); - out << indent() << "obj.printTo(out);" << endl - << indent() << "return out;" << endl; - scope_down(out); + << "& obj);" << endl; out << endl; } -void t_cpp_generator::generate_struct_print_method_decl(std::ofstream& out, t_struct* tstruct) { +void t_cpp_generator::generate_struct_ostream_operator(std::ostream& out, t_struct* tstruct) { + if (!has_custom_ostream(tstruct)) { + // thrift defines this behavior + out << "std::ostream& operator<<(std::ostream& out, const " + << tstruct->get_name() + << "& obj)" << endl; + scope_up(out); + out << indent() << "obj.printTo(out);" << endl + << indent() << "return out;" << endl; + scope_down(out); + out << endl; + } +} + +void t_cpp_generator::generate_struct_print_method_decl(std::ostream& out, t_struct* tstruct) { out << "void "; if (tstruct) { out << tstruct->get_name() << "::"; @@ -1485,7 +1591,7 @@ void t_cpp_generator::generate_struct_print_method_decl(std::ofstream& out, t_st out << "printTo(std::ostream& out) const"; } -void t_cpp_generator::generate_exception_what_method_decl(std::ofstream& out, +void t_cpp_generator::generate_exception_what_method_decl(std::ostream& out, t_struct* tstruct, bool external) { out << "const char* "; @@ -1496,33 +1602,33 @@ void t_cpp_generator::generate_exception_what_method_decl(std::ofstream& out, } namespace struct_ostream_operator_generator { -void generate_required_field_value(std::ofstream& out, const t_field* field) { +void generate_required_field_value(std::ostream& out, const t_field* field) { out << " << to_string(" << field->get_name() << ")"; } -void generate_optional_field_value(std::ofstream& out, const t_field* field) { +void generate_optional_field_value(std::ostream& out, const t_field* field) { out << "; (__isset." << field->get_name() << " ? (out"; generate_required_field_value(out, field); out << ") : (out << \"\"))"; } -void generate_field_value(std::ofstream& out, const t_field* field) { +void generate_field_value(std::ostream& out, const t_field* field) { if (field->get_req() == t_field::T_OPTIONAL) generate_optional_field_value(out, field); else generate_required_field_value(out, field); } -void generate_field_name(std::ofstream& out, const t_field* field) { +void generate_field_name(std::ostream& out, const t_field* field) { out << "\"" << field->get_name() << "=\""; } -void generate_field(std::ofstream& out, const t_field* field) { +void generate_field(std::ostream& out, const t_field* field) { generate_field_name(out, field); generate_field_value(out, field); } -void generate_fields(std::ofstream& out, +void generate_fields(std::ostream& out, const vector& fields, const std::string& indent) { const vector::const_iterator beg = fields.begin(); @@ -1544,7 +1650,7 @@ void generate_fields(std::ofstream& out, /** * Generates operator<< */ -void t_cpp_generator::generate_struct_print_method(std::ofstream& out, t_struct* tstruct) { +void t_cpp_generator::generate_struct_print_method(std::ostream& out, t_struct* tstruct) { out << indent(); generate_struct_print_method_decl(out, tstruct); out << " {" << endl; @@ -1563,7 +1669,7 @@ void t_cpp_generator::generate_struct_print_method(std::ofstream& out, t_struct* /** * Generates what() method for exceptions */ -void t_cpp_generator::generate_exception_what_method(std::ofstream& out, t_struct* tstruct) { +void t_cpp_generator::generate_exception_what_method(std::ostream& out, t_struct* tstruct) { out << indent(); generate_exception_what_method_decl(out, tstruct, true); out << " {" << endl; @@ -1612,7 +1718,7 @@ void t_cpp_generator::generate_service(t_service* tservice) { << endl; if (gen_cob_style_) { f_header_ << "#include " << endl << // TMemoryBuffer - "#include " << endl + "#include " << endl << "namespace apache { namespace thrift { namespace async {" << endl << "class TAsyncChannel;" << endl << "}}}" << endl; } @@ -1632,7 +1738,7 @@ void t_cpp_generator::generate_service(t_service* tservice) { f_header_ << endl << ns_open_ << endl << endl; - f_header_ << "#ifdef _WIN32\n" + f_header_ << "#ifdef _MSC_VER\n" " #pragma warning( push )\n" " #pragma warning (disable : 4250 ) //inheriting methods via dominance \n" "#endif\n\n"; @@ -1674,9 +1780,13 @@ void t_cpp_generator::generate_service(t_service* tservice) { generate_service_client(tservice, ""); generate_service_processor(tservice, ""); generate_service_multiface(tservice); - generate_service_skeleton(tservice); generate_service_client(tservice, "Concurrent"); + // Generate skeleton + if (!gen_no_skeleton_) { + generate_service_skeleton(tservice); + } + // Generate all the cob components if (gen_cob_style_) { generate_service_interface(tservice, "CobCl"); @@ -1685,10 +1795,14 @@ void t_cpp_generator::generate_service(t_service* tservice) { generate_service_null(tservice, "CobSv"); generate_service_client(tservice, "Cob"); generate_service_processor(tservice, "Cob"); - generate_service_async_skeleton(tservice); + + if (!gen_no_skeleton_) { + generate_service_async_skeleton(tservice); + } + } - f_header_ << "#ifdef _WIN32\n" + f_header_ << "#ifdef _MSC_VER\n" " #pragma warning( pop )\n" "#endif\n\n"; @@ -1722,7 +1836,7 @@ void t_cpp_generator::generate_service(t_service* tservice) { void t_cpp_generator::generate_service_helpers(t_service* tservice) { vector functions = tservice->get_functions(); vector::iterator f_iter; - std::ofstream& out = (gen_templates_ ? f_service_tcc_ : f_service_); + std::ostream& out = (gen_templates_ ? f_service_tcc_ : f_service_); for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { t_struct* ts = (*f_iter)->get_arglist(); @@ -1854,7 +1968,7 @@ void t_cpp_generator::generate_service_interface_factory(t_service* tservice, st f_header_ << "class " << singleton_factory_name << " : virtual public " << factory_name << " {" << endl << " public:" << endl; indent_up(); - f_header_ << indent() << singleton_factory_name << "(const boost::shared_ptr<" << service_if_name + f_header_ << indent() << singleton_factory_name << "(const ::apache::thrift::stdcxx::shared_ptr<" << service_if_name << ">& iface) : iface_(iface) {}" << endl << indent() << "virtual ~" << singleton_factory_name << "() {}" << endl << endl << indent() << "virtual " << service_if_name << "* getHandler(" @@ -1862,7 +1976,7 @@ void t_cpp_generator::generate_service_interface_factory(t_service* tservice, st << " return iface_.get();" << endl << indent() << "}" << endl << indent() << "virtual void releaseHandler(" << base_if_name << "* /* handler */) {}" << endl; - f_header_ << endl << " protected:" << endl << indent() << "boost::shared_ptr<" << service_if_name + f_header_ << endl << " protected:" << endl << indent() << "::apache::thrift::stdcxx::shared_ptr<" << service_if_name << "> iface_;" << endl; indent_down(); @@ -1958,7 +2072,7 @@ void t_cpp_generator::generate_service_async_skeleton(t_service* tservice) { string ns = namespace_prefix(tservice->get_program()->get_namespace("cpp")); - ofstream f_skeleton; + ofstream_with_content_based_conditional_update f_skeleton; f_skeleton.open(f_skeleton_name.c_str()); f_skeleton << "// This autogenerated skeleton file illustrates one way to adapt a synchronous" << endl << "// interface into an asynchronous interface. You should copy it to another" @@ -1970,8 +2084,7 @@ void t_cpp_generator::generate_service_async_skeleton(t_service* tservice) { << "using namespace ::apache::thrift;" << endl << "using namespace ::apache::thrift::protocol;" << endl << "using namespace ::apache::thrift::transport;" << endl - << "using namespace ::apache::thrift::async;" << endl << endl - << "using boost::shared_ptr;" << endl << endl; + << "using namespace ::apache::thrift::async;" << endl << endl; // the following code would not compile: // using namespace ; @@ -2033,7 +2146,7 @@ void t_cpp_generator::generate_service_multiface(t_service* tservice) { extends_multiface = ", public " + extends + "Multiface"; } - string list_type = string("std::vector >"; + string list_type = string("std::vector >"; // Generate the header portion f_header_ << "class " << service_name_ << "Multiface : " @@ -2044,7 +2157,7 @@ void t_cpp_generator::generate_service_multiface(t_service* tservice) { << "& ifaces) : ifaces_(ifaces) {" << endl; if (!extends.empty()) { f_header_ << indent() - << " std::vector >::iterator iter;" + << " std::vector >::iterator iter;" << endl << indent() << " for (iter = ifaces.begin(); iter != ifaces.end(); ++iter) {" << endl << indent() << " " << extends << "Multiface::add(*iter);" << endl << indent() << " }" << endl; @@ -2057,7 +2170,7 @@ void t_cpp_generator::generate_service_multiface(t_service* tservice) { f_header_ << " protected:" << endl; indent_up(); f_header_ << indent() << list_type << " ifaces_;" << endl << indent() << service_name_ - << "Multiface() {}" << endl << indent() << "void add(boost::shared_ptr<" + << "Multiface() {}" << endl << indent() << "void add(::apache::thrift::stdcxx::shared_ptr<" << service_name_ << "If> iface) {" << endl; if (!extends.empty()) { f_header_ << indent() << " " << extends << "Multiface::add(iface);" << endl; @@ -2127,7 +2240,7 @@ void t_cpp_generator::generate_service_client(t_service* tservice, string style) ifstyle = "CobCl"; } - std::ofstream& out = (gen_templates_ ? f_service_tcc_ : f_service_); + std::ostream& out = (gen_templates_ ? f_service_tcc_ : f_service_); string template_header, template_suffix, short_suffix, protocol_type, _this; string const prot_factory_type = "::apache::thrift::protocol::TProtocolFactory"; if (gen_templates_) { @@ -2139,7 +2252,7 @@ void t_cpp_generator::generate_service_client(t_service* tservice, string style) } else { protocol_type = "::apache::thrift::protocol::TProtocol"; } - string prot_ptr = "boost::shared_ptr< " + protocol_type + ">"; + string prot_ptr = "apache::thrift::stdcxx::shared_ptr< " + protocol_type + ">"; string client_suffix = "Client" + template_suffix; string if_suffix = "If"; if (style == "Cob") { @@ -2216,18 +2329,18 @@ void t_cpp_generator::generate_service_client(t_service* tservice, string style) // Note that these are not currently templated for simplicity. // TODO(simpkins): should they be templated? f_header_ << indent() - << "boost::shared_ptr< ::apache::thrift::protocol::TProtocol> getInputProtocol() {" + << "apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> getInputProtocol() {" << endl << indent() << " return " << _this << "piprot_;" << endl << indent() << "}" << endl; f_header_ << indent() - << "boost::shared_ptr< ::apache::thrift::protocol::TProtocol> getOutputProtocol() {" + << "apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> getOutputProtocol() {" << endl << indent() << " return " << _this << "poprot_;" << endl << indent() << "}" << endl; } else /* if (style == "Cob") */ { f_header_ << indent() << service_name_ << style << "Client" << short_suffix << "(" - << "boost::shared_ptr< ::apache::thrift::async::TAsyncChannel> channel, " + << "apache::thrift::stdcxx::shared_ptr< ::apache::thrift::async::TAsyncChannel> channel, " << "::apache::thrift::protocol::TProtocolFactory* protocolFactory) :" << endl; if (extends.empty()) { f_header_ << indent() << " channel_(channel)," << endl << indent() @@ -2237,9 +2350,9 @@ void t_cpp_generator::generate_service_client(t_service* tservice, string style) if (gen_templates_) { // TProtocolFactory classes return generic TProtocol pointers. // We have to dynamic cast to the Protocol_ type we are expecting. - f_header_ << indent() << " piprot_(boost::dynamic_pointer_cast(" + f_header_ << indent() << " piprot_(::apache::thrift::stdcxx::dynamic_pointer_cast(" << "protocolFactory->getProtocol(itrans_)))," << endl << indent() - << " poprot_(boost::dynamic_pointer_cast(" + << " poprot_(::apache::thrift::stdcxx::dynamic_pointer_cast(" << "protocolFactory->getProtocol(otrans_))) {" << endl; // Throw a TException if either dynamic cast failed. f_header_ << indent() << " if (!piprot_ || !poprot_) {" << endl << indent() @@ -2261,7 +2374,7 @@ void t_cpp_generator::generate_service_client(t_service* tservice, string style) if (style == "Cob") { f_header_ << indent() - << "boost::shared_ptr< ::apache::thrift::async::TAsyncChannel> getChannel() {" << endl + << "::apache::thrift::stdcxx::shared_ptr< ::apache::thrift::async::TAsyncChannel> getChannel() {" << endl << indent() << " return " << _this << "channel_;" << endl << indent() << "}" << endl; if (!gen_no_client_completion_) { f_header_ << indent() << "virtual void completed__(bool /* success */) {}" << endl; @@ -2313,11 +2426,11 @@ void t_cpp_generator::generate_service_client(t_service* tservice, string style) if (style == "Cob") { f_header_ << indent() - << "boost::shared_ptr< ::apache::thrift::async::TAsyncChannel> channel_;" << endl + << "::apache::thrift::stdcxx::shared_ptr< ::apache::thrift::async::TAsyncChannel> channel_;" << endl << indent() - << "boost::shared_ptr< ::apache::thrift::transport::TMemoryBuffer> itrans_;" << endl + << "::apache::thrift::stdcxx::shared_ptr< ::apache::thrift::transport::TMemoryBuffer> itrans_;" << endl << indent() - << "boost::shared_ptr< ::apache::thrift::transport::TMemoryBuffer> otrans_;" + << "::apache::thrift::stdcxx::shared_ptr< ::apache::thrift::transport::TMemoryBuffer> otrans_;" << endl; } f_header_ << @@ -2399,11 +2512,11 @@ void t_cpp_generator::generate_service_client(t_service* tservice, string style) } else { if (!(*f_iter)->is_oneway()) { out << indent() << _this << "channel_->sendAndRecvMessage(" - << "tcxx::bind(cob, this), " << _this << "otrans_.get(), " << _this << "itrans_.get());" + << "::apache::thrift::stdcxx::bind(cob, this), " << _this << "otrans_.get(), " << _this << "itrans_.get());" << endl; } else { out << indent() << _this << "channel_->sendMessage(" - << "tcxx::bind(cob, this), " << _this << "otrans_.get());" << endl; + << "::apache::thrift::stdcxx::bind(cob, this), " << _this << "otrans_.get());" << endl; } } scope_down(out); @@ -2718,8 +2831,8 @@ protected: t_cpp_generator* generator_; t_service* service_; - std::ofstream& f_header_; - std::ofstream& f_out_; + std::ostream& f_header_; + std::ostream& f_out_; string service_name_; string style_; string pstyle_; @@ -2754,8 +2867,8 @@ ProcessorGenerator::ProcessorGenerator(t_cpp_generator* generator, class_name_ = service_name_ + pstyle_ + "Processor"; if_name_ = service_name_ + "CobSvIf"; - finish_cob_ = "tcxx::function cob, "; - finish_cob_decl_ = "tcxx::function, "; + finish_cob_ = "::apache::thrift::stdcxx::function cob, "; + finish_cob_decl_ = "::apache::thrift::stdcxx::function, "; cob_arg_ = "cob, "; ret_type_ = "void "; } else { @@ -2816,7 +2929,7 @@ void ProcessorGenerator::generate_class_definition() { // Protected data members f_header_ << " protected:" << endl; indent_up(); - f_header_ << indent() << "boost::shared_ptr<" << if_name_ << "> iface_;" << endl; + f_header_ << indent() << "::apache::thrift::stdcxx::shared_ptr<" << if_name_ << "> iface_;" << endl; f_header_ << indent() << "virtual " << ret_type_ << "dispatchCall(" << finish_cob_ << "::apache::thrift::protocol::TProtocol* iprot, " << "::apache::thrift::protocol::TProtocol* oprot, " @@ -2872,29 +2985,29 @@ void ProcessorGenerator::generate_class_definition() { ? "" : ", const " + type_name((*f_iter)->get_returntype()) + "& _return"); f_header_ << indent() << "void return_" << (*f_iter)->get_name() - << "(tcxx::function cob, int32_t seqid, " + << "(::apache::thrift::stdcxx::function cob, int32_t seqid, " << "::apache::thrift::protocol::TProtocol* oprot, " << "void* ctx" << ret_arg << ");" << endl; if (generator_->gen_templates_) { f_header_ << indent() << "void return_" << (*f_iter)->get_name() - << "(tcxx::function cob, int32_t seqid, " + << "(::apache::thrift::stdcxx::function cob, int32_t seqid, " << "Protocol_* oprot, void* ctx" << ret_arg << ");" << endl; } // XXX Don't declare throw if it doesn't exist f_header_ << indent() << "void throw_" << (*f_iter)->get_name() - << "(tcxx::function cob, int32_t seqid, " + << "(::apache::thrift::stdcxx::function cob, int32_t seqid, " << "::apache::thrift::protocol::TProtocol* oprot, void* ctx, " << "::apache::thrift::TDelayedException* _throw);" << endl; if (generator_->gen_templates_) { f_header_ << indent() << "void throw_" << (*f_iter)->get_name() - << "(tcxx::function cob, int32_t seqid, " + << "(::apache::thrift::stdcxx::function cob, int32_t seqid, " << "Protocol_* oprot, void* ctx, " << "::apache::thrift::TDelayedException* _throw);" << endl; } } } - f_header_ << " public:" << endl << indent() << class_name_ << "(boost::shared_ptr<" << if_name_ + f_header_ << " public:" << endl << indent() << class_name_ << "(::apache::thrift::stdcxx::shared_ptr<" << if_name_ << "> iface) :" << endl; if (!extends_.empty()) { f_header_ << indent() << " " << extends_ << "(iface)," << endl; @@ -3032,14 +3145,14 @@ void ProcessorGenerator::generate_factory() { << endl << " public:" << endl; indent_up(); - f_header_ << indent() << factory_class_name_ << "(const ::boost::shared_ptr< " << if_factory_name + f_header_ << indent() << factory_class_name_ << "(const ::apache::thrift::stdcxx::shared_ptr< " << if_factory_name << " >& handlerFactory) :" << endl << indent() << " handlerFactory_(handlerFactory) {}" << endl << endl << indent() - << "::boost::shared_ptr< ::apache::thrift::" + << "::apache::thrift::stdcxx::shared_ptr< ::apache::thrift::" << (style_ == "Cob" ? "async::TAsyncProcessor" : "TProcessor") << " > " << "getProcessor(const ::apache::thrift::TConnectionInfo& connInfo);" << endl; - f_header_ << endl << " protected:" << endl << indent() << "::boost::shared_ptr< " + f_header_ << endl << " protected:" << endl << indent() << "::apache::thrift::stdcxx::shared_ptr< " << if_factory_name << " > handlerFactory_;" << endl; indent_down(); @@ -3054,17 +3167,17 @@ void ProcessorGenerator::generate_factory() { } // Generate the getProcessor() method - f_out_ << template_header_ << indent() << "::boost::shared_ptr< ::apache::thrift::" + f_out_ << template_header_ << indent() << "::apache::thrift::stdcxx::shared_ptr< ::apache::thrift::" << (style_ == "Cob" ? "async::TAsyncProcessor" : "TProcessor") << " > " << factory_class_name_ << template_suffix_ << "::getProcessor(" << "const ::apache::thrift::TConnectionInfo& connInfo) {" << endl; indent_up(); f_out_ << indent() << "::apache::thrift::ReleaseHandler< " << if_factory_name - << " > cleanup(handlerFactory_);" << endl << indent() << "::boost::shared_ptr< " + << " > cleanup(handlerFactory_);" << endl << indent() << "::apache::thrift::stdcxx::shared_ptr< " << if_name_ << " > handler(" << "handlerFactory_->getHandler(connInfo), cleanup);" << endl << indent() - << "::boost::shared_ptr< ::apache::thrift::" + << "::apache::thrift::stdcxx::shared_ptr< ::apache::thrift::" << (style_ == "Cob" ? "async::TAsyncProcessor" : "TProcessor") << " > " << "processor(new " << class_name_ << template_suffix_ << "(handler));" << endl << indent() << "return processor;" << endl; @@ -3093,7 +3206,7 @@ void t_cpp_generator::generate_function_helpers(t_service* tservice, t_function* return; } - std::ofstream& out = (gen_templates_ ? f_service_tcc_ : f_service_); + std::ostream& out = (gen_templates_ ? f_service_tcc_ : f_service_); t_struct result(program_, tservice->get_name() + "_" + tfunction->get_name() + "_result"); t_field success(tfunction->get_returntype(), "success", 0); @@ -3140,7 +3253,7 @@ void t_cpp_generator::generate_process_function(t_service* tservice, vector::const_iterator x_iter; string service_func_name = "\"" + tservice->get_name() + "." + tfunction->get_name() + "\""; - std::ofstream& out = (gen_templates_ ? f_service_tcc_ : f_service_); + std::ostream& out = (gen_templates_ ? f_service_tcc_ : f_service_); string prot_type = (specialized ? "Protocol_" : "::apache::thrift::protocol::TProtocol"); string class_suffix; @@ -3299,7 +3412,7 @@ void t_cpp_generator::generate_process_function(t_service* tservice, out << indent() << "template " << endl; } out << "void " << tservice->get_name() << "AsyncProcessor" << class_suffix << "::process_" - << tfunction->get_name() << "(tcxx::function cob, int32_t seqid, " + << tfunction->get_name() << "(::apache::thrift::stdcxx::function cob, int32_t seqid, " << prot_type << "* iprot, " << prot_type << "* oprot)" << endl; scope_up(out); @@ -3356,28 +3469,28 @@ void t_cpp_generator::generate_process_function(t_service* tservice, // No return. Just hand off our cob. // TODO(dreiss): Call the cob immediately? out << indent() << "iface_->" << tfunction->get_name() << "(" - << "tcxx::bind(cob, true)" << endl; + << "::apache::thrift::stdcxx::bind(cob, true)" << endl; indent_up(); indent_up(); } else { string ret_arg, ret_placeholder; if (!tfunction->get_returntype()->is_void()) { ret_arg = ", const " + type_name(tfunction->get_returntype()) + "& _return"; - ret_placeholder = ", tcxx::placeholders::_1"; + ret_placeholder = ", ::apache::thrift::stdcxx::placeholders::_1"; } // When gen_templates_ is true, the return_ and throw_ functions are // overloaded. We have to declare pointers to them so that the compiler // can resolve the correct overloaded version. out << indent() << "void (" << tservice->get_name() << "AsyncProcessor" << class_suffix - << "::*return_fn)(tcxx::function " + << "::*return_fn)(::apache::thrift::stdcxx::function " << "cob, int32_t seqid, " << prot_type << "* oprot, void* ctx" << ret_arg << ") =" << endl; out << indent() << " &" << tservice->get_name() << "AsyncProcessor" << class_suffix << "::return_" << tfunction->get_name() << ";" << endl; if (!xceptions.empty()) { out << indent() << "void (" << tservice->get_name() << "AsyncProcessor" << class_suffix - << "::*throw_fn)(tcxx::function " + << "::*throw_fn)(::apache::thrift::stdcxx::function " << "cob, int32_t seqid, " << prot_type << "* oprot, void* ctx, " << "::apache::thrift::TDelayedException* _throw) =" << endl; out << indent() << " &" << tservice->get_name() << "AsyncProcessor" << class_suffix @@ -3387,11 +3500,11 @@ void t_cpp_generator::generate_process_function(t_service* tservice, out << indent() << "iface_->" << tfunction->get_name() << "(" << endl; indent_up(); indent_up(); - out << indent() << "tcxx::bind(return_fn, this, cob, seqid, oprot, ctx" << ret_placeholder + out << indent() << "::apache::thrift::stdcxx::bind(return_fn, this, cob, seqid, oprot, ctx" << ret_placeholder << ")"; if (!xceptions.empty()) { - out << ',' << endl << indent() << "tcxx::bind(throw_fn, this, cob, seqid, oprot, " - << "ctx, tcxx::placeholders::_1)"; + out << ',' << endl << indent() << "::apache::thrift::stdcxx::bind(throw_fn, this, cob, seqid, oprot, " + << "ctx, ::apache::thrift::stdcxx::placeholders::_1)"; } } @@ -3416,7 +3529,7 @@ void t_cpp_generator::generate_process_function(t_service* tservice, out << indent() << "template " << endl; } out << "void " << tservice->get_name() << "AsyncProcessor" << class_suffix << "::return_" - << tfunction->get_name() << "(tcxx::function cob, int32_t seqid, " + << tfunction->get_name() << "(::apache::thrift::stdcxx::function cob, int32_t seqid, " << prot_type << "* oprot, void* ctx" << ret_arg_decl << ')' << endl; scope_up(out); @@ -3464,7 +3577,7 @@ void t_cpp_generator::generate_process_function(t_service* tservice, out << indent() << "template " << endl; } out << "void " << tservice->get_name() << "AsyncProcessor" << class_suffix << "::throw_" - << tfunction->get_name() << "(tcxx::function cob, int32_t seqid, " + << tfunction->get_name() << "(::apache::thrift::stdcxx::function cob, int32_t seqid, " << prot_type << "* oprot, void* ctx, " << "::apache::thrift::TDelayedException* _throw)" << endl; scope_up(out); @@ -3552,7 +3665,7 @@ void t_cpp_generator::generate_service_skeleton(t_service* tservice) { string ns = namespace_prefix(tservice->get_program()->get_namespace("cpp")); - ofstream f_skeleton; + ofstream_with_content_based_conditional_update f_skeleton; f_skeleton.open(f_skeleton_name.c_str()); f_skeleton << "// This autogenerated skeleton file illustrates how to build a server." << endl << "// You should copy it to another filename to avoid overwriting it." << endl << endl @@ -3564,8 +3677,7 @@ void t_cpp_generator::generate_service_skeleton(t_service* tservice) { << "using namespace ::apache::thrift;" << endl << "using namespace ::apache::thrift::protocol;" << endl << "using namespace ::apache::thrift::transport;" << endl - << "using namespace ::apache::thrift::server;" << endl << endl - << "using boost::shared_ptr;" << endl << endl; + << "using namespace ::apache::thrift::server;" << endl << endl; // the following code would not compile: // using namespace ; @@ -3595,13 +3707,13 @@ void t_cpp_generator::generate_service_skeleton(t_service* tservice) { f_skeleton << indent() << "int main(int argc, char **argv) {" << endl; indent_up(); f_skeleton - << indent() << "int port = 9090;" << endl << indent() << "shared_ptr<" << svcname + << indent() << "int port = 9090;" << endl << indent() << "::apache::thrift::stdcxx::shared_ptr<" << svcname << "Handler> handler(new " << svcname << "Handler());" << endl << indent() - << "shared_ptr processor(new " << svcname << "Processor(handler));" << endl - << indent() << "shared_ptr serverTransport(new TServerSocket(port));" + << "::apache::thrift::stdcxx::shared_ptr processor(new " << svcname << "Processor(handler));" << endl + << indent() << "::apache::thrift::stdcxx::shared_ptr serverTransport(new TServerSocket(port));" << endl << indent() - << "shared_ptr transportFactory(new TBufferedTransportFactory());" << endl - << indent() << "shared_ptr protocolFactory(new TBinaryProtocolFactory());" + << "::apache::thrift::stdcxx::shared_ptr transportFactory(new TBufferedTransportFactory());" << endl + << indent() << "::apache::thrift::stdcxx::shared_ptr protocolFactory(new TBinaryProtocolFactory());" << endl << endl << indent() << "TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory);" << endl << indent() << "server.serve();" << endl << indent() << "return 0;" << endl; @@ -3615,7 +3727,7 @@ void t_cpp_generator::generate_service_skeleton(t_service* tservice) { /** * Deserializes a field of any type. */ -void t_cpp_generator::generate_deserialize_field(ofstream& out, +void t_cpp_generator::generate_deserialize_field(ostream& out, t_field* tfield, string prefix, string suffix) { @@ -3639,7 +3751,7 @@ void t_cpp_generator::generate_deserialize_field(ofstream& out, throw "compiler error: cannot serialize void field in a struct: " + name; break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { out << "readBinary(" << name << ");"; } else { out << "readString(" << name << ");"; @@ -3684,13 +3796,13 @@ void t_cpp_generator::generate_deserialize_field(ofstream& out, * buffer for deserialization, and that there is a variable protocol which * is a reference to a TProtocol serialization object. */ -void t_cpp_generator::generate_deserialize_struct(ofstream& out, +void t_cpp_generator::generate_deserialize_struct(ostream& out, t_struct* tstruct, string prefix, bool pointer) { if (pointer) { indent(out) << "if (!" << prefix << ") { " << endl; - indent(out) << " " << prefix << " = boost::shared_ptr<" << type_name(tstruct) << ">(new " + indent(out) << " " << prefix << " = ::apache::thrift::stdcxx::shared_ptr<" << type_name(tstruct) << ">(new " << type_name(tstruct) << ");" << endl; indent(out) << "}" << endl; indent(out) << "xfer += " << prefix << "->read(iprot);" << endl; @@ -3708,7 +3820,7 @@ void t_cpp_generator::generate_deserialize_struct(ofstream& out, } } -void t_cpp_generator::generate_deserialize_container(ofstream& out, t_type* ttype, string prefix) { +void t_cpp_generator::generate_deserialize_container(ostream& out, t_type* ttype, string prefix) { scope_up(out); string size = tmp("_size"); @@ -3769,7 +3881,7 @@ void t_cpp_generator::generate_deserialize_container(ofstream& out, t_type* ttyp /** * Generates code to deserialize a map */ -void t_cpp_generator::generate_deserialize_map_element(ofstream& out, t_map* tmap, string prefix) { +void t_cpp_generator::generate_deserialize_map_element(ostream& out, t_map* tmap, string prefix) { string key = tmp("_key"); string val = tmp("_val"); t_field fkey(tmap->get_key_type(), key); @@ -3784,7 +3896,7 @@ void t_cpp_generator::generate_deserialize_map_element(ofstream& out, t_map* tma generate_deserialize_field(out, &fval); } -void t_cpp_generator::generate_deserialize_set_element(ofstream& out, t_set* tset, string prefix) { +void t_cpp_generator::generate_deserialize_set_element(ostream& out, t_set* tset, string prefix) { string elem = tmp("_elem"); t_field felem(tset->get_elem_type(), elem); @@ -3795,7 +3907,7 @@ void t_cpp_generator::generate_deserialize_set_element(ofstream& out, t_set* tse indent(out) << prefix << ".insert(" << elem << ");" << endl; } -void t_cpp_generator::generate_deserialize_list_element(ofstream& out, +void t_cpp_generator::generate_deserialize_list_element(ostream& out, t_list* tlist, string prefix, bool use_push, @@ -3818,7 +3930,7 @@ void t_cpp_generator::generate_deserialize_list_element(ofstream& out, * @param tfield The field to serialize * @param prefix Name to prepend to field name */ -void t_cpp_generator::generate_serialize_field(ofstream& out, +void t_cpp_generator::generate_serialize_field(ostream& out, t_field* tfield, string prefix, string suffix) { @@ -3846,7 +3958,7 @@ void t_cpp_generator::generate_serialize_field(ofstream& out, throw "compiler error: cannot serialize void field in a struct: " + name; break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { out << "writeBinary(" << name << ");"; } else { out << "writeString(" << name << ");"; @@ -3891,7 +4003,7 @@ void t_cpp_generator::generate_serialize_field(ofstream& out, * @param tstruct The struct to serialize * @param prefix String prefix to attach to all fields */ -void t_cpp_generator::generate_serialize_struct(ofstream& out, +void t_cpp_generator::generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix, bool pointer) { @@ -3908,7 +4020,7 @@ void t_cpp_generator::generate_serialize_struct(ofstream& out, } } -void t_cpp_generator::generate_serialize_container(ofstream& out, t_type* ttype, string prefix) { +void t_cpp_generator::generate_serialize_container(ostream& out, t_type* ttype, string prefix) { scope_up(out); if (ttype->is_map()) { @@ -3954,7 +4066,7 @@ void t_cpp_generator::generate_serialize_container(ofstream& out, t_type* ttype, * Serializes the members of a map. * */ -void t_cpp_generator::generate_serialize_map_element(ofstream& out, t_map* tmap, string iter) { +void t_cpp_generator::generate_serialize_map_element(ostream& out, t_map* tmap, string iter) { t_field kfield(tmap->get_key_type(), iter + "->first"); generate_serialize_field(out, &kfield, ""); @@ -3965,7 +4077,7 @@ void t_cpp_generator::generate_serialize_map_element(ofstream& out, t_map* tmap, /** * Serializes the members of a set. */ -void t_cpp_generator::generate_serialize_set_element(ofstream& out, t_set* tset, string iter) { +void t_cpp_generator::generate_serialize_set_element(ostream& out, t_set* tset, string iter) { t_field efield(tset->get_elem_type(), "(*" + iter + ")"); generate_serialize_field(out, &efield, ""); } @@ -3973,7 +4085,7 @@ void t_cpp_generator::generate_serialize_set_element(ofstream& out, t_set* tset, /** * Serializes the members of a list. */ -void t_cpp_generator::generate_serialize_list_element(ofstream& out, t_list* tlist, string iter) { +void t_cpp_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string iter) { t_field efield(tlist->get_elem_type(), "(*" + iter + ")"); generate_serialize_field(out, &efield, ""); } @@ -4182,7 +4294,7 @@ string t_cpp_generator::declare_field(t_field* tfield, } result += type_name(tfield->get_type()); if (is_reference(tfield)) { - result = "boost::shared_ptr<" + result + ">"; + result = "::apache::thrift::stdcxx::shared_ptr<" + result + ">"; } if (pointer) { result += "*"; @@ -4261,13 +4373,13 @@ string t_cpp_generator::function_signature(t_function* tfunction, cob_type = (ttype->is_void() ? "()" : ("(" + type_name(ttype) + " const& _return)")); if (has_xceptions) { exn_cob - = ", tcxx::function /* exn_cob */"; + = ", ::apache::thrift::stdcxx::function /* exn_cob */"; } } else { throw "UNKNOWN STYLE"; } - return "void " + prefix + tfunction->get_name() + "(tcxx::function cob" + return "void " + prefix + tfunction->get_name() + "(::apache::thrift::stdcxx::function cob" + exn_cob + argument_list(arglist, name_params, true) + ")"; } else { throw "UNKNOWN STYLE"; @@ -4371,4 +4483,7 @@ THRIFT_REGISTER_GENERATOR( " templates: Generate templatized reader/writer methods.\n" " pure_enums: Generate pure enums instead of wrapper classes.\n" " include_prefix: Use full include paths in generated files.\n" - " moveable_types: Generate move constructors and assignment operators.\n") + " moveable_types: Generate move constructors and assignment operators.\n" + " no_ostream_operators:\n" + " Omit generation of ostream definitions.\n" + " no_skeleton: Omits generation of skeleton.\n") diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_csharp_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_csharp_generator.cc index ae3c48b..37d6f9d 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_csharp_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_csharp_generator.cc @@ -37,7 +37,7 @@ #include "thrift/generate/t_oop_generator.h" using std::map; -using std::ofstream; +using std::ostream; using std::ostringstream; using std::string; using std::stringstream; @@ -100,46 +100,46 @@ public: void generate_union(t_struct* tunion); void generate_xception(t_struct* txception); void generate_service(t_service* tservice); - void generate_property(ofstream& out, t_field* tfield, bool isPublic, bool generateIsset); - void generate_csharp_property(ofstream& out, + void generate_property(ostream& out, t_field* tfield, bool isPublic, bool generateIsset); + void generate_csharp_property(ostream& out, t_field* tfield, bool isPublic, bool includeIsset = true, std::string fieldPrefix = ""); - bool print_const_value(std::ofstream& out, + bool print_const_value(std::ostream& out, std::string name, t_type* type, t_const_value* value, bool in_static, bool defval = false, bool needtype = false); - std::string render_const_value(std::ofstream& out, + std::string render_const_value(std::ostream& out, std::string name, t_type* type, t_const_value* value); - void print_const_constructor(std::ofstream& out, std::vector consts); - void print_const_def_value(std::ofstream& out, + void print_const_constructor(std::ostream& out, std::vector consts); + void print_const_def_value(std::ostream& out, std::string name, t_type* type, t_const_value* value); void generate_csharp_struct(t_struct* tstruct, bool is_exception); void generate_csharp_union(t_struct* tunion); - void generate_csharp_struct_definition(std::ofstream& out, + void generate_csharp_struct_definition(std::ostream& out, t_struct* tstruct, bool is_xception = false, bool in_class = false, bool is_result = false); - void generate_csharp_union_definition(std::ofstream& out, t_struct* tunion); - void generate_csharp_union_class(std::ofstream& out, t_struct* tunion, t_field* tfield); - void generate_csharp_wcffault(std::ofstream& out, t_struct* tstruct); - void generate_csharp_struct_reader(std::ofstream& out, t_struct* tstruct); - void generate_csharp_struct_result_writer(std::ofstream& out, t_struct* tstruct); - void generate_csharp_struct_writer(std::ofstream& out, t_struct* tstruct); - void generate_csharp_struct_tostring(std::ofstream& out, t_struct* tstruct); - void generate_csharp_struct_equals(std::ofstream& out, t_struct* tstruct); - void generate_csharp_struct_hashcode(std::ofstream& out, t_struct* tstruct); - void generate_csharp_union_reader(std::ofstream& out, t_struct* tunion); + void generate_csharp_union_definition(std::ostream& out, t_struct* tunion); + void generate_csharp_union_class(std::ostream& out, t_struct* tunion, t_field* tfield); + void generate_csharp_wcffault(std::ostream& out, t_struct* tstruct); + void generate_csharp_struct_reader(std::ostream& out, t_struct* tstruct); + void generate_csharp_struct_result_writer(std::ostream& out, t_struct* tstruct); + void generate_csharp_struct_writer(std::ostream& out, t_struct* tstruct); + void generate_csharp_struct_tostring(std::ostream& out, t_struct* tstruct); + void generate_csharp_struct_equals(std::ostream& out, t_struct* tstruct); + void generate_csharp_struct_hashcode(std::ostream& out, t_struct* tstruct); + void generate_csharp_union_reader(std::ostream& out, t_struct* tunion); void generate_function_helpers(t_function* tfunction); void generate_service_interface(t_service* tservice); @@ -156,36 +156,36 @@ public: void generate_process_function(t_service* tservice, t_function* function); void generate_process_function_async(t_service* tservice, t_function* function); - void generate_deserialize_field(std::ofstream& out, + void generate_deserialize_field(std::ostream& out, t_field* tfield, std::string prefix = "", bool is_propertyless = false); - void generate_deserialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); - void generate_deserialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); - void generate_deserialize_set_element(std::ofstream& out, t_set* tset, std::string prefix = ""); - void generate_deserialize_map_element(std::ofstream& out, t_map* tmap, std::string prefix = ""); - void generate_deserialize_list_element(std::ofstream& out, t_list* list, std::string prefix = ""); - void generate_serialize_field(std::ofstream& out, + void generate_deserialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); + void generate_deserialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); + void generate_deserialize_set_element(std::ostream& out, t_set* tset, std::string prefix = ""); + void generate_deserialize_map_element(std::ostream& out, t_map* tmap, std::string prefix = ""); + void generate_deserialize_list_element(std::ostream& out, t_list* list, std::string prefix = ""); + void generate_serialize_field(std::ostream& out, t_field* tfield, std::string prefix = "", bool is_element = false, bool is_propertyless = false); - void generate_serialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); - void generate_serialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); - void generate_serialize_map_element(std::ofstream& out, + void generate_serialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); + void generate_serialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); + void generate_serialize_map_element(std::ostream& out, t_map* tmap, std::string iter, std::string map); - void generate_serialize_set_element(std::ofstream& out, t_set* tmap, std::string iter); - void generate_serialize_list_element(std::ofstream& out, t_list* tlist, std::string iter); + void generate_serialize_set_element(std::ostream& out, t_set* tmap, std::string iter); + void generate_serialize_list_element(std::ostream& out, t_list* tlist, std::string iter); - void generate_csharp_doc(std::ofstream& out, t_field* field); - void generate_csharp_doc(std::ofstream& out, t_doc* tdoc); - void generate_csharp_doc(std::ofstream& out, t_function* tdoc); - void generate_csharp_docstring_comment(std::ofstream& out, string contents); + void generate_csharp_doc(std::ostream& out, t_field* field); + void generate_csharp_doc(std::ostream& out, t_doc* tdoc); + void generate_csharp_doc(std::ostream& out, t_function* tdoc); + void generate_csharp_docstring_comment(std::ostream& out, string contents); - void start_csharp_namespace(std::ofstream& out); - void end_csharp_namespace(std::ofstream& out); + void start_csharp_namespace(std::ostream& out); + void end_csharp_namespace(std::ostream& out); std::string csharp_type_usings(); std::string csharp_thrift_usings(); @@ -224,7 +224,7 @@ public: private: std::string namespace_name_; - std::ofstream f_service_; + ofstream_with_content_based_conditional_update f_service_; std::string namespace_dir_; bool async_; bool nullable_; @@ -403,14 +403,14 @@ void t_csharp_generator::init_keywords() { csharp_keywords["yield"] = 1; } -void t_csharp_generator::start_csharp_namespace(ofstream& out) { +void t_csharp_generator::start_csharp_namespace(ostream& out) { if (!namespace_name_.empty()) { out << "namespace " << namespace_name_ << "\n"; scope_up(out); } } -void t_csharp_generator::end_csharp_namespace(ofstream& out) { +void t_csharp_generator::end_csharp_namespace(ostream& out) { if (!namespace_name_.empty()) { scope_down(out); } @@ -438,7 +438,7 @@ void t_csharp_generator::generate_typedef(t_typedef* ttypedef) { void t_csharp_generator::generate_enum(t_enum* tenum) { string f_enum_name = namespace_dir_ + "/" + (tenum->get_name()) + ".cs"; - ofstream f_enum; + ofstream_with_content_based_conditional_update f_enum; f_enum.open(f_enum_name.c_str()); f_enum << autogen_comment() << endl; @@ -471,7 +471,7 @@ void t_csharp_generator::generate_consts(std::vector consts) { return; } string f_consts_name = namespace_dir_ + '/' + program_name_ + ".Constants.cs"; - ofstream f_consts; + ofstream_with_content_based_conditional_update f_consts; f_consts.open(f_consts_name.c_str()); f_consts << autogen_comment() << csharp_type_usings() << endl; @@ -504,15 +504,15 @@ void t_csharp_generator::generate_consts(std::vector consts) { f_consts.close(); } -void t_csharp_generator::print_const_def_value(std::ofstream& out, +void t_csharp_generator::print_const_def_value(std::ostream& out, string name, t_type* type, t_const_value* value) { if (type->is_struct() || type->is_xception()) { const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; prepare_member_name_mapping((t_struct*)type); for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { t_field* field = NULL; @@ -532,8 +532,8 @@ void t_csharp_generator::print_const_def_value(std::ofstream& out, } else if (type->is_map()) { t_type* ktype = ((t_map*)type)->get_key_type(); t_type* vtype = ((t_map*)type)->get_val_type(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { string key = render_const_value(out, name, ktype, v_iter->first); string val = render_const_value(out, name, vtype, v_iter->second); @@ -557,7 +557,7 @@ void t_csharp_generator::print_const_def_value(std::ofstream& out, } } -void t_csharp_generator::print_const_constructor(std::ofstream& out, std::vector consts) { +void t_csharp_generator::print_const_constructor(std::ostream& out, std::vector consts) { indent(out) << "static " << make_valid_csharp_identifier(program_name_).c_str() << "Constants()" << endl; scope_up(out); @@ -574,7 +574,7 @@ void t_csharp_generator::print_const_constructor(std::ofstream& out, std::vector // it seems like all that methods that call this are using in_static to be the opposite of what it // would imply -bool t_csharp_generator::print_const_value(std::ofstream& out, +bool t_csharp_generator::print_const_value(std::ostream& out, string name, t_type* type, t_const_value* value, @@ -614,7 +614,7 @@ bool t_csharp_generator::print_const_value(std::ofstream& out, return need_static_construction; } -std::string t_csharp_generator::render_const_value(ofstream& out, +std::string t_csharp_generator::render_const_value(ostream& out, string name, t_type* type, t_const_value* value) { @@ -671,7 +671,7 @@ void t_csharp_generator::generate_xception(t_struct* txception) { void t_csharp_generator::generate_csharp_struct(t_struct* tstruct, bool is_exception) { string f_struct_name = namespace_dir_ + "/" + (tstruct->get_name()) + ".cs"; - ofstream f_struct; + ofstream_with_content_based_conditional_update f_struct; f_struct.open(f_struct_name.c_str()); @@ -682,7 +682,7 @@ void t_csharp_generator::generate_csharp_struct(t_struct* tstruct, bool is_excep f_struct.close(); } -void t_csharp_generator::generate_csharp_struct_definition(ofstream& out, +void t_csharp_generator::generate_csharp_struct_definition(ostream& out, t_struct* tstruct, bool is_exception, bool in_class, @@ -843,7 +843,7 @@ void t_csharp_generator::generate_csharp_struct_definition(ofstream& out, } else { out << ", "; } - out << type_name((*m_iter)->get_type()) << " " << (*m_iter)->get_name(); + out << type_name((*m_iter)->get_type()) << " " << normalize_name((*m_iter)->get_name()); } } out << ") : this() {" << endl; @@ -851,7 +851,7 @@ void t_csharp_generator::generate_csharp_struct_definition(ofstream& out, for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { if (field_is_required((*m_iter))) { - indent(out) << "this." << prop_name((*m_iter)) << " = " << (*m_iter)->get_name() << ";" + indent(out) << "this." << prop_name((*m_iter)) << " = " << normalize_name((*m_iter)->get_name()) << ";" << endl; } } @@ -885,7 +885,7 @@ void t_csharp_generator::generate_csharp_struct_definition(ofstream& out, } } -void t_csharp_generator::generate_csharp_wcffault(ofstream& out, t_struct* tstruct) { +void t_csharp_generator::generate_csharp_wcffault(ostream& out, t_struct* tstruct) { out << endl; indent(out) << "#if !SILVERLIGHT" << endl; indent(out) << "[Serializable]" << endl; @@ -915,7 +915,7 @@ void t_csharp_generator::generate_csharp_wcffault(ofstream& out, t_struct* tstru out << endl; } -void t_csharp_generator::generate_csharp_struct_reader(ofstream& out, t_struct* tstruct) { +void t_csharp_generator::generate_csharp_struct_reader(ostream& out, t_struct* tstruct) { indent(out) << "public void Read (TProtocol iprot)" << endl; scope_up(out); @@ -986,7 +986,10 @@ void t_csharp_generator::generate_csharp_struct_reader(ofstream& out, t_struct* if (field_is_required((*f_iter))) { indent(out) << "if (!isset_" << (*f_iter)->get_name() << ")" << endl; indent_up(); - indent(out) << "throw new TProtocolException(TProtocolException.INVALID_DATA);" << endl; + out << indent() + << "throw new TProtocolException(TProtocolException.INVALID_DATA, " + << "\"required field " << prop_name((*f_iter)) << " not set\");" + << endl; indent_down(); } } @@ -1002,7 +1005,7 @@ void t_csharp_generator::generate_csharp_struct_reader(ofstream& out, t_struct* indent(out) << "}" << endl << endl; } -void t_csharp_generator::generate_csharp_struct_writer(ofstream& out, t_struct* tstruct) { +void t_csharp_generator::generate_csharp_struct_writer(ostream& out, t_struct* tstruct) { out << indent() << "public void Write(TProtocol oprot) {" << endl; indent_up(); @@ -1022,20 +1025,36 @@ void t_csharp_generator::generate_csharp_struct_writer(ofstream& out, t_struct* for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { bool is_required = field_is_required((*f_iter)); bool has_default = field_has_default((*f_iter)); - if (nullable_ && !has_default && !is_required) { - indent(out) << "if (" << prop_name((*f_iter)) << " != null) {" << endl; - indent_up(); - } else if (!is_required) { - bool null_allowed = type_can_be_null((*f_iter)->get_type()); + bool null_allowed = type_can_be_null((*f_iter)->get_type()); + + if (is_required) + { if (null_allowed) { - indent(out) << "if (" << prop_name((*f_iter)) << " != null && __isset." - << normalize_name((*f_iter)->get_name()) << ") {" << endl; - indent_up(); - } else { - indent(out) << "if (__isset." << normalize_name((*f_iter)->get_name()) << ") {" << endl; + indent(out) << "if (" << prop_name((*f_iter)) << " == null)" << endl; indent_up(); + out << indent() + << "throw new TProtocolException(TProtocolException.INVALID_DATA, " + << "\"required field " << prop_name((*f_iter)) << " not set\");" + << endl; + indent_down(); } } + else + { + if (nullable_ && !has_default) { + indent(out) << "if (" << prop_name((*f_iter)) << " != null) {" << endl; + } + else if (null_allowed) { + out << indent() + << "if (" << prop_name((*f_iter)) << " != null && __isset." + << normalize_name((*f_iter)->get_name()) << ") {" + << endl; + } + else { + indent(out) << "if (__isset." << normalize_name((*f_iter)->get_name()) << ") {" << endl; + } + indent_up(); + } indent(out) << "field.Name = \"" << (*f_iter)->get_name() << "\";" << endl; indent(out) << "field.Type = " << type_to_enum((*f_iter)->get_type()) << ";" << endl; indent(out) << "field.ID = " << (*f_iter)->get_key() << ";" << endl; @@ -1065,7 +1084,7 @@ void t_csharp_generator::generate_csharp_struct_writer(ofstream& out, t_struct* indent(out) << "}" << endl << endl; } -void t_csharp_generator::generate_csharp_struct_result_writer(ofstream& out, t_struct* tstruct) { +void t_csharp_generator::generate_csharp_struct_result_writer(ostream& out, t_struct* tstruct) { indent(out) << "public void Write(TProtocol oprot) {" << endl; indent_up(); @@ -1137,7 +1156,7 @@ void t_csharp_generator::generate_csharp_struct_result_writer(ofstream& out, t_s indent(out) << "}" << endl << endl; } -void t_csharp_generator::generate_csharp_struct_tostring(ofstream& out, t_struct* tstruct) { +void t_csharp_generator::generate_csharp_struct_tostring(ostream& out, t_struct* tstruct) { indent(out) << "public override string ToString() {" << endl; indent_up(); @@ -1211,7 +1230,7 @@ void t_csharp_generator::generate_csharp_struct_tostring(ofstream& out, t_struct void t_csharp_generator::generate_csharp_union(t_struct* tunion) { string f_union_name = namespace_dir_ + "/" + (tunion->get_name()) + ".cs"; - ofstream f_union; + ofstream_with_content_based_conditional_update f_union; f_union.open(f_union_name.c_str()); @@ -1222,7 +1241,7 @@ void t_csharp_generator::generate_csharp_union(t_struct* tunion) { f_union.close(); } -void t_csharp_generator::generate_csharp_union_definition(std::ofstream& out, t_struct* tunion) { +void t_csharp_generator::generate_csharp_union_definition(std::ostream& out, t_struct* tunion) { // Let's define the class first start_csharp_namespace(out); @@ -1273,7 +1292,7 @@ void t_csharp_generator::generate_csharp_union_definition(std::ofstream& out, t_ end_csharp_namespace(out); } -void t_csharp_generator::generate_csharp_union_class(std::ofstream& out, +void t_csharp_generator::generate_csharp_union_class(std::ostream& out, t_struct* tunion, t_field* tfield) { indent(out) << "public class " << tfield->get_name() << " : " << tunion->get_name() << " {" @@ -1322,7 +1341,7 @@ void t_csharp_generator::generate_csharp_union_class(std::ofstream& out, indent(out) << "}" << endl << endl; } -void t_csharp_generator::generate_csharp_struct_equals(ofstream& out, t_struct* tstruct) { +void t_csharp_generator::generate_csharp_struct_equals(ostream& out, t_struct* tstruct) { indent(out) << "public override bool Equals(object that) {" << endl; indent_up(); @@ -1350,7 +1369,7 @@ void t_csharp_generator::generate_csharp_struct_equals(ofstream& out, t_struct* << normalize_name((*f_iter)->get_name()) << ") || ("; } t_type* ttype = (*f_iter)->get_type(); - if (ttype->is_container() || (ttype->is_base_type() && (((t_base_type*)ttype)->is_binary()))) { + if (ttype->is_container() || ttype->is_binary()) { out << "TCollections.Equals("; } else { out << "System.Object.Equals("; @@ -1371,7 +1390,7 @@ void t_csharp_generator::generate_csharp_struct_equals(ofstream& out, t_struct* indent(out) << "}" << endl << endl; } -void t_csharp_generator::generate_csharp_struct_hashcode(ofstream& out, t_struct* tstruct) { +void t_csharp_generator::generate_csharp_struct_hashcode(ostream& out, t_struct* tstruct) { indent(out) << "public override int GetHashCode() {" << endl; indent_up(); @@ -1671,6 +1690,7 @@ void t_csharp_generator::generate_service_client(t_service* tservice) { if (!async_) { indent(f_service_) << "#if SILVERLIGHT" << endl; + indent(f_service_) << endl; } // Begin_ indent(f_service_) << "public " << function_signature_async_begin(*f_iter, "Begin_") << endl; @@ -1747,51 +1767,52 @@ void t_csharp_generator::generate_service_client(t_service* tservice) { indent(f_service_) << "#endif" << endl << endl; } - // "Normal" Synchronous invoke generate_csharp_doc(f_service_, *f_iter); indent(f_service_) << "public " << function_signature(*f_iter) << endl; scope_up(f_service_); + // silverlight invoke if (!async_) { - indent(f_service_) << "#if !SILVERLIGHT" << endl; - indent(f_service_) << "send_" << funname << "("; + indent(f_service_) << "#if SILVERLIGHT" << endl; - first = true; + indent(f_service_) << "var asyncResult = Begin_" << funname << "(null, null"; for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) { - if (first) { - first = false; - } else { - f_service_ << ", "; - } - f_service_ << normalize_name((*fld_iter)->get_name()); + f_service_ << ", " << normalize_name((*fld_iter)->get_name()); } f_service_ << ");" << endl; - + if (!(*f_iter)->is_oneway()) { f_service_ << indent(); if (!(*f_iter)->get_returntype()->is_void()) { f_service_ << "return "; } - f_service_ << "recv_" << funname << "();" << endl; + f_service_ << "End_" << funname << "(asyncResult);" << endl; } f_service_ << endl; indent(f_service_) << "#else" << endl; } - // Silverlight synchronous invoke - indent(f_service_) << "var asyncResult = Begin_" << funname << "(null, null"; + // synchronous invoke + indent(f_service_) << "send_" << funname << "("; + + first = true; for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) { - f_service_ << ", " << normalize_name((*fld_iter)->get_name()); + if (first) { + first = false; + } else { + f_service_ << ", "; + } + f_service_ << normalize_name((*fld_iter)->get_name()); } f_service_ << ");" << endl; - + if (!(*f_iter)->is_oneway()) { f_service_ << indent(); if (!(*f_iter)->get_returntype()->is_void()) { f_service_ << "return "; } - f_service_ << "End_" << funname << "(asyncResult);" << endl; + f_service_ << "recv_" << funname << "();" << endl; } f_service_ << endl; @@ -1810,12 +1831,8 @@ void t_csharp_generator::generate_service_client(t_service* tservice) { if (!async_) { indent(f_service_) << "#if SILVERLIGHT" << endl; } + indent(f_service_) << "public " << function_signature_async_begin(&send_function) << endl; - if (!async_) { - indent(f_service_) << "#else" << endl; - indent(f_service_) << "public " << function_signature(&send_function) << endl; - indent(f_service_) << "#endif" << endl; - } scope_up(f_service_); f_service_ << indent() << "oprot_.WriteMessageBegin(new TMessage(\"" << funname << "\", " @@ -1830,20 +1847,40 @@ void t_csharp_generator::generate_service_client(t_service* tservice) { f_service_ << indent() << "args.Write(oprot_);" << endl << indent() << "oprot_.WriteMessageEnd();" << endl; - ; + indent(f_service_) << "return oprot_.Transport.BeginFlush(callback, state);" << endl; + + scope_down(f_service_); + f_service_ << endl; - if (!async_) { - indent(f_service_) << "#if SILVERLIGHT" << endl; - } - indent(f_service_) << "return oprot_.Transport.BeginFlush(callback, state);" << endl; if (!async_) { indent(f_service_) << "#else" << endl; - indent(f_service_) << "oprot_.Transport.Flush();" << endl; + f_service_ << endl; + } + + indent(f_service_) << "public " << function_signature(&send_function) << endl; + scope_up(f_service_); + + f_service_ << indent() << "oprot_.WriteMessageBegin(new TMessage(\"" << funname << "\", " + << ((*f_iter)->is_oneway() ? "TMessageType.Oneway" : "TMessageType.Call") + << ", seqid_));" << endl << indent() << argsname << " args = new " << argsname + << "();" << endl; + + for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) { + f_service_ << indent() << "args." << prop_name(*fld_iter) << " = " + << normalize_name((*fld_iter)->get_name()) << ";" << endl; + } + + f_service_ << indent() << "args.Write(oprot_);" << endl << indent() + << "oprot_.WriteMessageEnd();" << endl; + + indent(f_service_) << "oprot_.Transport.Flush();" << endl; + cleanup_member_name_mapping(arg_struct); + scope_down(f_service_); + + if (!async_) { indent(f_service_) << "#endif" << endl; } - cleanup_member_name_mapping(arg_struct); - scope_down(f_service_); f_service_ << endl; if (!(*f_iter)->is_oneway()) { @@ -2030,7 +2067,7 @@ void t_csharp_generator::generate_service_server_async(t_service* tservice) { string extends_processor = ""; if (tservice->get_extends() != NULL) { extends = type_name(tservice->get_extends()); - extends_processor = extends + ".Processor, "; + extends_processor = extends + ".AsyncProcessor, "; } indent(f_service_) << "public class AsyncProcessor : " << extends_processor << "TAsyncProcessor {" << endl; @@ -2359,7 +2396,7 @@ void t_csharp_generator::generate_process_function_async(t_service* tservice, t_ f_service_ << endl; } -void t_csharp_generator::generate_csharp_union_reader(std::ofstream& out, t_struct* tunion) { +void t_csharp_generator::generate_csharp_union_reader(std::ostream& out, t_struct* tunion) { // Thanks to THRIFT-1768, we don't need to check for required fields in the union const vector& fields = tunion->get_members(); vector::const_iterator f_iter; @@ -2433,7 +2470,7 @@ void t_csharp_generator::generate_csharp_union_reader(std::ofstream& out, t_stru indent(out) << "}" << endl << endl; } -void t_csharp_generator::generate_deserialize_field(ofstream& out, +void t_csharp_generator::generate_deserialize_field(ostream& out, t_field* tfield, string prefix, bool is_propertyless) { @@ -2468,7 +2505,7 @@ void t_csharp_generator::generate_deserialize_field(ofstream& out, throw "compiler error: cannot serialize void field in a struct: " + name; break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { out << "ReadBinary();"; } else { out << "ReadString();"; @@ -2506,7 +2543,7 @@ void t_csharp_generator::generate_deserialize_field(ofstream& out, } } -void t_csharp_generator::generate_deserialize_struct(ofstream& out, +void t_csharp_generator::generate_deserialize_struct(ostream& out, t_struct* tstruct, string prefix) { if (union_ && tstruct->is_union()) { @@ -2517,7 +2554,7 @@ void t_csharp_generator::generate_deserialize_struct(ofstream& out, } } -void t_csharp_generator::generate_deserialize_container(ofstream& out, +void t_csharp_generator::generate_deserialize_container(ostream& out, t_type* ttype, string prefix) { scope_up(out); @@ -2568,7 +2605,7 @@ void t_csharp_generator::generate_deserialize_container(ofstream& out, scope_down(out); } -void t_csharp_generator::generate_deserialize_map_element(ofstream& out, +void t_csharp_generator::generate_deserialize_map_element(ostream& out, t_map* tmap, string prefix) { string key = tmp("_key"); @@ -2586,7 +2623,7 @@ void t_csharp_generator::generate_deserialize_map_element(ofstream& out, indent(out) << prefix << "[" << key << "] = " << val << ";" << endl; } -void t_csharp_generator::generate_deserialize_set_element(ofstream& out, +void t_csharp_generator::generate_deserialize_set_element(ostream& out, t_set* tset, string prefix) { string elem = tmp("_elem"); @@ -2599,7 +2636,7 @@ void t_csharp_generator::generate_deserialize_set_element(ofstream& out, indent(out) << prefix << ".Add(" << elem << ");" << endl; } -void t_csharp_generator::generate_deserialize_list_element(ofstream& out, +void t_csharp_generator::generate_deserialize_list_element(ostream& out, t_list* tlist, string prefix) { string elem = tmp("_elem"); @@ -2612,7 +2649,7 @@ void t_csharp_generator::generate_deserialize_list_element(ofstream& out, indent(out) << prefix << ".Add(" << elem << ");" << endl; } -void t_csharp_generator::generate_serialize_field(ofstream& out, +void t_csharp_generator::generate_serialize_field(ostream& out, t_field* tfield, string prefix, bool is_element, @@ -2645,7 +2682,7 @@ void t_csharp_generator::generate_serialize_field(ofstream& out, throw "compiler error: cannot serialize void field in a struct: " + name; break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { out << "WriteBinary("; } else { out << "WriteString("; @@ -2685,14 +2722,14 @@ void t_csharp_generator::generate_serialize_field(ofstream& out, } } -void t_csharp_generator::generate_serialize_struct(ofstream& out, +void t_csharp_generator::generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix) { (void)tstruct; out << indent() << prefix << ".Write(oprot);" << endl; } -void t_csharp_generator::generate_serialize_container(ofstream& out, t_type* ttype, string prefix) { +void t_csharp_generator::generate_serialize_container(ostream& out, t_type* ttype, string prefix) { scope_up(out); if (ttype->is_map()) { @@ -2744,7 +2781,7 @@ void t_csharp_generator::generate_serialize_container(ofstream& out, t_type* tty scope_down(out); } -void t_csharp_generator::generate_serialize_map_element(ofstream& out, +void t_csharp_generator::generate_serialize_map_element(ostream& out, t_map* tmap, string iter, string map) { @@ -2754,25 +2791,25 @@ void t_csharp_generator::generate_serialize_map_element(ofstream& out, generate_serialize_field(out, &vfield, "", true); } -void t_csharp_generator::generate_serialize_set_element(ofstream& out, t_set* tset, string iter) { +void t_csharp_generator::generate_serialize_set_element(ostream& out, t_set* tset, string iter) { t_field efield(tset->get_elem_type(), iter); generate_serialize_field(out, &efield, "", true); } -void t_csharp_generator::generate_serialize_list_element(ofstream& out, +void t_csharp_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string iter) { t_field efield(tlist->get_elem_type(), iter); generate_serialize_field(out, &efield, "", true); } -void t_csharp_generator::generate_property(ofstream& out, +void t_csharp_generator::generate_property(ostream& out, t_field* tfield, bool isPublic, bool generateIsset) { generate_csharp_property(out, tfield, isPublic, generateIsset, "_"); } -void t_csharp_generator::generate_csharp_property(ofstream& out, +void t_csharp_generator::generate_csharp_property(ostream& out, t_field* tfield, bool isPublic, bool generateIsset, @@ -2801,6 +2838,8 @@ void t_csharp_generator::generate_csharp_property(ofstream& out, } if (ttype->is_base_type()) { use_nullable = ((t_base_type*)ttype)->get_base() != t_base_type::TYPE_STRING; + } else if (ttype->is_enum()) { + use_nullable = true; } } indent(out) << "return " << fieldPrefix + tfield->get_name() << ";" << endl; @@ -2888,6 +2927,7 @@ void t_csharp_generator::prepare_member_name_mapping(void* scope, const string& structname) { // begin new scope member_mapping_scope dummy; + dummy.scope_member = 0; member_mapping_scopes.push_back(dummy); member_mapping_scope& active = member_mapping_scopes.back(); active.scope_member = scope; @@ -3018,7 +3058,7 @@ string t_csharp_generator::declare_field(t_field* tfield, bool init, std::string ttype = ((t_typedef*)ttype)->get_type(); } if (ttype->is_base_type() && field_has_default(tfield)) { - ofstream dummy; + std::ofstream dummy; result += " = " + render_const_value(dummy, tfield->get_name(), ttype, tfield->get_value()); } else if (ttype->is_base_type()) { t_base_type::t_base tbase = ((t_base_type*)ttype)->get_base(); @@ -3136,11 +3176,11 @@ string t_csharp_generator::type_to_enum(t_type* type) { throw "INVALID TYPE IN type_to_enum: " + type->get_name(); } -void t_csharp_generator::generate_csharp_docstring_comment(ofstream& out, string contents) { +void t_csharp_generator::generate_csharp_docstring_comment(ostream& out, string contents) { generate_docstring_comment(out, "/// \n", "/// ", contents, "/// \n"); } -void t_csharp_generator::generate_csharp_doc(ofstream& out, t_field* field) { +void t_csharp_generator::generate_csharp_doc(ostream& out, t_field* field) { if (field->get_type()->is_enum()) { string combined_message = field->get_doc() + "\nget_type()) + "\"/>"; @@ -3150,13 +3190,13 @@ void t_csharp_generator::generate_csharp_doc(ofstream& out, t_field* field) { } } -void t_csharp_generator::generate_csharp_doc(ofstream& out, t_doc* tdoc) { +void t_csharp_generator::generate_csharp_doc(ostream& out, t_doc* tdoc) { if (tdoc->has_doc()) { generate_csharp_docstring_comment(out, tdoc->get_doc()); } } -void t_csharp_generator::generate_csharp_doc(ofstream& out, t_function* tfunction) { +void t_csharp_generator::generate_csharp_doc(ostream& out, t_function* tfunction) { if (tfunction->has_doc()) { stringstream ps; const vector& fields = tfunction->get_arglist()->get_members(); diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_d_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_d_generator.cc index 4816681..df56cfc 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_d_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_d_generator.cc @@ -103,7 +103,7 @@ protected: // Include type modules from other imported programs. const vector& includes = program_->get_includes(); for (size_t i = 0; i < includes.size(); ++i) { - f_types_ << "import " << render_package(*(includes[i])) << includes[i]->get_name() + f_types_ << "public import " << render_package(*(includes[i])) << includes[i]->get_name() << "_types;" << endl; } if (!includes.empty()) @@ -118,7 +118,7 @@ protected: virtual void generate_consts(std::vector consts) { if (!consts.empty()) { string f_consts_name = package_dir_ + program_name_ + "_constants.d"; - ofstream f_consts; + ofstream_with_content_based_conditional_update f_consts; f_consts.open(f_consts_name.c_str()); f_consts << autogen_comment() << "module " << render_package(*program_) << program_name_ @@ -131,6 +131,7 @@ protected: vector::iterator c_iter; for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) { + this->emit_doc(*c_iter, f_consts); string name = (*c_iter)->get_name(); t_type* type = (*c_iter)->get_type(); indent(f_consts) << "immutable(" << render_type_name(type) << ") " << name << ";" << endl; @@ -159,6 +160,7 @@ protected: } virtual void generate_typedef(t_typedef* ttypedef) { + this->emit_doc(ttypedef, f_types_); f_types_ << indent() << "alias " << render_type_name(ttypedef->get_type()) << " " << ttypedef->get_symbolic() << ";" << endl << endl; } @@ -166,21 +168,17 @@ protected: virtual void generate_enum(t_enum* tenum) { vector constants = tenum->get_constants(); + this->emit_doc(tenum, f_types_); string enum_name = tenum->get_name(); f_types_ << indent() << "enum " << enum_name << " {" << endl; indent_up(); vector::const_iterator c_iter; - bool first = true; for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) { - if (first) { - first = false; - } else { - f_types_ << "," << endl; - } + this->emit_doc(*c_iter, f_types_); indent(f_types_) << (*c_iter)->get_name(); - f_types_ << " = " << (*c_iter)->get_value(); + f_types_ << " = " << (*c_iter)->get_value() << ","; } f_types_ << endl; @@ -203,7 +201,7 @@ protected: // Service implementation file includes string f_servicename = package_dir_ + svc_name + ".d"; - std::ofstream f_service; + ofstream_with_content_based_conditional_update f_service; f_service.open(f_servicename.c_str()); f_service << autogen_comment() << "module " << render_package(*program_) << svc_name << ";" << endl << endl; @@ -225,6 +223,7 @@ protected: extends = " : " + render_type_name(tservice->get_extends()); } + this->emit_doc(tservice, f_service); f_service << indent() << "interface " << svc_name << extends << " {" << endl; indent_up(); @@ -236,6 +235,7 @@ protected: vector functions = tservice->get_functions(); vector::iterator fn_iter; for (fn_iter = functions.begin(); fn_iter != functions.end(); ++fn_iter) { + this->emit_doc(*fn_iter, f_service); f_service << indent(); print_function_signature(f_service, *fn_iter); f_service << ";" << endl; @@ -339,12 +339,26 @@ protected: // Server skeleton generation. string f_skeletonname = package_dir_ + svc_name + "_server.skeleton.d"; - std::ofstream f_skeleton; + ofstream_with_content_based_conditional_update f_skeleton; f_skeleton.open(f_skeletonname.c_str()); print_server_skeleton(f_skeleton, tservice); f_skeleton.close(); } + void emit_doc(t_doc *doc, std::ostream& out) { + if (!doc->has_doc()) { + return; + } + indent(out) << "/**" << std::endl; + indent_up(); + // No endl -- comments reliably have a newline at the end. + // This is true even for stuff like: + // /** method infos */ void foo(/** huh?*/ 1: i64 stuff) + indent(out) << doc->get_doc(); + indent_down(); + indent(out) << "*/" << std::endl; + } + private: /** * Writes a server skeleton for the passed service to out. @@ -381,8 +395,8 @@ private: out << indent() << "// Your implementation goes here." << endl << indent() << "writeln(\"" << (*f_iter)->get_name() << " called\");" << endl; - t_base_type* rt = (t_base_type*)(*f_iter)->get_returntype(); - if (rt->get_base() != t_base_type::TYPE_VOID) { + t_type* rt = (*f_iter)->get_returntype(); + if (!rt->is_void()) { indent(out) << "return typeof(return).init;" << endl; } @@ -543,8 +557,8 @@ private: const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { t_type* field_type = NULL; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { @@ -562,8 +576,8 @@ private: } else if (type->is_map()) { t_type* ktype = ((t_map*)type)->get_key_type(); t_type* vtype = ((t_map*)type)->get_val_type(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { string key = render_const_value(ktype, v_iter->first); string val = render_const_value(vtype, v_iter->second); @@ -719,8 +733,8 @@ private: * File streams, stored here to avoid passing them as parameters to every * function. */ - ofstream f_types_; - ofstream f_header_; + ofstream_with_content_based_conditional_update f_types_; + ofstream_with_content_based_conditional_update f_header_; string package_dir_; }; diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_dart_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_dart_generator.cc index 19bbb7b..414c333 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_dart_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_dart_generator.cc @@ -31,7 +31,7 @@ #include "thrift/generate/t_oop_generator.h" using std::map; -using std::ofstream; +using std::ostream; using std::ostringstream; using std::string; using std::stringstream; @@ -141,13 +141,13 @@ public: void generate_xception(t_struct* txception); void generate_service(t_service* tservice); - void print_const_value(std::ofstream& out, + void print_const_value(std::ostream& out, std::string name, t_type* type, t_const_value* value, bool in_static, bool defval = false); - std::string render_const_value(ofstream& out, + std::string render_const_value(ostream& out, std::string name, t_type* type, t_const_value* value); @@ -158,21 +158,21 @@ public: void generate_dart_struct(t_struct* tstruct, bool is_exception); - void generate_dart_struct_definition(std::ofstream& out, + void generate_dart_struct_definition(std::ostream& out, t_struct* tstruct, bool is_xception = false, bool is_result = false, string export_file_name = ""); - void generate_dart_struct_reader(std::ofstream& out, t_struct* tstruct); - void generate_dart_validator(std::ofstream& out, t_struct* tstruct); - void generate_dart_struct_result_writer(std::ofstream& out, t_struct* tstruct); - void generate_dart_struct_writer(std::ofstream& out, t_struct* tstruct); - void generate_dart_struct_tostring(std::ofstream& out, t_struct* tstruct); + void generate_dart_struct_reader(std::ostream& out, t_struct* tstruct); + void generate_dart_validator(std::ostream& out, t_struct* tstruct); + void generate_dart_struct_result_writer(std::ostream& out, t_struct* tstruct); + void generate_dart_struct_writer(std::ostream& out, t_struct* tstruct); + void generate_dart_struct_tostring(std::ostream& out, t_struct* tstruct); std::string get_dart_type_string(t_type* type); - void generate_generic_field_getters(std::ofstream& out, t_struct* tstruct); - void generate_generic_field_setters(std::ofstream& out, t_struct* tstruct); - void generate_generic_isset_method(std::ofstream& out, t_struct* tstruct); - void generate_dart_bean_boilerplate(std::ofstream& out, t_struct* tstruct); + void generate_generic_field_getters(std::ostream& out, t_struct* tstruct); + void generate_generic_field_setters(std::ostream& out, t_struct* tstruct); + void generate_generic_isset_method(std::ostream& out, t_struct* tstruct); + void generate_dart_bean_boilerplate(std::ostream& out, t_struct* tstruct); void generate_function_helpers(t_function* tfunction); std::string init_value(t_field* tfield); @@ -184,7 +184,7 @@ public: std::string get_constants_class_name(std::string name); std::string generate_isset_check(t_field* field); std::string generate_isset_check(std::string field); - void generate_isset_set(ofstream& out, t_field* field); + void generate_isset_set(ostream& out, t_field* field); void generate_service_interface(t_service* tservice); void generate_service_helpers(t_service* tservice); @@ -196,38 +196,38 @@ public: * Serialization constructs */ - void generate_deserialize_field(std::ofstream& out, t_field* tfield, std::string prefix = ""); + void generate_deserialize_field(std::ostream& out, t_field* tfield, std::string prefix = ""); - void generate_deserialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); + void generate_deserialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); - void generate_deserialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); + void generate_deserialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); - void generate_deserialize_set_element(std::ofstream& out, t_set* tset, std::string prefix = ""); + void generate_deserialize_set_element(std::ostream& out, t_set* tset, std::string prefix = ""); - void generate_deserialize_map_element(std::ofstream& out, t_map* tmap, std::string prefix = ""); + void generate_deserialize_map_element(std::ostream& out, t_map* tmap, std::string prefix = ""); - void generate_deserialize_list_element(std::ofstream& out, + void generate_deserialize_list_element(std::ostream& out, t_list* tlist, std::string prefix = ""); - void generate_serialize_field(std::ofstream& out, t_field* tfield, std::string prefix = ""); + void generate_serialize_field(std::ostream& out, t_field* tfield, std::string prefix = ""); - void generate_serialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); + void generate_serialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); - void generate_serialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); + void generate_serialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); - void generate_serialize_map_element(std::ofstream& out, + void generate_serialize_map_element(std::ostream& out, t_map* tmap, std::string iter, std::string map); - void generate_serialize_set_element(std::ofstream& out, t_set* tmap, std::string iter); + void generate_serialize_set_element(std::ostream& out, t_set* tmap, std::string iter); - void generate_serialize_list_element(std::ofstream& out, t_list* tlist, std::string iter); + void generate_serialize_list_element(std::ostream& out, t_list* tlist, std::string iter); - void generate_dart_doc(std::ofstream& out, t_doc* tdoc); + void generate_dart_doc(std::ostream& out, t_doc* tdoc); - void generate_dart_doc(std::ofstream& out, t_function* tdoc); + void generate_dart_doc(std::ostream& out, t_function* tdoc); /** * Helper rendering functions @@ -265,7 +265,7 @@ public: std::string constant_name(std::string name); private: - std::ofstream f_service_; + ofstream_with_content_based_conditional_update f_service_; std::string library_name_; std::string library_prefix_; @@ -391,7 +391,7 @@ void t_dart_generator::generate_dart_library() { f_library_name = get_out_dir() + "/" + library_name_ + ".dart"; } - ofstream f_library; + ofstream_with_content_based_conditional_update f_library; f_library.open(f_library_name.c_str()); f_library << autogen_comment() << endl; @@ -413,7 +413,7 @@ void t_dart_generator::export_class_to_library(string file_name, string class_na void t_dart_generator::generate_dart_pubspec() { string f_pubspec_name = base_dir_ + "/pubspec.yaml"; - ofstream f_pubspec; + ofstream_with_content_based_conditional_update f_pubspec; f_pubspec.open(f_pubspec_name.c_str()); indent(f_pubspec) << "name: " << library_name_ << endl; @@ -478,7 +478,7 @@ void t_dart_generator::generate_enum(t_enum* tenum) { string file_name = get_file_name(tenum->get_name()); string f_enum_name = src_dir_ + "/" + file_name + ".dart"; - ofstream f_enum; + ofstream_with_content_based_conditional_update f_enum; f_enum.open(f_enum_name.c_str()); // Comment and add library @@ -540,7 +540,7 @@ void t_dart_generator::generate_consts(std::vector consts) { string file_name = get_file_name(class_name); string f_consts_name = src_dir_ + "/" + file_name + ".dart"; - ofstream f_consts; + ofstream_with_content_based_conditional_update f_consts; f_consts.open(f_consts_name.c_str()); // Print header @@ -566,7 +566,7 @@ void t_dart_generator::generate_consts(std::vector consts) { f_consts.close(); } -void t_dart_generator::print_const_value(std::ofstream& out, +void t_dart_generator::print_const_value(std::ostream& out, string name, t_type* type, t_const_value* value, @@ -594,8 +594,8 @@ void t_dart_generator::print_const_value(std::ofstream& out, } else if (type->is_struct() || type->is_xception()) { const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; out << type_name(type) << " " << name << " = new " << type_name(type) << "()"; indent_up(); for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { @@ -623,8 +623,8 @@ void t_dart_generator::print_const_value(std::ofstream& out, t_type* ktype = ((t_map*)type)->get_key_type(); t_type* vtype = ((t_map*)type)->get_val_type(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { string key = render_const_value(out, name, ktype, v_iter->first); @@ -668,7 +668,7 @@ void t_dart_generator::print_const_value(std::ofstream& out, } } -string t_dart_generator::render_const_value(ofstream& out, +string t_dart_generator::render_const_value(ostream& out, string name, t_type* type, t_const_value* value) { @@ -740,7 +740,7 @@ void t_dart_generator::generate_xception(t_struct* txception) { void t_dart_generator::generate_dart_struct(t_struct* tstruct, bool is_exception) { string file_name = get_file_name(tstruct->get_name()); string f_struct_name = src_dir_ + "/" + file_name + ".dart"; - ofstream f_struct; + ofstream_with_content_based_conditional_update f_struct; f_struct.open(f_struct_name.c_str()); f_struct << autogen_comment() << dart_library(file_name) << endl; @@ -764,7 +764,7 @@ void t_dart_generator::generate_dart_struct(t_struct* tstruct, bool is_exception * @param in_class If inside a class, needs to be static class * @param is_result If this is a result it needs a different writer */ -void t_dart_generator::generate_dart_struct_definition(ofstream& out, +void t_dart_generator::generate_dart_struct_definition(ostream& out, t_struct* tstruct, bool is_exception, bool is_result, @@ -777,10 +777,10 @@ void t_dart_generator::generate_dart_struct_definition(ofstream& out, } indent(out) << "class " << class_name << " "; - if (is_exception) { - out << "extends Error "; - } out << "implements TBase"; + if (is_exception) { + out << ", Exception "; + } scope_up(out); indent(out) << "static final TStruct _STRUCT_DESC = new TStruct(\"" << class_name @@ -861,7 +861,7 @@ void t_dart_generator::generate_dart_struct_definition(ofstream& out, * * @param tstruct The struct definition */ -void t_dart_generator::generate_dart_struct_reader(ofstream& out, t_struct* tstruct) { +void t_dart_generator::generate_dart_struct_reader(ostream& out, t_struct* tstruct) { indent(out) << "read(TProtocol iprot)"; scope_up(out); @@ -949,7 +949,7 @@ void t_dart_generator::generate_dart_struct_reader(ofstream& out, t_struct* tstr // generates dart method to perform various checks // (e.g. check that all required fields are set) -void t_dart_generator::generate_dart_validator(ofstream& out, t_struct* tstruct) { +void t_dart_generator::generate_dart_validator(ostream& out, t_struct* tstruct) { indent(out) << "validate()"; scope_up(out); @@ -1000,7 +1000,7 @@ void t_dart_generator::generate_dart_validator(ofstream& out, t_struct* tstruct) * * @param tstruct The struct definition */ -void t_dart_generator::generate_dart_struct_writer(ofstream& out, t_struct* tstruct) { +void t_dart_generator::generate_dart_struct_writer(ostream& out, t_struct* tstruct) { out << indent() << "write(TProtocol oprot)"; scope_up(out); @@ -1056,7 +1056,7 @@ void t_dart_generator::generate_dart_struct_writer(ofstream& out, t_struct* tstr * * @param tstruct The struct definition */ -void t_dart_generator::generate_dart_struct_result_writer(ofstream& out, t_struct* tstruct) { +void t_dart_generator::generate_dart_struct_result_writer(ostream& out, t_struct* tstruct) { indent(out) << "write(TProtocol oprot)"; scope_up(out); @@ -1097,7 +1097,7 @@ void t_dart_generator::generate_dart_struct_result_writer(ofstream& out, t_struc scope_down(out, endl2); } -void t_dart_generator::generate_generic_field_getters(std::ofstream& out, +void t_dart_generator::generate_generic_field_getters(std::ostream& out, t_struct* tstruct) { // create the getter indent(out) << "getFieldValue(int fieldID)"; @@ -1127,7 +1127,7 @@ void t_dart_generator::generate_generic_field_getters(std::ofstream& out, scope_down(out, endl2); // method } -void t_dart_generator::generate_generic_field_setters(std::ofstream& out, +void t_dart_generator::generate_generic_field_setters(std::ostream& out, t_struct* tstruct) { // create the setter @@ -1172,7 +1172,7 @@ void t_dart_generator::generate_generic_field_setters(std::ofstream& out, } // Creates a generic isSet method that takes the field number as argument -void t_dart_generator::generate_generic_isset_method(std::ofstream& out, t_struct* tstruct) { +void t_dart_generator::generate_generic_isset_method(std::ostream& out, t_struct* tstruct) { const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; @@ -1208,7 +1208,7 @@ void t_dart_generator::generate_generic_isset_method(std::ofstream& out, t_struc * * @param tstruct The struct definition */ -void t_dart_generator::generate_dart_bean_boilerplate(ofstream& out, +void t_dart_generator::generate_dart_bean_boilerplate(ostream& out, t_struct* tstruct) { const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; @@ -1257,7 +1257,7 @@ void t_dart_generator::generate_dart_bean_boilerplate(ofstream& out, * * @param tstruct The struct definition */ -void t_dart_generator::generate_dart_struct_tostring(ofstream& out, +void t_dart_generator::generate_dart_struct_tostring(ostream& out, t_struct* tstruct) { indent(out) << "String toString()"; scope_up(out); @@ -1292,7 +1292,7 @@ void t_dart_generator::generate_dart_struct_tostring(ofstream& out, scope_up(out); } - if (field->get_type()->is_base_type() && ((t_base_type*)(field->get_type()))->is_binary()) { + if (field->get_type()->is_binary()) { indent(out) << "ret.write(\"BINARY\");" << endl; } else if (field->get_type()->is_enum()) { indent(out) << "String " << field_name << "_name = " @@ -1784,7 +1784,7 @@ void t_dart_generator::generate_process_function(t_service* tservice, t_function * @param tfield The field * @param prefix The variable name or container for this field */ -void t_dart_generator::generate_deserialize_field(ofstream& out, t_field* tfield, string prefix) { +void t_dart_generator::generate_deserialize_field(ostream& out, t_field* tfield, string prefix) { t_type* type = get_true_type(tfield->get_type()); string field_name = get_member_name(tfield->get_name()); @@ -1809,7 +1809,7 @@ void t_dart_generator::generate_deserialize_field(ofstream& out, t_field* tfield throw "compiler error: cannot serialize void field in a struct: " + name; break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { out << "readBinary();"; } else { out << "readString();"; @@ -1850,7 +1850,7 @@ void t_dart_generator::generate_deserialize_field(ofstream& out, t_field* tfield /** * Generates an unserializer for a struct, invokes read() */ -void t_dart_generator::generate_deserialize_struct(ofstream& out, t_struct* tstruct, string prefix) { +void t_dart_generator::generate_deserialize_struct(ostream& out, t_struct* tstruct, string prefix) { indent(out) << prefix << " = new " << type_name(tstruct) << "();" << endl; indent(out) << prefix << ".read(iprot);" << endl; } @@ -1858,7 +1858,7 @@ void t_dart_generator::generate_deserialize_struct(ofstream& out, t_struct* tstr /** * Deserializes a container by reading its size and then iterating */ -void t_dart_generator::generate_deserialize_container(ofstream& out, t_type* ttype, string prefix) { +void t_dart_generator::generate_deserialize_container(ostream& out, t_type* ttype, string prefix) { indent(out); scope_up(out, ""); @@ -1915,7 +1915,7 @@ void t_dart_generator::generate_deserialize_container(ofstream& out, t_type* tty /** * Generates code to deserialize a map */ -void t_dart_generator::generate_deserialize_map_element(ofstream& out, t_map* tmap, string prefix) { +void t_dart_generator::generate_deserialize_map_element(ostream& out, t_map* tmap, string prefix) { string key = tmp("_key"); string val = tmp("_val"); t_field fkey(tmap->get_key_type(), key); @@ -1933,7 +1933,7 @@ void t_dart_generator::generate_deserialize_map_element(ofstream& out, t_map* tm /** * Deserializes a set element */ -void t_dart_generator::generate_deserialize_set_element(ofstream& out, t_set* tset, string prefix) { +void t_dart_generator::generate_deserialize_set_element(ostream& out, t_set* tset, string prefix) { string elem = tmp("_elem"); t_field felem(tset->get_elem_type(), elem); @@ -1947,7 +1947,7 @@ void t_dart_generator::generate_deserialize_set_element(ofstream& out, t_set* ts /** * Deserializes a list element */ -void t_dart_generator::generate_deserialize_list_element(ofstream& out, +void t_dart_generator::generate_deserialize_list_element(ostream& out, t_list* tlist, string prefix) { string elem = tmp("_elem"); @@ -1966,7 +1966,7 @@ void t_dart_generator::generate_deserialize_list_element(ofstream& out, * @param tfield The field to serialize * @param prefix Name to prepend to field name */ -void t_dart_generator::generate_serialize_field(ofstream& out, t_field* tfield, string prefix) { +void t_dart_generator::generate_serialize_field(ostream& out, t_field* tfield, string prefix) { t_type* type = get_true_type(tfield->get_type()); string field_name = get_member_name(tfield->get_name()); @@ -1991,7 +1991,7 @@ void t_dart_generator::generate_serialize_field(ofstream& out, t_field* tfield, throw "compiler error: cannot serialize void field in a struct: " + name; break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { out << "writeBinary(" << name << ");"; } else { out << "writeString(" << name << ");"; @@ -2036,7 +2036,7 @@ void t_dart_generator::generate_serialize_field(ofstream& out, t_field* tfield, * @param tstruct The struct to serialize * @param prefix String prefix to attach to all fields */ -void t_dart_generator::generate_serialize_struct(ofstream& out, t_struct* tstruct, string prefix) { +void t_dart_generator::generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix) { (void)tstruct; indent(out) << prefix << ".write(oprot);" << endl; } @@ -2047,7 +2047,7 @@ void t_dart_generator::generate_serialize_struct(ofstream& out, t_struct* tstruc * @param ttype The type of container * @param prefix String prefix for fields */ -void t_dart_generator::generate_serialize_container(ofstream& out, t_type* ttype, string prefix) { +void t_dart_generator::generate_serialize_container(ostream& out, t_type* ttype, string prefix) { indent(out); scope_up(out, ""); @@ -2098,7 +2098,7 @@ void t_dart_generator::generate_serialize_container(ofstream& out, t_type* ttype /** * Serializes the members of a map. */ -void t_dart_generator::generate_serialize_map_element(ofstream& out, +void t_dart_generator::generate_serialize_map_element(ostream& out, t_map* tmap, string iter, string map) { @@ -2111,7 +2111,7 @@ void t_dart_generator::generate_serialize_map_element(ofstream& out, /** * Serializes the members of a set. */ -void t_dart_generator::generate_serialize_set_element(ofstream& out, t_set* tset, string iter) { +void t_dart_generator::generate_serialize_set_element(ostream& out, t_set* tset, string iter) { t_field efield(tset->get_elem_type(), iter); generate_serialize_field(out, &efield, ""); } @@ -2119,7 +2119,7 @@ void t_dart_generator::generate_serialize_set_element(ofstream& out, t_set* tset /** * Serializes the members of a list. */ -void t_dart_generator::generate_serialize_list_element(ofstream& out, t_list* tlist, string iter) { +void t_dart_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string iter) { t_field efield(tlist->get_elem_type(), iter); generate_serialize_field(out, &efield, ""); } @@ -2194,7 +2194,7 @@ string t_dart_generator::declare_field(t_field* tfield, bool init) { if (init) { t_type* ttype = get_true_type(tfield->get_type()); if (ttype->is_base_type() && tfield->get_value() != NULL) { - ofstream dummy; + std:: ofstream dummy; result += " = " + render_const_value(dummy, field_name, ttype, tfield->get_value()); } else if (ttype->is_base_type()) { t_base_type::t_base tbase = ((t_base_type*)ttype)->get_base(); @@ -2452,7 +2452,7 @@ string t_dart_generator::constant_name(string name) { /** * Emits a doc comment if the provided object has a doc in Thrift */ -void t_dart_generator::generate_dart_doc(ofstream& out, t_doc* tdoc) { +void t_dart_generator::generate_dart_doc(ostream& out, t_doc* tdoc) { if (tdoc->has_doc()) { generate_docstring_comment(out, "", "/// ", tdoc->get_doc(), ""); } @@ -2461,7 +2461,7 @@ void t_dart_generator::generate_dart_doc(ofstream& out, t_doc* tdoc) { /** * Emits a doc comment if the provided function object has a doc in Thrift */ -void t_dart_generator::generate_dart_doc(ofstream& out, t_function* tfunction) { +void t_dart_generator::generate_dart_doc(ostream& out, t_function* tfunction) { if (tfunction->has_doc()) { stringstream ss; ss << tfunction->get_doc(); @@ -2488,7 +2488,7 @@ std::string t_dart_generator::generate_isset_check(std::string field_name) { return "is" + get_cap_name("set") + get_cap_name(field_name) + "()"; } -void t_dart_generator::generate_isset_set(ofstream& out, t_field* field) { +void t_dart_generator::generate_isset_set(ostream& out, t_field* field) { if (!type_can_be_null(field->get_type())) { string field_name = get_member_name(field->get_name()); indent(out) << "this.__isset_" << field_name << " = true;" << endl; diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_delphi_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_delphi_generator.cc index 8b1a445..8bd77e8 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_delphi_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_delphi_generator.cc @@ -65,6 +65,7 @@ public: constprefix_ = false; events_ = false; xmldoc_ = false; + async_ = false; for( iter = parsed_options.begin(); iter != parsed_options.end(); ++iter) { if( iter->first.compare("ansistr_binary") == 0) { ansistr_binary_ = true; @@ -76,6 +77,8 @@ public: events_ = true; } else if( iter->first.compare("xmldoc") == 0) { xmldoc_ = true; + } else if( iter->first.compare("async") == 0) { + async_ = true; } else { throw "unknown option delphi:" + iter->first; } @@ -128,7 +131,7 @@ public: bool is_xception_class, bool is_union, bool is_xception_factory, - std::string xception_factroy_name); + std::string xception_factory_name); void generate_delphi_clear_union_value(ostream& out, std::string cls_prefix, std::string name, @@ -138,7 +141,7 @@ public: bool is_xception_class, bool is_union, bool is_xception_factory, - std::string xception_factroy_name); + std::string xception_factory_name); void generate_delphi_isset_reader_impl(ostream& out, std::string cls_prefix, std::string name, @@ -236,6 +239,7 @@ public: void generate_function_helpers(t_function* tfunction); void generate_service_interface(t_service* tservice); + void generate_service_interface(t_service* tservice, bool for_async); void generate_service_helpers(t_service* tservice); void generate_service_client(t_service* tservice); void generate_service_server(t_service* tservice); @@ -323,6 +327,7 @@ public: std::string prefix = "", bool is_xception_class = false); std::string function_signature(t_function* tfunction, + bool for_async, std::string full_cls = "", bool is_xception = false); std::string argument_list(t_struct* tstruct); @@ -399,6 +404,7 @@ private: bool constprefix_; bool events_; bool xmldoc_; + bool async_; void indent_up_impl() { ++indent_impl_; }; void indent_down_impl() { --indent_impl_; }; std::string indent_impl() { @@ -636,10 +642,21 @@ void t_delphi_generator::create_keywords() { // reserved/predefined variables and types (lowercase!) delphi_keywords["result"] = 1; + delphi_keywords["system"] = 1; + delphi_keywords["sysutils"] = 1; + delphi_keywords["thrift"] = 1; delphi_keywords["tbytes"] = 1; delphi_keywords["tobject"] = 1; delphi_keywords["tclass"] = 1; delphi_keywords["tinterfacedobject"] = 1; + delphi_keywords["ansistring"] = 1; + delphi_keywords["string"] = 1; + delphi_keywords["boolean"] = 1; + delphi_keywords["shortint"] = 1; + delphi_keywords["smallint"] = 1; + delphi_keywords["integer"] = 1; + delphi_keywords["int64"] = 1; + delphi_keywords["double"] = 1; delphi_reserved_method["create"] = 1; delphi_reserved_method["free"] = 1; @@ -721,15 +738,19 @@ void t_delphi_generator::init_generator() { has_enum = false; has_const = false; create_keywords(); + add_delphi_uses_list("Classes"); add_delphi_uses_list("SysUtils"); add_delphi_uses_list("Generics.Collections"); + if(async_) { + add_delphi_uses_list("System.Threading"); + } + add_delphi_uses_list("Thrift"); add_delphi_uses_list("Thrift.Utils"); add_delphi_uses_list("Thrift.Collections"); add_delphi_uses_list("Thrift.Protocol"); add_delphi_uses_list("Thrift.Transport"); - if (register_types_) { add_delphi_uses_list("Thrift.TypeRegistry"); } @@ -742,7 +763,7 @@ void t_delphi_generator::init_generator() { unitname = includes[i]->get_name(); nsname = includes[i]->get_namespace("delphi"); if ("" != nsname) { - unitname = nsname; + unitname = normalize_name(nsname); } add_delphi_uses_list(unitname); } @@ -762,8 +783,10 @@ void t_delphi_generator::close_generator() { } } + unitname = normalize_name(unitname); + std::string f_name = get_out_dir() + "/" + unitname + ".pas"; - std::ofstream f_all; + ofstream_with_content_based_conditional_update f_all; f_all.open(f_name.c_str()); @@ -1195,8 +1218,8 @@ void t_delphi_generator::print_const_def_value(std::ostream& vars, if (type->is_struct() || type->is_xception()) { const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { t_type* field_type = NULL; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { @@ -1215,8 +1238,8 @@ void t_delphi_generator::print_const_def_value(std::ostream& vars, } else if (type->is_map()) { t_type* ktype = ((t_map*)type)->get_key_type(); t_type* vtype = ((t_map*)type)->get_val_type(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { string key = render_const_value(vars, out, name, ktype, v_iter->first); string val = render_const_value(vars, out, name, vtype, v_iter->second); @@ -1460,8 +1483,6 @@ void t_delphi_generator::generate_delphi_struct_impl(ostream& out, indent_up_impl(); if (is_exception && (!is_x_factory)) { indent_impl(out) << "inherited Create('');" << endl; - indent_impl(out) << "F" << exception_factory_name << " := T" << exception_factory_name - << "Impl.Create;" << endl; } else { indent_impl(out) << "inherited;" << endl; } @@ -1507,6 +1528,19 @@ void t_delphi_generator::generate_delphi_struct_impl(ostream& out, indent_down_impl(); indent_impl(out) << "end;" << endl << endl; + if (is_exception && (!is_x_factory)) { + indent_impl(out) << "function " << cls_prefix << cls_nm << "." << exception_factory_name + << ": I" << exception_factory_name << ";" << endl; + indent_impl(out) << "begin" << endl; + indent_up_impl(); + indent_impl(out) << "if F" << exception_factory_name << " = nil" << endl; + indent_impl(out) << "then F" << exception_factory_name << " := T" << exception_factory_name << "Impl.Create;" << endl; + indent_impl(out) << endl; + indent_impl(out) << "result := F" << exception_factory_name << ";" << endl; + indent_down_impl(); + indent_impl(out) << "end;" << endl << endl; + } + if (tstruct->is_union()) { indent_impl(out) << "procedure " << cls_prefix << cls_nm << "." << "ClearUnionValues;" << endl; @@ -1692,7 +1726,7 @@ void t_delphi_generator::generate_delphi_struct_definition(ostream& out, for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { if ((*m_iter)->get_req() != t_field::T_REQUIRED) { isset_name = "__isset_" + prop_name(*m_iter, is_exception); - indent(out) << "property " << isset_name << ": Boolean read Get" << isset_name << ";" + indent(out) << "property " << isset_name << ": System.Boolean read Get" << isset_name << ";" << endl; } } @@ -1741,7 +1775,7 @@ void t_delphi_generator::generate_delphi_struct_definition(ostream& out, for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { if ((*m_iter)->get_req() != t_field::T_REQUIRED) { isset_name = "F__isset_" + prop_name(*m_iter, is_exception); - indent(out) << isset_name << ": Boolean;" << endl; + indent(out) << isset_name << ": System.Boolean;" << endl; } } } @@ -1764,7 +1798,7 @@ void t_delphi_generator::generate_delphi_struct_definition(ostream& out, for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { if ((*m_iter)->get_req() != t_field::T_REQUIRED) { isset_name = "__isset_" + prop_name(*m_iter, is_exception); - indent(out) << "function Get" << isset_name << ": Boolean;" << endl; + indent(out) << "function Get" << isset_name << ": System.Boolean;" << endl; } } } @@ -1790,8 +1824,7 @@ void t_delphi_generator::generate_delphi_struct_definition(ostream& out, if (is_exception && (!is_x_factory)) { out << endl; indent(out) << "// Exception Factory" << endl; - indent(out) << "property " << exception_factory_name << ": " << struct_intf_name << " read F" - << exception_factory_name << " write F" << exception_factory_name << ";" << endl; + indent(out) << "function " << exception_factory_name << ": " << struct_intf_name << ";" << endl; } if ((!is_exception) || is_x_factory) { @@ -1821,7 +1854,7 @@ void t_delphi_generator::generate_delphi_struct_definition(ostream& out, for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { if ((*m_iter)->get_req() != t_field::T_REQUIRED) { isset_name = "__isset_" + prop_name(*m_iter, is_exception); - indent(out) << "property " << isset_name << ": Boolean read Get" << isset_name << ";" + indent(out) << "property " << isset_name << ": System.Boolean read Get" << isset_name << ";" << endl; } } @@ -1850,19 +1883,28 @@ void t_delphi_generator::generate_service(t_service* tservice) { } void t_delphi_generator::generate_service_interface(t_service* tservice) { + generate_service_interface(tservice,false); + if(async_) { + generate_service_interface(tservice,true); + } +} + + +void t_delphi_generator::generate_service_interface(t_service* tservice, bool for_async) { string extends = ""; string extends_iface = ""; + string iface_name = for_async ? "IAsync" : "Iface"; indent_up(); generate_delphi_doc(s_service, tservice); if (tservice->get_extends() != NULL) { extends = type_name(tservice->get_extends(), true, true); - extends_iface = extends + ".Iface"; + extends_iface = extends + "." + iface_name; generate_delphi_doc(s_service, tservice); - indent(s_service) << "Iface = interface(" << extends_iface << ")" << endl; + indent(s_service) << iface_name << " = interface(" << extends_iface << ")" << endl; } else { - indent(s_service) << "Iface = interface" << endl; + indent(s_service) << iface_name << " = interface" << endl; } indent_up(); @@ -1870,7 +1912,7 @@ void t_delphi_generator::generate_service_interface(t_service* tservice) { vector::iterator f_iter; for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { generate_delphi_doc(s_service, *f_iter); - indent(s_service) << function_signature(*f_iter) << endl; + indent(s_service) << function_signature(*f_iter, for_async) << endl; } indent_down(); indent(s_service) << "end;" << endl << endl; @@ -1896,20 +1938,15 @@ void t_delphi_generator::generate_service_helpers(t_service* tservice) { void t_delphi_generator::generate_service_client(t_service* tservice) { indent_up(); string extends = ""; - string extends_client = ""; - if (tservice->get_extends() != NULL) { - extends = type_name(tservice->get_extends()); - extends_client = extends + ".Client, "; - } + string extends_client = "TInterfacedObject"; + string implements = async_ ? "Iface, IAsync" : "Iface"; generate_delphi_doc(s_service, tservice); if (tservice->get_extends() != NULL) { extends = type_name(tservice->get_extends(), true, true); extends_client = extends + ".TClient"; - indent(s_service) << "TClient = class(" << extends_client << ", Iface)" << endl; - } else { - indent(s_service) << "TClient = class( TInterfacedObject, Iface)" << endl; } + indent(s_service) << "TClient = class( " << extends_client << ", " << implements << ")" << endl; indent(s_service) << "public" << endl; indent_up(); @@ -1945,7 +1982,7 @@ void t_delphi_generator::generate_service_client(t_service* tservice) { indent_up(); indent(s_service) << "iprot_: IProtocol;" << endl; indent(s_service) << "oprot_: IProtocol;" << endl; - indent(s_service) << "seqid_: Integer;" << endl; + indent(s_service) << "seqid_: System.Integer;" << endl; indent_down(); indent(s_service) << "public" << endl; @@ -1960,12 +1997,24 @@ void t_delphi_generator::generate_service_client(t_service* tservice) { indent(s_service) << "protected" << endl; indent_up(); + indent(s_service) << "// Iface" << endl; for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { string funname = (*f_iter)->get_name(); generate_delphi_doc(s_service, *f_iter); - indent(s_service) << function_signature(*f_iter) << endl; + indent(s_service) << function_signature(*f_iter, false) << endl; } + + if( async_) { + indent(s_service) << endl; + indent(s_service) << "// IAsync" << endl; + for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { + string funname = (*f_iter)->get_name(); + generate_delphi_doc(s_service, *f_iter); + indent(s_service) << function_signature(*f_iter, true) << endl; + } + } + indent_down(); indent(s_service) << "public" << endl; @@ -1976,36 +2025,65 @@ void t_delphi_generator::generate_service_client(t_service* tservice) { for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { string funname = (*f_iter)->get_name(); - indent_impl(s_service_impl) << function_signature(*f_iter, full_cls) << endl; - indent_impl(s_service_impl) << "begin" << endl; - indent_up_impl(); - indent_impl(s_service_impl) << "send_" << funname << "("; - - t_struct* arg_struct = (*f_iter)->get_arglist(); - - const vector& fields = arg_struct->get_members(); vector::const_iterator fld_iter; - bool first = true; - for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) { - if (first) { - first = false; - } else { - s_service_impl << ", "; - } - s_service_impl << normalize_name((*fld_iter)->get_name()); - } - s_service_impl << ");" << endl; + t_struct* arg_struct = (*f_iter)->get_arglist(); + const vector& fields = arg_struct->get_members(); - if (!(*f_iter)->is_oneway()) { - s_service_impl << indent_impl(); - if (!(*f_iter)->get_returntype()->is_void()) { - s_service_impl << "Result := "; - } - s_service_impl << "recv_" << funname << "();" << endl; - } + // one for sync only, two for async+sync + int mode = async_ ? 1 : 0; + while( mode >= 0) { + bool for_async = (mode != 0); + mode--; - indent_down_impl(); - indent_impl(s_service_impl) << "end;" << endl << endl; + indent_impl(s_service_impl) << function_signature(*f_iter, for_async, full_cls) << endl; + indent_impl(s_service_impl) << "begin" << endl; + indent_up_impl(); + + t_type* ttype = (*f_iter)->get_returntype(); + if( for_async) { + if (is_void(ttype)) { + // Delphi forces us to specify a type with IFuture, so we use Integer=0 for void methods + indent_impl(s_service_impl) << "result := TTask.Future(function: System.Integer" << endl; + } else { + string rettype = type_name(ttype, false, true, false, true); + indent_impl(s_service_impl) << "result := TTask.Future<" << rettype << ">(function: " << rettype << endl; + } + indent_impl(s_service_impl) << "begin" << endl; + indent_up_impl(); + } + + indent_impl(s_service_impl) << "send_" << funname << "("; + + bool first = true; + for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) { + if (first) { + first = false; + } else { + s_service_impl << ", "; + } + s_service_impl << normalize_name((*fld_iter)->get_name()); + } + s_service_impl << ");" << endl; + + if (!(*f_iter)->is_oneway()) { + s_service_impl << indent_impl(); + if (!(*f_iter)->get_returntype()->is_void()) { + s_service_impl << "Result := "; + } + s_service_impl << "recv_" << funname << "();" << endl; + } + + if( for_async) { + if (is_void(ttype)) { + indent_impl(s_service_impl) << "Result := 0;" << endl; // no IFuture in Delphi + } + indent_down_impl(); + indent_impl(s_service_impl) << "end);" << endl; + } + + indent_down_impl(); + indent_impl(s_service_impl) << "end;" << endl << endl; + } t_function send_function(g_type_void, string("send_") + (*f_iter)->get_name(), @@ -2018,18 +2096,18 @@ void t_delphi_generator::generate_service_client(t_service* tservice) { string argsvar = tmp("_args"); string msgvar = tmp("_msg"); - indent(s_service) << function_signature(&send_function) << endl; - indent_impl(s_service_impl) << function_signature(&send_function, full_cls) << endl; + indent(s_service) << function_signature(&send_function, false) << endl; + indent_impl(s_service_impl) << function_signature(&send_function, false, full_cls) << endl; indent_impl(s_service_impl) << "var" << endl; indent_up_impl(); indent_impl(s_service_impl) << argsvar << " : " << args_intfnm << ";" << endl; - indent_impl(s_service_impl) << msgvar << " : Thrift.Protocol.IMessage;" << endl; + indent_impl(s_service_impl) << msgvar << " : Thrift.Protocol.TThriftMessage;" << endl; indent_down_impl(); indent_impl(s_service_impl) << "begin" << endl; indent_up_impl(); indent_impl(s_service_impl) << "seqid_ := seqid_ + 1;" << endl; - indent_impl(s_service_impl) << msgvar << " := Thrift.Protocol.TMessageImpl.Create('" << funname + indent_impl(s_service_impl) << "Thrift.Protocol.Init( " << msgvar << ", '" << funname << "', " << ((*f_iter)->is_oneway() ? "TMessageType.Oneway" : "TMessageType.Call") << ", seqid_);" << endl; @@ -2072,11 +2150,11 @@ void t_delphi_generator::generate_service_client(t_service* tservice) { string appexvar = tmp("_ax"); string retvar = tmp("_ret"); - indent(s_service) << function_signature(&recv_function) << endl; - indent_impl(s_service_impl) << function_signature(&recv_function, full_cls) << endl; + indent(s_service) << function_signature(&recv_function, false) << endl; + indent_impl(s_service_impl) << function_signature(&recv_function, false, full_cls) << endl; indent_impl(s_service_impl) << "var" << endl; indent_up_impl(); - indent_impl(s_service_impl) << msgvar << " : Thrift.Protocol.IMessage;" << endl; + indent_impl(s_service_impl) << msgvar << " : Thrift.Protocol.TThriftMessage;" << endl; if (xceptions.size() > 0) { indent_impl(s_service_impl) << exceptvar << " : Exception;" << endl; } @@ -2131,7 +2209,7 @@ void t_delphi_generator::generate_service_client(t_service* tservice) { if (!(*f_iter)->get_returntype()->is_void()) { indent_impl(s_service_impl) - << "raise TApplicationExceptionMissingResult.Create('" + << "raise TApplicationExceptionMissingResult.Create('" << (*f_iter)->get_name() << " failed: unknown result');" << endl; } @@ -2207,7 +2285,7 @@ void t_delphi_generator::generate_service_server(t_service* tservice) { indent_up(); indent(s_service) << "type" << endl; indent_up(); - indent(s_service) << "TProcessFunction = reference to procedure( seqid: Integer; const iprot: " + indent(s_service) << "TProcessFunction = reference to procedure( seqid: System.Integer; const iprot: " "IProtocol; const oprot: IProtocol" << (events_ ? "; const events : IRequestEvents" : "") << ");" << endl; indent_down(); @@ -2222,19 +2300,19 @@ void t_delphi_generator::generate_service_server(t_service* tservice) { indent_up(); if (extends.empty()) { indent(s_service) << "function Process( const iprot: IProtocol; const oprot: IProtocol; const " - "events : IProcessorEvents): Boolean;" << endl; + "events : IProcessorEvents): System.Boolean;" << endl; } else { indent(s_service) << "function Process( const iprot: IProtocol; const oprot: IProtocol; const " - "events : IProcessorEvents): Boolean; reintroduce;" << endl; + "events : IProcessorEvents): System.Boolean; reintroduce;" << endl; } indent_impl(s_service_impl) << "function " << full_cls << ".Process( const iprot: IProtocol; " "const oprot: IProtocol; const events " - ": IProcessorEvents): Boolean;" << endl; + ": IProcessorEvents): System.Boolean;" << endl; ; indent_impl(s_service_impl) << "var" << endl; indent_up_impl(); - indent_impl(s_service_impl) << "msg : Thrift.Protocol.IMessage;" << endl; + indent_impl(s_service_impl) << "msg : Thrift.Protocol.TThriftMessage;" << endl; indent_impl(s_service_impl) << "fn : TProcessFunction;" << endl; indent_impl(s_service_impl) << "x : TApplicationException;" << endl; if (events_) { @@ -2254,10 +2332,10 @@ void t_delphi_generator::generate_service_server(t_service* tservice) { indent_impl(s_service_impl) << "TProtocolUtil.Skip(iprot, TType.Struct);" << endl; indent_impl(s_service_impl) << "iprot.ReadMessageEnd();" << endl; indent_impl(s_service_impl) << "x := " - "TApplicationExceptionUnknownMethod.Create(" - "'Invalid method name: ''' + msg.Name + '''');" << endl; + "TApplicationExceptionUnknownMethod.Create(" + "'Invalid method name: ''' + msg.Name + '''');" << endl; indent_impl(s_service_impl) - << "msg := Thrift.Protocol.TMessageImpl.Create(msg.Name, TMessageType.Exception, msg.SeqID);" + << "Thrift.Protocol.Init( msg, msg.Name, TMessageType.Exception, msg.SeqID);" << endl; indent_impl(s_service_impl) << "oprot.WriteMessageBegin( msg);" << endl; indent_impl(s_service_impl) << "x.Write(oprot);" << endl; @@ -2356,7 +2434,7 @@ void t_delphi_generator::generate_process_function(t_service* tservice, t_functi string result_intfnm = normalize_clsnm(org_resultname, "I"); indent(s_service) << "procedure " << funcname - << "_Process( seqid: Integer; const iprot: IProtocol; const oprot: IProtocol" + << "_Process( seqid: System.Integer; const iprot: IProtocol; const oprot: IProtocol" << (events_ ? "; const events : IRequestEvents" : "") << ");" << endl; if (tfunction->is_oneway()) { @@ -2367,13 +2445,13 @@ void t_delphi_generator::generate_process_function(t_service* tservice, t_functi indent_impl(s_service_impl) << "procedure " << full_cls << "." << funcname - << "_Process( seqid: Integer; const iprot: IProtocol; const oprot: IProtocol" + << "_Process( seqid: System.Integer; const iprot: IProtocol; const oprot: IProtocol" << (events_ ? "; const events : IRequestEvents" : "") << ");" << endl; indent_impl(s_service_impl) << "var" << endl; indent_up_impl(); indent_impl(s_service_impl) << "args: " << args_intfnm << ";" << endl; if (!tfunction->is_oneway()) { - indent_impl(s_service_impl) << "msg: Thrift.Protocol.IMessage;" << endl; + indent_impl(s_service_impl) << "msg: Thrift.Protocol.TThriftMessage;" << endl; indent_impl(s_service_impl) << "ret: " << result_intfnm << ";" << endl; indent_impl(s_service_impl) << "appx : TApplicationException;" << endl; } @@ -2452,14 +2530,14 @@ void t_delphi_generator::generate_process_function(t_service* tservice, t_functi indent_impl(s_service_impl) << "if events <> nil then events.UnhandledError(E);" << endl; } if (!tfunction->is_oneway()) { - indent_impl(s_service_impl) << "appx := TApplicationExceptionInternalError.Create(E.Message);" + indent_impl(s_service_impl) << "appx := TApplicationExceptionInternalError.Create(E.Message);" << endl; indent_impl(s_service_impl) << "try" << endl; indent_up_impl(); if(events_) { indent_impl(s_service_impl) << "if events <> nil then events.PreWrite;" << endl; } - indent_impl(s_service_impl) << "msg := Thrift.Protocol.TMessageImpl.Create('" + indent_impl(s_service_impl) << "Thrift.Protocol.Init( msg, '" << tfunction->get_name() << "', TMessageType.Exception, seqid);" << endl; indent_impl(s_service_impl) << "oprot.WriteMessageBegin( msg);" << endl; @@ -2487,7 +2565,7 @@ void t_delphi_generator::generate_process_function(t_service* tservice, t_functi if (events_) { indent_impl(s_service_impl) << "if events <> nil then events.PreWrite;" << endl; } - indent_impl(s_service_impl) << "msg := Thrift.Protocol.TMessageImpl.Create('" + indent_impl(s_service_impl) << "Thrift.Protocol.Init( msg, '" << tfunction->get_name() << "', TMessageType.Reply, seqid); " << endl; indent_impl(s_service_impl) << "oprot.WriteMessageBegin( msg); " << endl; @@ -2541,7 +2619,7 @@ void t_delphi_generator::generate_deserialize_field(ostream& out, throw "compiler error: cannot serialize void field in a struct: " + name; break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { if (ansistr_binary_) { out << "ReadAnsiString();"; } else { @@ -2619,15 +2697,15 @@ void t_delphi_generator::generate_deserialize_container(ostream& out, } if (ttype->is_map()) { - local_var = obj + ": IMap;"; + local_var = obj + ": TThriftMap;"; } else if (ttype->is_set()) { - local_var = obj + ": ISet;"; + local_var = obj + ": TThriftSet;"; } else if (ttype->is_list()) { - local_var = obj + ": IList;"; + local_var = obj + ": TThriftList;"; } local_vars << " " << local_var << endl; counter = tmp("_i"); - local_var = counter + ": Integer;"; + local_var = counter + ": System.Integer;"; local_vars << " " << local_var << endl; indent_impl(out) << name << " := " << type_name(ttype, true) << ".Create;" << endl; @@ -2742,7 +2820,7 @@ void t_delphi_generator::generate_serialize_field(ostream& out, throw "compiler error: cannot serialize void field in a struct: " + name; break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { if (ansistr_binary_) { out << "WriteAnsiString("; } else { @@ -2775,7 +2853,7 @@ void t_delphi_generator::generate_serialize_field(ostream& out, throw "compiler error: no Delphi name for base type " + t_base_type::t_base_name(tbase); } } else if (type->is_enum()) { - out << "WriteI32(Integer(" << name << "));"; + out << "WriteI32(System.Integer(" << name << "));"; } out << endl; } else { @@ -2803,23 +2881,23 @@ void t_delphi_generator::generate_serialize_container(ostream& out, string obj; if (ttype->is_map()) { obj = tmp("map"); - local_vars << " " << obj << " : IMap;" << endl; - indent_impl(out) << obj << " := TMapImpl.Create( " + local_vars << " " << obj << " : TThriftMap;" << endl; + indent_impl(out) << "Thrift.Protocol.Init( " << obj << ", " << type_to_enum(((t_map*)ttype)->get_key_type()) << ", " << type_to_enum(((t_map*)ttype)->get_val_type()) << ", " << prefix << ".Count);" << endl; indent_impl(out) << "oprot.WriteMapBegin( " << obj << ");" << endl; } else if (ttype->is_set()) { obj = tmp("set_"); - local_vars << " " << obj << " : ISet;" << endl; - indent_impl(out) << obj << " := TSetImpl.Create(" + local_vars << " " << obj << " : TThriftSet;" << endl; + indent_impl(out) << "Thrift.Protocol.Init( " << obj << ", " << type_to_enum(((t_set*)ttype)->get_elem_type()) << ", " << prefix << ".Count);" << endl; indent_impl(out) << "oprot.WriteSetBegin( " << obj << ");" << endl; } else if (ttype->is_list()) { obj = tmp("list_"); - local_vars << " " << obj << " : IList;" << endl; - indent_impl(out) << obj << " := TListImpl.Create(" + local_vars << " " << obj << " : TThriftList;" << endl; + indent_impl(out) << "Thrift.Protocol.Init( " << obj << ", " << type_to_enum(((t_list*)ttype)->get_elem_type()) << ", " << prefix << ".Count);" << endl; indent_impl(out) << "oprot.WriteListBegin( " << obj << ");" << endl; @@ -3086,25 +3164,25 @@ string t_delphi_generator::base_type_name(t_base_type* tbase) { case t_base_type::TYPE_STRING: if (tbase->is_binary()) { if (ansistr_binary_) { - return "AnsiString"; + return "System.AnsiString"; } else { - return "TBytes"; + return "SysUtils.TBytes"; } } else { - return "string"; + return "System.string"; } case t_base_type::TYPE_BOOL: - return "Boolean"; + return "System.Boolean"; case t_base_type::TYPE_I8: - return "ShortInt"; + return "System.ShortInt"; case t_base_type::TYPE_I16: - return "SmallInt"; + return "System.SmallInt"; case t_base_type::TYPE_I32: - return "Integer"; + return "System.Integer"; case t_base_type::TYPE_I64: - return "Int64"; + return "System.Int64"; case t_base_type::TYPE_DOUBLE: - return "Double"; + return "System.Double"; default: throw "compiler error: no Delphi name for base type " + t_base_type::t_base_name(tbase->get_base()); @@ -3126,6 +3204,7 @@ string t_delphi_generator::declare_field(t_field* tfield, } string t_delphi_generator::function_signature(t_function* tfunction, + bool for_async, std::string full_cls, bool is_xception) { t_type* ttype = tfunction->get_returntype(); @@ -3135,13 +3214,25 @@ string t_delphi_generator::function_signature(t_function* tfunction, } else { prefix = full_cls + "."; } - if (is_void(ttype)) { - return "procedure " + prefix + normalize_name(tfunction->get_name(), true, is_xception) + "(" - + argument_list(tfunction->get_arglist()) + ");"; + + if( for_async) { + if (is_void(ttype)) { + return "function " + prefix + normalize_name(tfunction->get_name(), true, is_xception) + "Async(" + + argument_list(tfunction->get_arglist()) + "): IFuture;"; // no IFuture in Delphi + } else { + return "function " + prefix + normalize_name(tfunction->get_name(), true, is_xception) + "Async(" + + argument_list(tfunction->get_arglist()) + "): IFuture<" + + type_name(ttype, false, true, is_xception, true) + ">;"; + } } else { - return "function " + prefix + normalize_name(tfunction->get_name(), true, is_xception) + "(" - + argument_list(tfunction->get_arglist()) + "): " - + type_name(ttype, false, true, is_xception, true) + ";"; + if (is_void(ttype)) { + return "procedure " + prefix + normalize_name(tfunction->get_name(), true, is_xception) + "(" + + argument_list(tfunction->get_arglist()) + ");"; + } else { + return "function " + prefix + normalize_name(tfunction->get_name(), true, is_xception) + "(" + + argument_list(tfunction->get_arglist()) + "): " + + type_name(ttype, false, true, is_xception, true) + ";"; + } } } @@ -3268,7 +3359,7 @@ string t_delphi_generator::empty_value(t_type* type) { case t_base_type::TYPE_VOID: return "0"; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { if (ansistr_binary_) { return "''"; } else { @@ -3326,7 +3417,7 @@ void t_delphi_generator::generate_delphi_property_reader_definition(ostream& out void t_delphi_generator::generate_delphi_isset_reader_definition(ostream& out, t_field* tfield, bool is_xception) { - indent(out) << "function Get__isset_" << prop_name(tfield, is_xception) << ": Boolean;" << endl; + indent(out) << "function Get__isset_" << prop_name(tfield, is_xception) << ": System.Boolean;" << endl; } void t_delphi_generator::generate_delphi_clear_union_value(ostream& out, @@ -3369,7 +3460,7 @@ void t_delphi_generator::generate_delphi_property_writer_impl(ostream& out, bool is_xception_class, bool is_union, bool is_xception_factory, - std::string xception_factroy_name) { + std::string xception_factory_name) { (void)type; t_type* ftype = tfield->get_type(); @@ -3390,7 +3481,7 @@ void t_delphi_generator::generate_delphi_property_writer_impl(ostream& out, indent_impl(out) << fieldPrefix << prop_name(tfield, is_xception_class) << " := Value;" << endl; if (is_xception_class && (!is_xception_factory)) { - indent_impl(out) << "F" << xception_factroy_name << "." << prop_name(tfield, is_xception_class) + indent_impl(out) << xception_factory_name << "." << prop_name(tfield, is_xception_class) << " := Value;" << endl; } @@ -3432,7 +3523,7 @@ void t_delphi_generator::generate_delphi_isset_reader_impl(ostream& out, string isset_name = "__isset_" + prop_name(tfield, is_xception); indent_impl(out) << "function " << cls_prefix << name << "." - << "Get" << isset_name << ": Boolean;" << endl; + << "Get" << isset_name << ": System.Boolean;" << endl; indent_impl(out) << "begin" << endl; indent_up_impl(); indent_impl(out) << "Result := " << fieldPrefix << isset_name << ";" << endl; @@ -3457,7 +3548,7 @@ void t_delphi_generator::generate_delphi_create_exception_impl(ostream& out, indent_impl(out) << "Result := " << exception_cls_nm << ".Create;" << endl; string factory_name = normalize_clsnm(tstruct->get_name(), "", true) + "Factory"; - indent_impl(out) << "Result." << factory_name << " := Self;" << endl; + indent_impl(out) << "Result.F" << factory_name << " := Self;" << endl; const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; @@ -3467,8 +3558,7 @@ void t_delphi_generator::generate_delphi_create_exception_impl(ostream& out, for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { propname = prop_name(*f_iter, is_exception); if ((*f_iter)->get_req() != t_field::T_REQUIRED) { - indent_impl(out) << "if __isset_" << propname << " then" << endl; - indent_impl(out) << "begin" << endl; + indent_impl(out) << "if __isset_" << propname << " then begin" << endl; indent_up_impl(); } indent_impl(out) << "Result." << propname << " := " << propname << ";" << endl; @@ -3504,7 +3594,7 @@ void t_delphi_generator::generate_delphi_struct_reader_impl(ostream& out, // local bools for required fields for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { if ((*f_iter)->get_req() == t_field::T_REQUIRED) { - indent_impl(local_vars) << "_req_isset_" << prop_name(*f_iter, is_exception) << " : Boolean;" + indent_impl(local_vars) << "_req_isset_" << prop_name(*f_iter, is_exception) << " : System.Boolean;" << endl; indent_impl(code_block) << "_req_isset_" << prop_name(*f_iter, is_exception) << " := FALSE;" << endl; @@ -3548,7 +3638,7 @@ void t_delphi_generator::generate_delphi_struct_reader_impl(ostream& out, << ") then begin" << endl; indent_up_impl(); - generate_deserialize_field(code_block, is_exception, *f_iter, "", local_vars); + generate_deserialize_field(code_block, is_exception, *f_iter, "Self.", local_vars); // required field? if ((*f_iter)->get_req() == t_field::T_REQUIRED) { @@ -3617,8 +3707,8 @@ void t_delphi_generator::generate_delphi_struct_reader_impl(ostream& out, << endl; indent_impl(out) << "var" << endl; indent_up_impl(); - indent_impl(out) << "field_ : IField;" << endl; - indent_impl(out) << "struc : IStruct;" << endl; + indent_impl(out) << "field_ : TThriftField;" << endl; + indent_impl(out) << "struc : TThriftStruct;" << endl; indent_down_impl(); out << local_vars.str() << endl; out << code_block.str(); @@ -3642,11 +3732,11 @@ void t_delphi_generator::generate_delphi_struct_result_writer_impl(ostream& out, indent_impl(local_vars) << "tracker : IProtocolRecursionTracker;" << endl; indent_impl(code_block) << "tracker := oprot.NextRecursionLevel;" << endl; - indent_impl(code_block) << "struc := TStructImpl.Create('" << name << "');" << endl; + indent_impl(code_block) << "Thrift.Protocol.Init( struc, '" << name << "');" << endl; indent_impl(code_block) << "oprot.WriteStructBegin(struc);" << endl; if (fields.size() > 0) { - indent_impl(code_block) << "field_ := TFieldImpl.Create;" << endl; + indent_impl(code_block) << "Thrift.Protocol.Init( field_);" << endl; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { indent_impl(code_block) << "if (__isset_" << prop_name(*f_iter, is_exception) << ") then" << endl; @@ -3657,7 +3747,7 @@ void t_delphi_generator::generate_delphi_struct_result_writer_impl(ostream& out, << endl; indent_impl(code_block) << "field_.ID := " << (*f_iter)->get_key() << ";" << endl; indent_impl(code_block) << "oprot.WriteFieldBegin(field_);" << endl; - generate_serialize_field(code_block, is_exception, *f_iter, "", local_vars); + generate_serialize_field(code_block, is_exception, *f_iter, "Self.", local_vars); indent_impl(code_block) << "oprot.WriteFieldEnd();" << endl; indent_down_impl(); } @@ -3677,10 +3767,10 @@ void t_delphi_generator::generate_delphi_struct_result_writer_impl(ostream& out, << endl; indent_impl(out) << "var" << endl; indent_up_impl(); - indent_impl(out) << "struc : IStruct;" << endl; + indent_impl(out) << "struc : TThriftStruct;" << endl; if (fields.size() > 0) { - indent_impl(out) << "field_ : IField;" << endl; + indent_impl(out) << "field_ : TThriftField;" << endl; } out << local_vars.str(); @@ -3706,11 +3796,11 @@ void t_delphi_generator::generate_delphi_struct_writer_impl(ostream& out, indent_impl(local_vars) << "tracker : IProtocolRecursionTracker;" << endl; indent_impl(code_block) << "tracker := oprot.NextRecursionLevel;" << endl; - indent_impl(code_block) << "struc := TStructImpl.Create('" << name << "');" << endl; + indent_impl(code_block) << "Thrift.Protocol.Init( struc, '" << name << "');" << endl; indent_impl(code_block) << "oprot.WriteStructBegin(struc);" << endl; if (fields.size() > 0) { - indent_impl(code_block) << "field_ := TFieldImpl.Create;" << endl; + indent_impl(code_block) << "Thrift.Protocol.Init( field_);" << endl; } for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { @@ -3720,13 +3810,13 @@ void t_delphi_generator::generate_delphi_struct_writer_impl(ostream& out, bool has_isset = (!is_required); if (is_required && null_allowed) { null_allowed = false; - indent_impl(code_block) << "if (" << fieldname << " = nil)" << endl; - indent_impl(code_block) << "then raise TProtocolExceptionInvalidData.Create(" + indent_impl(code_block) << "if (Self." << fieldname << " = nil)" << endl; + indent_impl(code_block) << "then raise TProtocolExceptionInvalidData.Create(" << "'required field " << fieldname << " not set');" << endl; } if (null_allowed) { - indent_impl(code_block) << "if (" << fieldname << " <> nil)"; + indent_impl(code_block) << "if (Self." << fieldname << " <> nil)"; if (has_isset) { code_block << " and __isset_" << fieldname; } @@ -3743,7 +3833,7 @@ void t_delphi_generator::generate_delphi_struct_writer_impl(ostream& out, << endl; indent_impl(code_block) << "field_.ID := " << (*f_iter)->get_key() << ";" << endl; indent_impl(code_block) << "oprot.WriteFieldBegin(field_);" << endl; - generate_serialize_field(code_block, is_exception, *f_iter, "", local_vars); + generate_serialize_field(code_block, is_exception, *f_iter, "Self.", local_vars); indent_impl(code_block) << "oprot.WriteFieldEnd();" << endl; if (null_allowed || has_isset) { indent_down_impl(); @@ -3765,9 +3855,9 @@ void t_delphi_generator::generate_delphi_struct_writer_impl(ostream& out, << endl; indent_impl(out) << "var" << endl; indent_up_impl(); - indent_impl(out) << "struc : IStruct;" << endl; + indent_impl(out) << "struc : TThriftStruct;" << endl; if (fields.size() > 0) { - indent_impl(out) << "field_ : IField;" << endl; + indent_impl(out) << "field_ : TThriftField;" << endl; } out << local_vars.str(); indent_down_impl(); @@ -3802,7 +3892,7 @@ void t_delphi_generator::generate_delphi_struct_tostring_impl(ostream& out, for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { bool is_optional = ((*f_iter)->get_req() != t_field::T_REQUIRED); if (is_optional) { - indent_impl(out) << tmp_first << " : Boolean;" << endl; + indent_impl(out) << tmp_first << " : System.Boolean;" << endl; useFirstFlag = true; } break; @@ -3825,7 +3915,7 @@ void t_delphi_generator::generate_delphi_struct_tostring_impl(ostream& out, bool null_allowed = type_can_be_null((*f_iter)->get_type()); bool is_optional = ((*f_iter)->get_req() != t_field::T_REQUIRED); if (null_allowed) { - indent_impl(out) << "if (" << prop_name((*f_iter), is_exception) << " <> nil)"; + indent_impl(out) << "if (Self." << prop_name((*f_iter), is_exception) << " <> nil)"; if (is_optional) { out << " and __isset_" << prop_name(*f_iter, is_exception); } @@ -3857,14 +3947,14 @@ void t_delphi_generator::generate_delphi_struct_tostring_impl(ostream& out, } if (ttype->is_xception() || ttype->is_struct()) { - indent_impl(out) << "if (" << prop_name((*f_iter), is_exception) << " = nil) then " << tmp_sb - << ".Append('') else " << tmp_sb << ".Append(" + indent_impl(out) << "if (Self." << prop_name((*f_iter), is_exception) << " = nil) then " << tmp_sb + << ".Append('') else " << tmp_sb << ".Append( Self." << prop_name((*f_iter), is_exception) << ".ToString());" << endl; } else if (ttype->is_enum()) { - indent_impl(out) << tmp_sb << ".Append(Integer(" << prop_name((*f_iter), is_exception) + indent_impl(out) << tmp_sb << ".Append(System.Integer( Self." << prop_name((*f_iter), is_exception) << "));" << endl; } else { - indent_impl(out) << tmp_sb << ".Append(" << prop_name((*f_iter), is_exception) << ");" + indent_impl(out) << tmp_sb << ".Append( Self." << prop_name((*f_iter), is_exception) << ");" << endl; } @@ -3917,4 +4007,5 @@ THRIFT_REGISTER_GENERATOR( " and container instances by interface or TypeInfo()\n" " constprefix: Name TConstants classes after IDL to reduce ambiguities\n" " events: Enable and use processing events in the generated code.\n" - " xmldoc: Enable XMLDoc comments for Help Insight etc.\n") + " xmldoc: Enable XMLDoc comments for Help Insight etc.\n" + " async: Generate IAsync interface to use Parallel Programming Library (XE7+ only).\n") diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_erl_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_erl_generator.cc index 4869414..587133f 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_erl_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_erl_generator.cc @@ -20,6 +20,7 @@ #include #include #include +#include #include #include @@ -56,6 +57,9 @@ public: legacy_names_ = false; maps_ = false; otp16_ = false; + export_lines_first_ = true; + export_types_lines_first_ = true; + for( iter = parsed_options.begin(); iter != parsed_options.end(); ++iter) { if( iter->first.compare("legacynames") == 0) { legacy_names_ = true; @@ -117,6 +121,8 @@ public: void generate_type_metadata(std::string function_name, vector names); void generate_enum_info(t_enum* tenum); void generate_enum_metadata(); + void generate_const_function(t_const* tconst, ostringstream& exports, ostringstream& functions); + void generate_const_functions(); /** * Service-level generation functions @@ -135,6 +141,7 @@ public: std::string erl_imports(); std::string render_includes(); std::string type_name(t_type* ttype); + std::string render_const_list_values(t_type* type, t_const_value* value); std::string function_signature(t_function* tfunction, std::string prefix = ""); @@ -187,7 +194,6 @@ private: void export_function(t_function* tfunction, std::string prefix = ""); void export_string(std::string name, int num); - void export_types_function(t_function* tfunction, std::string prefix = ""); void export_types_string(std::string name, int num); /** @@ -214,13 +220,15 @@ private: std::ostringstream f_info_; std::ostringstream f_info_ext_; - std::ofstream f_types_file_; - std::ofstream f_types_hrl_file_; + ofstream_with_content_based_conditional_update f_types_file_; + ofstream_with_content_based_conditional_update f_types_hrl_file_; + + ofstream_with_content_based_conditional_update f_consts_file_; + ofstream_with_content_based_conditional_update f_consts_hrl_file_; - std::ofstream f_consts_; std::ostringstream f_service_; - std::ofstream f_service_file_; - std::ofstream f_service_hrl_; + ofstream_with_content_based_conditional_update f_service_file_; + ofstream_with_content_based_conditional_update f_service_hrl_; /** * Metadata containers @@ -229,6 +237,7 @@ private: std::vector v_enum_names_; std::vector v_exception_names_; std::vector v_enums_; + std::vector v_consts_; }; /** @@ -245,31 +254,41 @@ void t_erl_generator::init_generator() { export_lines_first_ = true; export_types_lines_first_ = true; + string program_module_name = make_safe_for_module_name(program_name_); + // types files - string f_types_name = get_out_dir() + make_safe_for_module_name(program_name_) + "_types.erl"; - string f_types_hrl_name = get_out_dir() + make_safe_for_module_name(program_name_) + "_types.hrl"; + string f_types_name = get_out_dir() + program_module_name + "_types.erl"; + string f_types_hrl_name = get_out_dir() + program_module_name + "_types.hrl"; f_types_file_.open(f_types_name.c_str()); f_types_hrl_file_.open(f_types_hrl_name.c_str()); - hrl_header(f_types_hrl_file_, make_safe_for_module_name(program_name_) + "_types"); + hrl_header(f_types_hrl_file_, program_module_name + "_types"); - f_types_file_ << erl_autogen_comment() << endl << "-module(" - << make_safe_for_module_name(program_name_) << "_types)." << endl << erl_imports() - << endl; + f_types_file_ << erl_autogen_comment() << endl + << "-module(" << program_module_name << "_types)." << endl + << erl_imports() << endl; - f_types_file_ << "-include(\"" << make_safe_for_module_name(program_name_) << "_types.hrl\")." - << endl << endl; + f_types_file_ << "-include(\"" << program_module_name << "_types.hrl\")." << endl + << endl; f_types_hrl_file_ << render_includes() << endl; - // consts file - string f_consts_name = get_out_dir() + make_safe_for_module_name(program_name_) - + "_constants.hrl"; - f_consts_.open(f_consts_name.c_str()); + // consts files + string f_consts_name = get_out_dir() + program_module_name + "_constants.erl"; + string f_consts_hrl_name = get_out_dir() + program_module_name + "_constants.hrl"; - f_consts_ << erl_autogen_comment() << endl << erl_imports() << endl << "-include(\"" - << make_safe_for_module_name(program_name_) << "_types.hrl\")." << endl << endl; + f_consts_file_.open(f_consts_name.c_str()); + f_consts_hrl_file_.open(f_consts_hrl_name.c_str()); + + f_consts_file_ << erl_autogen_comment() << endl + << "-module(" << program_module_name << "_constants)." << endl + << erl_imports() << endl + << "-include(\"" << program_module_name << "_types.hrl\")." << endl + << endl; + + f_consts_hrl_file_ << erl_autogen_comment() << endl << erl_imports() << endl + << "-include(\"" << program_module_name << "_types.hrl\")." << endl << endl; } /** @@ -350,6 +369,8 @@ void t_erl_generator::close_generator() { f_types_file_ << f_info_ext_.str(); f_types_file_ << "struct_info_ext(_) -> erlang:error(function_clause)." << endl << endl; + generate_const_functions(); + generate_type_metadata("struct_names", v_struct_names_); generate_enum_metadata(); generate_type_metadata("enum_names", v_enum_names_); @@ -359,7 +380,38 @@ void t_erl_generator::close_generator() { f_types_file_.close(); f_types_hrl_file_.close(); - f_consts_.close(); + f_consts_file_.close(); + f_consts_hrl_file_.close(); +} + +const std::string emit_double_as_string(const double value) { + std::stringstream double_output_stream; + // sets the maximum precision: http://en.cppreference.com/w/cpp/io/manip/setprecision + // sets the output format to fixed: http://en.cppreference.com/w/cpp/io/manip/fixed (not in scientific notation) + double_output_stream << std::setprecision(std::numeric_limits::digits10 + 1); + + #ifdef _MSC_VER + // strtod is broken in MSVC compilers older than 2015, so std::fixed fails to format a double literal. + // more details: https://blogs.msdn.microsoft.com/vcblog/2014/06/18/ + // c-runtime-crt-features-fixes-and-breaking-changes-in-visual-studio-14-ctp1/ + // and + // http://www.exploringbinary.com/visual-c-plus-plus-strtod-still-broken/ + #if _MSC_VER >= MSC_2015_VER + double_output_stream << std::fixed; + #else + // note that if this function is called from the erlang generator and the MSVC compiler is older than 2015, + // the double literal must be output in the scientific format. There can be some cases where the + // mantissa of the output does not have fractionals, which is illegal in Erlang. + // example => 10000000000000000.0 being output as 1e+16 + double_output_stream << std::scientific; + #endif + #else + double_output_stream << std::fixed; + #endif + + double_output_stream << value; + + return double_output_stream.str(); } void t_erl_generator::generate_type_metadata(std::string function_name, vector names) { @@ -392,6 +444,68 @@ void t_erl_generator::generate_typedef(t_typedef* ttypedef) { (void)ttypedef; } + +void t_erl_generator::generate_const_function(t_const* tconst, ostringstream& exports, ostringstream& functions) { + t_type* type = get_true_type(tconst->get_type()); + string name = tconst->get_name(); + t_const_value* value = tconst->get_value(); + + if (type->is_map()) { + t_type* ktype = ((t_map*)type)->get_key_type(); + t_type* vtype = ((t_map*)type)->get_val_type(); + string const_fun_name = lowercase(name); + + // Emit const function export. + if (exports.tellp() > 0) { exports << ", "; } + exports << const_fun_name << "/1, " << const_fun_name << "/2"; + + // Emit const function definition. + map::const_iterator i, end = value->get_map().end(); + // The one-argument form throws an error if the key does not exist in the map. + for (i = value->get_map().begin(); i != end;) { + functions << const_fun_name << "(" << render_const_value(ktype, i->first) << ") -> " + << render_const_value(vtype, i->second); + ++i; + functions << (i != end ? ";\n" : ".\n\n"); + } + + // The two-argument form returns a default value if the key does not exist in the map. + for (i = value->get_map().begin(); i != end; ++i) { + functions << const_fun_name << "(" << render_const_value(ktype, i->first) << ", _) -> " + << render_const_value(vtype, i->second) << ";\n"; + } + functions << const_fun_name << "(_, Default) -> Default.\n\n"; + } else if (type->is_list()) { + string const_fun_name = lowercase(name); + + if (exports.tellp() > 0) { exports << ", "; } + exports << const_fun_name << "/1, " << const_fun_name << "/2"; + + size_t list_size = value->get_list().size(); + string rendered_list = render_const_list_values(type, value); + functions << const_fun_name << "(N) when N >= 1, N =< " << list_size << " ->\n" + << indent_str() << "element(N, {" << rendered_list << "}).\n"; + functions << const_fun_name << "(N, _) when N >= 1, N =< " << list_size << " ->\n" + << indent_str() << "element(N, {" << rendered_list << "});\n" + << const_fun_name << "(_, Default) -> Default.\n\n"; + indent_down(); + } +} + +void t_erl_generator::generate_const_functions() { + ostringstream exports; + ostringstream functions; + vector::iterator c_iter; + for (c_iter = v_consts_.begin(); c_iter != v_consts_.end(); ++c_iter) { + generate_const_function(*c_iter, exports, functions); + } + if (exports.tellp() > 0) { + f_consts_file_ << "-export([" << exports.str() << "]).\n\n" + << functions.str(); + } +} + + /** * Generates code for an enumerated type. Done using a class to scope * the values. @@ -458,8 +572,11 @@ void t_erl_generator::generate_const(t_const* tconst) { string name = tconst->get_name(); t_const_value* value = tconst->get_value(); - f_consts_ << "-define(" << constify(make_safe_for_module_name(program_name_)) << "_" - << constify(name) << ", " << render_const_value(type, value) << ")." << endl << endl; + // Save the tconst so that function can be emitted in generate_const_functions(). + v_consts_.push_back(tconst); + + f_consts_hrl_file_ << "-define(" << constify(make_safe_for_module_name(program_name_)) << "_" + << constify(name) << ", " << render_const_value(type, value) << ")." << endl << endl; } /** @@ -488,9 +605,9 @@ string t_erl_generator::render_const_value(t_type* type, t_const_value* value) { break; case t_base_type::TYPE_DOUBLE: if (value->get_type() == t_const_value::CV_INTEGER) { - out << value->get_integer(); + out << "float(" << value->get_integer() << ")"; } else { - out << value->get_double(); + out << emit_double_as_string(value->get_double()); } break; default: @@ -503,8 +620,8 @@ string t_erl_generator::render_const_value(t_type* type, t_const_value* value) { out << "#" << type_name(type) << "{"; const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; bool first = true; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { @@ -539,7 +656,7 @@ string t_erl_generator::render_const_value(t_type* type, t_const_value* value) { } else { out << "dict:from_list(["; } - map::const_iterator i, end = value->get_map().end(); + map::const_iterator i, end = value->get_map().end(); for (i = value->get_map().begin(); i != end;) { out << "{" << render_const_value(ktype, i->first) << "," << render_const_value(vtype, i->second) << "}"; @@ -560,28 +677,32 @@ string t_erl_generator::render_const_value(t_type* type, t_const_value* value) { } out << "])"; } else if (type->is_list()) { - t_type* etype; - etype = ((t_list*)type)->get_elem_type(); - out << "["; - - bool first = true; - const vector& val = value->get_list(); - vector::const_iterator v_iter; - for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { - if (first) { - first = false; - } else { - out << ","; - } - out << render_const_value(etype, *v_iter); - } - out << "]"; + out << "[" << render_const_list_values(type, value) << "]"; } else { throw "CANNOT GENERATE CONSTANT FOR TYPE: " + type->get_name(); } return out.str(); } +string t_erl_generator::render_const_list_values(t_type* type, t_const_value* value) { + std::ostringstream out; + t_type* etype = ((t_list*)type)->get_elem_type(); + + bool first = true; + const vector& val = value->get_list(); + vector::const_iterator v_iter; + for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { + if (first) { + first = false; + } else { + out << ","; + } + out << render_const_value(etype, *v_iter); + } + return out.str(); +} + + string t_erl_generator::render_default_value(t_field* field) { t_type* type = field->get_type(); if (type->is_struct() || type->is_xception()) { @@ -626,7 +747,7 @@ string t_erl_generator::render_member_type(t_field* field) { return type_name(type) + "()"; } else if (type->is_map()) { if (maps_) { - return "#{}"; + return "map()"; } else if (otp16_) { return "dict()"; } else { @@ -719,6 +840,8 @@ void t_erl_generator::generate_erl_struct_member(ostream& out, t_field* tmember) if (has_default_value(tmember)) out << " = " << render_member_value(tmember); out << " :: " << render_member_type(tmember); + if (tmember->get_req() != t_field::T_REQUIRED) + out << " | 'undefined'"; } bool t_erl_generator::has_default_value(t_field* field) { @@ -967,13 +1090,6 @@ void t_erl_generator::export_string(string name, int num) { export_lines_ << name << "/" << num; } -void t_erl_generator::export_types_function(t_function* tfunction, string prefix) { - - export_types_string(prefix + tfunction->get_name(), - 1 // This - + ((tfunction->get_arglist())->get_members()).size()); -} - void t_erl_generator::export_types_string(string name, int num) { if (export_types_lines_first_) { export_types_lines_first_ = false; @@ -984,10 +1100,13 @@ void t_erl_generator::export_types_string(string name, int num) { } void t_erl_generator::export_function(t_function* tfunction, string prefix) { - + t_struct::members_type::size_type num = tfunction->get_arglist()->get_members().size(); + if (num > static_cast(std::numeric_limits().max())) { + throw "integer overflow in t_erl_generator::export_function, name " + tfunction->get_name(); + } export_string(prefix + tfunction->get_name(), 1 // This - + ((tfunction->get_arglist())->get_members()).size()); + + static_cast(num)); } /** @@ -1012,19 +1131,14 @@ string t_erl_generator::argument_list(t_struct* tstruct) { } string t_erl_generator::type_name(t_type* ttype) { - string prefix = ""; - string erl_namespace = ttype->get_program()->get_namespace("erl"); - - if (erl_namespace.length() > 0) { - prefix = erl_namespace + "."; + string prefix = ttype->get_program()->get_namespace("erl"); + size_t prefix_length = prefix.length(); + if (prefix_length > 0 && prefix[prefix_length - 1] != '_') { + prefix += '.'; } string name = ttype->get_name(); - if (ttype->is_struct() || ttype->is_xception() || ttype->is_service()) { - name = ttype->get_name(); - } - return atomify(prefix + name); } diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_generator.cc index 0c1f49d..ca3f5dd 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_generator.cc @@ -76,6 +76,77 @@ void t_generator::generate_program() { close_generator(); } +std::set t_generator::lang_keywords() const { + std::string keywords[] = { "BEGIN", "END", "__CLASS__", "__DIR__", "__FILE__", "__FUNCTION__", + "__LINE__", "__METHOD__", "__NAMESPACE__", "abstract", "alias", "and", "args", "as", + "assert", "begin", "break", "case", "catch", "class", "clone", "continue", "declare", + "def", "default", "del", "delete", "do", "dynamic", "elif", "else", "elseif", "elsif", + "end", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "ensure", + "except", "exec", "finally", "float", "for", "foreach", "from", "function", "global", + "goto", "if", "implements", "import", "in", "inline", "instanceof", "interface", "is", + "lambda", "module", "native", "new", "next", "nil", "not", "or", "package", "pass", + "public", "print", "private", "protected", "raise", "redo", "rescue", "retry", "register", + "return", "self", "sizeof", "static", "super", "switch", "synchronized", "then", "this", + "throw", "transient", "try", "undef", "unless", "unsigned", "until", "use", "var", + "virtual", "volatile", "when", "while", "with", "xor", "yield" }; + return std::set(keywords, keywords + sizeof(keywords)/sizeof(keywords[0]) ); +} + +void t_generator::validate_input() const { + validate(program_->get_enums()); + validate(program_->get_typedefs()); + validate(program_->get_objects()); + validate(program_->get_consts()); + validate(program_->get_services()); +} + +template +void t_generator::validate(const vector& list) const{ + typename vector::const_iterator it; + for(it=list.begin(); it != list.end(); ++it) { + validate(*it); + } +} + +void t_generator::validate(t_function const* f) const { + validate_id(f->get_name()); + validate(f->get_arglist()); + validate(f->get_xceptions()); +} + +void t_generator::validate(t_service const* s) const { + validate_id(s->get_name()); + validate(s->get_functions()); +} + +void t_generator::validate(t_enum const* en) const { + validate_id(en->get_name()); + validate(en->get_constants()); +} +void t_generator::validate(t_struct const* s) const { + validate_id(s->get_name()); + validate(s->get_members()); +} + +void t_generator::validate(t_enum_value const* en_val) const { + validate_id(en_val->get_name()); +} +void t_generator::validate(t_typedef const* td) const { + validate_id(td->get_name()); +} +void t_generator::validate(t_const const* c) const { + validate_id(c->get_name()); +} +void t_generator::validate(t_field const* f) const { + validate_id(f->get_name()); +} + +void t_generator::validate_id(const string& id) const { + if (keywords_.find(id) != keywords_.end()) { + failure("Cannot use reserved language keyword: \"%s\"", id.c_str()); + } +} + string t_generator::escape_string(const string& in) const { string result = ""; for (string::const_iterator it = in.begin(); it < in.end(); it++) { @@ -101,21 +172,22 @@ void t_generator::generate_docstring_comment(ostream& out, const string& line_prefix, const string& contents, const string& comment_end) { - if (comment_start != "") + if (!comment_start.empty()) indent(out) << comment_start; stringstream docs(contents, ios_base::in); while (!(docs.eof() || docs.fail())) { char line[1024]; docs.getline(line, 1024); - // Just prnt a newline when the line & prefix are empty. - if (strlen(line) == 0 && line_prefix == "" && !docs.eof()) { - out << std::endl; - } else if (strlen(line) > 0 || !docs.eof()) { // skip the empty last line + if (strlen(line) > 0) { indent(out) << line_prefix << line << std::endl; + } else if (line_prefix.empty()){ + out << std::endl; + } else if(!docs.eof()) { + indent(out) << line_prefix << std::endl; } } - if (comment_end != "") + if (!comment_end.empty()) indent(out) << comment_end; } diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_generator.h b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_generator.h index 051bbc4..cb9d076 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_generator.h +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_generator.h @@ -19,12 +19,17 @@ #ifndef T_GENERATOR_H #define T_GENERATOR_H +#define MSC_2015_VER 1900 +#include #include +#include #include #include +#include #include #include "thrift/common.h" +#include "thrift/logging.h" #include "thrift/version.h" #include "thrift/generate/t_generator_registry.h" #include "thrift/parse/t_program.h" @@ -37,7 +42,8 @@ */ class t_generator { public: - t_generator(t_program* program) { + t_generator(t_program* program) + : keywords_(lang_keywords()){ tmp_ = 0; indent_ = 0; program_ = program; @@ -91,9 +97,35 @@ public: return escape_string(constval->get_string()); } -protected: /** - * Optional methods that may be imlemented by subclasses to take necessary + * Check if all identifiers are valid for the target language + */ + virtual void validate_input() const; + +protected: + virtual std::set lang_keywords() const; + + /** + * A list of reserved words that cannot be used as identifiers. + */ + const std::set keywords_; + + virtual void validate_id(const std::string& id) const; + + virtual void validate(t_enum const* en) const; + virtual void validate(t_enum_value const* en_val) const; + virtual void validate(t_typedef const* td) const; + virtual void validate(t_const const* c) const; + virtual void validate(t_service const* s) const; + virtual void validate(t_struct const* c) const; + virtual void validate(t_field const* f) const; + virtual void validate(t_function const* f) const; + + template + void validate(const std::vector& list) const; + + /** + * Optional methods that may be implemented by subclasses to take necessary * steps at the beginning or end of code generation. */ @@ -172,6 +204,17 @@ protected: void indent_down() { --indent_; } + /** + * Indentation validation helper + */ + int indent_count() { return indent_; } + + void indent_validate( int expected, const char * func_name) { + if (indent_ != expected) { + pverbose("Wrong indent count in %s: difference = %i \n", func_name, (expected - indent_)); + } + } + /** * Indentation print function */ @@ -212,6 +255,7 @@ protected: } return in; } + /** * Transforms a camel case string to an equivalent one separated by underscores * e.g. aMultiWord -> a_multi_word @@ -230,6 +274,7 @@ protected: } return in; } + /** * Transforms a string with words separated by underscores to a camel case equivalent * e.g. a_multi_word -> aMultiWord @@ -256,6 +301,30 @@ protected: return out.str(); } + const std::string emit_double_as_string(const double value) { + std::stringstream double_output_stream; + // sets the maximum precision: http://en.cppreference.com/w/cpp/io/manip/setprecision + // sets the output format to fixed: http://en.cppreference.com/w/cpp/io/manip/fixed (not in scientific notation) + double_output_stream << std::setprecision(std::numeric_limits::digits10 + 1); + + #ifdef _MSC_VER + // strtod is broken in MSVC compilers older than 2015, so std::fixed fails to format a double literal. + // more details: https://blogs.msdn.microsoft.com/vcblog/2014/06/18/ + // c-runtime-crt-features-fixes-and-breaking-changes-in-visual-studio-14-ctp1/ + // and + // http://www.exploringbinary.com/visual-c-plus-plus-strtod-still-broken/ + #if _MSC_VER >= MSC_2015_VER + double_output_stream << std::fixed; + #endif + #else + double_output_stream << std::fixed; + #endif + + double_output_stream << value; + + return double_output_stream.str(); + } + public: /** * Get the true type behind a series of typedefs. @@ -307,4 +376,77 @@ private: int tmp_; }; +template > +class template_ofstream_with_content_based_conditional_update : public std::ostringstream { +public: + template_ofstream_with_content_based_conditional_update(): contents_written(false) {} + + template_ofstream_with_content_based_conditional_update(std::string const& output_file_path_) + : output_file_path(output_file_path_), contents_written(false) {} + + ~template_ofstream_with_content_based_conditional_update() { + if (!contents_written) { + close(); + } + } + + void open(std::string const& output_file_path_) { + output_file_path = output_file_path_; + clear_buf(); + contents_written = false; + } + + void close() { + if (contents_written || output_file_path == "") + return; + + if (!is_readable(output_file_path)) { + dump(); + return; + } + + std::ifstream old_file; + old_file.exceptions(old_file.exceptions() | std::ifstream::badbit | std::ifstream::failbit); + old_file.open(output_file_path.c_str(), std::ios::in); + + if (old_file) { + std::string const old_file_contents(static_cast(std::ostringstream() << old_file.rdbuf()).str()); + old_file.close(); + + if (old_file_contents != str()) { + dump(); + } + } + } + +protected: + void dump() { + std::ofstream out_file; + out_file.exceptions(out_file.exceptions() | std::ofstream::badbit | std::ofstream::failbit); + try { + out_file.open(output_file_path.c_str(), std::ios::out); + } + catch (const std::ios_base::failure& e) { + ::failure("failed to write the output to the file '%s', details: '%s'", output_file_path.c_str(), e.what()); + } + out_file << str(); + out_file.close(); + clear_buf(); + contents_written = true; + } + + void clear_buf() { + str(std::string()); + } + + static bool is_readable(std::string const& file_name) { + return static_cast(std::ifstream(file_name.c_str())); + } + +private: + std::string output_file_path; + bool contents_written; +}; +typedef template_ofstream_with_content_based_conditional_update ofstream_with_content_based_conditional_update; + #endif diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_go_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_go_generator.cc index 9919cb1..5ada4fa 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_go_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_go_generator.cc @@ -25,9 +25,10 @@ * guide for ensuring uniformity and readability. */ -#include #include #include +#include +#include #include #include @@ -41,7 +42,7 @@ #include "thrift/generate/t_generator.h" using std::map; -using std::ofstream; +using std::ostream; using std::ostringstream; using std::string; using std::stringstream; @@ -60,7 +61,7 @@ static const string endl = "\n"; // avoid ostream << std::endl flushes */ bool format_go_output(const string& file_path); -const string DEFAULT_THRIFT_IMPORT = "git.apache.org/thrift.git/lib/go/thrift"; +const string DEFAULT_THRIFT_IMPORT = "github.com/apache/thrift/lib/go/thrift"; static std::string package_flag; /** @@ -118,34 +119,34 @@ public: void generate_xception(t_struct* txception); void generate_service(t_service* tservice); - std::string render_const_value(t_type* type, t_const_value* value, const string& name); + std::string render_const_value(t_type* type, t_const_value* value, const string& name, bool opt = false); /** * Struct generation code */ void generate_go_struct(t_struct* tstruct, bool is_exception); - void generate_go_struct_definition(std::ofstream& out, + void generate_go_struct_definition(std::ostream& out, t_struct* tstruct, bool is_xception = false, bool is_result = false, bool is_args = false); - void generate_go_struct_initializer(std::ofstream& out, + void generate_go_struct_initializer(std::ostream& out, t_struct* tstruct, bool is_args_or_result = false); - void generate_isset_helpers(std::ofstream& out, + void generate_isset_helpers(std::ostream& out, t_struct* tstruct, const string& tstruct_name, bool is_result = false); - void generate_countsetfields_helper(std::ofstream& out, + void generate_countsetfields_helper(std::ostream& out, t_struct* tstruct, const string& tstruct_name, bool is_result = false); - void generate_go_struct_reader(std::ofstream& out, + void generate_go_struct_reader(std::ostream& out, t_struct* tstruct, const string& tstruct_name, bool is_result = false); - void generate_go_struct_writer(std::ofstream& out, + void generate_go_struct_writer(std::ostream& out, t_struct* tstruct, const string& tstruct_name, bool is_result = false, @@ -170,74 +171,73 @@ public: * Serialization constructs */ - void generate_deserialize_field(std::ofstream& out, + void generate_deserialize_field(std::ostream& out, t_field* tfield, bool declare, std::string prefix = "", bool inclass = false, bool coerceData = false, bool inkey = false, - bool in_container = false, - bool use_true_type = false); + bool in_container = false); - void generate_deserialize_struct(std::ofstream& out, + void generate_deserialize_struct(std::ostream& out, t_struct* tstruct, bool is_pointer_field, bool declare, std::string prefix = ""); - void generate_deserialize_container(std::ofstream& out, + void generate_deserialize_container(std::ostream& out, t_type* ttype, bool pointer_field, bool declare, std::string prefix = ""); - void generate_deserialize_set_element(std::ofstream& out, + void generate_deserialize_set_element(std::ostream& out, t_set* tset, bool declare, std::string prefix = ""); - void generate_deserialize_map_element(std::ofstream& out, + void generate_deserialize_map_element(std::ostream& out, t_map* tmap, bool declare, std::string prefix = ""); - void generate_deserialize_list_element(std::ofstream& out, + void generate_deserialize_list_element(std::ostream& out, t_list* tlist, bool declare, std::string prefix = ""); - void generate_serialize_field(std::ofstream& out, + void generate_serialize_field(std::ostream& out, t_field* tfield, std::string prefix = "", bool inkey = false); - void generate_serialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); + void generate_serialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); - void generate_serialize_container(std::ofstream& out, + void generate_serialize_container(std::ostream& out, t_type* ttype, bool pointer_field, std::string prefix = ""); - void generate_serialize_map_element(std::ofstream& out, + void generate_serialize_map_element(std::ostream& out, t_map* tmap, std::string kiter, std::string viter); - void generate_serialize_set_element(std::ofstream& out, t_set* tmap, std::string iter); + void generate_serialize_set_element(std::ostream& out, t_set* tmap, std::string iter); - void generate_serialize_list_element(std::ofstream& out, t_list* tlist, std::string iter); + void generate_serialize_list_element(std::ostream& out, t_list* tlist, std::string iter); - void generate_go_docstring(std::ofstream& out, t_struct* tstruct); + void generate_go_docstring(std::ostream& out, t_struct* tstruct); - void generate_go_docstring(std::ofstream& out, t_function* tfunction); + void generate_go_docstring(std::ostream& out, t_function* tfunction); - void generate_go_docstring(std::ofstream& out, + void generate_go_docstring(std::ostream& out, t_doc* tdoc, t_struct* tstruct, const char* subheader); - void generate_go_docstring(std::ofstream& out, t_doc* tdoc); + void generate_go_docstring(std::ostream& out, t_doc* tdoc); /** * Helper rendering functions @@ -290,9 +290,9 @@ private: * File streams */ - std::ofstream f_types_; + ofstream_with_content_based_conditional_update f_types_; std::string f_types_name_; - std::ofstream f_consts_; + ofstream_with_content_based_conditional_update f_consts_; std::string f_consts_name_; std::stringstream f_const_values_; @@ -329,7 +329,7 @@ bool t_go_generator::omit_initialization(t_field* tfield) { throw ""; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { //[]byte are always inline return false; } @@ -357,7 +357,7 @@ bool t_go_generator::omit_initialization(t_field* tfield) { static bool type_need_reference(t_type* type) { type = type->get_true_type(); if (type->is_map() || type->is_set() || type->is_list() || type->is_struct() - || type->is_xception() || (type->is_string() && ((t_base_type*)type)->is_binary())) { + || type->is_xception() || type->is_binary()) { return false; } return true; @@ -377,7 +377,6 @@ bool t_go_generator::is_pointer_field(t_field* tfield, bool in_container_value) if (!(tfield->get_req() == t_field::T_OPTIONAL)) { return false; } - bool has_default = tfield->get_value(); if (type->is_base_type()) { t_base_type::t_base tbase = ((t_base_type*)type)->get_base(); @@ -387,7 +386,7 @@ bool t_go_generator::is_pointer_field(t_field* tfield, bool in_container_value) throw ""; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { //[]byte are always inline return false; } @@ -433,7 +432,11 @@ std::string t_go_generator::camelcase(const std::string& value) const { if (islower(value2[i + 1])) { value2.replace(i, 2, 1, toupper(value2[i + 1])); } - fix_common_initialism(value2, i); + + if (i > static_cast(std::numeric_limits().max())) { + throw "integer overflow in t_go_generator::camelcase, value = " + value; + } + fix_common_initialism(value2, static_cast(i)); } } @@ -745,14 +748,6 @@ void t_go_generator::init_generator() { f_consts_name_ = package_dir_ + "/" + program_name_ + "-consts.go"; f_consts_.open(f_consts_name_.c_str()); - vector services = program_->get_services(); - vector::iterator sv_iter; - - for (sv_iter = services.begin(); sv_iter != services.end(); ++sv_iter) { - string service_dir = package_dir_ + "/" + underscore((*sv_iter)->get_name()) + "-remote"; - MKDIR(service_dir.c_str()); - } - // Print header f_types_ << go_autogen_comment() << go_package() << render_includes(false); @@ -762,7 +757,7 @@ void t_go_generator::init_generator() { // Create file for the GoUnusedProtection__ variable string f_unused_prot_name_ = package_dir_ + "/" + "GoUnusedProtection__.go"; - ofstream f_unused_prot_; + ofstream_with_content_based_conditional_update f_unused_prot_; f_unused_prot_.open(f_unused_prot_name_.c_str()); f_unused_prot_ << go_autogen_comment() << go_package() << render_import_protection(); f_unused_prot_.close(); @@ -868,15 +863,18 @@ string t_go_generator::go_package() { */ string t_go_generator::go_imports_begin(bool consts) { string extra; + // If not writing constants, and there are enums, need extra imports. if (!consts && get_program()->get_enums().size() > 0) { - extra = + extra += "\t\"database/sql/driver\"\n" "\t\"errors\"\n"; } return string( "import (\n" "\t\"bytes\"\n" + "\t\"context\"\n" + "\t\"reflect\"\n" + extra + "\t\"fmt\"\n" "\t\"" + gen_thrift_import_ + "\"\n"); @@ -885,7 +883,7 @@ string t_go_generator::go_imports_begin(bool consts) { /** * End the import statement, include undscore-assignments * - * These "_ =" prevent the go compiler complaining about used imports. + * These "_ =" prevent the go compiler complaining about unused imports. * This will have to do in lieu of more intelligent import statement construction */ string t_go_generator::go_imports_end() { @@ -894,6 +892,8 @@ string t_go_generator::go_imports_end() { "// (needed to ensure safety because of naive import list construction.)\n" "var _ = thrift.ZERO\n" "var _ = fmt.Printf\n" + "var _ = context.Background\n" + "var _ = reflect.DeepEqual\n" "var _ = bytes.Equal\n\n"); } @@ -1033,7 +1033,6 @@ void t_go_generator::generate_const(t_const* tconst) { t_type* type = tconst->get_type(); string name = publicize(tconst->get_name()); t_const_value* value = tconst->get_value(); - if (type->is_base_type() || type->is_enum()) { indent(f_consts_) << "const " << name << " = " << render_const_value(type, value, name) << endl; } else { @@ -1049,45 +1048,96 @@ void t_go_generator::generate_const(t_const* tconst) { * is NOT performed in this function as it is always run beforehand using the * validate_types method in main.cc */ -string t_go_generator::render_const_value(t_type* type, t_const_value* value, const string& name) { +string t_go_generator::render_const_value(t_type* type, t_const_value* value, const string& name, bool opt) { type = get_true_type(type); std::ostringstream out; if (type->is_base_type()) { t_base_type::t_base tbase = ((t_base_type*)type)->get_base(); - switch (tbase) { - case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { - out << "[]byte(\"" << get_escaped_string(value) << "\")"; - } else { - out << '"' << get_escaped_string(value) << '"'; + if (opt) { + out << "&(&struct{x "; + switch (tbase) { + case t_base_type::TYPE_BOOL: + out << "bool}{"; + out << (value->get_integer() > 0 ? "true" : "false"); + break; + + case t_base_type::TYPE_I8: + out << "int8}{"; + out << value->get_integer(); + break; + case t_base_type::TYPE_I16: + out << "int16}{"; + out << value->get_integer(); + break; + case t_base_type::TYPE_I32: + out << "int32}{"; + out << value->get_integer(); + break; + case t_base_type::TYPE_I64: + out << "int64}{"; + out << value->get_integer(); + break; + + case t_base_type::TYPE_DOUBLE: + out << "float64}{"; + if (value->get_type() == t_const_value::CV_INTEGER) { + out << value->get_integer(); + } else { + out << value->get_double(); + } + break; + + case t_base_type::TYPE_STRING: + out << "string}{"; + out << '"' + get_escaped_string(value) + '"'; + break; + + default: + throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase); } + out << "}).x"; + } else { + switch (tbase) { + case t_base_type::TYPE_STRING: + if (type->is_binary()) { + out << "[]byte(\"" << get_escaped_string(value) << "\")"; + } else { + out << '"' << get_escaped_string(value) << '"'; + } - break; + break; - case t_base_type::TYPE_BOOL: - out << (value->get_integer() > 0 ? "true" : "false"); - break; + case t_base_type::TYPE_BOOL: + out << (value->get_integer() > 0 ? "true" : "false"); + break; - case t_base_type::TYPE_I8: - case t_base_type::TYPE_I16: - case t_base_type::TYPE_I32: - case t_base_type::TYPE_I64: - out << value->get_integer(); - break; + case t_base_type::TYPE_I8: + case t_base_type::TYPE_I16: + case t_base_type::TYPE_I32: + case t_base_type::TYPE_I64: + if (opt) { + out << "&(&struct{x int}{"; + } + out << value->get_integer(); + if (opt) { + out << "}).x"; + } + break; - case t_base_type::TYPE_DOUBLE: - if (value->get_type() == t_const_value::CV_INTEGER) { - out << value->get_integer(); - } else { - out << value->get_double(); + case t_base_type::TYPE_DOUBLE: + if (value->get_type() == t_const_value::CV_INTEGER) { + out << value->get_integer(); + } else { + out << value->get_double(); + } + + break; + + default: + throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase); } - - break; - - default: - throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase); } } else if (type->is_enum()) { indent(out) << value->get_integer(); @@ -1096,24 +1146,24 @@ string t_go_generator::render_const_value(t_type* type, t_const_value* value, co indent_up(); const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { t_type* field_type = NULL; - + bool is_optional = false; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { if ((*f_iter)->get_name() == v_iter->first->get_string()) { field_type = (*f_iter)->get_type(); + is_optional = is_pointer_field(*f_iter); } } if (field_type == NULL) { throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string(); } - out << endl << indent() << publicize(v_iter->first->get_string()) << ": " - << render_const_value(field_type, v_iter->second, name) << "," << endl; + << render_const_value(field_type, v_iter->second, name, is_optional) << "," << endl; } indent_down(); @@ -1122,10 +1172,10 @@ string t_go_generator::render_const_value(t_type* type, t_const_value* value, co } else if (type->is_map()) { t_type* ktype = ((t_map*)type)->get_key_type(); t_type* vtype = ((t_map*)type)->get_val_type(); - const map& val = value->get_map(); + const map& val = value->get_map(); out << "map[" << type_to_go_type(ktype) << "]" << type_to_go_type(vtype) << "{" << endl; indent_up(); - map::const_iterator v_iter; + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { out << indent() << render_const_value(ktype, v_iter->first, name) << ": " @@ -1150,12 +1200,12 @@ string t_go_generator::render_const_value(t_type* type, t_const_value* value, co } else if (type->is_set()) { t_type* etype = ((t_set*)type)->get_elem_type(); const vector& val = value->get_list(); - out << "map[" << type_to_go_key_type(etype) << "]struct{}{" << endl; + out << "[]" << type_to_go_key_type(etype) << "{" << endl; indent_up(); vector::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { - out << indent() << render_const_value(etype, *v_iter, name) << ": struct{}{}," << endl; + out << indent() << render_const_value(etype, *v_iter, name) << ", "; } indent_down(); @@ -1200,7 +1250,7 @@ void t_go_generator::get_publicized_name_and_def_value(t_field* tfield, *OUT_def_value = tfield->get_value(); } -void t_go_generator::generate_go_struct_initializer(ofstream& out, +void t_go_generator::generate_go_struct_initializer(ostream& out, t_struct* tstruct, bool is_args_or_result) { out << publicize(type_name(tstruct), is_args_or_result) << "{"; @@ -1226,7 +1276,7 @@ void t_go_generator::generate_go_struct_initializer(ofstream& out, * * @param tstruct The struct definition */ -void t_go_generator::generate_go_struct_definition(ofstream& out, +void t_go_generator::generate_go_struct_definition(ostream& out, t_struct* tstruct, bool is_exception, bool is_result, @@ -1273,7 +1323,7 @@ void t_go_generator::generate_go_struct_definition(ofstream& out, if (tstruct->is_union()) (*m_iter)->set_req(t_field::T_OPTIONAL); if (sorted_keys_pos != (*m_iter)->get_key()) { - int first_unused = std::max(1, sorted_keys_pos++); + int first_unused = (std::max)(1, sorted_keys_pos++); while (sorted_keys_pos != (*m_iter)->get_key()) { ++sorted_keys_pos; } @@ -1337,6 +1387,14 @@ void t_go_generator::generate_go_struct_definition(ofstream& out, } out << endl; } + + // num_setable is used for deciding if Count* methods will be generated for union fields. + // This applies to all nullable fields including slices (used for set, list and binary) and maps, not just pointers. + t_type* type = fieldType->get_true_type(); + if (is_pointer_field(*m_iter)|| type->is_map() || type->is_set() || type->is_list() || type->is_binary()) { + num_setable += 1; + } + if (is_pointer_field(*m_iter)) { string goOptType = type_to_go_type_with_opt(fieldType, true); string maybepointer = goOptType != goType ? "*" : ""; @@ -1347,7 +1405,6 @@ void t_go_generator::generate_go_struct_definition(ofstream& out, out << indent() << " }" << endl; out << indent() << "return " << maybepointer << "p." << publicized_name << endl; out << indent() << "}" << endl; - num_setable += 1; } else { out << endl; out << indent() << "func (p *" << tstruct_name << ") Get" << publicized_name << "() " @@ -1383,7 +1440,7 @@ void t_go_generator::generate_go_struct_definition(ofstream& out, /** * Generates the IsSet helper methods for a struct */ -void t_go_generator::generate_isset_helpers(ofstream& out, +void t_go_generator::generate_isset_helpers(ostream& out, t_struct* tstruct, const string& tstruct_name, bool is_result) { @@ -1399,7 +1456,7 @@ void t_go_generator::generate_isset_helpers(ofstream& out, << endl; indent_up(); t_type* ttype = (*f_iter)->get_type()->get_true_type(); - bool is_byteslice = ttype->is_base_type() && ((t_base_type*)ttype)->is_binary(); + bool is_byteslice = ttype->is_binary(); bool compare_to_nil_only = ttype->is_set() || ttype->is_list() || ttype->is_map() || (is_byteslice && !(*f_iter)->get_value()); if (is_pointer_field(*f_iter) || compare_to_nil_only) { @@ -1422,7 +1479,7 @@ void t_go_generator::generate_isset_helpers(ofstream& out, /** * Generates the CountSetFields helper method for a struct */ -void t_go_generator::generate_countsetfields_helper(ofstream& out, +void t_go_generator::generate_countsetfields_helper(ostream& out, t_struct* tstruct, const string& tstruct_name, bool is_result) { @@ -1439,7 +1496,9 @@ void t_go_generator::generate_countsetfields_helper(ofstream& out, if ((*f_iter)->get_req() == t_field::T_REQUIRED) continue; - if (!is_pointer_field(*f_iter)) + t_type* type = (*f_iter)->get_type()->get_true_type(); + + if (!(is_pointer_field(*f_iter) || type->is_map() || type->is_set() || type->is_list() || type->is_binary())) continue; const string field_name(publicize(escape_string((*f_iter)->get_name()))); @@ -1459,7 +1518,7 @@ void t_go_generator::generate_countsetfields_helper(ofstream& out, /** * Generates the read method for a struct */ -void t_go_generator::generate_go_struct_reader(ofstream& out, +void t_go_generator::generate_go_struct_reader(ostream& out, t_struct* tstruct, const string& tstruct_name, bool is_result) { @@ -1527,17 +1586,25 @@ void t_go_generator::generate_go_struct_reader(ofstream& out, thriftFieldTypeId = "thrift.STRING"; } - out << indent() << "if err := p." << field_method_prefix << field_method_suffix << "(iprot); err != nil {" + out << indent() << "if fieldTypeId == " << thriftFieldTypeId << " {" << endl; + out << indent() << " if err := p." << field_method_prefix << field_method_suffix << "(iprot); err != nil {" << endl; - out << indent() << " return err" << endl; - out << indent() << "}" << endl; + out << indent() << " return err" << endl; + out << indent() << " }" << endl; // Mark required field as read if ((*f_iter)->get_req() == t_field::T_REQUIRED) { const string field_name(publicize(escape_string((*f_iter)->get_name()))); - out << indent() << "isset" << field_name << " = true" << endl; + out << indent() << " isset" << field_name << " = true" << endl; } + out << indent() << "} else {" << endl; + out << indent() << " if err := iprot.Skip(fieldTypeId); err != nil {" << endl; + out << indent() << " return err" << endl; + out << indent() << " }" << endl; + out << indent() << "}" << endl; + + indent_down(); } @@ -1606,7 +1673,7 @@ void t_go_generator::generate_go_struct_reader(ofstream& out, } } -void t_go_generator::generate_go_struct_writer(ofstream& out, +void t_go_generator::generate_go_struct_writer(ostream& out, t_struct* tstruct, const string& tstruct_name, bool is_result, @@ -1854,17 +1921,13 @@ void t_go_generator::generate_service_client(t_service* tservice) { if (!extends_client.empty()) { f_types_ << indent() << "*" << extends_client << endl; } else { - f_types_ << indent() << "Transport thrift.TTransport" << endl; - f_types_ << indent() << "ProtocolFactory thrift.TProtocolFactory" << endl; - f_types_ << indent() << "InputProtocol thrift.TProtocol" << endl; - f_types_ << indent() << "OutputProtocol thrift.TProtocol" << endl; - f_types_ << indent() << "SeqId int32" << endl; - /*f_types_ << indent() << "reqs map[int32]Deferred" << endl*/; + f_types_ << indent() << "c thrift.TClient" << endl; } indent_down(); f_types_ << indent() << "}" << endl << endl; - // Constructor function + + // Legacy constructor function f_types_ << indent() << "func New" << serviceName << "ClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *" << serviceName << "Client {" << endl; @@ -1875,19 +1938,15 @@ void t_go_generator::generate_service_client(t_service* tservice) { f_types_ << "{" << extends_field << ": " << extends_client_new << "Factory(t, f)}"; } else { indent_up(); - f_types_ << "{Transport: t," << endl; - f_types_ << indent() << "ProtocolFactory: f," << endl; - f_types_ << indent() << "InputProtocol: f.GetProtocol(t)," << endl; - f_types_ << indent() << "OutputProtocol: f.GetProtocol(t)," << endl; - f_types_ << indent() << "SeqId: 0," << endl; - /*f_types_ << indent() << "Reqs: make(map[int32]Deferred)" << endl*/; + f_types_ << "{" << endl; + f_types_ << indent() << "c: thrift.NewTStandardClient(f.GetProtocol(t), f.GetProtocol(t))," << endl; indent_down(); f_types_ << indent() << "}" << endl; } indent_down(); f_types_ << indent() << "}" << endl << endl; - // Constructor function + // Legacy constructor function with custom input & output protocols f_types_ << indent() << "func New" << serviceName << "ClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *" @@ -1900,18 +1959,41 @@ void t_go_generator::generate_service_client(t_service* tservice) { << endl; } else { indent_up(); - f_types_ << "{Transport: t," << endl; - f_types_ << indent() << "ProtocolFactory: nil," << endl; - f_types_ << indent() << "InputProtocol: iprot," << endl; - f_types_ << indent() << "OutputProtocol: oprot," << endl; - f_types_ << indent() << "SeqId: 0," << endl; - /*f_types_ << indent() << "Reqs: make(map[int32]interface{})" << endl*/; + f_types_ << "{" << endl; + f_types_ << indent() << "c: thrift.NewTStandardClient(iprot, oprot)," << endl; indent_down(); f_types_ << indent() << "}" << endl; } indent_down(); f_types_ << indent() << "}" << endl << endl; + + // Constructor function + f_types_ << indent() << "func New" << serviceName + << "Client(c thrift.TClient) *" << serviceName << "Client {" << endl; + indent_up(); + f_types_ << indent() << "return &" << serviceName << "Client{" << endl; + + indent_up(); + if (!extends.empty()) { + f_types_ << indent() << extends_field << ": " << extends_client_new << "(c)," << endl; + } else { + f_types_ << indent() << "c: c," << endl; + } + indent_down(); + f_types_ << indent() << "}" << endl; + + indent_down(); + f_types_ << indent() << "}" << endl << endl; + + if (extends.empty()) { + f_types_ << indent() << "func (p *" << serviceName << "Client) Client_() thrift.TClient {" << endl; + indent_up(); + f_types_ << indent() << "return p.c" << endl; + indent_down(); + f_types_ << indent() << "}" << endl; + } + // Generate client method implementations vector functions = tservice->get_functions(); vector::const_iterator f_iter; @@ -1926,177 +2008,75 @@ void t_go_generator::generate_service_client(t_service* tservice) { f_types_ << indent() << "func (p *" << serviceName << "Client) " << function_signature_if(*f_iter, "", true) << " {" << endl; indent_up(); - /* - f_types_ << - indent() << "p.SeqId += 1" << endl; - if (!(*f_iter)->is_oneway()) { - f_types_ << - indent() << "d := defer.Deferred()" << endl << - indent() << "p.Reqs[p.SeqId] = d" << endl; - } - */ - f_types_ << indent() << "if err = p.send" << funname << "("; - bool first = true; + + std::string method = (*f_iter)->get_name(); + std::string argsType = publicize(method + "_args", true); + std::string argsName = tmp("_args"); + f_types_ << indent() << "var " << argsName << " " << argsType << endl; for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) { - if (first) { - first = false; - } else { - f_types_ << ", "; - } - - f_types_ << variable_name_to_go_name((*fld_iter)->get_name()); + f_types_ << indent() << argsName << "." << publicize((*fld_iter)->get_name()) + << " = " << variable_name_to_go_name((*fld_iter)->get_name()) << endl; } - f_types_ << "); err != nil { return }" << endl; - if (!(*f_iter)->is_oneway()) { - f_types_ << indent() << "return p.recv" << funname << "()" << endl; - } else { - f_types_ << indent() << "return" << endl; - } + std::string resultName = tmp("_result"); + std::string resultType = publicize(method + "_result", true); + f_types_ << indent() << "var " << resultName << " " << resultType << endl; + f_types_ << indent() << "if err = p.Client_().Call(ctx, \"" + << method << "\", &" << argsName << ", &" << resultName << "); err != nil {" << endl; - indent_down(); - f_types_ << indent() << "}" << endl << endl; - f_types_ << indent() << "func (p *" << serviceName << "Client) send" - << function_signature(*f_iter) << "(err error) {" << endl; - indent_up(); - std::string argsname = publicize((*f_iter)->get_name() + "_args", true); - // Serialize the request header - f_types_ << indent() << "oprot := p.OutputProtocol" << endl; - f_types_ << indent() << "if oprot == nil {" << endl; - f_types_ << indent() << " oprot = p.ProtocolFactory.GetProtocol(p.Transport)" << endl; - f_types_ << indent() << " p.OutputProtocol = oprot" << endl; - f_types_ << indent() << "}" << endl; - f_types_ << indent() << "p.SeqId++" << endl; - f_types_ << indent() << "if err = oprot.WriteMessageBegin(\"" << (*f_iter)->get_name() - << "\", " << ((*f_iter)->is_oneway() ? "thrift.ONEWAY" : "thrift.CALL") - << ", p.SeqId); err != nil {" << endl; - indent_up(); - f_types_ << indent() << " return" << endl; - indent_down(); - f_types_ << indent() << "}" << endl; - f_types_ << indent() << "args := " << argsname << "{" << endl; - - for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) { - f_types_ << indent() << publicize((*fld_iter)->get_name()) << " : " - << variable_name_to_go_name((*fld_iter)->get_name()) << "," << endl; - } - f_types_ << indent() << "}" << endl; - - // Write to the stream - f_types_ << indent() << "if err = args." << write_method_name_ << "(oprot); err != nil {" << endl; - indent_up(); - f_types_ << indent() << " return" << endl; - indent_down(); - f_types_ << indent() << "}" << endl; - f_types_ << indent() << "if err = oprot.WriteMessageEnd(); err != nil {" << endl; - indent_up(); - f_types_ << indent() << " return" << endl; - indent_down(); - f_types_ << indent() << "}" << endl; - f_types_ << indent() << "return oprot.Flush()" << endl; - indent_down(); - f_types_ << indent() << "}" << endl << endl; - - if (!(*f_iter)->is_oneway()) { - std::string resultname = publicize((*f_iter)->get_name() + "_result", true); - // Open function - f_types_ << endl << indent() << "func (p *" << serviceName << "Client) recv" - << publicize((*f_iter)->get_name()) << "() ("; - - if (!(*f_iter)->get_returntype()->is_void()) { - f_types_ << "value " << type_to_go_type((*f_iter)->get_returntype()) << ", "; - } - - f_types_ << "err error) {" << endl; indent_up(); - // TODO(mcslee): Validate message reply here, seq ids etc. - string error(tmp("error")); - string error2(tmp("error")); - f_types_ << indent() << "iprot := p.InputProtocol" << endl; - f_types_ << indent() << "if iprot == nil {" << endl; - f_types_ << indent() << " iprot = p.ProtocolFactory.GetProtocol(p.Transport)" << endl; - f_types_ << indent() << " p.InputProtocol = iprot" << endl; - f_types_ << indent() << "}" << endl; - f_types_ << indent() << "method, mTypeId, seqId, err := iprot.ReadMessageBegin()" << endl; - f_types_ << indent() << "if err != nil {" << endl; - f_types_ << indent() << " return" << endl; - f_types_ << indent() << "}" << endl; - f_types_ << indent() << "if method != \"" << (*f_iter)->get_name() << "\" {" << endl; - f_types_ << indent() << " err = thrift.NewTApplicationException(" - << "thrift.WRONG_METHOD_NAME, \"" << (*f_iter)->get_name() - << " failed: wrong method name\")" << endl; - f_types_ << indent() << " return" << endl; - f_types_ << indent() << "}" << endl; - f_types_ << indent() << "if p.SeqId != seqId {" << endl; - f_types_ << indent() << " err = thrift.NewTApplicationException(" - << "thrift.BAD_SEQUENCE_ID, \"" << (*f_iter)->get_name() - << " failed: out of sequence response\")" << endl; - f_types_ << indent() << " return" << endl; - f_types_ << indent() << "}" << endl; - f_types_ << indent() << "if mTypeId == thrift.EXCEPTION {" << endl; - f_types_ << indent() << " " << error - << " := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, " - "\"Unknown Exception\")" << endl; - f_types_ << indent() << " var " << error2 << " error" << endl; - f_types_ << indent() << " " << error2 << ", err = " << error << ".Read(iprot)" << endl; - f_types_ << indent() << " if err != nil {" << endl; - f_types_ << indent() << " return" << endl; - f_types_ << indent() << " }" << endl; - f_types_ << indent() << " if err = iprot.ReadMessageEnd(); err != nil {" << endl; - f_types_ << indent() << " return" << endl; - f_types_ << indent() << " }" << endl; - f_types_ << indent() << " err = " << error2 << endl; - f_types_ << indent() << " return" << endl; - f_types_ << indent() << "}" << endl; - f_types_ << indent() << "if mTypeId != thrift.REPLY {" << endl; - f_types_ << indent() << " err = thrift.NewTApplicationException(" - << "thrift.INVALID_MESSAGE_TYPE_EXCEPTION, \"" << (*f_iter)->get_name() - << " failed: invalid message type\")" << endl; - f_types_ << indent() << " return" << endl; - f_types_ << indent() << "}" << endl; - f_types_ << indent() << "result := " << resultname << "{}" << endl; - f_types_ << indent() << "if err = result." << read_method_name_ << "(iprot); err != nil {" << endl; - f_types_ << indent() << " return" << endl; - f_types_ << indent() << "}" << endl; - f_types_ << indent() << "if err = iprot.ReadMessageEnd(); err != nil {" << endl; - f_types_ << indent() << " return" << endl; + f_types_ << indent() << "return" << endl; + indent_down(); f_types_ << indent() << "}" << endl; t_struct* xs = (*f_iter)->get_xceptions(); const std::vector& xceptions = xs->get_members(); vector::const_iterator x_iter; - for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) { - const std::string pubname = publicize((*x_iter)->get_name()); + if (!xceptions.empty()) { + f_types_ << indent() << "switch {" << endl; - f_types_ << indent() << "if result." << pubname << " != nil {" << endl; - f_types_ << indent() << " err = result." << pubname << endl; - f_types_ << indent() << " return " << endl; - f_types_ << indent() << "}"; + for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) { + const std::string pubname = publicize((*x_iter)->get_name()); + const std::string field = resultName + "." + pubname; - if ((x_iter + 1) != xceptions.end()) { - f_types_ << " else "; - } else { - f_types_ << endl; + f_types_ << indent() << "case " << field << "!= nil:" << endl; + indent_up(); + + if (!(*f_iter)->get_returntype()->is_void()) { + f_types_ << indent() << "return r, " << field << endl; + } else { + f_types_ << indent() << "return "<< field << endl; + } + + indent_down(); } + + f_types_ << indent() << "}" << endl << endl; } - // Careful, only return _result if not a void function if (!(*f_iter)->get_returntype()->is_void()) { - f_types_ << indent() << "value = result.GetSuccess()" << endl; + f_types_ << indent() << "return " << resultName << ".GetSuccess(), nil" << endl; + } else { + f_types_ << indent() << "return nil" << endl; } + } else { + // TODO: would be nice to not to duplicate the call generation + f_types_ << indent() << "if err := p.Client_().Call(ctx, \"" + << method << "\", &"<< argsName << ", nil); err != nil {" << endl; - f_types_ << indent() << "return" << endl; - // Close function + indent_up(); + f_types_ << indent() << "return err" << endl; indent_down(); - f_types_ << indent() << "}" << endl << endl; + f_types_ << indent() << "}" << endl; + f_types_ << indent() << "return nil" << endl; } - } - // indent_down(); - f_types_ << endl; + indent_down(); + f_types_ << "}" << endl << endl; + } } /** @@ -2115,10 +2095,18 @@ void t_go_generator::generate_service_remote(t_service* tservice) { parent = parent->get_extends(); } + // This file is not useful if there are no functions; don't generate it + if (functions.size() == 0) { + return; + } + + string f_remote_dir = package_dir_ + "/" + underscore(service_name_) + "-remote"; + MKDIR(f_remote_dir.c_str()); + vector::iterator f_iter; - string f_remote_name = package_dir_ + "/" + underscore(service_name_) + "-remote/" + string f_remote_name = f_remote_dir + "/" + underscore(service_name_) + "-remote.go"; - ofstream f_remote; + ofstream_with_content_based_conditional_update f_remote; f_remote.open(f_remote_name.c_str()); string service_module = get_real_go_module(program_); string::size_type loc; @@ -2132,9 +2120,12 @@ void t_go_generator::generate_service_remote(t_service* tservice) { string unused_protection; + string ctxPackage = "context"; + f_remote << go_autogen_comment(); f_remote << indent() << "package main" << endl << endl; f_remote << indent() << "import (" << endl; + f_remote << indent() << " \"" << ctxPackage << "\"" << endl; f_remote << indent() << " \"flag\"" << endl; f_remote << indent() << " \"fmt\"" << endl; f_remote << indent() << " \"math\"" << endl; @@ -2183,6 +2174,24 @@ void t_go_generator::generate_service_remote(t_service* tservice) { f_remote << indent() << " os.Exit(0)" << endl; f_remote << indent() << "}" << endl; f_remote << indent() << endl; + + f_remote << indent() << "type httpHeaders map[string]string" << endl; + f_remote << indent() << endl; + f_remote << indent() << "func (h httpHeaders) String() string {" << endl; + f_remote << indent() << " var m map[string]string = h" << endl; + f_remote << indent() << " return fmt.Sprintf(\"%s\", m)" << endl; + f_remote << indent() << "}" << endl; + f_remote << indent() << endl; + f_remote << indent() << "func (h httpHeaders) Set(value string) error {" << endl; + f_remote << indent() << " parts := strings.Split(value, \": \")" << endl; + f_remote << indent() << " if len(parts) != 2 {" << endl; + f_remote << indent() << " return fmt.Errorf(\"header should be of format 'Key: Value'\")" << endl; + f_remote << indent() << " }" << endl; + f_remote << indent() << " h[parts[0]] = parts[1]" << endl; + f_remote << indent() << " return nil" << endl; + f_remote << indent() << "}" << endl; + f_remote << indent() << endl; + f_remote << indent() << "func main() {" << endl; indent_up(); f_remote << indent() << "flag.Usage = Usage" << endl; @@ -2192,7 +2201,8 @@ void t_go_generator::generate_service_remote(t_service* tservice) { f_remote << indent() << "var urlString string" << endl; f_remote << indent() << "var framed bool" << endl; f_remote << indent() << "var useHttp bool" << endl; - f_remote << indent() << "var parsedUrl url.URL" << endl; + f_remote << indent() << "headers := make(httpHeaders)" << endl; + f_remote << indent() << "var parsedUrl *url.URL" << endl; f_remote << indent() << "var trans thrift.TTransport" << endl; f_remote << indent() << "_ = strconv.Atoi" << endl; f_remote << indent() << "_ = math.Abs" << endl; @@ -2206,16 +2216,18 @@ void t_go_generator::generate_service_remote(t_service* tservice) { f_remote << indent() << "flag.BoolVar(&framed, \"framed\", false, \"Use framed transport\")" << endl; f_remote << indent() << "flag.BoolVar(&useHttp, \"http\", false, \"Use http\")" << endl; + f_remote << indent() << "flag.Var(headers, \"H\", \"Headers to set on the http(s) request (e.g. -H \\\"Key: Value\\\")\")" << endl; f_remote << indent() << "flag.Parse()" << endl; f_remote << indent() << endl; f_remote << indent() << "if len(urlString) > 0 {" << endl; - f_remote << indent() << " parsedUrl, err := url.Parse(urlString)" << endl; + f_remote << indent() << " var err error" << endl; + f_remote << indent() << " parsedUrl, err = url.Parse(urlString)" << endl; f_remote << indent() << " if err != nil {" << endl; f_remote << indent() << " fmt.Fprintln(os.Stderr, \"Error parsing URL: \", err)" << endl; f_remote << indent() << " flag.Usage()" << endl; f_remote << indent() << " }" << endl; f_remote << indent() << " host = parsedUrl.Host" << endl; - f_remote << indent() << " useHttp = len(parsedUrl.Scheme) <= 0 || parsedUrl.Scheme == \"http\"" + f_remote << indent() << " useHttp = len(parsedUrl.Scheme) <= 0 || parsedUrl.Scheme == \"http\" || parsedUrl.Scheme == \"https\"" << endl; f_remote << indent() << "} else if useHttp {" << endl; f_remote << indent() << " _, err := url.Parse(fmt.Sprint(\"http://\", host, \":\", port))" @@ -2230,6 +2242,12 @@ void t_go_generator::generate_service_remote(t_service* tservice) { f_remote << indent() << "var err error" << endl; f_remote << indent() << "if useHttp {" << endl; f_remote << indent() << " trans, err = thrift.NewTHttpClient(parsedUrl.String())" << endl; + f_remote << indent() << " if len(headers) > 0 {" << endl; + f_remote << indent() << " httptrans := trans.(*thrift.THttpClient)" << endl; + f_remote << indent() << " for key, value := range headers {" << endl; + f_remote << indent() << " httptrans.SetHeader(key, value)" << endl; + f_remote << indent() << " }" << endl; + f_remote << indent() << " }" << endl; f_remote << indent() << "} else {" << endl; f_remote << indent() << " portStr := fmt.Sprint(port)" << endl; f_remote << indent() << " if strings.Contains(host, \":\") {" << endl; @@ -2275,8 +2293,10 @@ void t_go_generator::generate_service_remote(t_service* tservice) { f_remote << indent() << " Usage()" << endl; f_remote << indent() << " os.Exit(1)" << endl; f_remote << indent() << "}" << endl; + f_remote << indent() << "iprot := protocolFactory.GetProtocol(trans)" << endl; + f_remote << indent() << "oprot := protocolFactory.GetProtocol(trans)" << endl; f_remote << indent() << "client := " << package_name_ << ".New" << publicize(service_name_) - << "ClientFactory(trans, protocolFactory)" << endl; + << "Client(thrift.NewTStandardClient(iprot, oprot))" << endl; f_remote << indent() << "if err := trans.Open(); err != nil {" << endl; f_remote << indent() << " fmt.Fprintln(os.Stderr, \"Error opening socket to \", " "host, \":\", port, \" \", err)" << endl; @@ -2302,7 +2322,7 @@ void t_go_generator::generate_service_remote(t_service* tservice) { f_remote << indent() << "}" << endl; for (std::vector::size_type i = 0; i < num_args; ++i) { - int flagArg = i + 1; + std::vector::size_type flagArg = i + 1; t_type* the_type(args[i]->get_type()); t_type* the_type2(get_true_type(the_type)); @@ -2324,7 +2344,7 @@ void t_go_generator::generate_service_remote(t_service* tservice) { break; case t_base_type::TYPE_STRING: - if (((t_base_type*)the_type2)->is_binary()) { + if (the_type2->is_binary()) { f_remote << indent() << "argvalue" << i << " := []byte(flag.Arg(" << flagArg << "))" << endl; } else { @@ -2414,7 +2434,7 @@ void t_go_generator::generate_service_remote(t_service* tservice) { f_remote << indent() << " Usage()" << endl; f_remote << indent() << " return" << endl; f_remote << indent() << "}" << endl; - f_remote << indent() << factory << " := thrift.NewTSimpleJSONProtocolFactory()" << endl; + f_remote << indent() << factory << " := thrift.NewTJSONProtocolFactory()" << endl; f_remote << indent() << jsProt << " := " << factory << ".GetProtocol(" << mbTrans << ")" << endl; f_remote << indent() << "argvalue" << i << " := " << tstruct_module << ".New" << tstruct_name @@ -2442,7 +2462,7 @@ void t_go_generator::generate_service_remote(t_service* tservice) { f_remote << indent() << " Usage()" << endl; f_remote << indent() << " return" << endl; f_remote << indent() << "}" << endl; - f_remote << indent() << factory << " := thrift.NewTSimpleJSONProtocolFactory()" << endl; + f_remote << indent() << factory << " := thrift.NewTJSONProtocolFactory()" << endl; f_remote << indent() << jsProt << " := " << factory << ".GetProtocol(" << mbTrans << ")" << endl; f_remote << indent() << "containerStruct" << i << " := " << package_name_ << ".New" @@ -2474,9 +2494,11 @@ void t_go_generator::generate_service_remote(t_service* tservice) { f_remote << indent() << "fmt.Print(client." << pubName << "("; bool argFirst = true; + f_remote << "context.Background()"; for (std::vector::size_type i = 0; i < num_args; ++i) { if (argFirst) { argFirst = false; + f_remote << ", "; } else { f_remote << ", "; } @@ -2610,12 +2632,12 @@ void t_go_generator::generate_service_server(t_service* tservice) { f_types_ << indent() << "return " << self << endl; f_types_ << indent() << "}" << endl << endl; f_types_ << indent() << "func (p *" << serviceName - << "Processor) Process(iprot, oprot thrift.TProtocol) (success bool, err " + << "Processor) Process(ctx context.Context, iprot, oprot thrift.TProtocol) (success bool, err " "thrift.TException) {" << endl; f_types_ << indent() << " name, _, seqId, err := iprot.ReadMessageBegin()" << endl; f_types_ << indent() << " if err != nil { return false, err }" << endl; f_types_ << indent() << " if processor, ok := p.GetProcessorFunction(name); ok {" << endl; - f_types_ << indent() << " return processor.Process(seqId, iprot, oprot)" << endl; + f_types_ << indent() << " return processor.Process(ctx, seqId, iprot, oprot)" << endl; f_types_ << indent() << " }" << endl; f_types_ << indent() << " iprot.Skip(thrift.STRUCT)" << endl; f_types_ << indent() << " iprot.ReadMessageEnd()" << endl; @@ -2625,7 +2647,7 @@ void t_go_generator::generate_service_server(t_service* tservice) { f_types_ << indent() << " oprot.WriteMessageBegin(name, thrift.EXCEPTION, seqId)" << endl; f_types_ << indent() << " " << x << ".Write(oprot)" << endl; f_types_ << indent() << " oprot.WriteMessageEnd()" << endl; - f_types_ << indent() << " oprot.Flush()" << endl; + f_types_ << indent() << " oprot.Flush(ctx)" << endl; f_types_ << indent() << " return false, " << x << endl; f_types_ << indent() << "" << endl; f_types_ << indent() << "}" << endl << endl; @@ -2668,6 +2690,7 @@ void t_go_generator::generate_process_function(t_service* tservice, t_function* + publicize(tfunction->get_name()); string argsname = publicize(tfunction->get_name() + "_args", true); string resultname = publicize(tfunction->get_name() + "_result", true); + // t_struct* xs = tfunction->get_xceptions(); // const std::vector& xceptions = xs->get_members(); vector::const_iterator x_iter; @@ -2675,7 +2698,7 @@ void t_go_generator::generate_process_function(t_service* tservice, t_function* f_types_ << indent() << " handler " << publicize(tservice->get_name()) << endl; f_types_ << indent() << "}" << endl << endl; f_types_ << indent() << "func (p *" << processorName - << ") Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err " + << ") Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err " "thrift.TException) {" << endl; indent_up(); f_types_ << indent() << "args := " << argsname << "{}" << endl; @@ -2689,7 +2712,7 @@ void t_go_generator::generate_process_function(t_service* tservice, t_function* << "\", thrift.EXCEPTION, seqId)" << endl; f_types_ << indent() << " x.Write(oprot)" << endl; f_types_ << indent() << " oprot.WriteMessageEnd()" << endl; - f_types_ << indent() << " oprot.Flush()" << endl; + f_types_ << indent() << " oprot.Flush(ctx)" << endl; } f_types_ << indent() << " return false, err" << endl; f_types_ << indent() << "}" << endl << endl; @@ -2719,9 +2742,11 @@ void t_go_generator::generate_process_function(t_service* tservice, t_function* f_types_ << "err2 = p.handler." << publicize(tfunction->get_name()) << "("; bool first = true; + f_types_ << "ctx"; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { if (first) { first = false; + f_types_ << ", "; } else { f_types_ << ", "; } @@ -2755,7 +2780,7 @@ void t_go_generator::generate_process_function(t_service* tservice, t_function* << "\", thrift.EXCEPTION, seqId)" << endl; f_types_ << indent() << " x.Write(oprot)" << endl; f_types_ << indent() << " oprot.WriteMessageEnd()" << endl; - f_types_ << indent() << " oprot.Flush()" << endl; + f_types_ << indent() << " oprot.Flush(ctx)" << endl; } f_types_ << indent() << " return true, err2" << endl; @@ -2792,7 +2817,7 @@ void t_go_generator::generate_process_function(t_service* tservice, t_function* << endl; f_types_ << indent() << " err = err2" << endl; f_types_ << indent() << "}" << endl; - f_types_ << indent() << "if err2 = oprot.Flush(); err == nil && err2 != nil {" << endl; + f_types_ << indent() << "if err2 = oprot.Flush(ctx); err == nil && err2 != nil {" << endl; f_types_ << indent() << " err = err2" << endl; f_types_ << indent() << "}" << endl; f_types_ << indent() << "if err != nil {" << endl; @@ -2810,15 +2835,14 @@ void t_go_generator::generate_process_function(t_service* tservice, t_function* /** * Deserializes a field of any type. */ -void t_go_generator::generate_deserialize_field(ofstream& out, +void t_go_generator::generate_deserialize_field(ostream& out, t_field* tfield, bool declare, string prefix, bool inclass, bool coerceData, bool inkey, - bool in_container_value, - bool use_true_type) { + bool in_container_value) { (void)inclass; (void)coerceData; t_type* orig_type = tfield->get_type(); @@ -2840,10 +2864,8 @@ void t_go_generator::generate_deserialize_field(ofstream& out, } else if (type->is_base_type() || type->is_enum()) { if (declare) { - t_type* actual_type = use_true_type ? tfield->get_type()->get_true_type() - : tfield->get_type(); - - string type_name = inkey ? type_to_go_key_type(actual_type) : type_to_go_type(actual_type); + string type_name = inkey ? type_to_go_key_type(tfield->get_type()) + : type_to_go_type(tfield->get_type()); out << "var " << tfield->get_name() << " " << type_name << endl; } @@ -2859,7 +2881,7 @@ void t_go_generator::generate_deserialize_field(ofstream& out, break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary() && !inkey) { + if (type->is_binary() && !inkey) { out << "ReadBinary()"; } else { out << "ReadString()"; @@ -2905,7 +2927,7 @@ void t_go_generator::generate_deserialize_field(ofstream& out, out << "} else {" << endl; string wrap; - if (type->is_enum() || (orig_type->is_typedef() && !use_true_type)) { + if (type->is_enum() || orig_type->is_typedef()) { wrap = publicize(type_name(orig_type)); } else if (((t_base_type*)type)->get_base() == t_base_type::TYPE_I8) { wrap = "int8"; @@ -2929,7 +2951,7 @@ void t_go_generator::generate_deserialize_field(ofstream& out, /** * Generates an unserializer for a struct, calling read() */ -void t_go_generator::generate_deserialize_struct(ofstream& out, +void t_go_generator::generate_deserialize_struct(ostream& out, t_struct* tstruct, bool pointer_field, bool declare, @@ -2948,7 +2970,7 @@ void t_go_generator::generate_deserialize_struct(ofstream& out, * Serialize a container by writing out the header followed by * data and then a footer. */ -void t_go_generator::generate_deserialize_container(ofstream& out, +void t_go_generator::generate_deserialize_container(ostream& out, t_type* orig_type, bool pointer_field, bool declare, @@ -2969,13 +2991,11 @@ void t_go_generator::generate_deserialize_container(ofstream& out, out << indent() << "tMap := make(" << type_to_go_type(orig_type) << ", size)" << endl; out << indent() << prefix << eq << " " << (pointer_field ? "&" : "") << "tMap" << endl; } else if (ttype->is_set()) { - t_set* t = (t_set*)ttype; out << indent() << "_, size, err := iprot.ReadSetBegin()" << endl; out << indent() << "if err != nil {" << endl; out << indent() << " return thrift.PrependError(\"error reading set begin: \", err)" << endl; out << indent() << "}" << endl; - out << indent() << "tSet := make(map[" - << type_to_go_key_type(t->get_elem_type()->get_true_type()) << "]struct{}, size)" << endl; + out << indent() << "tSet := make(" << type_to_go_type(orig_type) << ", 0, size)" << endl; out << indent() << prefix << eq << " " << (pointer_field ? "&" : "") << "tSet" << endl; } else if (ttype->is_list()) { out << indent() << "_, size, err := iprot.ReadListBegin()" << endl; @@ -3026,7 +3046,7 @@ void t_go_generator::generate_deserialize_container(ofstream& out, /** * Generates code to deserialize a map */ -void t_go_generator::generate_deserialize_map_element(ofstream& out, +void t_go_generator::generate_deserialize_map_element(ostream& out, t_map* tmap, bool declare, string prefix) { @@ -3045,7 +3065,7 @@ void t_go_generator::generate_deserialize_map_element(ofstream& out, /** * Write a set element */ -void t_go_generator::generate_deserialize_set_element(ofstream& out, +void t_go_generator::generate_deserialize_set_element(ostream& out, t_set* tset, bool declare, string prefix) { @@ -3053,14 +3073,14 @@ void t_go_generator::generate_deserialize_set_element(ofstream& out, string elem = tmp("_elem"); t_field felem(tset->get_elem_type(), elem); felem.set_req(t_field::T_OPT_IN_REQ_OUT); - generate_deserialize_field(out, &felem, true, "", false, false, false, true, true); - indent(out) << prefix << "[" << elem << "] = struct{}{}" << endl; + generate_deserialize_field(out, &felem, true, "", false, false, false, true); + indent(out) << prefix << " = append(" << prefix << ", " << elem << ")" << endl; } /** * Write a list element */ -void t_go_generator::generate_deserialize_list_element(ofstream& out, +void t_go_generator::generate_deserialize_list_element(ostream& out, t_list* tlist, bool declare, string prefix) { @@ -3068,7 +3088,7 @@ void t_go_generator::generate_deserialize_list_element(ofstream& out, string elem = tmp("_elem"); t_field felem(((t_list*)tlist)->get_elem_type(), elem); felem.set_req(t_field::T_OPT_IN_REQ_OUT); - generate_deserialize_field(out, &felem, true, "", false, false, false, true, true); + generate_deserialize_field(out, &felem, true, "", false, false, false, true); indent(out) << prefix << " = append(" << prefix << ", " << elem << ")" << endl; } @@ -3078,7 +3098,7 @@ void t_go_generator::generate_deserialize_list_element(ofstream& out, * @param tfield The field to serialize * @param prefix Name to prepend to field name */ -void t_go_generator::generate_serialize_field(ofstream& out, +void t_go_generator::generate_serialize_field(ostream& out, t_field* tfield, string prefix, bool inkey) { @@ -3110,7 +3130,7 @@ void t_go_generator::generate_serialize_field(ofstream& out, break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary() && !inkey) { + if (type->is_binary() && !inkey) { out << "WriteBinary(" << name << ")"; } else { out << "WriteString(string(" << name << "))"; @@ -3165,7 +3185,7 @@ void t_go_generator::generate_serialize_field(ofstream& out, * @param tstruct The struct to serialize * @param prefix String prefix to attach to all fields */ -void t_go_generator::generate_serialize_struct(ofstream& out, t_struct* tstruct, string prefix) { +void t_go_generator::generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix) { (void)tstruct; out << indent() << "if err := " << prefix << "." << write_method_name_ << "(oprot); err != nil {" << endl; out << indent() << " return thrift.PrependError(fmt.Sprintf(\"%T error writing struct: \", " @@ -3173,7 +3193,7 @@ void t_go_generator::generate_serialize_struct(ofstream& out, t_struct* tstruct, out << indent() << "}" << endl; } -void t_go_generator::generate_serialize_container(ofstream& out, +void t_go_generator::generate_serialize_container(ostream& out, t_type* ttype, bool pointer_field, string prefix) { @@ -3213,7 +3233,14 @@ void t_go_generator::generate_serialize_container(ofstream& out, indent(out) << "}" << endl; } else if (ttype->is_set()) { t_set* tset = (t_set*)ttype; - out << indent() << "for v, _ := range " << prefix << " {" << endl; + out << indent() << "for i := 0; iget_elem_type(), ""); efield.set_req(t_field::T_OPT_IN_REQ_OUT); generate_serialize_field(out, &efield, prefix); @@ -3271,7 +3298,7 @@ void t_go_generator::generate_serialize_set_element(ofstream& out, t_set* tset, /** * Serializes the members of a list. */ -void t_go_generator::generate_serialize_list_element(ofstream& out, t_list* tlist, string prefix) { +void t_go_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string prefix) { t_field efield(tlist->get_elem_type(), ""); efield.set_req(t_field::T_OPT_IN_REQ_OUT); generate_serialize_field(out, &efield, prefix); @@ -3280,21 +3307,21 @@ void t_go_generator::generate_serialize_list_element(ofstream& out, t_list* tlis /** * Generates the docstring for a given struct. */ -void t_go_generator::generate_go_docstring(ofstream& out, t_struct* tstruct) { +void t_go_generator::generate_go_docstring(ostream& out, t_struct* tstruct) { generate_go_docstring(out, tstruct, tstruct, "Attributes"); } /** * Generates the docstring for a given function. */ -void t_go_generator::generate_go_docstring(ofstream& out, t_function* tfunction) { +void t_go_generator::generate_go_docstring(ostream& out, t_function* tfunction) { generate_go_docstring(out, tfunction, tfunction->get_arglist(), "Parameters"); } /** * Generates the docstring for a struct or function. */ -void t_go_generator::generate_go_docstring(ofstream& out, +void t_go_generator::generate_go_docstring(ostream& out, t_doc* tdoc, t_struct* tstruct, const char* subheader) { @@ -3337,7 +3364,7 @@ void t_go_generator::generate_go_docstring(ofstream& out, /** * Generates the docstring for a generic object. */ -void t_go_generator::generate_go_docstring(ofstream& out, t_doc* tdoc) { +void t_go_generator::generate_go_docstring(ostream& out, t_doc* tdoc) { if (tdoc->has_doc()) { generate_docstring_comment(out, "", "//", tdoc->get_doc(), ""); } @@ -3404,9 +3431,13 @@ string t_go_generator::function_signature(t_function* tfunction, string prefix) * @return String of rendered function definition */ string t_go_generator::function_signature_if(t_function* tfunction, string prefix, bool addError) { - // TODO(mcslee): Nitpicky, no ',' if argument_list is empty string signature = publicize(prefix + tfunction->get_name()) + "("; - signature += argument_list(tfunction->get_arglist()) + ") ("; + signature += "ctx context.Context"; + if (!tfunction->get_arglist()->get_members().empty()) { + signature += ", " + argument_list(tfunction->get_arglist()); + } + signature += ") ("; + t_type* ret = tfunction->get_returntype(); t_struct* exceptions = tfunction->get_xceptions(); string errs = argument_list(exceptions); @@ -3494,7 +3525,7 @@ string t_go_generator::type_to_enum(t_type* type) { case t_base_type::TYPE_STRING: /* this is wrong, binary is still a string type internally - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { return "thrift.BINARY"; } */ @@ -3548,7 +3579,7 @@ string t_go_generator::type_to_go_key_type(t_type* type) { throw "Cannot produce a valid type for a Go map key: " + type_to_go_type(type) + " - aborting."; } - if (resolved_type->is_string() && ((t_base_type*)resolved_type)->is_binary()) + if (resolved_type->is_binary()) return "string"; return type_to_go_type(type); @@ -3581,7 +3612,7 @@ string t_go_generator::type_to_go_type_with_opt(t_type* type, throw ""; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { return maybe_pointer + "[]byte"; } @@ -3616,8 +3647,8 @@ string t_go_generator::type_to_go_type_with_opt(t_type* type, return maybe_pointer + string("map[") + keyType + "]" + valueType; } else if (type->is_set()) { t_set* t = (t_set*)type; - string elemType = type_to_go_key_type(t->get_elem_type()); - return maybe_pointer + string("map[") + elemType + string("]struct{}"); + string elemType = type_to_go_type(t->get_elem_type()); + return maybe_pointer + string("[]") + elemType; } else if (type->is_list()) { t_list* t = (t_list*)type; string elemType = type_to_go_type(t->get_elem_type()); @@ -3662,7 +3693,7 @@ bool format_go_output(const string& file_path) { // before submitting a patch that enables this feature again. Thank you. (void) file_path; return false; - + /* const string command = "gofmt -w " + file_path; diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_gv_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_gv_generator.cc index 72b7c82..7f8301a 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_gv_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_gv_generator.cc @@ -87,7 +87,7 @@ protected: void print_const_value(t_type* type, t_const_value* tvalue); private: - std::ofstream f_out_; + ofstream_with_content_based_conditional_update f_out_; std::list edges; bool exception_arrows; }; @@ -225,7 +225,7 @@ void t_gv_generator::print_type(t_type* ttype, string struct_field_ref) { f_out_ << "\\>"; } } else if (ttype->is_base_type()) { - f_out_ << (((t_base_type*)ttype)->is_binary() ? "binary" : ttype->get_name()); + f_out_ << (ttype->is_binary() ? "binary" : ttype->get_name()); } else { f_out_ << ttype->get_name(); edges.push_back(struct_field_ref + " -> " + ttype->get_name()); @@ -249,8 +249,8 @@ void t_gv_generator::print_const_value(t_type* type, t_const_value* tvalue) { break; case t_const_value::CV_MAP: { f_out_ << "\\{ "; - map map_elems = tvalue->get_map(); - map::iterator map_iter; + map map_elems = tvalue->get_map(); + map::iterator map_iter; for (map_iter = map_elems.begin(); map_iter != map_elems.end(); map_iter++) { if (!first) { f_out_ << ", "; diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_haxe_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_haxe_generator.cc index e7be1a5..3b88c4d 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_haxe_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_haxe_generator.cc @@ -31,7 +31,7 @@ #include "thrift/generate/t_oop_generator.h" using std::map; -using std::ofstream; +using std::ostream; using std::ostringstream; using std::string; using std::stringstream; @@ -89,13 +89,13 @@ public: void generate_xception(t_struct* txception); void generate_service(t_service* tservice); - void print_const_value(std::ofstream& out, + void print_const_value(std::ostream& out, std::string name, t_type* type, t_const_value* value, bool in_static, bool defval = false); - std::string render_const_value(ofstream& out, + std::string render_const_value(ostream& out, std::string name, t_type* type, t_const_value* value); @@ -106,18 +106,18 @@ public: void generate_haxe_struct(t_struct* tstruct, bool is_exception, bool is_result = false); - void generate_haxe_struct_definition(std::ofstream& out, + void generate_haxe_struct_definition(std::ostream& out, t_struct* tstruct, bool is_xception = false, bool is_result = false); // removed -- equality,compare_to - void generate_haxe_struct_reader(std::ofstream& out, t_struct* tstruct); - void generate_haxe_validator(std::ofstream& out, t_struct* tstruct); - void generate_haxe_struct_result_writer(std::ofstream& out, t_struct* tstruct); - void generate_haxe_struct_writer(std::ofstream& out, t_struct* tstruct); - void generate_haxe_struct_tostring(std::ofstream& out, t_struct* tstruct); - void generate_haxe_meta_data_map(std::ofstream& out, t_struct* tstruct); - void generate_field_value_meta_data(std::ofstream& out, t_type* type); + void generate_haxe_struct_reader(std::ostream& out, t_struct* tstruct); + void generate_haxe_validator(std::ostream& out, t_struct* tstruct); + void generate_haxe_struct_result_writer(std::ostream& out, t_struct* tstruct); + void generate_haxe_struct_writer(std::ostream& out, t_struct* tstruct); + void generate_haxe_struct_tostring(std::ostream& out, t_struct* tstruct); + void generate_haxe_meta_data_map(std::ostream& out, t_struct* tstruct); + void generate_field_value_meta_data(std::ostream& out, t_type* type); std::string get_haxe_type_string(t_type* type); void generate_reflection_setters(std::ostringstream& out, t_type* type, @@ -127,15 +127,15 @@ public: t_type* type, std::string field_name, std::string cap_name); - void generate_generic_field_getters_setters(std::ofstream& out, t_struct* tstruct); - void generate_generic_isset_method(std::ofstream& out, t_struct* tstruct); - void generate_property_getters_setters(std::ofstream& out, t_struct* tstruct); + void generate_generic_field_getters_setters(std::ostream& out, t_struct* tstruct); + void generate_generic_isset_method(std::ostream& out, t_struct* tstruct); + void generate_property_getters_setters(std::ostream& out, t_struct* tstruct); void generate_function_helpers(t_function* tfunction); std::string get_cap_name(std::string name); std::string generate_isset_check(t_field* field); std::string generate_isset_check(std::string field); - void generate_isset_set(ofstream& out, t_field* field); + void generate_isset_set(ostream& out, t_field* field); // removed std::string isset_field_id(t_field* field); void generate_service_interface(t_service* tservice); @@ -149,30 +149,30 @@ public: * Serialization constructs */ - void generate_deserialize_field(std::ofstream& out, t_field* tfield, std::string prefix = ""); - void generate_deserialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); - void generate_deserialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); - void generate_deserialize_set_element(std::ofstream& out, t_set* tset, std::string prefix = ""); - void generate_deserialize_map_element(std::ofstream& out, t_map* tmap, std::string prefix = ""); - void generate_deserialize_list_element(std::ofstream& out, + void generate_deserialize_field(std::ostream& out, t_field* tfield, std::string prefix = ""); + void generate_deserialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); + void generate_deserialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); + void generate_deserialize_set_element(std::ostream& out, t_set* tset, std::string prefix = ""); + void generate_deserialize_map_element(std::ostream& out, t_map* tmap, std::string prefix = ""); + void generate_deserialize_list_element(std::ostream& out, t_list* tlist, std::string prefix = ""); - void generate_serialize_field(std::ofstream& out, t_field* tfield, std::string prefix = ""); - void generate_serialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); - void generate_serialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); - void generate_serialize_set_element(std::ofstream& out, t_set* tmap, std::string iter); - void generate_serialize_list_element(std::ofstream& out, t_list* tlist, std::string iter); - void generate_serialize_map_element(std::ofstream& out, + void generate_serialize_field(std::ostream& out, t_field* tfield, std::string prefix = ""); + void generate_serialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); + void generate_serialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); + void generate_serialize_set_element(std::ostream& out, t_set* tmap, std::string iter); + void generate_serialize_list_element(std::ostream& out, t_list* tlist, std::string iter); + void generate_serialize_map_element(std::ostream& out, t_map* tmap, std::string iter, std::string map); - void generate_haxe_doc(std::ofstream& out, t_doc* tdoc); - void generate_haxe_doc(std::ofstream& out, t_function* tdoc); + void generate_haxe_doc(std::ostream& out, t_doc* tdoc); + void generate_haxe_doc(std::ostream& out, t_function* tdoc); - void generate_rtti_decoration(std::ofstream& out); - void generate_macro_decoration(std::ofstream& out); + void generate_rtti_decoration(std::ostream& out); + void generate_macro_decoration(std::ostream& out); /** * Helper rendering functions @@ -229,7 +229,7 @@ private: */ std::string package_name_; - std::ofstream f_service_; + ofstream_with_content_based_conditional_update f_service_; std::string package_dir_; }; @@ -386,7 +386,7 @@ void t_haxe_generator::generate_typedef(t_typedef* ttypedef) { void t_haxe_generator::generate_enum(t_enum* tenum) { // Make output file string f_enum_name = package_dir_ + "/" + get_cap_name(tenum->get_name()) + ".hx"; - ofstream f_enum; + ofstream_with_content_based_conditional_update f_enum; f_enum.open(f_enum_name.c_str()); // Comment and package it @@ -448,7 +448,7 @@ void t_haxe_generator::generate_consts(std::vector consts) { } string f_consts_name = package_dir_ + "/" + get_cap_name(program_name_) + "Constants.hx"; - ofstream f_consts; + ofstream_with_content_based_conditional_update f_consts; f_consts.open(f_consts_name.c_str()); // Print header @@ -475,7 +475,7 @@ void t_haxe_generator::generate_consts(std::vector consts) { f_consts.close(); } -void t_haxe_generator::print_const_value(std::ofstream& out, +void t_haxe_generator::print_const_value(std::ostream& out, string name, t_type* type, t_const_value* value, @@ -503,8 +503,8 @@ void t_haxe_generator::print_const_value(std::ofstream& out, } else if (type->is_struct() || type->is_xception()) { const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; out << name << ":" << type_name(type) << " = new " << type_name(type, false, true) << "();" << endl; if (!in_static) { @@ -548,8 +548,8 @@ void t_haxe_generator::print_const_value(std::ofstream& out, } t_type* ktype = ((t_map*)type)->get_key_type(); t_type* vtype = ((t_map*)type)->get_val_type(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { string key = render_const_value(out, name, ktype, v_iter->first); string val = render_const_value(out, name, vtype, v_iter->second); @@ -599,7 +599,7 @@ void t_haxe_generator::print_const_value(std::ofstream& out, } } -string t_haxe_generator::render_const_value(ofstream& out, +string t_haxe_generator::render_const_value(ostream& out, string name, t_type* type, t_const_value* value) { @@ -676,7 +676,7 @@ void t_haxe_generator::generate_xception(t_struct* txception) { void t_haxe_generator::generate_haxe_struct(t_struct* tstruct, bool is_exception, bool is_result) { // Make output file string f_struct_name = package_dir_ + "/" + get_cap_name(tstruct->get_name()) + ".hx"; - ofstream f_struct; + ofstream_with_content_based_conditional_update f_struct; f_struct.open(f_struct_name.c_str()); f_struct << autogen_comment() << haxe_package() << ";" << endl; @@ -703,7 +703,7 @@ void t_haxe_generator::generate_haxe_struct(t_struct* tstruct, bool is_exception * @param in_class If inside a class, needs to be static class * @param is_result If this is a result it needs a different writer */ -void t_haxe_generator::generate_haxe_struct_definition(ofstream& out, +void t_haxe_generator::generate_haxe_struct_definition(ostream& out, t_struct* tstruct, bool is_exception, bool is_result) { @@ -817,7 +817,7 @@ void t_haxe_generator::generate_haxe_struct_definition(ofstream& out, * * @param tstruct The struct definition */ -void t_haxe_generator::generate_haxe_struct_reader(ofstream& out, t_struct* tstruct) { +void t_haxe_generator::generate_haxe_struct_reader(ostream& out, t_struct* tstruct) { out << indent() << "public function read( iprot : TProtocol) : Void {" << endl; indent_up(); @@ -910,7 +910,7 @@ void t_haxe_generator::generate_haxe_struct_reader(ofstream& out, t_struct* tstr // generates haxe method to perform various checks // (e.g. check that all required fields are set) -void t_haxe_generator::generate_haxe_validator(ofstream& out, t_struct* tstruct) { +void t_haxe_generator::generate_haxe_validator(ostream& out, t_struct* tstruct) { indent(out) << "public function validate() : Void {" << endl; indent_up(); @@ -961,7 +961,7 @@ void t_haxe_generator::generate_haxe_validator(ofstream& out, t_struct* tstruct) * * @param tstruct The struct definition */ -void t_haxe_generator::generate_haxe_struct_writer(ofstream& out, t_struct* tstruct) { +void t_haxe_generator::generate_haxe_struct_writer(ostream& out, t_struct* tstruct) { out << indent() << "public function write(oprot:TProtocol) : Void {" << endl; indent_up(); @@ -1031,7 +1031,7 @@ void t_haxe_generator::generate_haxe_struct_writer(ofstream& out, t_struct* tstr * * @param tstruct The struct definition */ -void t_haxe_generator::generate_haxe_struct_result_writer(ofstream& out, t_struct* tstruct) { +void t_haxe_generator::generate_haxe_struct_result_writer(ostream& out, t_struct* tstruct) { out << indent() << "public function write(oprot:TProtocol) : Void {" << endl; indent_up(); @@ -1116,7 +1116,7 @@ void t_haxe_generator::generate_reflection_setters(ostringstream& out, indent_down(); } -void t_haxe_generator::generate_generic_field_getters_setters(std::ofstream& out, +void t_haxe_generator::generate_generic_field_getters_setters(std::ostream& out, t_struct* tstruct) { std::ostringstream getter_stream; @@ -1174,7 +1174,7 @@ void t_haxe_generator::generate_generic_field_getters_setters(std::ofstream& out } // Creates a generic isSet method that takes the field number as argument -void t_haxe_generator::generate_generic_isset_method(std::ofstream& out, t_struct* tstruct) { +void t_haxe_generator::generate_generic_isset_method(std::ostream& out, t_struct* tstruct) { const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; @@ -1210,7 +1210,7 @@ void t_haxe_generator::generate_generic_isset_method(std::ofstream& out, t_struc * * @param tstruct The struct definition */ -void t_haxe_generator::generate_property_getters_setters(ofstream& out, t_struct* tstruct) { +void t_haxe_generator::generate_property_getters_setters(ostream& out, t_struct* tstruct) { const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { @@ -1272,7 +1272,7 @@ void t_haxe_generator::generate_property_getters_setters(ofstream& out, t_struct * * @param tstruct The struct definition */ -void t_haxe_generator::generate_haxe_struct_tostring(ofstream& out, t_struct* tstruct) { +void t_haxe_generator::generate_haxe_struct_tostring(ostream& out, t_struct* tstruct) { out << indent() << "public " << "function toString() : String {" << endl; indent_up(); @@ -1304,7 +1304,7 @@ void t_haxe_generator::generate_haxe_struct_tostring(ofstream& out, t_struct* ts indent_up(); } - if (field->get_type()->is_base_type() && ((t_base_type*)(field->get_type()))->is_binary()) { + if (field->get_type()->is_binary()) { indent(out) << " ret += \"BINARY\";" << endl; } else if (field->get_type()->is_enum()) { indent(out) << "var " << field->get_name() @@ -1346,7 +1346,7 @@ void t_haxe_generator::generate_haxe_struct_tostring(ofstream& out, t_struct* ts * * @param tstruct The struct definition */ -void t_haxe_generator::generate_haxe_meta_data_map(ofstream& out, t_struct* tstruct) { +void t_haxe_generator::generate_haxe_meta_data_map(ostream& out, t_struct* tstruct) { const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; @@ -1434,7 +1434,7 @@ std::string t_haxe_generator::get_haxe_type_string(t_type* type) { } } -void t_haxe_generator::generate_field_value_meta_data(std::ofstream& out, t_type* type) { +void t_haxe_generator::generate_field_value_meta_data(std::ostream& out, t_type* type) { out << endl; indent_up(); indent_up(); @@ -2176,7 +2176,7 @@ void t_haxe_generator::generate_process_function(t_service* tservice, t_function * @param tfield The field * @param prefix The variable name or container for this field */ -void t_haxe_generator::generate_deserialize_field(ofstream& out, t_field* tfield, string prefix) { +void t_haxe_generator::generate_deserialize_field(ostream& out, t_field* tfield, string prefix) { t_type* type = get_true_type(tfield->get_type()); if (type->is_void()) { @@ -2200,7 +2200,7 @@ void t_haxe_generator::generate_deserialize_field(ofstream& out, t_field* tfield throw "compiler error: cannot serialize void field in a struct: " + name; break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { out << "readBinary();"; } else { out << "readString();"; @@ -2241,7 +2241,7 @@ void t_haxe_generator::generate_deserialize_field(ofstream& out, t_field* tfield /** * Generates an unserializer for a struct, invokes read() */ -void t_haxe_generator::generate_deserialize_struct(ofstream& out, +void t_haxe_generator::generate_deserialize_struct(ostream& out, t_struct* tstruct, string prefix) { out << indent() << prefix << " = new " << get_cap_name(type_name(tstruct)) << "();" << endl @@ -2251,7 +2251,7 @@ void t_haxe_generator::generate_deserialize_struct(ofstream& out, /** * Deserializes a container by reading its size and then iterating */ -void t_haxe_generator::generate_deserialize_container(ofstream& out, t_type* ttype, string prefix) { +void t_haxe_generator::generate_deserialize_container(ostream& out, t_type* ttype, string prefix) { scope_up(out); string obj; @@ -2309,7 +2309,7 @@ void t_haxe_generator::generate_deserialize_container(ofstream& out, t_type* tty /** * Generates code to deserialize a map */ -void t_haxe_generator::generate_deserialize_map_element(ofstream& out, t_map* tmap, string prefix) { +void t_haxe_generator::generate_deserialize_map_element(ostream& out, t_map* tmap, string prefix) { string key = tmp("_key"); string val = tmp("_val"); t_field fkey(tmap->get_key_type(), key); @@ -2327,7 +2327,7 @@ void t_haxe_generator::generate_deserialize_map_element(ofstream& out, t_map* tm /** * Deserializes a set element */ -void t_haxe_generator::generate_deserialize_set_element(ofstream& out, t_set* tset, string prefix) { +void t_haxe_generator::generate_deserialize_set_element(ostream& out, t_set* tset, string prefix) { string elem = tmp("_elem"); t_field felem(tset->get_elem_type(), elem); @@ -2341,7 +2341,7 @@ void t_haxe_generator::generate_deserialize_set_element(ofstream& out, t_set* ts /** * Deserializes a list element */ -void t_haxe_generator::generate_deserialize_list_element(ofstream& out, +void t_haxe_generator::generate_deserialize_list_element(ostream& out, t_list* tlist, string prefix) { string elem = tmp("_elem"); @@ -2360,7 +2360,7 @@ void t_haxe_generator::generate_deserialize_list_element(ofstream& out, * @param tfield The field to serialize * @param prefix Name to prepend to field name */ -void t_haxe_generator::generate_serialize_field(ofstream& out, t_field* tfield, string prefix) { +void t_haxe_generator::generate_serialize_field(ostream& out, t_field* tfield, string prefix) { t_type* type = get_true_type(tfield->get_type()); // Do nothing for void types @@ -2384,7 +2384,7 @@ void t_haxe_generator::generate_serialize_field(ofstream& out, t_field* tfield, throw "compiler error: cannot serialize void field in a struct: " + name; break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { out << "writeBinary(" << name << ");"; } else { out << "writeString(" << name << ");"; @@ -2429,7 +2429,7 @@ void t_haxe_generator::generate_serialize_field(ofstream& out, t_field* tfield, * @param tstruct The struct to serialize * @param prefix String prefix to attach to all fields */ -void t_haxe_generator::generate_serialize_struct(ofstream& out, t_struct* tstruct, string prefix) { +void t_haxe_generator::generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix) { (void)tstruct; out << indent() << prefix << ".write(oprot);" << endl; } @@ -2440,7 +2440,7 @@ void t_haxe_generator::generate_serialize_struct(ofstream& out, t_struct* tstruc * @param ttype The type of container * @param prefix String prefix for fields */ -void t_haxe_generator::generate_serialize_container(ofstream& out, t_type* ttype, string prefix) { +void t_haxe_generator::generate_serialize_container(ostream& out, t_type* ttype, string prefix) { scope_up(out); if (ttype->is_map()) { @@ -2498,7 +2498,7 @@ void t_haxe_generator::generate_serialize_container(ofstream& out, t_type* ttype /** * Serializes the members of a map. */ -void t_haxe_generator::generate_serialize_map_element(ofstream& out, +void t_haxe_generator::generate_serialize_map_element(ostream& out, t_map* tmap, string iter, string map) { @@ -2511,7 +2511,7 @@ void t_haxe_generator::generate_serialize_map_element(ofstream& out, /** * Serializes the members of a set. */ -void t_haxe_generator::generate_serialize_set_element(ofstream& out, t_set* tset, string iter) { +void t_haxe_generator::generate_serialize_set_element(ostream& out, t_set* tset, string iter) { t_field efield(tset->get_elem_type(), iter); generate_serialize_field(out, &efield, ""); } @@ -2519,7 +2519,7 @@ void t_haxe_generator::generate_serialize_set_element(ofstream& out, t_set* tset /** * Serializes the members of a list. */ -void t_haxe_generator::generate_serialize_list_element(ofstream& out, t_list* tlist, string iter) { +void t_haxe_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string iter) { t_field efield(tlist->get_elem_type(), iter); generate_serialize_field(out, &efield, ""); } @@ -2553,9 +2553,10 @@ string t_haxe_generator::type_name(t_type* ttype, bool in_container, bool in_ini t_base_type::t_base tbase = ((t_base_type*)tkey)->get_base(); switch (tbase) { case t_base_type::TYPE_STRING: - if (!(((t_base_type*)tkey)->is_binary())) { + if (!(tkey->is_binary())) { return "StringMap< " + type_name(tval) + ">"; } + break; // default to ObjectMap<> case t_base_type::TYPE_I8: case t_base_type::TYPE_I16: case t_base_type::TYPE_I32: @@ -2573,14 +2574,15 @@ string t_haxe_generator::type_name(t_type* ttype, bool in_container, bool in_ini } if (ttype->is_set()) { - t_type* tkey = get_true_type(((t_list*)ttype)->get_elem_type()); + t_type* tkey = get_true_type(((t_set*)ttype)->get_elem_type()); if (tkey->is_base_type()) { t_base_type::t_base tbase = ((t_base_type*)tkey)->get_base(); switch (tbase) { case t_base_type::TYPE_STRING: - if (!(((t_base_type*)tkey)->is_binary())) { + if (!(tkey->is_binary())) { return "StringSet"; } + break; // default to ObjectSet case t_base_type::TYPE_I8: case t_base_type::TYPE_I16: case t_base_type::TYPE_I32: @@ -2659,7 +2661,7 @@ string t_haxe_generator::declare_field(t_field* tfield, bool init) { if (init) { t_type* ttype = get_true_type(tfield->get_type()); if (ttype->is_base_type() && tfield->get_value() != NULL) { - ofstream dummy; + std::ofstream dummy; result += " = " + render_const_value(dummy, tfield->get_name(), ttype, tfield->get_value()); } else if (ttype->is_base_type()) { t_base_type::t_base tbase = ((t_base_type*)ttype)->get_base(); @@ -2902,7 +2904,7 @@ string t_haxe_generator::constant_name(string name) { /** * Enables RTTI for a class or interface */ -void t_haxe_generator::generate_rtti_decoration(ofstream& out) { +void t_haxe_generator::generate_rtti_decoration(ostream& out) { if (rtti_) { out << "@:rtti" << endl; } @@ -2911,7 +2913,7 @@ void t_haxe_generator::generate_rtti_decoration(ofstream& out) { /** * Adds build macros to a class or interface */ -void t_haxe_generator::generate_macro_decoration(ofstream& out) { +void t_haxe_generator::generate_macro_decoration(ostream& out) { if (!buildmacro_.empty()) { out << "#if ! macro" << endl; out << "@:build( " << buildmacro_ << ")" << endl; // current class/interface @@ -2923,7 +2925,7 @@ void t_haxe_generator::generate_macro_decoration(ofstream& out) { /** * Emits a haxeDoc comment if the provided object has a doc in Thrift */ -void t_haxe_generator::generate_haxe_doc(ofstream& out, t_doc* tdoc) { +void t_haxe_generator::generate_haxe_doc(ostream& out, t_doc* tdoc) { if (tdoc->has_doc()) { generate_docstring_comment(out, "/**\n", " * ", tdoc->get_doc(), " */\n"); } @@ -2932,7 +2934,7 @@ void t_haxe_generator::generate_haxe_doc(ofstream& out, t_doc* tdoc) { /** * Emits a haxeDoc comment if the provided function object has a doc in Thrift */ -void t_haxe_generator::generate_haxe_doc(ofstream& out, t_function* tfunction) { +void t_haxe_generator::generate_haxe_doc(ostream& out, t_function* tfunction) { if (tfunction->has_doc()) { stringstream ss; ss << tfunction->get_doc(); @@ -2957,7 +2959,7 @@ std::string t_haxe_generator::generate_isset_check(std::string field_name) { return "is" + get_cap_name("set") + get_cap_name(field_name) + "()"; } -void t_haxe_generator::generate_isset_set(ofstream& out, t_field* field) { +void t_haxe_generator::generate_isset_set(ostream& out, t_field* field) { if (!type_can_be_null(field->get_type())) { indent(out) << "this.__isset_" << field->get_name() << " = true;" << endl; } diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_hs_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_hs_generator.cc index a3ccd8d..ce7cd0c 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_hs_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_hs_generator.cc @@ -33,7 +33,7 @@ #include "thrift/generate/t_oop_generator.h" using std::map; -using std::ofstream; +using std::ostream; using std::ostringstream; using std::string; using std::stringstream; @@ -87,22 +87,22 @@ public: void generate_hs_struct(t_struct* tstruct, bool is_exception); - void generate_hs_struct_definition(ofstream& out, + void generate_hs_struct_definition(ostream& out, t_struct* tstruct, bool is_xception = false, bool helper = false); - void generate_hs_struct_reader(ofstream& out, t_struct* tstruct); + void generate_hs_struct_reader(ostream& out, t_struct* tstruct); - void generate_hs_struct_writer(ofstream& out, t_struct* tstruct); + void generate_hs_struct_writer(ostream& out, t_struct* tstruct); - void generate_hs_struct_arbitrary(ofstream& out, t_struct* tstruct); + void generate_hs_struct_arbitrary(ostream& out, t_struct* tstruct); void generate_hs_function_helpers(t_function* tfunction); - void generate_hs_typemap(ofstream& out, t_struct* tstruct); + void generate_hs_typemap(ostream& out, t_struct* tstruct); - void generate_hs_default(ofstream& out, t_struct* tstruct); + void generate_hs_default(ostream& out, t_struct* tstruct); /** * Service-level generation functions @@ -118,29 +118,29 @@ public: * Serialization constructs */ - void generate_deserialize_field(ofstream& out, t_field* tfield, string prefix); + void generate_deserialize_field(ostream& out, t_field* tfield, string prefix); - void generate_deserialize_struct(ofstream& out, t_struct* tstruct, string name = ""); + void generate_deserialize_struct(ostream& out, t_struct* tstruct, string name = ""); - void generate_deserialize_container(ofstream& out, t_type* ttype, string arg = ""); + void generate_deserialize_container(ostream& out, t_type* ttype, string arg = ""); - void generate_deserialize_set_element(ofstream& out, t_set* tset); + void generate_deserialize_set_element(ostream& out, t_set* tset); - void generate_deserialize_list_element(ofstream& out, t_list* tlist, string prefix = ""); + void generate_deserialize_list_element(ostream& out, t_list* tlist, string prefix = ""); - void generate_deserialize_type(ofstream& out, t_type* type, string arg = ""); + void generate_deserialize_type(ostream& out, t_type* type, string arg = ""); - void generate_serialize_type(ofstream& out, t_type* type, string name = ""); + void generate_serialize_type(ostream& out, t_type* type, string name = ""); - void generate_serialize_struct(ofstream& out, t_struct* tstruct, string prefix = ""); + void generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix = ""); - void generate_serialize_container(ofstream& out, t_type* ttype, string prefix = ""); + void generate_serialize_container(ostream& out, t_type* ttype, string prefix = ""); - void generate_serialize_map_element(ofstream& out, t_map* tmap, string kiter, string viter); + void generate_serialize_map_element(ostream& out, t_map* tmap, string kiter, string viter); - void generate_serialize_set_element(ofstream& out, t_set* tmap, string iter); + void generate_serialize_set_element(ostream& out, t_set* tmap, string iter); - void generate_serialize_list_element(ofstream& out, t_list* tlist, string iter); + void generate_serialize_list_element(ostream& out, t_list* tlist, string iter); /** * Helper rendering functions @@ -170,11 +170,11 @@ public: string render_hs_type_for_function_name(t_type* type); private: - ofstream f_types_; - ofstream f_consts_; - ofstream f_service_; - ofstream f_iface_; - ofstream f_client_; + ofstream_with_content_based_conditional_update f_types_; + ofstream_with_content_based_conditional_update f_consts_; + ofstream_with_content_based_conditional_update f_service_; + ofstream_with_content_based_conditional_update f_iface_; + ofstream_with_content_based_conditional_update f_client_; }; /** @@ -424,10 +424,10 @@ string t_hs_generator::render_const_value(t_type* type, t_const_value* value) { out << "default_" << cname << "{"; const vector& fields = ((t_struct*)type)->get_members(); - const map& val = value->get_map(); + const map& val = value->get_map(); bool first = true; - for (map::const_iterator v_iter = val.begin(); + for (map::const_iterator v_iter = val.begin(); v_iter != val.end(); ++v_iter) { t_field* field = NULL; @@ -458,8 +458,8 @@ string t_hs_generator::render_const_value(t_type* type, t_const_value* value) { t_type* ktype = ((t_map*)type)->get_key_type(); t_type* vtype = ((t_map*)type)->get_val_type(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; out << "(Map.fromList ["; @@ -530,7 +530,7 @@ void t_hs_generator::generate_hs_struct(t_struct* tstruct, bool is_exception) { * * @param tstruct The struct definition */ -void t_hs_generator::generate_hs_struct_definition(ofstream& out, +void t_hs_generator::generate_hs_struct_definition(ostream& out, t_struct* tstruct, bool is_exception, bool helper) { @@ -586,7 +586,7 @@ void t_hs_generator::generate_hs_struct_definition(ofstream& out, generate_hs_default(out, tstruct); } -void t_hs_generator::generate_hs_struct_arbitrary(ofstream& out, t_struct* tstruct) { +void t_hs_generator::generate_hs_struct_arbitrary(ostream& out, t_struct* tstruct) { string tname = type_name(tstruct); string name = tstruct->get_name(); const vector& members = tstruct->get_members(); @@ -652,7 +652,7 @@ void t_hs_generator::generate_hs_struct_arbitrary(ofstream& out, t_struct* tstru /** * Generates the read method for a struct */ -void t_hs_generator::generate_hs_struct_reader(ofstream& out, t_struct* tstruct) { +void t_hs_generator::generate_hs_struct_reader(ostream& out, t_struct* tstruct) { const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; @@ -711,18 +711,18 @@ void t_hs_generator::generate_hs_struct_reader(ofstream& out, t_struct* tstruct) string tmap = type_name(tstruct, "typemap_"); indent(out) << "to_" << sname << " _ = P.error \"not a struct\"" << endl; - indent(out) << "read_" << sname << " :: (T.Transport t, T.Protocol p) => p t -> P.IO " << sname + indent(out) << "read_" << sname << " :: T.Protocol p => p -> P.IO " << sname << endl; indent(out) << "read_" << sname << " iprot = to_" << sname; out << " <$> T.readVal iprot (T.T_STRUCT " << tmap << ")" << endl; indent(out) << "decode_" << sname - << " :: (T.Protocol p, T.Transport t) => p t -> LBS.ByteString -> " << sname << endl; + << " :: T.StatelessProtocol p => p -> LBS.ByteString -> " << sname << endl; indent(out) << "decode_" << sname << " iprot bs = to_" << sname << " $ "; out << "T.deserializeVal iprot (T.T_STRUCT " << tmap << ") bs" << endl; } -void t_hs_generator::generate_hs_struct_writer(ofstream& out, t_struct* tstruct) { +void t_hs_generator::generate_hs_struct_writer(ostream& out, t_struct* tstruct) { string name = type_name(tstruct); const vector& fields = tstruct->get_sorted_members(); vector::const_iterator f_iter; @@ -818,13 +818,13 @@ void t_hs_generator::generate_hs_struct_writer(ofstream& out, t_struct* tstruct) indent_down(); // write - indent(out) << "write_" << name << " :: (T.Protocol p, T.Transport t) => p t -> " << name + indent(out) << "write_" << name << " :: T.Protocol p => p -> " << name << " -> P.IO ()" << endl; indent(out) << "write_" << name << " oprot record = T.writeVal oprot $ from_"; out << name << " record" << endl; // encode - indent(out) << "encode_" << name << " :: (T.Protocol p, T.Transport t) => p t -> " << name + indent(out) << "encode_" << name << " :: T.StatelessProtocol p => p -> " << name << " -> LBS.ByteString" << endl; indent(out) << "encode_" << name << " oprot record = T.serializeVal oprot $ "; out << "from_" << name << " record" << endl; @@ -906,7 +906,7 @@ void t_hs_generator::generate_hs_function_helpers(t_function* tfunction) { * Generate the map from field names to (type, id) * @param tstruct the Struct */ -void t_hs_generator::generate_hs_typemap(ofstream& out, t_struct* tstruct) { +void t_hs_generator::generate_hs_typemap(ostream& out, t_struct* tstruct) { string name = type_name(tstruct); const vector& fields = tstruct->get_sorted_members(); vector::const_iterator f_iter; @@ -932,7 +932,7 @@ void t_hs_generator::generate_hs_typemap(ofstream& out, t_struct* tstruct) { * generate the struct with default values filled in * @param tstruct the Struct */ -void t_hs_generator::generate_hs_default(ofstream& out, t_struct* tstruct) { +void t_hs_generator::generate_hs_default(ostream& out, t_struct* tstruct) { string name = type_name(tstruct); string fname = type_name(tstruct, "default_"); const vector& fields = tstruct->get_sorted_members(); @@ -1085,8 +1085,9 @@ void t_hs_generator::generate_service_client(t_service* tservice) { // Serialize the request header string fname = (*f_iter)->get_name(); string msgType = (*f_iter)->is_oneway() ? "T.M_ONEWAY" : "T.M_CALL"; - indent(f_client_) << "T.writeMessageBegin op (\"" << fname << "\", " << msgType << ", seqn)" + indent(f_client_) << "T.writeMessage op (\"" << fname << "\", " << msgType << ", seqn) $" << endl; + indent_up(); indent(f_client_) << "write_" << argsname << " op (" << argsname << "{"; bool first = true; @@ -1102,10 +1103,7 @@ void t_hs_generator::generate_service_client(t_service* tservice) { first = false; } f_client_ << "})" << endl; - indent(f_client_) << "T.writeMessageEnd op" << endl; - - // Write to the stream - indent(f_client_) << "T.tFlush (T.getTransport op)" << endl; + indent_down(); indent_down(); if (!(*f_iter)->is_oneway()) { @@ -1119,12 +1117,12 @@ void t_hs_generator::generate_service_client(t_service* tservice) { indent(f_client_) << funname << " ip = do" << endl; indent_up(); - indent(f_client_) << "(fname, mtype, rseqid) <- T.readMessageBegin ip" << endl; + indent(f_client_) << "T.readMessage ip $ \\(fname, mtype, rseqid) -> do" << endl; + indent_up(); indent(f_client_) << "M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; " - "T.readMessageEnd ip ; X.throw exn }" << endl; + "X.throw exn }" << endl; indent(f_client_) << "res <- read_" << resultname << " ip" << endl; - indent(f_client_) << "T.readMessageEnd ip" << endl; t_struct* xs = (*f_iter)->get_xceptions(); const vector& xceptions = xs->get_members(); @@ -1142,6 +1140,7 @@ void t_hs_generator::generate_service_client(t_service* tservice) { // Close function indent_down(); + indent_down(); } } @@ -1180,11 +1179,11 @@ void t_hs_generator::generate_service_server(t_service* tservice) { f_service_ << "do" << endl; indent_up(); indent(f_service_) << "_ <- T.readVal iprot (T.T_STRUCT Map.empty)" << endl; - indent(f_service_) << "T.writeMessageBegin oprot (name,T.M_EXCEPTION,seqid)" << endl; + indent(f_service_) << "T.writeMessage oprot (name,T.M_EXCEPTION,seqid) $" << endl; + indent_up(); indent(f_service_) << "T.writeAppExn oprot (T.AppExn T.AE_UNKNOWN_METHOD (\"Unknown function " "\" ++ LT.unpack name))" << endl; - indent(f_service_) << "T.writeMessageEnd oprot" << endl; - indent(f_service_) << "T.tFlush (T.getTransport oprot)" << endl; + indent_down(); indent_down(); } @@ -1194,9 +1193,8 @@ void t_hs_generator::generate_service_server(t_service* tservice) { indent(f_service_) << "process handler (iprot, oprot) = do" << endl; indent_up(); - indent(f_service_) << "(name, typ, seqid) <- T.readMessageBegin iprot" << endl; - indent(f_service_) << "proc_ handler (iprot,oprot) (name,typ,seqid)" << endl; - indent(f_service_) << "T.readMessageEnd iprot" << endl; + indent(f_service_) << "T.readMessage iprot (" << endl; + indent(f_service_) << " proc_ handler (iprot,oprot))" << endl; indent(f_service_) << "P.return P.True" << endl; indent_down(); } @@ -1286,11 +1284,11 @@ void t_hs_generator::generate_process_function(t_service* tservice, t_function* if (tfunction->is_oneway()) { indent(f_service_) << "P.return ()"; } else { - indent(f_service_) << "T.writeMessageBegin oprot (\"" << tfunction->get_name() - << "\", T.M_REPLY, seqid)" << endl; - indent(f_service_) << "write_" << resultname << " oprot res" << endl; - indent(f_service_) << "T.writeMessageEnd oprot" << endl; - indent(f_service_) << "T.tFlush (T.getTransport oprot)"; + indent(f_service_) << "T.writeMessage oprot (\"" << tfunction->get_name() + << "\", T.M_REPLY, seqid) $" << endl; + indent_up(); + indent(f_service_) << "write_" << resultname << " oprot res"; + indent_down(); } if (n > 0) { f_service_ << ")"; @@ -1307,11 +1305,11 @@ void t_hs_generator::generate_process_function(t_service* tservice, t_function* indent(f_service_) << "let res = default_" << resultname << "{" << field_name(resultname, (*x_iter)->get_name()) << " = P.Just e}" << endl; - indent(f_service_) << "T.writeMessageBegin oprot (\"" << tfunction->get_name() - << "\", T.M_REPLY, seqid)" << endl; - indent(f_service_) << "write_" << resultname << " oprot res" << endl; - indent(f_service_) << "T.writeMessageEnd oprot" << endl; - indent(f_service_) << "T.tFlush (T.getTransport oprot)"; + indent(f_service_) << "T.writeMessage oprot (\"" << tfunction->get_name() + << "\", T.M_REPLY, seqid) $" << endl; + indent_up(); + indent(f_service_) << "write_" << resultname << " oprot res"; + indent_down(); } else { indent(f_service_) << "P.return ()"; } @@ -1324,11 +1322,11 @@ void t_hs_generator::generate_process_function(t_service* tservice, t_function* indent_up(); if (!tfunction->is_oneway()) { - indent(f_service_) << "T.writeMessageBegin oprot (\"" << tfunction->get_name() - << "\", T.M_EXCEPTION, seqid)" << endl; - indent(f_service_) << "T.writeAppExn oprot (T.AppExn T.AE_UNKNOWN \"\")" << endl; - indent(f_service_) << "T.writeMessageEnd oprot" << endl; - indent(f_service_) << "T.tFlush (T.getTransport oprot)"; + indent(f_service_) << "T.writeMessage oprot (\"" << tfunction->get_name() + << "\", T.M_EXCEPTION, seqid) $" << endl; + indent_up(); + indent(f_service_) << "T.writeAppExn oprot (T.AppExn T.AE_UNKNOWN \"\")"; + indent_down(); } else { indent(f_service_) << "P.return ()"; } @@ -1344,7 +1342,7 @@ void t_hs_generator::generate_process_function(t_service* tservice, t_function* /** * Deserializes a field of any type. */ -void t_hs_generator::generate_deserialize_field(ofstream& out, t_field* tfield, string prefix) { +void t_hs_generator::generate_deserialize_field(ostream& out, t_field* tfield, string prefix) { (void)prefix; t_type* type = tfield->get_type(); generate_deserialize_type(out, type, prefix); @@ -1353,7 +1351,7 @@ void t_hs_generator::generate_deserialize_field(ofstream& out, t_field* tfield, /** * Deserializes a field of any type. */ -void t_hs_generator::generate_deserialize_type(ofstream& out, t_type* type, string arg) { +void t_hs_generator::generate_deserialize_type(ostream& out, t_type* type, string arg) { type = get_true_type(type); string val = tmp("_val"); out << "(case " << arg << " of {" << type_to_constructor(type) << " " << val << " -> "; @@ -1369,11 +1367,11 @@ void t_hs_generator::generate_deserialize_type(ofstream& out, t_type* type, stri } else if (type->is_base_type()) { t_base_type::t_base tbase = ((t_base_type*)type)->get_base(); - if (tbase == t_base_type::TYPE_STRING && !((t_base_type*)type)->is_binary()) { + if (tbase == t_base_type::TYPE_STRING && !type->is_binary()) { out << "E.decodeUtf8 "; } out << val; - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { // Since wire type of binary is the same as string, we actually receive T.TString not // T.TBinary out << "; T.TString " << val << " -> " << val; @@ -1390,7 +1388,7 @@ void t_hs_generator::generate_deserialize_type(ofstream& out, t_type* type, stri /** * Generates an unserializer for a struct, calling read() */ -void t_hs_generator::generate_deserialize_struct(ofstream& out, t_struct* tstruct, string name) { +void t_hs_generator::generate_deserialize_struct(ostream& out, t_struct* tstruct, string name) { out << "(" << type_name(tstruct, "to_") << " (T.TStruct " << name << "))"; } @@ -1399,7 +1397,7 @@ void t_hs_generator::generate_deserialize_struct(ofstream& out, t_struct* tstruc * Serialize a container by writing out the header followed by * data and then a footer. */ -void t_hs_generator::generate_deserialize_container(ofstream& out, t_type* ttype, string arg) { +void t_hs_generator::generate_deserialize_container(ostream& out, t_type* ttype, string arg) { string val = tmp("_v"); // Declare variables, read header @@ -1415,12 +1413,12 @@ void t_hs_generator::generate_deserialize_container(ofstream& out, t_type* ttype } else if (ttype->is_set()) { out << "(Set.fromList $ P.map (\\" << val << " -> "; - generate_deserialize_type(out, ((t_map*)ttype)->get_key_type(), val); + generate_deserialize_type(out, ((t_set*)ttype)->get_elem_type(), val); out << ") " << arg << ")"; } else if (ttype->is_list()) { out << "(Vector.fromList $ P.map (\\" << val << " -> "; - generate_deserialize_type(out, ((t_map*)ttype)->get_key_type(), val); + generate_deserialize_type(out, ((t_list*)ttype)->get_elem_type(), val); out << ") " << arg << ")"; } } @@ -1431,7 +1429,7 @@ void t_hs_generator::generate_deserialize_container(ofstream& out, t_type* ttype * @param tfield The field to serialize * @param prefix Name to prepend to field name */ -void t_hs_generator::generate_serialize_type(ofstream& out, t_type* type, string name) { +void t_hs_generator::generate_serialize_type(ostream& out, t_type* type, string name) { type = get_true_type(type); // Do nothing for void types @@ -1448,7 +1446,7 @@ void t_hs_generator::generate_serialize_type(ofstream& out, t_type* type, string if (type->is_base_type()) { t_base_type::t_base tbase = ((t_base_type*)type)->get_base(); out << type_to_constructor(type) << " "; - if (tbase == t_base_type::TYPE_STRING && !((t_base_type*)type)->is_binary()) { + if (tbase == t_base_type::TYPE_STRING && !type->is_binary()) { out << "$ E.encodeUtf8 "; } out << name; @@ -1469,11 +1467,11 @@ void t_hs_generator::generate_serialize_type(ofstream& out, t_type* type, string * @param tstruct The struct to serialize * @param prefix String prefix to attach to all fields */ -void t_hs_generator::generate_serialize_struct(ofstream& out, t_struct* tstruct, string prefix) { +void t_hs_generator::generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix) { out << type_name(tstruct, "from_") << " " << prefix; } -void t_hs_generator::generate_serialize_container(ofstream& out, t_type* ttype, string prefix) { +void t_hs_generator::generate_serialize_container(ostream& out, t_type* ttype, string prefix) { string k = tmp("_k"); string v = tmp("_v"); @@ -1488,9 +1486,9 @@ void t_hs_generator::generate_serialize_container(ofstream& out, t_type* ttype, out << ")) $ Map.toList " << prefix; } else if (ttype->is_set()) { - out << "T.TSet " << type_to_enum(((t_list*)ttype)->get_elem_type()); + out << "T.TSet " << type_to_enum(((t_set*)ttype)->get_elem_type()); out << " $ P.map (\\" << v << " -> "; - generate_serialize_type(out, ((t_list*)ttype)->get_elem_type(), v); + generate_serialize_type(out, ((t_set*)ttype)->get_elem_type(), v); out << ") $ Set.toList " << prefix; } else if (ttype->is_list()) { @@ -1550,7 +1548,7 @@ string t_hs_generator::type_to_enum(t_type* type) { case t_base_type::TYPE_VOID: return "T.T_VOID"; case t_base_type::TYPE_STRING: - return ((t_base_type*)type)->is_binary() ? "T.T_BINARY" : "T.T_STRING"; + return type->is_binary() ? "T.T_BINARY" : "T.T_STRING"; case t_base_type::TYPE_BOOL: return "T.T_BOOL"; case t_base_type::TYPE_I8: @@ -1577,7 +1575,7 @@ string t_hs_generator::type_to_enum(t_type* type) { return "(T.T_MAP " + ktype + " " + vtype + ")"; } else if (type->is_set()) { - return "(T.T_SET " + type_to_enum(((t_list*)type)->get_elem_type()) + ")"; + return "(T.T_SET " + type_to_enum(((t_set*)type)->get_elem_type()) + ")"; } else if (type->is_list()) { return "(T.T_LIST " + type_to_enum(((t_list*)type)->get_elem_type()) + ")"; @@ -1645,7 +1643,7 @@ string t_hs_generator::render_hs_type(t_type* type, bool needs_parens) { case t_base_type::TYPE_VOID: return "()"; case t_base_type::TYPE_STRING: - return (((t_base_type*)type)->is_binary() ? "LBS.ByteString" : "LT.Text"); + return (type->is_binary() ? "LBS.ByteString" : "LT.Text"); case t_base_type::TYPE_BOOL: return "P.Bool"; case t_base_type::TYPE_I8: @@ -1698,7 +1696,7 @@ string t_hs_generator::type_to_constructor(t_type* type) { case t_base_type::TYPE_VOID: throw "invalid type: T_VOID"; case t_base_type::TYPE_STRING: - return ((t_base_type*)type)->is_binary() ? "T.TBinary" : "T.TString"; + return type->is_binary() ? "T.TBinary" : "T.TString"; case t_base_type::TYPE_BOOL: return "T.TBool"; case t_base_type::TYPE_I8: diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_html_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_html_generator.cc index ec78e10..8dfa389 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_html_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_html_generator.cc @@ -90,7 +90,7 @@ public: std::string escape_html(std::string const& str); std::string escape_html_tags(std::string const& str); void generate_css(); - void generate_css_content(std::ofstream& f_target); + void generate_css_content(std::ostream& f_target); void generate_style_tag(); std::string make_file_link(std::string name); bool is_utf8_sequence(std::string const& str, size_t firstpos); @@ -114,7 +114,7 @@ public: void print_fn_args_doc(t_function* tfunction); private: - std::ofstream f_out_; + ofstream_with_content_based_conditional_update f_out_; std::string current_file_; input_type input_type_; std::map allowed_markup; @@ -359,7 +359,7 @@ void t_html_generator::generate_css() { } } -void t_html_generator::generate_css_content(std::ofstream& f_target) { +void t_html_generator::generate_css_content(std::ostream& f_target) { f_target << BOOTSTRAP_CSS() << endl; f_target << "/* Auto-generated CSS for generated Thrift docs */" << endl; f_target << "h3, h4 { margin-bottom: 6px; }" << endl; @@ -405,7 +405,7 @@ void t_html_generator::print_doc(t_doc* tdoc) { if (unsafe_) { f_out_ << tdoc->get_doc() << "
"; } else { - f_out_ << escape_html(tdoc->get_doc()) << "
"; + f_out_ << "
" << escape_html(tdoc->get_doc()) << "

"; } } } @@ -691,14 +691,14 @@ int t_html_generator::print_type(t_type* ttype) { f_out_ << ">"; } } else if (ttype->is_base_type()) { - f_out_ << (((t_base_type*)ttype)->is_binary() ? "binary" : ttype->get_name()); + f_out_ << (ttype->is_binary() ? "binary" : ttype->get_name()); len = ttype->get_name().size(); } else { string prog_name = ttype->get_program()->get_name(); string type_name = ttype->get_name(); f_out_ << "is_typedef()) { - f_out_ << "Typedef_"; + f_out_ << "Struct_"; } else if (ttype->is_struct() || ttype->is_xception()) { f_out_ << "Struct_"; } else if (ttype->is_enum()) { @@ -777,8 +777,8 @@ void t_html_generator::print_const_value(t_type* type, t_const_value* tvalue) { f_out_ << "{ "; const vector& fields = ((t_struct*)truetype)->get_members(); vector::const_iterator f_iter; - const map& val = tvalue->get_map(); - map::const_iterator v_iter; + const map& val = tvalue->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { t_type* field_type = NULL; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { @@ -800,8 +800,8 @@ void t_html_generator::print_const_value(t_type* type, t_const_value* tvalue) { f_out_ << " }"; } else if (truetype->is_map()) { f_out_ << "{ "; - map map_elems = tvalue->get_map(); - map::iterator map_iter; + map map_elems = tvalue->get_map(); + map::iterator map_iter; for (map_iter = map_elems.begin(); map_iter != map_elems.end(); map_iter++) { if (!first) { f_out_ << ", "; diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_java_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_java_generator.cc index fb581e4..2c84551 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_java_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_java_generator.cc @@ -25,6 +25,7 @@ #include #include #include +#include #include #include @@ -35,7 +36,7 @@ #include "thrift/generate/t_oop_generator.h" using std::map; -using std::ofstream; +using std::ostream; using std::ostringstream; using std::setfill; using std::setw; @@ -70,6 +71,8 @@ public: use_option_type_ = false; undated_generated_annotations_ = false; suppress_generated_annotations_ = false; + rethrow_unhandled_exceptions_ = false; + unsafe_binaries_ = false; for( iter = parsed_options.begin(); iter != parsed_options.end(); ++iter) { if( iter->first.compare("beans") == 0) { bean_style_ = true; @@ -91,6 +94,8 @@ public: reuse_objects_ = true; } else if( iter->first.compare("option_type") == 0) { use_option_type_ = true; + } else if( iter->first.compare("rethrow_unhandled_exceptions") == 0) { + rethrow_unhandled_exceptions_ = true; } else if( iter->first.compare("generated_annotations") == 0) { if( iter->second.compare("undated") == 0) { undated_generated_annotations_ = true; @@ -99,6 +104,8 @@ public: } else { throw "unknown option java:" + iter->first + "=" + iter->second; } + } else if( iter->first.compare("unsafe_binaries") == 0) { + unsafe_binaries_ = true; } else { throw "unknown option java:" + iter->first; } @@ -131,13 +138,13 @@ public: void generate_xception(t_struct* txception); void generate_service(t_service* tservice); - void print_const_value(std::ofstream& out, + void print_const_value(std::ostream& out, std::string name, t_type* type, t_const_value* value, bool in_static, bool defval = false); - std::string render_const_value(std::ofstream& out, t_type* type, t_const_value* value); + std::string render_const_value(std::ostream& out, t_type* type, t_const_value* value); /** * Service-level generation functions @@ -145,26 +152,26 @@ public: void generate_java_struct(t_struct* tstruct, bool is_exception); - void generate_java_struct_definition(std::ofstream& out, + void generate_java_struct_definition(std::ostream& out, t_struct* tstruct, bool is_xception = false, bool in_class = false, bool is_result = false); - void generate_java_struct_parcelable(std::ofstream& out, t_struct* tstruct); - void generate_java_struct_equality(std::ofstream& out, t_struct* tstruct); - void generate_java_struct_compare_to(std::ofstream& out, t_struct* tstruct); - void generate_java_struct_reader(std::ofstream& out, t_struct* tstruct); - void generate_java_validator(std::ofstream& out, t_struct* tstruct); - void generate_java_struct_result_writer(std::ofstream& out, t_struct* tstruct); - void generate_java_struct_writer(std::ofstream& out, t_struct* tstruct); - void generate_java_struct_tostring(std::ofstream& out, t_struct* tstruct); - void generate_java_struct_clear(std::ofstream& out, t_struct* tstruct); - void generate_java_struct_write_object(std::ofstream& out, t_struct* tstruct); - void generate_java_struct_read_object(std::ofstream& out, t_struct* tstruct); - void generate_java_meta_data_map(std::ofstream& out, t_struct* tstruct); - void generate_field_value_meta_data(std::ofstream& out, t_type* type); + void generate_java_struct_parcelable(std::ostream& out, t_struct* tstruct); + void generate_java_struct_equality(std::ostream& out, t_struct* tstruct); + void generate_java_struct_compare_to(std::ostream& out, t_struct* tstruct); + void generate_java_struct_reader(std::ostream& out, t_struct* tstruct); + void generate_java_validator(std::ostream& out, t_struct* tstruct); + void generate_java_struct_result_writer(std::ostream& out, t_struct* tstruct); + void generate_java_struct_writer(std::ostream& out, t_struct* tstruct); + void generate_java_struct_tostring(std::ostream& out, t_struct* tstruct); + void generate_java_struct_clear(std::ostream& out, t_struct* tstruct); + void generate_java_struct_write_object(std::ostream& out, t_struct* tstruct); + void generate_java_struct_read_object(std::ostream& out, t_struct* tstruct); + void generate_java_meta_data_map(std::ostream& out, t_struct* tstruct); + void generate_field_value_meta_data(std::ostream& out, t_type* type); std::string get_java_type_string(t_type* type); - void generate_java_struct_field_by_id(ofstream& out, t_struct* tstruct); + void generate_java_struct_field_by_id(ostream& out, t_struct* tstruct); void generate_reflection_setters(std::ostringstream& out, t_type* type, std::string field_name, @@ -173,9 +180,9 @@ public: t_type* type, std::string field_name, std::string cap_name); - void generate_generic_field_getters_setters(std::ofstream& out, t_struct* tstruct); - void generate_generic_isset_method(std::ofstream& out, t_struct* tstruct); - void generate_java_bean_boilerplate(std::ofstream& out, t_struct* tstruct); + void generate_generic_field_getters_setters(std::ostream& out, t_struct* tstruct); + void generate_generic_isset_method(std::ostream& out, t_struct* tstruct); + void generate_java_bean_boilerplate(std::ostream& out, t_struct* tstruct); void generate_function_helpers(t_function* tfunction); std::string as_camel_case(std::string name, bool ucfirst = true); @@ -183,7 +190,7 @@ public: std::string get_cap_name(std::string name); std::string generate_isset_check(t_field* field); std::string generate_isset_check(std::string field); - void generate_isset_set(ofstream& out, t_field* field, std::string prefix); + void generate_isset_set(ostream& out, t_field* field, std::string prefix); std::string isset_field_id(t_field* field); void generate_service_interface(t_service* tservice); @@ -197,102 +204,102 @@ public: void generate_process_async_function(t_service* tservice, t_function* tfunction); void generate_java_union(t_struct* tstruct); - void generate_union_constructor(ofstream& out, t_struct* tstruct); - void generate_union_getters_and_setters(ofstream& out, t_struct* tstruct); - void generate_union_is_set_methods(ofstream& out, t_struct* tstruct); - void generate_union_abstract_methods(ofstream& out, t_struct* tstruct); - void generate_check_type(ofstream& out, t_struct* tstruct); - void generate_standard_scheme_read_value(ofstream& out, t_struct* tstruct); - void generate_standard_scheme_write_value(ofstream& out, t_struct* tstruct); - void generate_tuple_scheme_read_value(ofstream& out, t_struct* tstruct); - void generate_tuple_scheme_write_value(ofstream& out, t_struct* tstruct); - void generate_get_field_desc(ofstream& out, t_struct* tstruct); - void generate_get_struct_desc(ofstream& out, t_struct* tstruct); - void generate_get_field_name(ofstream& out, t_struct* tstruct); + void generate_union_constructor(ostream& out, t_struct* tstruct); + void generate_union_getters_and_setters(ostream& out, t_struct* tstruct); + void generate_union_is_set_methods(ostream& out, t_struct* tstruct); + void generate_union_abstract_methods(ostream& out, t_struct* tstruct); + void generate_check_type(ostream& out, t_struct* tstruct); + void generate_standard_scheme_read_value(ostream& out, t_struct* tstruct); + void generate_standard_scheme_write_value(ostream& out, t_struct* tstruct); + void generate_tuple_scheme_read_value(ostream& out, t_struct* tstruct); + void generate_tuple_scheme_write_value(ostream& out, t_struct* tstruct); + void generate_get_field_desc(ostream& out, t_struct* tstruct); + void generate_get_struct_desc(ostream& out, t_struct* tstruct); + void generate_get_field_name(ostream& out, t_struct* tstruct); - void generate_union_comparisons(ofstream& out, t_struct* tstruct); - void generate_union_hashcode(ofstream& out, t_struct* tstruct); + void generate_union_comparisons(ostream& out, t_struct* tstruct); + void generate_union_hashcode(ostream& out, t_struct* tstruct); - void generate_scheme_map(ofstream& out, t_struct* tstruct); - void generate_standard_writer(ofstream& out, t_struct* tstruct, bool is_result); - void generate_standard_reader(ofstream& out, t_struct* tstruct); - void generate_java_struct_standard_scheme(ofstream& out, t_struct* tstruct, bool is_result); + void generate_scheme_map(ostream& out, t_struct* tstruct); + void generate_standard_writer(ostream& out, t_struct* tstruct, bool is_result); + void generate_standard_reader(ostream& out, t_struct* tstruct); + void generate_java_struct_standard_scheme(ostream& out, t_struct* tstruct, bool is_result); - void generate_java_struct_tuple_scheme(ofstream& out, t_struct* tstruct); - void generate_java_struct_tuple_reader(ofstream& out, t_struct* tstruct); - void generate_java_struct_tuple_writer(ofstream& out, t_struct* tstruct); + void generate_java_struct_tuple_scheme(ostream& out, t_struct* tstruct); + void generate_java_struct_tuple_reader(ostream& out, t_struct* tstruct); + void generate_java_struct_tuple_writer(ostream& out, t_struct* tstruct); - void generate_java_scheme_lookup(ofstream& out); + void generate_java_scheme_lookup(ostream& out); - void generate_javax_generated_annotation(ofstream& out); + void generate_javax_generated_annotation(ostream& out); /** * Serialization constructs */ - void generate_deserialize_field(std::ofstream& out, + void generate_deserialize_field(std::ostream& out, t_field* tfield, std::string prefix = "", bool has_metadata = true); - void generate_deserialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); + void generate_deserialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); - void generate_deserialize_container(std::ofstream& out, + void generate_deserialize_container(std::ostream& out, t_type* ttype, std::string prefix = "", bool has_metadata = true); - void generate_deserialize_set_element(std::ofstream& out, + void generate_deserialize_set_element(std::ostream& out, t_set* tset, std::string prefix = "", std::string obj = "", bool has_metadata = true); - void generate_deserialize_map_element(std::ofstream& out, + void generate_deserialize_map_element(std::ostream& out, t_map* tmap, std::string prefix = "", std::string obj = "", bool has_metadata = true); - void generate_deserialize_list_element(std::ofstream& out, + void generate_deserialize_list_element(std::ostream& out, t_list* tlist, std::string prefix = "", std::string obj = "", bool has_metadata = true); - void generate_serialize_field(std::ofstream& out, + void generate_serialize_field(std::ostream& out, t_field* tfield, std::string prefix = "", bool has_metadata = true); - void generate_serialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); + void generate_serialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); - void generate_serialize_container(std::ofstream& out, + void generate_serialize_container(std::ostream& out, t_type* ttype, std::string prefix = "", bool has_metadata = true); - void generate_serialize_map_element(std::ofstream& out, + void generate_serialize_map_element(std::ostream& out, t_map* tmap, std::string iter, std::string map, bool has_metadata = true); - void generate_serialize_set_element(std::ofstream& out, + void generate_serialize_set_element(std::ostream& out, t_set* tmap, std::string iter, bool has_metadata = true); - void generate_serialize_list_element(std::ofstream& out, + void generate_serialize_list_element(std::ostream& out, t_list* tlist, std::string iter, bool has_metadata = true); - void generate_deep_copy_container(std::ofstream& out, + void generate_deep_copy_container(std::ostream& out, std::string source_name_p1, std::string source_name_p2, std::string result_name, t_type* type); - void generate_deep_copy_non_container(std::ofstream& out, + void generate_deep_copy_non_container(std::ostream& out, std::string source_name, std::string dest_name, t_type* type); @@ -306,6 +313,7 @@ public: std::string java_package(); std::string java_suppressions(); + std::string java_nullable_annotation(); std::string type_name(t_type* ttype, bool in_container = false, bool in_init = false, @@ -326,9 +334,9 @@ public: t_type* ttype, bool include_types = false); std::string type_to_enum(t_type* ttype); - void generate_struct_desc(ofstream& out, t_struct* tstruct); - void generate_field_descs(ofstream& out, t_struct* tstruct); - void generate_field_name_constants(ofstream& out, t_struct* tstruct); + void generate_struct_desc(ostream& out, t_struct* tstruct); + void generate_field_descs(ostream& out, t_struct* tstruct); + void generate_field_name_constants(ostream& out, t_struct* tstruct); std::string make_valid_java_filename(std::string const& fromName); std::string make_valid_java_identifier(std::string const& fromName); @@ -344,6 +352,44 @@ public: return annotations.find("deprecated") != annotations.end(); } + bool is_enum_set(t_type* ttype) { + if (!sorted_containers_) { + ttype = get_true_type(ttype); + if (ttype->is_set()) { + t_set* tset = (t_set*)ttype; + t_type* elem_type = get_true_type(tset->get_elem_type()); + return elem_type->is_enum(); + } + } + return false; + } + + bool is_enum_map(t_type* ttype) { + if (!sorted_containers_) { + ttype = get_true_type(ttype); + if (ttype->is_map()) { + t_map* tmap = (t_map*)ttype; + t_type* key_type = get_true_type(tmap->get_key_type()); + return key_type->is_enum(); + } + } + return false; + } + + std::string inner_enum_type_name(t_type* ttype) { + ttype = get_true_type(ttype); + if (ttype->is_map()) { + t_map* tmap = (t_map*)ttype; + t_type* key_type = get_true_type(tmap->get_key_type()); + return type_name(key_type, true) + ".class"; + } else if (ttype->is_set()) { + t_set* tset = (t_set*)ttype; + t_type* elem_type = get_true_type(tset->get_elem_type()); + return type_name(elem_type, true) + ".class"; + } + return ""; + } + std::string constant_name(std::string name); private: @@ -352,7 +398,7 @@ private: */ std::string package_name_; - std::ofstream f_service_; + ofstream_with_content_based_conditional_update f_service_; std::string package_dir_; bool bean_style_; @@ -367,6 +413,8 @@ private: bool use_option_type_; bool undated_generated_annotations_; bool suppress_generated_annotations_; + bool rethrow_unhandled_exceptions_; + bool unsafe_binaries_; }; @@ -413,6 +461,10 @@ string t_java_generator::java_suppressions() { return "@SuppressWarnings({\"cast\", \"rawtypes\", \"serial\", \"unchecked\", \"unused\"})\n"; } +string t_java_generator::java_nullable_annotation() { + return "@org.apache.thrift.annotation.Nullable"; +} + /** * Nothing in Java */ @@ -439,17 +491,18 @@ void t_java_generator::generate_enum(t_enum* tenum) { bool is_deprecated = this->is_deprecated(tenum->annotations_); // Make output file string f_enum_name = package_dir_ + "/" + make_valid_java_filename(tenum->get_name()) + ".java"; - ofstream f_enum; + ofstream_with_content_based_conditional_update f_enum; f_enum.open(f_enum_name.c_str()); // Comment and package it f_enum << autogen_comment() << java_package() << endl; - // Add java imports - f_enum << string() + "import java.util.Map;\n" + "import java.util.HashMap;\n" - + "import org.apache.thrift.TEnum;" << endl << endl; - generate_java_doc(f_enum, tenum); + + if (!suppress_generated_annotations_) { + generate_javax_generated_annotation(f_enum); + } + if (is_deprecated) { indent(f_enum) << "@Deprecated" << endl; } @@ -496,6 +549,7 @@ void t_java_generator::generate_enum(t_enum* tenum) { << endl; indent(f_enum) << " * @return null if the value is not found." << endl; indent(f_enum) << " */" << endl; + indent(f_enum) << java_nullable_annotation() << endl; indent(f_enum) << "public static " + tenum->get_name() + " findByValue(int value) { " << endl; indent_up(); @@ -535,7 +589,7 @@ void t_java_generator::generate_consts(std::vector consts) { string f_consts_name = package_dir_ + '/' + make_valid_java_filename(program_name_) + "Constants.java"; - ofstream f_consts; + ofstream_with_content_based_conditional_update f_consts; f_consts.open(f_consts_name.c_str()); // Print header @@ -558,12 +612,13 @@ void t_java_generator::generate_consts(std::vector consts) { f_consts.close(); } + /** * Prints the value of a constant with the given type. Note that type checking * is NOT performed in this function as it is always run beforehand using the * validate_types method in main.cc */ -void t_java_generator::print_const_value(std::ofstream& out, +void t_java_generator::print_const_value(std::ostream& out, string name, t_type* type, t_const_value* value, @@ -581,10 +636,12 @@ void t_java_generator::print_const_value(std::ofstream& out, } else if (type->is_enum()) { out << name << " = " << render_const_value(out, type, value) << ";" << endl << endl; } else if (type->is_struct() || type->is_xception()) { - const vector& fields = ((t_struct*)type)->get_members(); + const vector& unsorted_fields = ((t_struct*)type)->get_members(); + vector fields = unsorted_fields; + std::sort(fields.begin(), fields.end(), t_field::key_compare()); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; out << name << " = new " << type_name(type, false, true) << "();" << endl; if (!in_static) { indent(out) << "static {" << endl; @@ -611,15 +668,19 @@ void t_java_generator::print_const_value(std::ofstream& out, } out << endl; } else if (type->is_map()) { - out << name << " = new " << type_name(type, false, true) << "();" << endl; + std::string constructor_args; + if (is_enum_map(type)) { + constructor_args = inner_enum_type_name(type); + } + out << name << " = new " << type_name(type, false, true) << "(" << constructor_args << ");" << endl; if (!in_static) { indent(out) << "static {" << endl; indent_up(); } t_type* ktype = ((t_map*)type)->get_key_type(); t_type* vtype = ((t_map*)type)->get_val_type(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { string key = render_const_value(out, ktype, v_iter->first); string val = render_const_value(out, vtype, v_iter->second); @@ -631,7 +692,11 @@ void t_java_generator::print_const_value(std::ofstream& out, } out << endl; } else if (type->is_list() || type->is_set()) { - out << name << " = new " << type_name(type, false, true) << "();" << endl; + if (is_enum_set(type)) { + out << name << " = " << type_name(type, false, true, true) << ".noneOf(" << inner_enum_type_name(type) << ");" << endl; + } else { + out << name << " = new " << type_name(type, false, true) << "();" << endl; + } if (!in_static) { indent(out) << "static {" << endl; indent_up(); @@ -658,7 +723,7 @@ void t_java_generator::print_const_value(std::ofstream& out, } } -string t_java_generator::render_const_value(ofstream& out, t_type* type, t_const_value* value) { +string t_java_generator::render_const_value(ostream& out, t_type* type, t_const_value* value) { type = get_true_type(type); std::ostringstream render; @@ -685,9 +750,9 @@ string t_java_generator::render_const_value(ofstream& out, t_type* type, t_const break; case t_base_type::TYPE_DOUBLE: if (value->get_type() == t_const_value::CV_INTEGER) { - render << "(double)" << value->get_integer(); + render << value->get_integer() << "d"; } else { - render << value->get_double(); + render << emit_double_as_string(value->get_double()); } break; default: @@ -740,7 +805,7 @@ void t_java_generator::generate_java_struct(t_struct* tstruct, bool is_exception // Make output file string f_struct_name = package_dir_ + "/" + make_valid_java_filename(tstruct->get_name()) + ".java"; - ofstream f_struct; + ofstream_with_content_based_conditional_update f_struct; f_struct.open(f_struct_name.c_str()); f_struct << autogen_comment() << java_package() << java_suppressions(); @@ -758,7 +823,7 @@ void t_java_generator::generate_java_union(t_struct* tstruct) { // Make output file string f_struct_name = package_dir_ + "/" + make_valid_java_filename(tstruct->get_name()) + ".java"; - ofstream f_struct; + ofstream_with_content_based_conditional_update f_struct; f_struct.open(f_struct_name.c_str()); f_struct << autogen_comment() << java_package() << java_suppressions(); @@ -768,6 +833,10 @@ void t_java_generator::generate_java_union(t_struct* tstruct) { bool is_final = (tstruct->annotations_.find("final") != tstruct->annotations_.end()); bool is_deprecated = this->is_deprecated(tstruct->annotations_); + if (!suppress_generated_annotations_) { + generate_javax_generated_annotation(f_struct); + } + if (is_deprecated) { indent(f_struct) << "@Deprecated" << endl; } @@ -829,7 +898,7 @@ void t_java_generator::generate_java_union(t_struct* tstruct) { f_struct.close(); } -void t_java_generator::generate_union_constructor(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_union_constructor(ostream& out, t_struct* tstruct) { const vector& members = tstruct->get_members(); vector::const_iterator m_iter; @@ -874,20 +943,24 @@ void t_java_generator::generate_union_constructor(ofstream& out, t_struct* tstru indent(out) << " return x;" << endl; indent(out) << "}" << endl << endl; - if (type->is_base_type() && ((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { indent(out) << "public static " << type_name(tstruct) << " " << (*m_iter)->get_name() << "(byte[] value) {" << endl; indent(out) << " " << type_name(tstruct) << " x = new " << type_name(tstruct) << "();" << endl; - indent(out) << " x.set" << get_cap_name((*m_iter)->get_name()) - << "(java.nio.ByteBuffer.wrap(value.clone()));" << endl; + indent(out) << " x.set" << get_cap_name((*m_iter)->get_name()); + if(unsafe_binaries_) { + indent(out) << "(java.nio.ByteBuffer.wrap(value));" << endl; + }else{ + indent(out) << "(java.nio.ByteBuffer.wrap(value.clone()));" << endl; + } indent(out) << " return x;" << endl; indent(out) << "}" << endl << endl; } } } -void t_java_generator::generate_union_getters_and_setters(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_union_getters_and_setters(ostream& out, t_struct* tstruct) { const vector& members = tstruct->get_members(); vector::const_iterator m_iter; @@ -905,7 +978,7 @@ void t_java_generator::generate_union_getters_and_setters(ofstream& out, t_struc bool is_deprecated = this->is_deprecated(field->annotations_); generate_java_doc(out, field); - if (type->is_base_type() && ((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { if (is_deprecated) { indent(out) << "@Deprecated" << endl; } @@ -922,9 +995,17 @@ void t_java_generator::generate_union_getters_and_setters(ofstream& out, t_struc << get_cap_name(field->get_name()) << "() {" << endl; indent(out) << " if (getSetField() == _Fields." << constant_name(field->get_name()) << ") {" << endl; - indent(out) + + if(unsafe_binaries_){ + indent(out) + << " return (java.nio.ByteBuffer)getFieldValue();" + << endl; + }else{ + indent(out) << " return org.apache.thrift.TBaseHelper.copyBinary((java.nio.ByteBuffer)getFieldValue());" << endl; + } + indent(out) << " } else {" << endl; indent(out) << " throw new java.lang.RuntimeException(\"Cannot get field '" << field->get_name() << "' because union is currently set to \" + getFieldDesc(getSetField()).name);" @@ -952,14 +1033,20 @@ void t_java_generator::generate_union_getters_and_setters(ofstream& out, t_struc out << endl; generate_java_doc(out, field); - if (type->is_base_type() && ((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { if (is_deprecated) { indent(out) << "@Deprecated" << endl; } indent(out) << "public void set" << get_cap_name(field->get_name()) << "(byte[] value) {" << endl; - indent(out) << " set" << get_cap_name(field->get_name()) - << "(java.nio.ByteBuffer.wrap(value.clone()));" << endl; + indent(out) << " set" << get_cap_name(field->get_name()); + + if(unsafe_binaries_){ + indent(out) << "(java.nio.ByteBuffer.wrap(value));" << endl; + }else{ + indent(out) << "(java.nio.ByteBuffer.wrap(value.clone()));" << endl; + } + indent(out) << "}" << endl; out << endl; @@ -978,7 +1065,7 @@ void t_java_generator::generate_union_getters_and_setters(ofstream& out, t_struc } } -void t_java_generator::generate_union_is_set_methods(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_union_is_set_methods(ostream& out, t_struct* tstruct) { const vector& members = tstruct->get_members(); vector::const_iterator m_iter; @@ -1001,7 +1088,7 @@ void t_java_generator::generate_union_is_set_methods(ofstream& out, t_struct* ts } } -void t_java_generator::generate_union_abstract_methods(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_union_abstract_methods(ostream& out, t_struct* tstruct) { generate_check_type(out, tstruct); out << endl; generate_standard_scheme_read_value(out, tstruct); @@ -1022,7 +1109,7 @@ void t_java_generator::generate_union_abstract_methods(ofstream& out, t_struct* indent(out) << "}" << endl; } -void t_java_generator::generate_check_type(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_check_type(ostream& out, t_struct* tstruct) { indent(out) << "@Override" << endl; indent(out) << "protected void checkType(_Fields setField, java.lang.Object value) throws java.lang.ClassCastException {" @@ -1059,7 +1146,7 @@ void t_java_generator::generate_check_type(ofstream& out, t_struct* tstruct) { indent(out) << "}" << endl; } -void t_java_generator::generate_standard_scheme_read_value(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_standard_scheme_read_value(ostream& out, t_struct* tstruct) { indent(out) << "@Override" << endl; indent(out) << "protected java.lang.Object standardSchemeReadValue(org.apache.thrift.protocol.TProtocol " "iprot, org.apache.thrift.protocol.TField field) throws " @@ -1115,7 +1202,7 @@ void t_java_generator::generate_standard_scheme_read_value(ofstream& out, t_stru indent(out) << "}" << endl; } -void t_java_generator::generate_standard_scheme_write_value(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_standard_scheme_write_value(ostream& out, t_struct* tstruct) { indent(out) << "@Override" << endl; indent(out) << "protected void standardSchemeWriteValue(org.apache.thrift.protocol.TProtocol " "oprot) throws org.apache.thrift.TException {" << endl; @@ -1152,7 +1239,7 @@ void t_java_generator::generate_standard_scheme_write_value(ofstream& out, t_str indent(out) << "}" << endl; } -void t_java_generator::generate_tuple_scheme_read_value(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_tuple_scheme_read_value(ostream& out, t_struct* tstruct) { indent(out) << "@Override" << endl; indent(out) << "protected java.lang.Object tupleSchemeReadValue(org.apache.thrift.protocol.TProtocol " "iprot, short fieldID) throws org.apache.thrift.TException {" << endl; @@ -1198,7 +1285,7 @@ void t_java_generator::generate_tuple_scheme_read_value(ofstream& out, t_struct* indent(out) << "}" << endl; } -void t_java_generator::generate_tuple_scheme_write_value(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_tuple_scheme_write_value(ostream& out, t_struct* tstruct) { indent(out) << "@Override" << endl; indent(out) << "protected void tupleSchemeWriteValue(org.apache.thrift.protocol.TProtocol oprot) " "throws org.apache.thrift.TException {" << endl; @@ -1235,7 +1322,7 @@ void t_java_generator::generate_tuple_scheme_write_value(ofstream& out, t_struct indent(out) << "}" << endl; } -void t_java_generator::generate_get_field_desc(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_get_field_desc(ostream& out, t_struct* tstruct) { indent(out) << "@Override" << endl; indent(out) << "protected org.apache.thrift.protocol.TField getFieldDesc(_Fields setField) {" << endl; @@ -1263,7 +1350,7 @@ void t_java_generator::generate_get_field_desc(ofstream& out, t_struct* tstruct) indent(out) << "}" << endl; } -void t_java_generator::generate_get_struct_desc(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_get_struct_desc(ostream& out, t_struct* tstruct) { (void)tstruct; indent(out) << "@Override" << endl; indent(out) << "protected org.apache.thrift.protocol.TStruct getStructDesc() {" << endl; @@ -1271,7 +1358,7 @@ void t_java_generator::generate_get_struct_desc(ofstream& out, t_struct* tstruct indent(out) << "}" << endl; } -void t_java_generator::generate_union_comparisons(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_union_comparisons(ostream& out, t_struct* tstruct) { // equality indent(out) << "public boolean equals(java.lang.Object other) {" << endl; indent(out) << " if (other instanceof " << tstruct->get_name() << ") {" << endl; @@ -1302,7 +1389,7 @@ void t_java_generator::generate_union_comparisons(ofstream& out, t_struct* tstru out << endl; } -void t_java_generator::generate_union_hashcode(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_union_hashcode(ostream& out, t_struct* tstruct) { (void)tstruct; indent(out) << "@Override" << endl; indent(out) << "public int hashCode() {" << endl; @@ -1332,7 +1419,7 @@ void t_java_generator::generate_union_hashcode(ofstream& out, t_struct* tstruct) * @param in_class If inside a class, needs to be static class * @param is_result If this is a result it needs a different writer */ -void t_java_generator::generate_java_struct_definition(ofstream& out, +void t_java_generator::generate_java_struct_definition(ostream& out, t_struct* tstruct, bool is_exception, bool in_class, @@ -1488,10 +1575,16 @@ void t_java_generator::generate_java_struct_definition(ofstream& out, for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { if ((*m_iter)->get_req() != t_field::T_OPTIONAL) { t_type* type = get_true_type((*m_iter)->get_type()); - if (type->is_base_type() && ((t_base_type*)type)->is_binary()) { - indent(out) << "this." << (*m_iter)->get_name() - << " = org.apache.thrift.TBaseHelper.copyBinary(" << (*m_iter)->get_name() - << ");" << endl; + if (type->is_binary()) { + if(unsafe_binaries_){ + indent(out) << "this." << (*m_iter)->get_name() + << " = " << (*m_iter)->get_name() + << ";" << endl; + }else{ + indent(out) << "this." << (*m_iter)->get_name() + << " = org.apache.thrift.TBaseHelper.copyBinary(" << (*m_iter)->get_name() + << ");" << endl; + } } else { indent(out) << "this." << (*m_iter)->get_name() << " = " << (*m_iter)->get_name() << ";" << endl; @@ -1591,7 +1684,7 @@ void t_java_generator::generate_java_struct_definition(ofstream& out, /** * generates parcelable interface implementation */ -void t_java_generator::generate_java_struct_parcelable(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_java_struct_parcelable(ostream& out, t_struct* tstruct) { string tname = tstruct->get_name(); const vector& members = tstruct->get_members(); @@ -1642,7 +1735,7 @@ void t_java_generator::generate_java_struct_parcelable(ofstream& out, t_struct* } else if (t->is_map()) { indent(out) << "out.writeMap(" << name << ");" << endl; } else if (t->is_base_type()) { - if (((t_base_type*)t)->is_binary()) { + if (t->is_binary()) { indent(out) << "out.writeInt(" << name << "!=null ? 1 : 0);" << endl; indent(out) << "if(" << name << " != null) { " << endl; indent_up(); @@ -1807,7 +1900,7 @@ void t_java_generator::generate_java_struct_parcelable(ofstream& out, t_struct* * * @param tstruct The struct definition */ -void t_java_generator::generate_java_struct_equality(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_java_struct_equality(ostream& out, t_struct* tstruct) { out << indent() << "@Override" << endl << indent() << "public boolean equals(java.lang.Object that) {" << endl; indent_up(); @@ -1853,7 +1946,7 @@ void t_java_generator::generate_java_struct_equality(ofstream& out, t_struct* ts << "this_present_" << name << " && that_present_" << name << "))" << endl << indent() << " return false;" << endl; - if (t->is_base_type() && ((t_base_type*)t)->is_binary()) { + if (t->is_binary()) { unequal = "!this." + name + ".equals(that." + name + ")"; } else if (can_be_null) { unequal = "!this." + name + ".equals(that." + name + ")"; @@ -1938,7 +2031,7 @@ void t_java_generator::generate_java_struct_equality(ofstream& out, t_struct* ts indent(out) << "}" << endl << endl; } -void t_java_generator::generate_java_struct_compare_to(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_java_struct_compare_to(ostream& out, t_struct* tstruct) { indent(out) << "@Override" << endl; indent(out) << "public int compareTo(" << type_name(tstruct) << " other) {" << endl; indent_up(); @@ -1981,7 +2074,7 @@ void t_java_generator::generate_java_struct_compare_to(ofstream& out, t_struct* * * @param tstruct The struct definition */ -void t_java_generator::generate_java_struct_reader(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_java_struct_reader(ostream& out, t_struct* tstruct) { (void)tstruct; indent(out) << "public void read(org.apache.thrift.protocol.TProtocol iprot) throws " "org.apache.thrift.TException {" << endl; @@ -1993,7 +2086,7 @@ void t_java_generator::generate_java_struct_reader(ofstream& out, t_struct* tstr // generates java method to perform various checks // (e.g. check that all required fields are set) -void t_java_generator::generate_java_validator(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_java_validator(ostream& out, t_struct* tstruct) { indent(out) << "public void validate() throws org.apache.thrift.TException {" << endl; indent_up(); @@ -2043,7 +2136,7 @@ void t_java_generator::generate_java_validator(ofstream& out, t_struct* tstruct) * * @param tstruct The struct definition */ -void t_java_generator::generate_java_struct_writer(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_java_struct_writer(ostream& out, t_struct* tstruct) { (void)tstruct; indent(out) << "public void write(org.apache.thrift.protocol.TProtocol oprot) throws " "org.apache.thrift.TException {" << endl; @@ -2062,7 +2155,7 @@ void t_java_generator::generate_java_struct_writer(ofstream& out, t_struct* tstr * * @param tstruct The struct definition */ -void t_java_generator::generate_java_struct_result_writer(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_java_struct_result_writer(ostream& out, t_struct* tstruct) { (void)tstruct; indent(out) << "public void write(org.apache.thrift.protocol.TProtocol oprot) throws " "org.apache.thrift.TException {" << endl; @@ -2073,8 +2166,9 @@ void t_java_generator::generate_java_struct_result_writer(ofstream& out, t_struc indent(out) << " }" << endl << endl; } -void t_java_generator::generate_java_struct_field_by_id(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_java_struct_field_by_id(ostream& out, t_struct* tstruct) { (void)tstruct; + indent(out) << java_nullable_annotation() << endl; indent(out) << "public _Fields fieldForId(int fieldId) {" << endl; indent(out) << " return _Fields.findByThriftId(fieldId);" << endl; indent(out) << "}" << endl << endl; @@ -2094,7 +2188,7 @@ void t_java_generator::generate_reflection_setters(ostringstream& out, t_type* type, string field_name, string cap_name) { - const bool is_binary = type->is_base_type() && ((t_base_type*)type)->is_binary(); + const bool is_binary = type->is_binary(); indent(out) << "case " << constant_name(field_name) << ":" << endl; indent_up(); indent(out) << "if (value == null) {" << endl; @@ -2117,7 +2211,7 @@ void t_java_generator::generate_reflection_setters(ostringstream& out, indent_down(); } -void t_java_generator::generate_generic_field_getters_setters(std::ofstream& out, +void t_java_generator::generate_generic_field_getters_setters(std::ostream& out, t_struct* tstruct) { std::ostringstream getter_stream; std::ostringstream setter_stream; @@ -2139,13 +2233,15 @@ void t_java_generator::generate_generic_field_getters_setters(std::ofstream& out // create the setter - indent(out) << "public void setFieldValue(_Fields field, java.lang.Object value) {" << endl; + indent(out) << "public void setFieldValue(_Fields field, " << java_nullable_annotation() + << " java.lang.Object value) {" << endl; indent(out) << " switch (field) {" << endl; out << setter_stream.str(); indent(out) << " }" << endl; indent(out) << "}" << endl << endl; // create the getter + indent(out) << java_nullable_annotation() << endl; indent(out) << "public java.lang.Object getFieldValue(_Fields field) {" << endl; indent_up(); indent(out) << "switch (field) {" << endl; @@ -2157,7 +2253,7 @@ void t_java_generator::generate_generic_field_getters_setters(std::ofstream& out } // Creates a generic isSet method that takes the field number as argument -void t_java_generator::generate_generic_isset_method(std::ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_generic_isset_method(std::ostream& out, t_struct* tstruct) { const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; @@ -2192,7 +2288,7 @@ void t_java_generator::generate_generic_isset_method(std::ofstream& out, t_struc * * @param tstruct The struct definition */ -void t_java_generator::generate_java_bean_boilerplate(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_java_bean_boilerplate(ostream& out, t_struct* tstruct) { isset_type issetType = needs_isset(tstruct); const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; @@ -2273,6 +2369,7 @@ void t_java_generator::generate_java_bean_boilerplate(ofstream& out, t_struct* t if (is_deprecated) { indent(out) << "@Deprecated" << endl; } + indent(out) << java_nullable_annotation() << endl; indent(out) << "public java.util.Iterator<" << type_name(element_type, true, false) << "> get" << cap_name; out << get_cap_name("iterator() {") << endl; @@ -2294,8 +2391,12 @@ void t_java_generator::generate_java_bean_boilerplate(ofstream& out, t_struct* t indent_up(); indent(out) << "if (this." << field_name << " == null) {" << endl; indent_up(); - indent(out) << "this." << field_name << " = new " << type_name(type, false, true) << "();" - << endl; + indent(out) << "this." << field_name; + if (is_enum_set(type)) { + out << " = " << type_name(type, false, true, true) << ".noneOf(" << inner_enum_type_name(type) << ");" << endl; + } else { + out << " = new " << type_name(type, false, true) << "();" << endl; + } indent_down(); indent(out) << "}" << endl; indent(out) << "this." << field_name << ".add(elem);" << endl; @@ -2316,7 +2417,11 @@ void t_java_generator::generate_java_bean_boilerplate(ofstream& out, t_struct* t indent_up(); indent(out) << "if (this." << field_name << " == null) {" << endl; indent_up(); - indent(out) << "this." << field_name << " = new " << type_name(type, false, true) << "();" + std::string constructor_args; + if (is_enum_map(type)) { + constructor_args = inner_enum_type_name(type); + } + indent(out) << "this." << field_name << " = new " << type_name(type, false, true) << "(" << constructor_args << ");" << endl; indent_down(); indent(out) << "}" << endl; @@ -2327,7 +2432,7 @@ void t_java_generator::generate_java_bean_boilerplate(ofstream& out, t_struct* t // Simple getter generate_java_doc(out, field); - if (type->is_base_type() && ((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { if (is_deprecated) { indent(out) << "@Deprecated" << endl; } @@ -2340,8 +2445,13 @@ void t_java_generator::generate_java_bean_boilerplate(ofstream& out, t_struct* t indent(out) << "public java.nio.ByteBuffer buffer" << get_cap_name("for") << cap_name << "() {" << endl; - indent(out) << " return org.apache.thrift.TBaseHelper.copyBinary(" << field_name << ");" - << endl; + if(unsafe_binaries_){ + indent(out) << " return " << field_name << ";" + << endl; + }else { + indent(out) << " return org.apache.thrift.TBaseHelper.copyBinary(" << field_name << ");" + << endl; + } indent(out) << "}" << endl << endl; } else { if (optional) { @@ -2372,6 +2482,9 @@ void t_java_generator::generate_java_bean_boilerplate(ofstream& out, t_struct* t if (is_deprecated) { indent(out) << "@Deprecated" << endl; } + if (type_can_be_null(type)) { + indent(out) << java_nullable_annotation() << endl; + } indent(out) << "public " << type_name(type); if (type->is_base_type() && ((t_base_type*)type)->get_base() == t_base_type::TYPE_BOOL) { out << " is"; @@ -2388,7 +2501,7 @@ void t_java_generator::generate_java_bean_boilerplate(ofstream& out, t_struct* t // Simple setter generate_java_doc(out, field); - if (type->is_base_type() && ((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { if (is_deprecated) { indent(out) << "@Deprecated" << endl; } @@ -2399,8 +2512,14 @@ void t_java_generator::generate_java_bean_boilerplate(ofstream& out, t_struct* t out << type_name(tstruct); } out << " set" << cap_name << "(byte[] " << field_name << ") {" << endl; - indent(out) << " this." << field_name << " = " << field_name << " == null ? (java.nio.ByteBuffer)null" - << " : java.nio.ByteBuffer.wrap(" << field_name << ".clone());" << endl; + indent(out) << " this." << field_name << " = " << field_name << " == null ? (java.nio.ByteBuffer)null"; + + if(unsafe_binaries_){ + indent(out) << " : java.nio.ByteBuffer.wrap(" << field_name << ");" << endl; + }else{ + indent(out) << " : java.nio.ByteBuffer.wrap(" << field_name << ".clone());" << endl; + } + if (!bean_style_) { indent(out) << " return this;" << endl; } @@ -2415,10 +2534,11 @@ void t_java_generator::generate_java_bean_boilerplate(ofstream& out, t_struct* t } else { out << type_name(tstruct); } - out << " set" << cap_name << "(" << type_name(type) << " " << field_name << ") {" << endl; + out << " set" << cap_name << "(" << (type_can_be_null(type) ? (java_nullable_annotation() + " ") : "") + << type_name(type) << " " << field_name << ") {" << endl; indent_up(); indent(out) << "this." << field_name << " = "; - if (type->is_base_type() && ((t_base_type*)type)->is_binary()) { + if (type->is_binary() && !unsafe_binaries_) { out << "org.apache.thrift.TBaseHelper.copyBinary(" << field_name << ")"; } else { out << field_name; @@ -2494,7 +2614,7 @@ void t_java_generator::generate_java_bean_boilerplate(ofstream& out, t_struct* t * * @param tstruct The struct definition */ -void t_java_generator::generate_java_struct_tostring(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_java_struct_tostring(ostream& out, t_struct* tstruct) { out << indent() << "@Override" << endl << indent() << "public java.lang.String toString() {" << endl; indent_up(); @@ -2526,20 +2646,15 @@ void t_java_generator::generate_java_struct_tostring(ofstream& out, t_struct* ts indent_up(); } - if (get_true_type(field->get_type())->is_base_type() - && ((t_base_type*)(get_true_type(field->get_type())))->is_binary()) { + if (get_true_type(field->get_type())->is_binary()) { indent(out) << "org.apache.thrift.TBaseHelper.toString(this." << field->get_name() << ", sb);" << endl; } else if ((field->get_type()->is_set()) - && (get_true_type(((t_set*)field->get_type())->get_elem_type())->is_base_type()) - && (((t_base_type*)get_true_type(((t_set*)field->get_type())->get_elem_type())) - ->is_binary())) { + && (get_true_type(((t_set*)field->get_type())->get_elem_type())->is_binary())) { indent(out) << "org.apache.thrift.TBaseHelper.toString(this." << field->get_name() << ", sb);" << endl; } else if ((field->get_type()->is_list()) - && (get_true_type(((t_list*)field->get_type())->get_elem_type())->is_base_type()) - && (((t_base_type*)get_true_type(((t_list*)field->get_type())->get_elem_type())) - ->is_binary())) { + && (get_true_type(((t_list*)field->get_type())->get_elem_type())->is_binary())) { indent(out) << "org.apache.thrift.TBaseHelper.toString(this." << field->get_name() << ", sb);" << endl; } else { @@ -2570,7 +2685,7 @@ void t_java_generator::generate_java_struct_tostring(ofstream& out, t_struct* ts * * @param tstruct The struct definition */ -void t_java_generator::generate_java_meta_data_map(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_java_meta_data_map(ostream& out, t_struct* tstruct) { const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; @@ -2667,13 +2782,11 @@ std::string t_java_generator::get_java_type_string(t_type* type) { } else { throw std::runtime_error("Unknown thrift type \"" + type->get_name() + "\" passed to t_java_generator::get_java_type_string!"); - return "Unknown thrift type \"" + type->get_name() - + "\" passed to t_java_generator::get_java_type_string!"; // This should never happen! } } -void t_java_generator::generate_field_value_meta_data(std::ofstream& out, t_type* type) { +void t_java_generator::generate_field_value_meta_data(std::ostream& out, t_type* type) { out << endl; indent_up(); indent_up(); @@ -2690,7 +2803,7 @@ void t_java_generator::generate_field_value_meta_data(std::ofstream& out, t_type } else if (type->is_set()) { indent(out) << "new org.apache.thrift.meta_data.SetMetaData(org.apache.thrift.protocol.TType.SET, "; - t_type* elem_type = ((t_list*)type)->get_elem_type(); + t_type* elem_type = ((t_set*)type)->get_elem_type(); generate_field_value_meta_data(out, elem_type); } else { // map indent(out) @@ -2710,7 +2823,7 @@ void t_java_generator::generate_field_value_meta_data(std::ofstream& out, t_type << get_java_type_string(type); if (type->is_typedef()) { indent(out) << ", \"" << ((t_typedef*)type)->get_symbolic() << "\""; - } else if (((t_base_type*)type)->is_binary()) { + } else if (type->is_binary()) { indent(out) << ", true"; } } @@ -3531,6 +3644,11 @@ void t_java_generator::generate_process_function(t_service* tservice, t_function indent(f_service_) << " return " << ((tfunction->is_oneway()) ? "true" : "false") << ";" << endl; indent(f_service_) << "}" << endl << endl; + indent(f_service_) << "@Override" << endl; + indent(f_service_) << "protected boolean rethrowUnhandledExceptions() {" << endl; + indent(f_service_) << " return " << ((rethrow_unhandled_exceptions_) ? "true" : "false") << ";" << endl; + indent(f_service_) << "}" << endl << endl; + indent(f_service_) << "public " << resultname << " getResult(I iface, " << argsname << " args) throws org.apache.thrift.TException {" << endl; indent_up(); @@ -3617,7 +3735,7 @@ void t_java_generator::generate_process_function(t_service* tservice, t_function * @param tfield The field * @param prefix The variable name or container for this field */ -void t_java_generator::generate_deserialize_field(ofstream& out, +void t_java_generator::generate_deserialize_field(ostream& out, t_field* tfield, string prefix, bool has_metadata) { @@ -3642,7 +3760,7 @@ void t_java_generator::generate_deserialize_field(ofstream& out, throw "compiler error: cannot serialize void field in a struct: " + name; break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { out << "readBinary();"; } else { out << "readString();"; @@ -3684,7 +3802,7 @@ void t_java_generator::generate_deserialize_field(ofstream& out, /** * Generates an unserializer for a struct, invokes read() */ -void t_java_generator::generate_deserialize_struct(ofstream& out, +void t_java_generator::generate_deserialize_struct(ostream& out, t_struct* tstruct, string prefix) { @@ -3703,7 +3821,7 @@ void t_java_generator::generate_deserialize_struct(ofstream& out, /** * Deserializes a container by reading its size and then iterating */ -void t_java_generator::generate_deserialize_container(ofstream& out, +void t_java_generator::generate_deserialize_container(ostream& out, t_type* ttype, string prefix, bool has_metadata) { @@ -3748,7 +3866,7 @@ void t_java_generator::generate_deserialize_container(ofstream& out, } else if (ttype->is_list()) { indent(out) << "org.apache.thrift.protocol.TList " << obj << " = new org.apache.thrift.protocol.TList(" - << type_to_enum(((t_set*)ttype)->get_elem_type()) << ", iprot.readI32());" + << type_to_enum(((t_list*)ttype)->get_elem_type()) << ", iprot.readI32());" << endl; } } @@ -3758,11 +3876,17 @@ void t_java_generator::generate_deserialize_container(ofstream& out, indent_up(); } - out << indent() << prefix << " = new " << type_name(ttype, false, true); + if (is_enum_set(ttype)) { + out << indent() << prefix << " = " << type_name(ttype, false, true, true) << ".noneOf"; + } else { + out << indent() << prefix << " = new " << type_name(ttype, false, true); + } - // size the collection correctly - if (sorted_containers_ && (ttype->is_map() || ttype->is_set())) { - // TreeSet and TreeMap don't have any constructor which takes a capactity as an argument + // construct the collection correctly i.e. with appropriate size/type + if (is_enum_set(ttype) || is_enum_map(ttype)) { + out << "(" << inner_enum_type_name(ttype) << ");" << endl; + } else if (sorted_containers_ && (ttype->is_map() || ttype->is_set())) { + // TreeSet and TreeMap don't have any constructor which takes a capacity as an argument out << "();" << endl; } else { out << "(" << (ttype->is_list() ? "" : "2*") << obj << ".size" @@ -3800,7 +3924,7 @@ void t_java_generator::generate_deserialize_container(ofstream& out, /** * Generates code to deserialize a map */ -void t_java_generator::generate_deserialize_map_element(ofstream& out, +void t_java_generator::generate_deserialize_map_element(ostream& out, t_map* tmap, string prefix, string obj, @@ -3824,8 +3948,17 @@ void t_java_generator::generate_deserialize_map_element(ofstream& out, generate_deserialize_field(out, &fkey, "", has_metadata); generate_deserialize_field(out, &fval, "", has_metadata); + if (get_true_type(fkey.get_type())->is_enum()) { + indent(out) << "if (" << key << " != null)" << endl; + scope_up(out); + } + indent(out) << prefix << ".put(" << key << ", " << val << ");" << endl; + if (get_true_type(fkey.get_type())->is_enum()) { + scope_down(out); + } + if (reuse_objects_ && !get_true_type(fkey.get_type())->is_base_type()) { indent(out) << key << " = null;" << endl; } @@ -3838,7 +3971,7 @@ void t_java_generator::generate_deserialize_map_element(ofstream& out, /** * Deserializes a set element */ -void t_java_generator::generate_deserialize_set_element(ofstream& out, +void t_java_generator::generate_deserialize_set_element(ostream& out, t_set* tset, string prefix, string obj, @@ -3857,8 +3990,17 @@ void t_java_generator::generate_deserialize_set_element(ofstream& out, generate_deserialize_field(out, &felem, "", has_metadata); + if (get_true_type(felem.get_type())->is_enum()) { + indent(out) << "if (" << elem << " != null)" << endl; + scope_up(out); + } + indent(out) << prefix << ".add(" << elem << ");" << endl; + if (get_true_type(felem.get_type())->is_enum()) { + scope_down(out); + } + if (reuse_objects_ && !get_true_type(felem.get_type())->is_base_type()) { indent(out) << elem << " = null;" << endl; } @@ -3867,7 +4009,7 @@ void t_java_generator::generate_deserialize_set_element(ofstream& out, /** * Deserializes a list element */ -void t_java_generator::generate_deserialize_list_element(ofstream& out, +void t_java_generator::generate_deserialize_list_element(ostream& out, t_list* tlist, string prefix, string obj, @@ -3886,8 +4028,17 @@ void t_java_generator::generate_deserialize_list_element(ofstream& out, generate_deserialize_field(out, &felem, "", has_metadata); + if (get_true_type(felem.get_type())->is_enum()) { + indent(out) << "if (" << elem << " != null)" << endl; + scope_up(out); + } + indent(out) << prefix << ".add(" << elem << ");" << endl; + if (get_true_type(felem.get_type())->is_enum()) { + scope_down(out); + } + if (reuse_objects_ && !get_true_type(felem.get_type())->is_base_type()) { indent(out) << elem << " = null;" << endl; } @@ -3899,7 +4050,7 @@ void t_java_generator::generate_deserialize_list_element(ofstream& out, * @param tfield The field to serialize * @param prefix Name to prepend to field name */ -void t_java_generator::generate_serialize_field(ofstream& out, +void t_java_generator::generate_serialize_field(ostream& out, t_field* tfield, string prefix, bool has_metadata) { @@ -3927,7 +4078,7 @@ void t_java_generator::generate_serialize_field(ofstream& out, throw "compiler error: cannot serialize void field in a struct: " + name; break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { out << "writeBinary(" << name << ");"; } else { out << "writeString(" << name << ");"; @@ -3972,7 +4123,7 @@ void t_java_generator::generate_serialize_field(ofstream& out, * @param tstruct The struct to serialize * @param prefix String prefix to attach to all fields */ -void t_java_generator::generate_serialize_struct(ofstream& out, t_struct* tstruct, string prefix) { +void t_java_generator::generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix) { (void)tstruct; out << indent() << prefix << ".write(oprot);" << endl; } @@ -3983,7 +4134,7 @@ void t_java_generator::generate_serialize_struct(ofstream& out, t_struct* tstruc * @param ttype The type of container * @param prefix String prefix for fields */ -void t_java_generator::generate_serialize_container(ofstream& out, +void t_java_generator::generate_serialize_container(ostream& out, t_type* ttype, string prefix, bool has_metadata) { @@ -4048,7 +4199,7 @@ void t_java_generator::generate_serialize_container(ofstream& out, /** * Serializes the members of a map. */ -void t_java_generator::generate_serialize_map_element(ofstream& out, +void t_java_generator::generate_serialize_map_element(ostream& out, t_map* tmap, string iter, string map, @@ -4063,7 +4214,7 @@ void t_java_generator::generate_serialize_map_element(ofstream& out, /** * Serializes the members of a set. */ -void t_java_generator::generate_serialize_set_element(ofstream& out, +void t_java_generator::generate_serialize_set_element(ostream& out, t_set* tset, string iter, bool has_metadata) { @@ -4074,7 +4225,7 @@ void t_java_generator::generate_serialize_set_element(ofstream& out, /** * Serializes the members of a list. */ -void t_java_generator::generate_serialize_list_element(ofstream& out, +void t_java_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string iter, bool has_metadata) { @@ -4103,7 +4254,9 @@ string t_java_generator::type_name(t_type* ttype, } else if (ttype->is_map()) { t_map* tmap = (t_map*)ttype; if (in_init) { - if (sorted_containers_) { + if (is_enum_map(tmap)) { + prefix = "java.util.EnumMap"; + } else if (sorted_containers_) { prefix = "java.util.TreeMap"; } else { prefix = "java.util.HashMap"; @@ -4116,7 +4269,9 @@ string t_java_generator::type_name(t_type* ttype, } else if (ttype->is_set()) { t_set* tset = (t_set*)ttype; if (in_init) { - if (sorted_containers_) { + if (is_enum_set(tset)) { + prefix = "java.util.EnumSet"; + } else if (sorted_containers_) { prefix = "java.util.TreeSet"; } else { prefix = "java.util.HashSet"; @@ -4190,11 +4345,15 @@ string t_java_generator::base_type_name(t_base_type* type, bool in_container) { */ string t_java_generator::declare_field(t_field* tfield, bool init, bool comment) { // TODO(mcslee): do we ever need to initialize the field? - string result = type_name(tfield->get_type()) + " " + tfield->get_name(); + string result = ""; + t_type* ttype = get_true_type(tfield->get_type()); + if (type_can_be_null(ttype)) { + result += java_nullable_annotation() + " "; + } + result += type_name(tfield->get_type()) + " " + tfield->get_name(); if (init) { - t_type* ttype = get_true_type(tfield->get_type()); if (ttype->is_base_type() && tfield->get_value() != NULL) { - ofstream dummy; + std::ofstream dummy; result += " = " + render_const_value(dummy, ttype, tfield->get_value()); } else if (ttype->is_base_type()) { t_base_type::t_base tbase = ((t_base_type*)ttype)->get_base(); @@ -4510,7 +4669,7 @@ string t_java_generator::constant_name(string name) { return constant_name; } -void t_java_generator::generate_deep_copy_container(ofstream& out, +void t_java_generator::generate_deep_copy_container(ostream& out, std::string source_name_p1, std::string source_name_p2, std::string result_name, @@ -4542,13 +4701,21 @@ void t_java_generator::generate_deep_copy_container(ofstream& out, return; } - std::string capacity; - if (!(sorted_containers_ && (container->is_map() || container->is_set()))) { + std::string constructor_args; + if (is_enum_set(container) || is_enum_map(container)) { + constructor_args = inner_enum_type_name(container); + } else if (!(sorted_containers_ && (container->is_map() || container->is_set()))) { // unsorted containers accept a capacity value - capacity = source_name + ".size()"; + constructor_args = source_name + ".size()"; + } + + if (is_enum_set(container)) { + indent(out) << type_name(type, true, false) << " " << result_name << " = " + << type_name(container, false, true, true) << ".noneOf(" << constructor_args << ");" << endl; + } else { + indent(out) << type_name(type, true, false) << " " << result_name << " = new " + << type_name(container, false, true) << "(" << constructor_args << ");" << endl; } - indent(out) << type_name(type, true, false) << " " << result_name << " = new " - << type_name(container, false, true) << "(" << capacity << ");" << endl; std::string iterator_element_name = source_name_p1 + "_element"; std::string result_element_name = result_name + "_copy"; @@ -4631,7 +4798,7 @@ void t_java_generator::generate_deep_copy_container(ofstream& out, indent(out) << result_name << ".add(" << result_element_name << ");" << endl; } else { // iterative copy - if (((t_base_type*)elem_type)->is_binary()) { + if (elem_type->is_binary()) { indent(out) << "java.nio.ByteBuffer temp_binary_element = "; generate_deep_copy_non_container(out, iterator_element_name, @@ -4652,13 +4819,14 @@ void t_java_generator::generate_deep_copy_container(ofstream& out, } } -void t_java_generator::generate_deep_copy_non_container(ofstream& out, +void t_java_generator::generate_deep_copy_non_container(ostream& out, std::string source_name, std::string dest_name, t_type* type) { (void)dest_name; + type = get_true_type(type); if (type->is_base_type() || type->is_enum() || type->is_typedef()) { - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { out << "org.apache.thrift.TBaseHelper.copyBinary(" << source_name << ")"; } else { // everything else can be copied directly @@ -4681,19 +4849,19 @@ std::string t_java_generator::generate_isset_check(std::string field_name) { return "is" + get_cap_name("set") + get_cap_name(field_name) + "()"; } -void t_java_generator::generate_isset_set(ofstream& out, t_field* field, string prefix) { +void t_java_generator::generate_isset_set(ostream& out, t_field* field, string prefix) { if (!type_can_be_null(field->get_type())) { indent(out) << prefix << "set" << get_cap_name(field->get_name()) << get_cap_name("isSet") << "(true);" << endl; } } -void t_java_generator::generate_struct_desc(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_struct_desc(ostream& out, t_struct* tstruct) { indent(out) << "private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new " "org.apache.thrift.protocol.TStruct(\"" << tstruct->get_name() << "\");" << endl; } -void t_java_generator::generate_field_descs(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_field_descs(ostream& out, t_struct* tstruct) { const vector& members = tstruct->get_members(); vector::const_iterator m_iter; @@ -4706,14 +4874,14 @@ void t_java_generator::generate_field_descs(ofstream& out, t_struct* tstruct) { } } -void t_java_generator::generate_scheme_map(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_scheme_map(ostream& out, t_struct* tstruct) { indent(out) << "private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new " << tstruct->get_name() << "StandardSchemeFactory();" << endl; indent(out) << "private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new " << tstruct->get_name() << "TupleSchemeFactory();" << endl; } -void t_java_generator::generate_field_name_constants(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_field_name_constants(ostream& out, t_struct* tstruct) { indent(out) << "/** The set of fields this struct contains, along with convenience methods for " "finding and manipulating them. */" << endl; indent(out) << "public enum _Fields implements org.apache.thrift.TFieldIdEnum {" << endl; @@ -4749,6 +4917,7 @@ void t_java_generator::generate_field_name_constants(ofstream& out, t_struct* ts indent(out) << " * Find the _Fields constant that matches fieldId, or null if its not found." << endl; indent(out) << " */" << endl; + indent(out) << java_nullable_annotation() << endl; indent(out) << "public static _Fields findByThriftId(int fieldId) {" << endl; indent_up(); indent(out) << "switch(fieldId) {" << endl; @@ -4784,6 +4953,7 @@ void t_java_generator::generate_field_name_constants(ofstream& out, t_struct* ts indent(out) << " * Find the _Fields constant that matches name, or null if its not found." << endl; indent(out) << " */" << endl; + indent(out) << java_nullable_annotation() << endl; indent(out) << "public static _Fields findByName(java.lang.String name) {" << endl; indent(out) << " return byName.get(name);" << endl; indent(out) << "}" << endl << endl; @@ -4839,7 +5009,7 @@ t_java_generator::isset_type t_java_generator::needs_isset(t_struct* tstruct, } } -void t_java_generator::generate_java_struct_clear(std::ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_java_struct_clear(std::ostream& out, t_struct* tstruct) { if (!java5_) { indent(out) << "@Override" << endl; } @@ -4903,7 +5073,7 @@ void t_java_generator::generate_java_struct_clear(std::ofstream& out, t_struct* } // generates java method to serialize (in the Java sense) the object -void t_java_generator::generate_java_struct_write_object(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_java_struct_write_object(ostream& out, t_struct* tstruct) { (void)tstruct; indent(out) << "private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {" @@ -4919,7 +5089,7 @@ void t_java_generator::generate_java_struct_write_object(ofstream& out, t_struct } // generates java method to serialize (in the Java sense) the object -void t_java_generator::generate_java_struct_read_object(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_java_struct_read_object(ostream& out, t_struct* tstruct) { indent(out) << "private void readObject(java.io.ObjectInputStream in) throws " "java.io.IOException, java.lang.ClassNotFoundException {" << endl; indent(out) << " try {" << endl; @@ -4948,7 +5118,7 @@ void t_java_generator::generate_java_struct_read_object(ofstream& out, t_struct* indent(out) << "}" << endl << endl; } -void t_java_generator::generate_standard_reader(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_standard_reader(ostream& out, t_struct* tstruct) { out << indent() << "public void read(org.apache.thrift.protocol.TProtocol iprot, " << tstruct->get_name() << " struct) throws org.apache.thrift.TException {" << endl; indent_up(); @@ -5038,7 +5208,7 @@ void t_java_generator::generate_standard_reader(ofstream& out, t_struct* tstruct out << indent() << "}" << endl; } -void t_java_generator::generate_standard_writer(ofstream& out, t_struct* tstruct, bool is_result) { +void t_java_generator::generate_standard_writer(ostream& out, t_struct* tstruct, bool is_result) { indent_up(); out << indent() << "public void write(org.apache.thrift.protocol.TProtocol oprot, " << tstruct->get_name() << " struct) throws org.apache.thrift.TException {" << endl; @@ -5091,7 +5261,7 @@ void t_java_generator::generate_standard_writer(ofstream& out, t_struct* tstruct indent_down(); } -void t_java_generator::generate_java_struct_standard_scheme(ofstream& out, +void t_java_generator::generate_java_struct_standard_scheme(ostream& out, t_struct* tstruct, bool is_result) { indent(out) << "private static class " << tstruct->get_name() @@ -5116,7 +5286,7 @@ void t_java_generator::generate_java_struct_standard_scheme(ofstream& out, out << indent() << "}" << endl << endl; } -void t_java_generator::generate_java_struct_tuple_reader(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_java_struct_tuple_reader(ostream& out, t_struct* tstruct) { indent(out) << "@Override" << endl; indent(out) << "public void read(org.apache.thrift.protocol.TProtocol prot, " << tstruct->get_name() << " struct) throws org.apache.thrift.TException {" << endl; @@ -5157,7 +5327,7 @@ void t_java_generator::generate_java_struct_tuple_reader(ofstream& out, t_struct indent(out) << "}" << endl; } -void t_java_generator::generate_java_struct_tuple_writer(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_java_struct_tuple_writer(ostream& out, t_struct* tstruct) { indent(out) << "@Override" << endl; indent(out) << "public void write(org.apache.thrift.protocol.TProtocol prot, " << tstruct->get_name() << " struct) throws org.apache.thrift.TException {" << endl; @@ -5211,7 +5381,7 @@ void t_java_generator::generate_java_struct_tuple_writer(ofstream& out, t_struct indent(out) << "}" << endl; } -void t_java_generator::generate_java_struct_tuple_scheme(ofstream& out, t_struct* tstruct) { +void t_java_generator::generate_java_struct_tuple_scheme(ostream& out, t_struct* tstruct) { indent(out) << "private static class " << tstruct->get_name() << "TupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {" << endl; indent_up(); @@ -5232,7 +5402,7 @@ void t_java_generator::generate_java_struct_tuple_scheme(ofstream& out, t_struct out << indent() << "}" << endl << endl; } -void t_java_generator::generate_java_scheme_lookup(ofstream& out) { +void t_java_generator::generate_java_scheme_lookup(ostream& out) { indent(out) << "private static S scheme(" << "org.apache.thrift.protocol.TProtocol proto) {" << endl; indent_up(); @@ -5244,7 +5414,7 @@ void t_java_generator::generate_java_scheme_lookup(ofstream& out) { indent(out) << "}" << endl; } -void t_java_generator::generate_javax_generated_annotation(ofstream& out) { +void t_java_generator::generate_javax_generated_annotation(ostream& out) { time_t seconds = time(NULL); struct tm* now = localtime(&seconds); indent(out) << "@javax.annotation.Generated(value = \"" << autogen_summary() << "\""; @@ -5269,6 +5439,9 @@ THRIFT_REGISTER_GENERATOR( " android_legacy: Do not use java.io.IOException(throwable) (available for Android 2.3 and " "above).\n" " option_type: Wrap optional fields in an Option type.\n" + " rethrow_unhandled_exceptions:\n" + " Enable rethrow of unhandled exceptions and let them propagate futher." + " (Default behavior is to catch and log it.)\n" " java5: Generate Java 1.5 compliant code (includes android_legacy flag).\n" " reuse-objects: Data objects will not be allocated, but existing instances will be used " "(read and write).\n" @@ -5277,4 +5450,5 @@ THRIFT_REGISTER_GENERATOR( "set/map.\n" " generated_annotations=[undated|suppress]:\n" " undated: suppress the date at @Generated annotations\n" - " suppress: suppress @Generated annotations entirely\n") + " suppress: suppress @Generated annotations entirely\n" + " unsafe_binaries: Do not copy ByteBuffers in constructors, getters, and setters.\n") diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_javame_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_javame_generator.cc index 94d66fc..fa743ca 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_javame_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_javame_generator.cc @@ -31,7 +31,7 @@ #include "thrift/generate/t_oop_generator.h" using std::map; -using std::ofstream; +using std::ostream; using std::ostringstream; using std::string; using std::stringstream; @@ -81,13 +81,13 @@ public: void generate_xception(t_struct* txception); void generate_service(t_service* tservice); - void print_const_value(std::ofstream& out, + void print_const_value(std::ostream& out, std::string name, t_type* type, t_const_value* value, bool in_static, bool defval = false); - std::string render_const_value(std::ofstream& out, + std::string render_const_value(std::ostream& out, std::string name, t_type* type, t_const_value* value); @@ -98,20 +98,20 @@ public: void generate_java_struct(t_struct* tstruct, bool is_exception); - void generate_java_struct_definition(std::ofstream& out, + void generate_java_struct_definition(std::ostream& out, t_struct* tstruct, bool is_xception = false, bool in_class = false, bool is_result = false); - void generate_java_struct_equality(std::ofstream& out, t_struct* tstruct); - void generate_java_struct_compare_to(std::ofstream& out, t_struct* tstruct); - void generate_java_struct_reader(std::ofstream& out, t_struct* tstruct); - void generate_java_validator(std::ofstream& out, t_struct* tstruct); - void generate_java_struct_result_writer(std::ofstream& out, t_struct* tstruct); - void generate_java_struct_writer(std::ofstream& out, t_struct* tstruct); - void generate_java_struct_tostring(std::ofstream& out, t_struct* tstruct); - void generate_java_struct_clear(std::ofstream& out, t_struct* tstruct); - void generate_field_value_meta_data(std::ofstream& out, t_type* type); + void generate_java_struct_equality(std::ostream& out, t_struct* tstruct); + void generate_java_struct_compare_to(std::ostream& out, t_struct* tstruct); + void generate_java_struct_reader(std::ostream& out, t_struct* tstruct); + void generate_java_validator(std::ostream& out, t_struct* tstruct); + void generate_java_struct_result_writer(std::ostream& out, t_struct* tstruct); + void generate_java_struct_writer(std::ostream& out, t_struct* tstruct); + void generate_java_struct_tostring(std::ostream& out, t_struct* tstruct); + void generate_java_struct_clear(std::ostream& out, t_struct* tstruct); + void generate_field_value_meta_data(std::ostream& out, t_type* type); std::string get_java_type_string(t_type* type); void generate_reflection_setters(std::ostringstream& out, t_type* type, @@ -121,14 +121,14 @@ public: t_type* type, std::string field_name, std::string cap_name); - void generate_generic_field_getters_setters(std::ofstream& out, t_struct* tstruct); - void generate_java_bean_boilerplate(std::ofstream& out, t_struct* tstruct); + void generate_generic_field_getters_setters(std::ostream& out, t_struct* tstruct); + void generate_java_bean_boilerplate(std::ostream& out, t_struct* tstruct); void generate_function_helpers(t_function* tfunction); std::string get_cap_name(std::string name); std::string generate_isset_check(t_field* field); std::string generate_isset_check(std::string field); - void generate_isset_set(ofstream& out, t_field* field); + void generate_isset_set(ostream& out, t_field* field); std::string isset_field_id(t_field* field); void generate_primitive_service_interface(t_service* tservice); @@ -139,66 +139,66 @@ public: void generate_process_function(t_service* tservice, t_function* tfunction); void generate_java_union(t_struct* tstruct); - void generate_union_constructor(ofstream& out, t_struct* tstruct); - void generate_union_getters_and_setters(ofstream& out, t_struct* tstruct); - void generate_union_abstract_methods(ofstream& out, t_struct* tstruct); - void generate_check_type(ofstream& out, t_struct* tstruct); - void generate_read_value(ofstream& out, t_struct* tstruct); - void generate_write_value(ofstream& out, t_struct* tstruct); - void generate_get_field_desc(ofstream& out, t_struct* tstruct); - void generate_get_struct_desc(ofstream& out, t_struct* tstruct); - void generate_get_field_name(ofstream& out, t_struct* tstruct); + void generate_union_constructor(ostream& out, t_struct* tstruct); + void generate_union_getters_and_setters(ostream& out, t_struct* tstruct); + void generate_union_abstract_methods(ostream& out, t_struct* tstruct); + void generate_check_type(ostream& out, t_struct* tstruct); + void generate_read_value(ostream& out, t_struct* tstruct); + void generate_write_value(ostream& out, t_struct* tstruct); + void generate_get_field_desc(ostream& out, t_struct* tstruct); + void generate_get_struct_desc(ostream& out, t_struct* tstruct); + void generate_get_field_name(ostream& out, t_struct* tstruct); - void generate_union_comparisons(ofstream& out, t_struct* tstruct); - void generate_union_hashcode(ofstream& out, t_struct* tstruct); + void generate_union_comparisons(ostream& out, t_struct* tstruct); + void generate_union_hashcode(ostream& out, t_struct* tstruct); /** * Serialization constructs */ - void generate_deserialize_field(std::ofstream& out, t_field* tfield, std::string prefix = ""); + void generate_deserialize_field(std::ostream& out, t_field* tfield, std::string prefix = ""); - void generate_deserialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); + void generate_deserialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); - void generate_deserialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); + void generate_deserialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); - void generate_deserialize_set_element(std::ofstream& out, t_set* tset, std::string prefix = ""); + void generate_deserialize_set_element(std::ostream& out, t_set* tset, std::string prefix = ""); - void generate_deserialize_map_element(std::ofstream& out, t_map* tmap, std::string prefix = ""); + void generate_deserialize_map_element(std::ostream& out, t_map* tmap, std::string prefix = ""); - void generate_deserialize_list_element(std::ofstream& out, + void generate_deserialize_list_element(std::ostream& out, t_list* tlist, std::string prefix = ""); - void generate_serialize_field(std::ofstream& out, t_field* tfield, std::string prefix = ""); + void generate_serialize_field(std::ostream& out, t_field* tfield, std::string prefix = ""); - void generate_serialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); + void generate_serialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); - void generate_serialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); + void generate_serialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); - void generate_serialize_map_element(std::ofstream& out, + void generate_serialize_map_element(std::ostream& out, t_map* tmap, std::string iter, std::string map); - void generate_serialize_set_element(std::ofstream& out, t_set* tmap, std::string iter); + void generate_serialize_set_element(std::ostream& out, t_set* tmap, std::string iter); - void generate_serialize_list_element(std::ofstream& out, t_list* tlist, std::string iter); + void generate_serialize_list_element(std::ostream& out, t_list* tlist, std::string iter); - void generate_java_doc(std::ofstream& out, t_field* field); + void generate_java_doc(std::ostream& out, t_field* field); - void generate_java_doc(std::ofstream& out, t_doc* tdoc); + void generate_java_doc(std::ostream& out, t_doc* tdoc); - void generate_java_doc(std::ofstream& out, t_function* tdoc); + void generate_java_doc(std::ostream& out, t_function* tdoc); - void generate_java_docstring_comment(std::ofstream& out, string contents); + void generate_java_docstring_comment(std::ostream& out, string contents); - void generate_deep_copy_container(std::ofstream& out, + void generate_deep_copy_container(std::ostream& out, std::string source_name_p1, std::string source_name_p2, std::string result_name, t_type* type); - void generate_deep_copy_non_container(std::ofstream& out, + void generate_deep_copy_non_container(std::ostream& out, std::string source_name, std::string dest_name, t_type* type); @@ -222,8 +222,8 @@ public: std::string argument_list(t_struct* tstruct, bool include_types = true); std::string type_to_enum(t_type* ttype); std::string get_enum_class_name(t_type* type); - void generate_struct_desc(ofstream& out, t_struct* tstruct); - void generate_field_descs(ofstream& out, t_struct* tstruct); + void generate_struct_desc(ostream& out, t_struct* tstruct); + void generate_field_descs(ostream& out, t_struct* tstruct); std::string box_type(t_type* type, string value); bool type_can_be_null(t_type* ttype) { @@ -241,7 +241,7 @@ private: */ std::string package_name_; - std::ofstream f_service_; + ofstream_with_content_based_conditional_update f_service_; std::string package_dir_; }; @@ -329,7 +329,7 @@ void t_javame_generator::generate_typedef(t_typedef* ttypedef) { void t_javame_generator::generate_enum(t_enum* tenum) { // Make output file string f_enum_name = package_dir_ + "/" + (tenum->get_name()) + ".java"; - ofstream f_enum; + ofstream_with_content_based_conditional_update f_enum; f_enum.open(f_enum_name.c_str()); // Comment and package it @@ -408,7 +408,7 @@ void t_javame_generator::generate_consts(std::vector consts) { } string f_consts_name = package_dir_ + "/" + program_name_ + "Constants.java"; - ofstream f_consts; + ofstream_with_content_based_conditional_update f_consts; f_consts.open(f_consts_name.c_str()); // Print header @@ -434,7 +434,7 @@ void t_javame_generator::generate_consts(std::vector consts) { * is NOT performed in this function as it is always run beforehand using the * validate_types method in main.cc */ -void t_javame_generator::print_const_value(std::ofstream& out, +void t_javame_generator::print_const_value(std::ostream& out, string name, t_type* type, t_const_value* value, @@ -454,8 +454,8 @@ void t_javame_generator::print_const_value(std::ofstream& out, } else if (type->is_struct() || type->is_xception()) { const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; out << name << " = new " << type_name(type, false, true) << "();" << endl; if (!in_static) { indent(out) << "static {" << endl; @@ -489,8 +489,8 @@ void t_javame_generator::print_const_value(std::ofstream& out, } t_type* ktype = ((t_map*)type)->get_key_type(); t_type* vtype = ((t_map*)type)->get_val_type(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { string key = render_const_value(out, name, ktype, v_iter->first); string val = render_const_value(out, name, vtype, v_iter->second); @@ -535,7 +535,7 @@ void t_javame_generator::print_const_value(std::ofstream& out, } } -string t_javame_generator::render_const_value(ofstream& out, +string t_javame_generator::render_const_value(ostream& out, string name, t_type* type, t_const_value* value) { @@ -638,7 +638,7 @@ void t_javame_generator::generate_xception(t_struct* txception) { void t_javame_generator::generate_java_struct(t_struct* tstruct, bool is_exception) { // Make output file string f_struct_name = package_dir_ + "/" + (tstruct->get_name()) + ".java"; - ofstream f_struct; + ofstream_with_content_based_conditional_update f_struct; f_struct.open(f_struct_name.c_str()); f_struct << autogen_comment() << java_package() << java_type_imports() << java_thrift_imports(); @@ -655,7 +655,7 @@ void t_javame_generator::generate_java_struct(t_struct* tstruct, bool is_excepti void t_javame_generator::generate_java_union(t_struct* tstruct) { // Make output file string f_struct_name = package_dir_ + "/" + (tstruct->get_name()) + ".java"; - ofstream f_struct; + ofstream_with_content_based_conditional_update f_struct; f_struct.open(f_struct_name.c_str()); f_struct << autogen_comment() << java_package() << java_type_imports() << java_thrift_imports(); @@ -699,7 +699,7 @@ void t_javame_generator::generate_java_union(t_struct* tstruct) { f_struct.close(); } -void t_javame_generator::generate_union_constructor(ofstream& out, t_struct* tstruct) { +void t_javame_generator::generate_union_constructor(ostream& out, t_struct* tstruct) { indent(out) << "public " << type_name(tstruct) << "() {" << endl; indent(out) << " super();" << endl; indent(out) << "}" << endl << endl; @@ -730,7 +730,7 @@ void t_javame_generator::generate_union_constructor(ofstream& out, t_struct* tst } } -void t_javame_generator::generate_union_getters_and_setters(ofstream& out, t_struct* tstruct) { +void t_javame_generator::generate_union_getters_and_setters(ostream& out, t_struct* tstruct) { const vector& members = tstruct->get_members(); vector::const_iterator m_iter; @@ -772,7 +772,7 @@ void t_javame_generator::generate_union_getters_and_setters(ofstream& out, t_str } } -void t_javame_generator::generate_union_abstract_methods(ofstream& out, t_struct* tstruct) { +void t_javame_generator::generate_union_abstract_methods(ostream& out, t_struct* tstruct) { generate_check_type(out, tstruct); out << endl; generate_read_value(out, tstruct); @@ -785,7 +785,7 @@ void t_javame_generator::generate_union_abstract_methods(ofstream& out, t_struct out << endl; } -void t_javame_generator::generate_check_type(ofstream& out, t_struct* tstruct) { +void t_javame_generator::generate_check_type(ostream& out, t_struct* tstruct) { indent(out) << "protected void checkType(_Fields setField, Object value) throws ClassCastException {" << endl; @@ -821,7 +821,7 @@ void t_javame_generator::generate_check_type(ofstream& out, t_struct* tstruct) { indent(out) << "}" << endl; } -void t_javame_generator::generate_read_value(ofstream& out, t_struct* tstruct) { +void t_javame_generator::generate_read_value(ostream& out, t_struct* tstruct) { indent(out) << "protected Object readValue(TProtocol iprot, TField field) throws TException {" << endl; @@ -875,7 +875,7 @@ void t_javame_generator::generate_read_value(ofstream& out, t_struct* tstruct) { indent(out) << "}" << endl; } -void t_javame_generator::generate_write_value(ofstream& out, t_struct* tstruct) { +void t_javame_generator::generate_write_value(ostream& out, t_struct* tstruct) { indent(out) << "protected void writeValue(TProtocol oprot) throws TException {" << endl; indent_up(); @@ -910,7 +910,7 @@ void t_javame_generator::generate_write_value(ofstream& out, t_struct* tstruct) indent(out) << "}" << endl; } -void t_javame_generator::generate_get_field_desc(ofstream& out, t_struct* tstruct) { +void t_javame_generator::generate_get_field_desc(ostream& out, t_struct* tstruct) { indent(out) << "protected TField getFieldDesc(_Fields setField) {" << endl; indent_up(); @@ -936,14 +936,14 @@ void t_javame_generator::generate_get_field_desc(ofstream& out, t_struct* tstruc indent(out) << "}" << endl; } -void t_javame_generator::generate_get_struct_desc(ofstream& out, t_struct* tstruct) { +void t_javame_generator::generate_get_struct_desc(ostream& out, t_struct* tstruct) { (void)tstruct; indent(out) << "protected TStruct getStructDesc() {" << endl; indent(out) << " return STRUCT_DESC;" << endl; indent(out) << "}" << endl; } -void t_javame_generator::generate_union_comparisons(ofstream& out, t_struct* tstruct) { +void t_javame_generator::generate_union_comparisons(ostream& out, t_struct* tstruct) { // equality indent(out) << "public boolean equals(Object other) {" << endl; indent(out) << " if (other instanceof " << tstruct->get_name() << ") {" << endl; @@ -973,7 +973,7 @@ void t_javame_generator::generate_union_comparisons(ofstream& out, t_struct* tst out << endl; } -void t_javame_generator::generate_union_hashcode(ofstream& out, t_struct* tstruct) { +void t_javame_generator::generate_union_hashcode(ostream& out, t_struct* tstruct) { (void)tstruct; indent(out) << "/**" << endl; indent(out) @@ -995,7 +995,7 @@ void t_javame_generator::generate_union_hashcode(ofstream& out, t_struct* tstruc * @param in_class If inside a class, needs to be static class * @param is_result If this is a result it needs a different writer */ -void t_javame_generator::generate_java_struct_definition(ofstream& out, +void t_javame_generator::generate_java_struct_definition(ostream& out, t_struct* tstruct, bool is_exception, bool in_class, @@ -1177,7 +1177,7 @@ void t_javame_generator::generate_java_struct_definition(ofstream& out, * * @param tstruct The struct definition */ -void t_javame_generator::generate_java_struct_equality(ofstream& out, t_struct* tstruct) { +void t_javame_generator::generate_java_struct_equality(ostream& out, t_struct* tstruct) { out << indent() << "public boolean equals(Object that) {" << endl; indent_up(); out << indent() << "if (that == null)" << endl << indent() << " return false;" << endl @@ -1222,7 +1222,7 @@ void t_javame_generator::generate_java_struct_equality(ofstream& out, t_struct* << "this_present_" << name << " && that_present_" << name << "))" << endl << indent() << " return false;" << endl; - if (t->is_base_type() && ((t_base_type*)t)->is_binary()) { + if (t->is_binary()) { unequal = "TBaseHelper.compareTo(this." + name + ", that." + name + ") != 0"; } else if (can_be_null) { unequal = "!this." + name + ".equals(that." + name + ")"; @@ -1246,7 +1246,7 @@ void t_javame_generator::generate_java_struct_equality(ofstream& out, t_struct* indent(out) << "}" << endl << endl; } -void t_javame_generator::generate_java_struct_compare_to(ofstream& out, t_struct* tstruct) { +void t_javame_generator::generate_java_struct_compare_to(ostream& out, t_struct* tstruct) { indent(out) << "public int compareTo(Object otherObject) {" << endl; // indent(out) << "public int compareTo(" << type_name(tstruct) << " other) {" << endl; indent_up(); @@ -1297,7 +1297,7 @@ void t_javame_generator::generate_java_struct_compare_to(ofstream& out, t_struct * * @param tstruct The struct definition */ -void t_javame_generator::generate_java_struct_reader(ofstream& out, t_struct* tstruct) { +void t_javame_generator::generate_java_struct_reader(ostream& out, t_struct* tstruct) { out << indent() << "public void read(TProtocol iprot) throws TException {" << endl; indent_up(); @@ -1365,7 +1365,7 @@ void t_javame_generator::generate_java_struct_reader(ofstream& out, t_struct* ts // generates java method to perform various checks // (e.g. check that all required fields are set) -void t_javame_generator::generate_java_validator(ofstream& out, t_struct* tstruct) { +void t_javame_generator::generate_java_validator(ostream& out, t_struct* tstruct) { indent(out) << "public void validate() throws TException {" << endl; indent_up(); @@ -1390,7 +1390,7 @@ void t_javame_generator::generate_java_validator(ofstream& out, t_struct* tstruc * * @param tstruct The struct definition */ -void t_javame_generator::generate_java_struct_writer(ofstream& out, t_struct* tstruct) { +void t_javame_generator::generate_java_struct_writer(ostream& out, t_struct* tstruct) { out << indent() << "public void write(TProtocol oprot) throws TException {" << endl; indent_up(); @@ -1449,7 +1449,7 @@ void t_javame_generator::generate_java_struct_writer(ofstream& out, t_struct* ts * * @param tstruct The struct definition */ -void t_javame_generator::generate_java_struct_result_writer(ofstream& out, t_struct* tstruct) { +void t_javame_generator::generate_java_struct_result_writer(ostream& out, t_struct* tstruct) { out << indent() << "public void write(TProtocol oprot) throws TException {" << endl; indent_up(); @@ -1527,7 +1527,7 @@ void t_javame_generator::generate_reflection_setters(ostringstream& out, indent_down(); } -void t_javame_generator::generate_generic_field_getters_setters(std::ofstream& out, +void t_javame_generator::generate_generic_field_getters_setters(std::ostream& out, t_struct* tstruct) { (void)out; std::ostringstream getter_stream; @@ -1555,7 +1555,7 @@ void t_javame_generator::generate_generic_field_getters_setters(std::ofstream& o * * @param tstruct The struct definition */ -void t_javame_generator::generate_java_bean_boilerplate(ofstream& out, t_struct* tstruct) { +void t_javame_generator::generate_java_bean_boilerplate(ostream& out, t_struct* tstruct) { const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { @@ -1708,7 +1708,7 @@ void t_javame_generator::generate_java_bean_boilerplate(ofstream& out, t_struct* * * @param tstruct The struct definition */ -void t_javame_generator::generate_java_struct_tostring(ofstream& out, t_struct* tstruct) { +void t_javame_generator::generate_java_struct_tostring(ostream& out, t_struct* tstruct) { out << indent() << "public String toString() {" << endl; indent_up(); @@ -1740,7 +1740,7 @@ void t_javame_generator::generate_java_struct_tostring(ofstream& out, t_struct* indent_up(); } - if (field->get_type()->is_base_type() && ((t_base_type*)(field->get_type()))->is_binary()) { + if (field->get_type()->is_binary()) { indent(out) << "TBaseHelper.toString(this." << field->get_name() << ", sb);" << endl; } else { indent(out) << "sb.append(this." << (*f_iter)->get_name() << ");" << endl; @@ -1819,7 +1819,7 @@ std::string t_javame_generator::get_java_type_string(t_type* type) { } } -void t_javame_generator::generate_field_value_meta_data(std::ofstream& out, t_type* type) { +void t_javame_generator::generate_field_value_meta_data(std::ostream& out, t_type* type) { out << endl; indent_up(); indent_up(); @@ -1894,7 +1894,7 @@ void t_javame_generator::generate_primitive_service_interface(t_service* tservic << endl << endl; string f_interface_name = package_dir_ + "/" + service_name_ + "Iface.java"; - std::ofstream f_iface; + ofstream_with_content_based_conditional_update f_iface; f_iface.open(f_interface_name.c_str()); string extends_iface = ""; @@ -2391,7 +2391,7 @@ void t_javame_generator::generate_process_function(t_service* tservice, t_functi * @param tfield The field * @param prefix The variable name or container for this field */ -void t_javame_generator::generate_deserialize_field(ofstream& out, t_field* tfield, string prefix) { +void t_javame_generator::generate_deserialize_field(ostream& out, t_field* tfield, string prefix) { t_type* type = get_true_type(tfield->get_type()); if (type->is_void()) { @@ -2413,7 +2413,7 @@ void t_javame_generator::generate_deserialize_field(ofstream& out, t_field* tfie throw "compiler error: cannot serialize void field in a struct: " + name; break; case t_base_type::TYPE_STRING: - if (!((t_base_type*)type)->is_binary()) { + if (!type->is_binary()) { out << "readString();"; } else { out << "readBinary();"; @@ -2455,7 +2455,7 @@ void t_javame_generator::generate_deserialize_field(ofstream& out, t_field* tfie /** * Generates an unserializer for a struct, invokes read() */ -void t_javame_generator::generate_deserialize_struct(ofstream& out, +void t_javame_generator::generate_deserialize_struct(ostream& out, t_struct* tstruct, string prefix) { out << indent() << prefix << " = new " << type_name(tstruct) << "();" << endl << indent() @@ -2465,7 +2465,7 @@ void t_javame_generator::generate_deserialize_struct(ofstream& out, /** * Deserializes a container by reading its size and then iterating */ -void t_javame_generator::generate_deserialize_container(ofstream& out, +void t_javame_generator::generate_deserialize_container(ostream& out, t_type* ttype, string prefix) { scope_up(out); @@ -2527,7 +2527,7 @@ void t_javame_generator::generate_deserialize_container(ofstream& out, /** * Generates code to deserialize a map */ -void t_javame_generator::generate_deserialize_map_element(ofstream& out, +void t_javame_generator::generate_deserialize_map_element(ostream& out, t_map* tmap, string prefix) { string key = tmp("_key"); @@ -2548,7 +2548,7 @@ void t_javame_generator::generate_deserialize_map_element(ofstream& out, /** * Deserializes a set element */ -void t_javame_generator::generate_deserialize_set_element(ofstream& out, +void t_javame_generator::generate_deserialize_set_element(ostream& out, t_set* tset, string prefix) { string elem = tmp("_elem"); @@ -2565,7 +2565,7 @@ void t_javame_generator::generate_deserialize_set_element(ofstream& out, /** * Deserializes a list element */ -void t_javame_generator::generate_deserialize_list_element(ofstream& out, +void t_javame_generator::generate_deserialize_list_element(ostream& out, t_list* tlist, string prefix) { string elem = tmp("_elem"); @@ -2584,7 +2584,7 @@ void t_javame_generator::generate_deserialize_list_element(ofstream& out, * @param tfield The field to serialize * @param prefix Name to prepend to field name */ -void t_javame_generator::generate_serialize_field(ofstream& out, t_field* tfield, string prefix) { +void t_javame_generator::generate_serialize_field(ostream& out, t_field* tfield, string prefix) { t_type* type = get_true_type(tfield->get_type()); // Do nothing for void types @@ -2609,7 +2609,7 @@ void t_javame_generator::generate_serialize_field(ofstream& out, t_field* tfield throw "compiler error: cannot serialize void field in a struct: " + name; break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { out << "writeBinary(" << name << ");"; } else { out << "writeString(" << name << ");"; @@ -2654,7 +2654,7 @@ void t_javame_generator::generate_serialize_field(ofstream& out, t_field* tfield * @param tstruct The struct to serialize * @param prefix String prefix to attach to all fields */ -void t_javame_generator::generate_serialize_struct(ofstream& out, +void t_javame_generator::generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix) { (void)tstruct; @@ -2667,7 +2667,7 @@ void t_javame_generator::generate_serialize_struct(ofstream& out, * @param ttype The type of container * @param prefix String prefix for fields */ -void t_javame_generator::generate_serialize_container(ofstream& out, t_type* ttype, string prefix) { +void t_javame_generator::generate_serialize_container(ostream& out, t_type* ttype, string prefix) { scope_up(out); if (ttype->is_map()) { @@ -2733,7 +2733,7 @@ void t_javame_generator::generate_serialize_container(ofstream& out, t_type* tty /** * Serializes the members of a map. */ -void t_javame_generator::generate_serialize_map_element(ofstream& out, +void t_javame_generator::generate_serialize_map_element(ostream& out, t_map* tmap, string iter, string map) { @@ -2747,7 +2747,7 @@ void t_javame_generator::generate_serialize_map_element(ofstream& out, /** * Serializes the members of a set. */ -void t_javame_generator::generate_serialize_set_element(ofstream& out, t_set* tset, string iter) { +void t_javame_generator::generate_serialize_set_element(ostream& out, t_set* tset, string iter) { t_field efield(tset->get_elem_type(), iter); generate_serialize_field(out, &efield, ""); } @@ -2755,7 +2755,7 @@ void t_javame_generator::generate_serialize_set_element(ofstream& out, t_set* ts /** * Serializes the members of a list. */ -void t_javame_generator::generate_serialize_list_element(ofstream& out, +void t_javame_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string iter) { t_field efield(tlist->get_elem_type(), iter); @@ -2847,7 +2847,7 @@ string t_javame_generator::declare_field(t_field* tfield, bool init) { if (init) { t_type* ttype = get_true_type(tfield->get_type()); if (ttype->is_base_type() && tfield->get_value() != NULL) { - ofstream dummy; + std::ofstream dummy; result += " = " + render_const_value(dummy, tfield->get_name(), ttype, tfield->get_value()); } else if (ttype->is_base_type()) { t_base_type::t_base tbase = ((t_base_type*)ttype)->get_base(); @@ -2997,11 +2997,11 @@ string t_javame_generator::constant_name(string name) { return constant_name; } -void t_javame_generator::generate_java_docstring_comment(ofstream& out, string contents) { +void t_javame_generator::generate_java_docstring_comment(ostream& out, string contents) { generate_docstring_comment(out, "/**\n", " * ", contents, " */\n"); } -void t_javame_generator::generate_java_doc(ofstream& out, t_field* field) { +void t_javame_generator::generate_java_doc(ostream& out, t_field* field) { if (field->get_type()->is_enum()) { string combined_message = field->get_doc() + "\n@see " + get_enum_class_name(field->get_type()); generate_java_docstring_comment(out, combined_message); @@ -3013,7 +3013,7 @@ void t_javame_generator::generate_java_doc(ofstream& out, t_field* field) { /** * Emits a JavaDoc comment if the provided object has a doc in Thrift */ -void t_javame_generator::generate_java_doc(ofstream& out, t_doc* tdoc) { +void t_javame_generator::generate_java_doc(ostream& out, t_doc* tdoc) { if (tdoc->has_doc()) { generate_java_docstring_comment(out, tdoc->get_doc()); } @@ -3022,7 +3022,7 @@ void t_javame_generator::generate_java_doc(ofstream& out, t_doc* tdoc) { /** * Emits a JavaDoc comment if the provided function object has a doc in Thrift */ -void t_javame_generator::generate_java_doc(ofstream& out, t_function* tfunction) { +void t_javame_generator::generate_java_doc(ostream& out, t_function* tfunction) { if (tfunction->has_doc()) { stringstream ss; ss << tfunction->get_doc(); @@ -3039,7 +3039,7 @@ void t_javame_generator::generate_java_doc(ofstream& out, t_function* tfunction) } } -void t_javame_generator::generate_deep_copy_container(ofstream& out, +void t_javame_generator::generate_deep_copy_container(ostream& out, std::string source_name_p1, std::string source_name_p2, std::string result_name, @@ -3144,7 +3144,7 @@ void t_javame_generator::generate_deep_copy_container(ofstream& out, } } else { // iterative copy - if (((t_base_type*)elem_type)->is_binary()) { + if (elem_type->is_binary()) { indent(out) << type_name(elem_type, true, false) << " temp_binary_element = "; generate_deep_copy_non_container(out, iterator_element_name, @@ -3169,13 +3169,13 @@ void t_javame_generator::generate_deep_copy_container(ofstream& out, } } -void t_javame_generator::generate_deep_copy_non_container(ofstream& out, +void t_javame_generator::generate_deep_copy_non_container(ostream& out, std::string source_name, std::string dest_name, t_type* type) { if (type->is_base_type() || type->is_enum() || type->is_typedef()) { // binary fields need to be copied with System.arraycopy - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { out << "new byte[" << source_name << ".length];" << endl; indent(out) << "System.arraycopy(" << source_name << ", 0, " << dest_name << ", 0, " << source_name << ".length)"; @@ -3200,7 +3200,7 @@ std::string t_javame_generator::generate_isset_check(std::string field_name) { return "is" + get_cap_name("set") + get_cap_name(field_name) + "()"; } -void t_javame_generator::generate_isset_set(ofstream& out, t_field* field) { +void t_javame_generator::generate_isset_set(ostream& out, t_field* field) { if (!type_can_be_null(field->get_type())) { indent(out) << "set" << get_cap_name(field->get_name()) << get_cap_name("isSet") << "(true);" << endl; @@ -3216,12 +3216,12 @@ std::string t_javame_generator::get_enum_class_name(t_type* type) { return package + type->get_name(); } -void t_javame_generator::generate_struct_desc(ofstream& out, t_struct* tstruct) { +void t_javame_generator::generate_struct_desc(ostream& out, t_struct* tstruct) { indent(out) << "private static final TStruct STRUCT_DESC = new TStruct(\"" << tstruct->get_name() << "\");" << endl; } -void t_javame_generator::generate_field_descs(ofstream& out, t_struct* tstruct) { +void t_javame_generator::generate_field_descs(ostream& out, t_struct* tstruct) { const vector& members = tstruct->get_members(); vector::const_iterator m_iter; @@ -3245,7 +3245,7 @@ bool t_javame_generator::has_bit_vector(t_struct* tstruct) { return false; } -void t_javame_generator::generate_java_struct_clear(std::ofstream& out, t_struct* tstruct) { +void t_javame_generator::generate_java_struct_clear(std::ostream& out, t_struct* tstruct) { indent(out) << "public void clear() {" << endl; const vector& members = tstruct->get_members(); diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_js_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_js_generator.cc index 3ccd248..61782b9 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_js_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_js_generator.cc @@ -20,7 +20,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -32,7 +34,7 @@ #include "thrift/version.h" using std::map; -using std::ofstream; +using std::ostream; using std::ostringstream; using std::string; using std::stringstream; @@ -58,10 +60,11 @@ public: gen_node_ = false; gen_jquery_ = false; gen_ts_ = false; + gen_es6_ = false; bool with_ns_ = false; - for( iter = parsed_options.begin(); iter != parsed_options.end(); ++iter) { + for (iter = parsed_options.begin(); iter != parsed_options.end(); ++iter) { if( iter->first.compare("node") == 0) { gen_node_ = true; } else if( iter->first.compare("jquery") == 0) { @@ -70,13 +73,15 @@ public: gen_ts_ = true; } else if( iter->first.compare("with_ns") == 0) { with_ns_ = true; + } else if( iter->first.compare("es6") == 0) { + gen_es6_ = true; } else { throw "unknown option js:" + iter->first; } } - if (gen_node_ && gen_ts_) { - throw "Invalid switch: [-gen js:node,ts] options not compatible"; + if (gen_es6_ && gen_jquery_) { + throw "Invalid switch: [-gen js:es6,jquery] options not compatible"; } if (gen_node_ && gen_jquery_) { @@ -88,6 +93,15 @@ public: throw "Invalid switch: [-gen js:with_ns] is only valid when using node.js"; } + // Depending on the processing flags, we will update these to be ES6 compatible + js_const_type_ = "var "; + js_let_type_ = "var "; + js_var_type_ = "var "; + if (gen_es6_) { + js_const_type_ = "const "; + js_let_type_ = "let "; + } + if (gen_node_) { out_dir_base_ = "gen-nodejs"; no_ns_ = !with_ns_; @@ -126,12 +140,12 @@ public: * Structs! */ void generate_js_struct(t_struct* tstruct, bool is_exception); - void generate_js_struct_definition(std::ofstream& out, + void generate_js_struct_definition(std::ostream& out, t_struct* tstruct, bool is_xception = false, bool is_exported = true); - void generate_js_struct_reader(std::ofstream& out, t_struct* tstruct); - void generate_js_struct_writer(std::ofstream& out, t_struct* tstruct); + void generate_js_struct_reader(std::ostream& out, t_struct* tstruct); + void generate_js_struct_writer(std::ostream& out, t_struct* tstruct); void generate_js_function_helpers(t_function* tfunction); /** @@ -148,43 +162,44 @@ public: * Serialization constructs */ - void generate_deserialize_field(std::ofstream& out, + void generate_deserialize_field(std::ostream& out, t_field* tfield, std::string prefix = "", bool inclass = false); - void generate_deserialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); + void generate_deserialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); - void generate_deserialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); + void generate_deserialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); - void generate_deserialize_set_element(std::ofstream& out, t_set* tset, std::string prefix = ""); + void generate_deserialize_set_element(std::ostream& out, t_set* tset, std::string prefix = ""); - void generate_deserialize_map_element(std::ofstream& out, t_map* tmap, std::string prefix = ""); + void generate_deserialize_map_element(std::ostream& out, t_map* tmap, std::string prefix = ""); - void generate_deserialize_list_element(std::ofstream& out, + void generate_deserialize_list_element(std::ostream& out, t_list* tlist, std::string prefix = ""); - void generate_serialize_field(std::ofstream& out, t_field* tfield, std::string prefix = ""); + void generate_serialize_field(std::ostream& out, t_field* tfield, std::string prefix = ""); - void generate_serialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); + void generate_serialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); - void generate_serialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); + void generate_serialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); - void generate_serialize_map_element(std::ofstream& out, + void generate_serialize_map_element(std::ostream& out, t_map* tmap, std::string kiter, std::string viter); - void generate_serialize_set_element(std::ofstream& out, t_set* tmap, std::string iter); + void generate_serialize_set_element(std::ostream& out, t_set* tmap, std::string iter); - void generate_serialize_list_element(std::ofstream& out, t_list* tlist, std::string iter); + void generate_serialize_list_element(std::ostream& out, t_list* tlist, std::string iter); /** * Helper rendering functions */ std::string js_includes(); + std::string ts_includes(); std::string render_includes(); std::string declare_field(t_field* tfield, bool init = false, bool obj = false); std::string function_signature(t_function* tfunction, @@ -267,7 +282,7 @@ public: * TypeScript Definition File helper functions */ - string ts_function_signature(t_function* tfunction, bool include_callback); + string ts_function_signature(t_function* tfunction, bool include_callback, bool optional_callback); string ts_get_type(t_type* type); /** @@ -284,11 +299,11 @@ public: string ts_declare() { return (ts_module_.empty() ? "declare " : ""); } /** - * Returns "?" if the given field is optional. + * Returns "?" if the given field is optional or has a default value. * @param t_field The field to check * @return string */ - string ts_get_req(t_field* field) { return (field->get_req() == t_field::T_OPTIONAL ? "?" : ""); } + string ts_get_req(t_field* field) {return (field->get_req() == t_field::T_OPTIONAL || field->get_value() != NULL ? "?" : ""); } /** * Returns the documentation, if the provided documentable object has one. @@ -327,6 +342,11 @@ private: */ bool gen_ts_; + /** + * True if we should generate ES6 code, i.e. with Promises + */ + bool gen_es6_; + /** * The name of the defined module(s), for TypeScript Definition Files. */ @@ -337,13 +357,28 @@ private: */ bool no_ns_; + /** + * The variable decorator for "const" variables. Will default to "var" if in an incompatible language. + */ + string js_const_type_; + + /** + * The variable decorator for "let" variables. Will default to "var" if in an incompatible language. + */ + string js_let_type_; + + /** + * The default variable decorator. Supports all javascript languages, but is not scoped to functions or closures. + */ + string js_var_type_; + /** * File streams */ - std::ofstream f_types_; - std::ofstream f_service_; - std::ofstream f_types_ts_; - std::ofstream f_service_ts_; + ofstream_with_content_based_conditional_update f_types_; + ofstream_with_content_based_conditional_update f_service_; + ofstream_with_content_based_conditional_update f_types_ts_; + ofstream_with_content_based_conditional_update f_service_ts_; }; /** @@ -370,18 +405,18 @@ void t_js_generator::init_generator() { // Print header f_types_ << autogen_comment(); - if (gen_node_ && no_ns_) { + if ((gen_node_ || gen_es6_) && no_ns_) { f_types_ << "\"use strict\";" << endl << endl; } f_types_ << js_includes() << endl << render_includes() << endl; if (gen_ts_) { - f_types_ts_ << autogen_comment() << endl; + f_types_ts_ << autogen_comment() << ts_includes() << endl; } if (gen_node_) { - f_types_ << "var ttypes = module.exports = {};" << endl; + f_types_ << js_const_type_ << "ttypes = module.exports = {};" << endl; } string pns; @@ -407,11 +442,27 @@ void t_js_generator::init_generator() { * Prints standard js imports */ string t_js_generator::js_includes() { + if (gen_node_) { + string result = js_const_type_ + "thrift = require('thrift');\n" + + js_const_type_ + "Thrift = thrift.Thrift;\n"; + if (!gen_es6_) { + result += js_const_type_ + "Q = thrift.Q;\n"; + } + return result; + } + + return ""; +} + +/** + * Prints standard ts imports + */ +string t_js_generator::ts_includes() { if (gen_node_) { return string( - "var thrift = require('thrift');\n" - "var Thrift = thrift.Thrift;\n" - "var Q = thrift.Q;\n"); + "import thrift = require('thrift');\n" + "import Thrift = thrift.Thrift;\n" + "import Q = thrift.Q;\n"); } return ""; @@ -426,7 +477,7 @@ string t_js_generator::render_includes() { if (gen_node_) { const vector& includes = program_->get_includes(); for (size_t i = 0; i < includes.size(); ++i) { - result += "var " + make_valid_nodeJs_identifier(includes[i]->get_name()) + "_ttypes = require('./" + includes[i]->get_name() + result += js_const_type_ + make_valid_nodeJs_identifier(includes[i]->get_name()) + "_ttypes = require('./" + includes[i]->get_name() + "_types');\n"; } if (includes.size() > 0) { @@ -478,8 +529,8 @@ void t_js_generator::generate_enum(t_enum* tenum) { indent_up(); - vector constants = tenum->get_constants(); - vector::iterator c_iter; + vector const& constants = tenum->get_constants(); + vector::const_iterator c_iter; for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) { int value = (*c_iter)->get_value(); if (gen_ts_) { @@ -515,7 +566,7 @@ void t_js_generator::generate_const(t_const* tconst) { f_types_ << render_const_value(type, value) << ";" << endl; if (gen_ts_) { - f_types_ts_ << ts_print_doc(tconst) << ts_indent() << ts_declare() << "var " << name << ": " + f_types_ts_ << ts_print_doc(tconst) << ts_indent() << ts_declare() << js_const_type_ << name << ": " << ts_get_type(type) << ";" << endl; } } @@ -549,7 +600,7 @@ string t_js_generator::render_const_value(t_type* type, t_const_value* value) { if (value->get_type() == t_const_value::CV_INTEGER) { out << value->get_integer(); } else { - out << value->get_double(); + out << emit_double_as_string(value->get_double()); } break; default: @@ -558,12 +609,12 @@ string t_js_generator::render_const_value(t_type* type, t_const_value* value) { } else if (type->is_enum()) { out << value->get_integer(); } else if (type->is_struct() || type->is_xception()) { - out << "new " << js_type_namespace(type->get_program()) << type->get_name() << "({" << endl; + out << "new " << js_type_namespace(type->get_program()) << type->get_name() << "({"; indent_up(); const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { t_type* field_type = NULL; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { @@ -576,12 +627,12 @@ string t_js_generator::render_const_value(t_type* type, t_const_value* value) { } if (v_iter != val.begin()) out << ","; - out << render_const_value(g_type_string, v_iter->first); + out << endl << indent() << render_const_value(g_type_string, v_iter->first); out << " : "; out << render_const_value(field_type, v_iter->second); } - - out << "})"; + indent_down(); + out << endl << indent() << "})"; } else if (type->is_map()) { t_type* ktype = ((t_map*)type)->get_key_type(); @@ -589,8 +640,8 @@ string t_js_generator::render_const_value(t_type* type, t_const_value* value) { out << "{" << endl; indent_up(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { if (v_iter != val.begin()) out << "," << endl; @@ -600,9 +651,8 @@ string t_js_generator::render_const_value(t_type* type, t_const_value* value) { out << " : "; out << render_const_value(vtype, v_iter->second); } - indent_down(); - out << endl << "}"; + out << endl << indent() << "}"; } else if (type->is_list() || type->is_set()) { t_type* etype; if (type->is_list()) { @@ -670,7 +720,7 @@ t_type* t_js_generator::get_contained_type(t_type* t) { * * @param tstruct The struct definition */ -void t_js_generator::generate_js_struct_definition(ofstream& out, +void t_js_generator::generate_js_struct_definition(ostream& out, t_struct* tstruct, bool is_exception, bool is_exported) { @@ -678,17 +728,16 @@ void t_js_generator::generate_js_struct_definition(ofstream& out, vector::const_iterator m_iter; if (gen_node_) { - string prefix = has_js_namespace(tstruct->get_program()) ? js_namespace(tstruct->get_program()) : "var "; - if (is_exported) { - out << prefix << tstruct->get_name() << " = " - << "module.exports." << tstruct->get_name() << " = function(args) {" << endl; - } else { - out << prefix << tstruct->get_name() << " = function(args) {" - << endl; + string prefix = has_js_namespace(tstruct->get_program()) ? js_namespace(tstruct->get_program()) : js_const_type_; + out << prefix << tstruct->get_name() << + (is_exported ? " = module.exports." + tstruct->get_name() : ""); + if (gen_ts_) { + f_types_ts_ << ts_print_doc(tstruct) << ts_indent() << ts_declare() << "class " + << tstruct->get_name() << (is_exception ? " extends Thrift.TException" : "") + << " {" << endl; } } else { - out << js_namespace(tstruct->get_program()) << tstruct->get_name() << " = function(args) {" - << endl; + out << js_namespace(tstruct->get_program()) << tstruct->get_name(); if (gen_ts_) { f_types_ts_ << ts_print_doc(tstruct) << ts_indent() << ts_declare() << "class " << tstruct->get_name() << (is_exception ? " extends Thrift.TException" : "") @@ -696,11 +745,28 @@ void t_js_generator::generate_js_struct_definition(ofstream& out, } } + if (gen_es6_) { + if (gen_node_ && is_exception) { + out << " = class extends Thrift.TException {" << endl; + } else { + out << " = class {" << endl; + } + indent_up(); + indent(out) << "constructor(args) {" << endl; + } else { + out << " = function(args) {" << endl; + } + indent_up(); + // Call super() method on inherited Error class if (gen_node_ && is_exception) { - out << indent() << "Thrift.TException.call(this, \"" << js_namespace(tstruct->get_program()) + if (gen_es6_) { + indent(out) << "super(args);" << endl; + } else { + indent(out) << "Thrift.TException.call(this, \"" << js_namespace(tstruct->get_program()) << tstruct->get_name() << "\");" << endl; + } out << indent() << "this.name = \"" << js_namespace(tstruct->get_program()) << tstruct->get_name() << "\";" << endl; } @@ -716,8 +782,14 @@ void t_js_generator::generate_js_struct_definition(ofstream& out, out << indent() << dval << ";" << endl; } if (gen_ts_) { - f_types_ts_ << ts_indent() << (*m_iter)->get_name() << ": " - << ts_get_type((*m_iter)->get_type()) << ";" << endl; + if (gen_node_) { + f_types_ts_ << ts_indent() << "public " << (*m_iter)->get_name() << ": " + << ts_get_type((*m_iter)->get_type()) << ";" << endl; + } else { + f_types_ts_ << ts_indent() << (*m_iter)->get_name() << ": " + << ts_get_type((*m_iter)->get_type()) << ";" << endl; + } + } } @@ -743,15 +815,17 @@ void t_js_generator::generate_js_struct_definition(ofstream& out, } } - out << indent() << "if (args) {" << endl; + indent(out) << "if (args) {" << endl; + indent_up(); if (gen_ts_) { f_types_ts_ << endl << ts_indent() << "constructor(args?: { "; } for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { t_type* t = get_true_type((*m_iter)->get_type()); - out << indent() << indent() << "if (args." << (*m_iter)->get_name() << " !== undefined && args." << (*m_iter)->get_name() << " !== null) {" - << endl << indent() << indent() << indent() << "this." << (*m_iter)->get_name(); + indent(out) << "if (args." << (*m_iter)->get_name() << " !== undefined && args." << (*m_iter)->get_name() << " !== null) {" << endl; + indent_up(); + indent(out) << "this." << (*m_iter)->get_name(); if (t->is_struct()) { out << (" = new " + js_type_namespace(t->get_program()) + t->get_name() + @@ -790,68 +864,90 @@ void t_js_generator::generate_js_struct_definition(ofstream& out, out << " = args." << (*m_iter)->get_name() << ";" << endl; } + indent_down(); if (!(*m_iter)->get_req()) { - out << indent() << indent() << "} else {" << endl << indent() << indent() << indent() - << "throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, " + indent(out) << "} else {" << endl; + indent(out) + << " throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, " "'Required field " << (*m_iter)->get_name() << " is unset!');" << endl; } - out << indent() << indent() << "}" << endl; + indent(out) << "}" << endl; if (gen_ts_) { f_types_ts_ << (*m_iter)->get_name() << ts_get_req(*m_iter) << ": " << ts_get_type((*m_iter)->get_type()) << "; "; } } - + indent_down(); out << indent() << "}" << endl; if (gen_ts_) { f_types_ts_ << "});" << endl; } } + // Done with constructor indent_down(); - out << "};" << endl; + if (gen_es6_) { + indent(out) << "}" << endl << endl; + } else { + indent(out) << "};" << endl; + } + if (gen_ts_) { f_types_ts_ << ts_indent() << "}" << endl; } - if (is_exception) { - out << "Thrift.inherits(" << js_namespace(tstruct->get_program()) << tstruct->get_name() - << ", Thrift.TException);" << endl; - out << js_namespace(tstruct->get_program()) << tstruct->get_name() << ".prototype.name = '" - << tstruct->get_name() << "';" << endl; - } else { - // init prototype - out << js_namespace(tstruct->get_program()) << tstruct->get_name() << ".prototype = {};" - << endl; + if (!gen_es6_) { + if (is_exception) { + out << "Thrift.inherits(" << js_namespace(tstruct->get_program()) << tstruct->get_name() + << ", Thrift.TException);" << endl; + out << js_namespace(tstruct->get_program()) << tstruct->get_name() << ".prototype.name = '" + << tstruct->get_name() << "';" << endl; + } else { + // init prototype manually if we aren't using es6 + out << js_namespace(tstruct->get_program()) << tstruct->get_name() << ".prototype = {};" + << endl; + } + } generate_js_struct_reader(out, tstruct); generate_js_struct_writer(out, tstruct); + + // Close out the class definition + if (gen_es6_) { + indent_down(); + indent(out) << "};" << endl; + } } /** * Generates the read() method for a struct */ -void t_js_generator::generate_js_struct_reader(ofstream& out, t_struct* tstruct) { +void t_js_generator::generate_js_struct_reader(ostream& out, t_struct* tstruct) { const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; - out << js_namespace(tstruct->get_program()) << tstruct->get_name() - << ".prototype.read = function(input) {" << endl; + if (gen_es6_) { + indent(out) << "read (input) {" << endl; + } else { + indent(out) << js_namespace(tstruct->get_program()) << tstruct->get_name() + << ".prototype.read = function(input) {" << endl; + } indent_up(); indent(out) << "input.readStructBegin();" << endl; // Loop over reading in fields - indent(out) << "while (true)" << endl; + indent(out) << "while (true) {" << endl; - scope_up(out); + indent_up(); - indent(out) << "var ret = input.readFieldBegin();" << endl; - indent(out) << "var fname = ret.fname;" << endl; - indent(out) << "var ftype = ret.ftype;" << endl; - indent(out) << "var fid = ret.fid;" << endl; + indent(out) << js_const_type_ << "ret = input.readFieldBegin();" << endl; + indent(out) << js_const_type_ << "ftype = ret.ftype;" << endl; + if (!fields.empty()) { + indent(out) << js_const_type_ << "fid = ret.fid;" << endl; + } // Check for field STOP marker and break indent(out) << "if (ftype == Thrift.Type.STOP) {" << endl; @@ -861,9 +957,9 @@ void t_js_generator::generate_js_struct_reader(ofstream& out, t_struct* tstruct) indent(out) << "}" << endl; if (!fields.empty()) { // Switch statement on the field we are reading - indent(out) << "switch (fid)" << endl; + indent(out) << "switch (fid) {" << endl; - scope_up(out); + indent_up(); // Generate deserialization code for known cases for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { @@ -905,19 +1001,28 @@ void t_js_generator::generate_js_struct_reader(ofstream& out, t_struct* tstruct) indent(out) << "return;" << endl; indent_down(); - out << indent() << "};" << endl << endl; + + if (gen_es6_) { + indent(out) << "}" << endl << endl; + } else { + indent(out) << "};" << endl << endl; + } } /** * Generates the write() method for a struct */ -void t_js_generator::generate_js_struct_writer(ofstream& out, t_struct* tstruct) { +void t_js_generator::generate_js_struct_writer(ostream& out, t_struct* tstruct) { string name = tstruct->get_name(); const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; - out << js_namespace(tstruct->get_program()) << tstruct->get_name() - << ".prototype.write = function(output) {" << endl; + if (gen_es6_) { + indent(out) << "write (output) {" << endl; + } else { + indent(out) << js_namespace(tstruct->get_program()) << tstruct->get_name() + << ".prototype.write = function(output) {" << endl; + } indent_up(); @@ -947,7 +1052,11 @@ void t_js_generator::generate_js_struct_writer(ofstream& out, t_struct* tstruct) out << indent() << "return;" << endl; indent_down(); - out << indent() << "};" << endl << endl; + if (gen_es6_) { + out << indent() << "}" << endl << endl; + } else { + out << indent() << "};" << endl << endl; + } } /** @@ -966,7 +1075,7 @@ void t_js_generator::generate_service(t_service* tservice) { f_service_ << autogen_comment(); - if (gen_node_ && no_ns_) { + if ((gen_node_ || gen_es6_) && no_ns_) { f_service_ << "\"use strict\";" << endl << endl; } @@ -978,6 +1087,39 @@ void t_js_generator::generate_service(t_service* tservice) { << ".d.ts\" />" << endl; } f_service_ts_ << autogen_comment() << endl; + if (gen_node_) { + f_service_ts_ << ts_includes() << endl; + f_service_ts_ << "import ttypes = require('./" + program_->get_name() + "_types');" << endl; + // Generate type aliases + // enum + vector const& enums = program_->get_enums(); + vector::const_iterator e_iter; + for (e_iter = enums.begin(); e_iter != enums.end(); ++e_iter) { + f_service_ts_ << "import " << (*e_iter)->get_name() << " = ttypes." + << js_namespace(program_) << (*e_iter)->get_name() << endl; + } + // const + vector const& consts = program_->get_consts(); + vector::const_iterator c_iter; + for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) { + f_service_ts_ << "import " << (*c_iter)->get_name() << " = ttypes." + << js_namespace(program_) << (*c_iter)->get_name() << endl; + } + // exception + vector const& exceptions = program_->get_xceptions(); + vector::const_iterator x_iter; + for (x_iter = exceptions.begin(); x_iter != exceptions.end(); ++x_iter) { + f_service_ts_ << "import " << (*x_iter)->get_name() << " = ttypes." + << js_namespace(program_) << (*x_iter)->get_name() << endl; + } + // structs + vector const& structs = program_->get_structs(); + vector::const_iterator s_iter; + for (s_iter = structs.begin(); s_iter != structs.end(); ++s_iter) { + f_service_ts_ << "import " << (*s_iter)->get_name() << " = ttypes." + << js_namespace(program_) << (*s_iter)->get_name() << endl; + } + } if (!ts_module_.empty()) { f_service_ts_ << "declare module " << ts_module_ << " {"; } @@ -985,15 +1127,15 @@ void t_js_generator::generate_service(t_service* tservice) { if (gen_node_) { if (tservice->get_extends() != NULL) { - f_service_ << "var " << tservice->get_extends()->get_name() << " = require('./" - << tservice->get_extends()->get_name() << "');" << endl << "var " + f_service_ << js_const_type_ << tservice->get_extends()->get_name() << " = require('./" + << tservice->get_extends()->get_name() << "');" << endl << js_const_type_ << tservice->get_extends()->get_name() << "Client = " << tservice->get_extends()->get_name() << ".Client;" << endl - << "var " << tservice->get_extends()->get_name() + << js_const_type_ << tservice->get_extends()->get_name() << "Processor = " << tservice->get_extends()->get_name() << ".Processor;" << endl; } - f_service_ << "var ttypes = require('./" + program_->get_name() + "_types');" << endl; + f_service_ << js_const_type_ << "ttypes = require('./" + program_->get_name() + "_types');" << endl; } generate_service_helpers(tservice); @@ -1023,38 +1165,77 @@ void t_js_generator::generate_service_processor(t_service* tservice) { vector::iterator f_iter; if (gen_node_) { - string prefix = has_js_namespace(tservice->get_program()) ? js_namespace(tservice->get_program()) : "var "; - f_service_ << prefix << service_name_ << "Processor = " << "exports.Processor = function(handler) "; + string prefix = has_js_namespace(tservice->get_program()) ? js_namespace(tservice->get_program()) : js_const_type_; + f_service_ << prefix << service_name_ << "Processor = " << "exports.Processor"; + if (gen_ts_) { + f_service_ts_ << endl << "declare class Processor "; + if (tservice->get_extends() != NULL) { + f_service_ts_ << "extends " << tservice->get_extends()->get_name() << "Processor "; + } + f_service_ts_ << "{" << endl; + indent_up(); + f_service_ts_ << ts_indent() << "private _handler: Object;" << endl << endl; + f_service_ts_ << ts_indent() << "constructor(handler: Object);" << endl; + f_service_ts_ << ts_indent() << "process(input: Thrift.TJSONProtocol, output: Thrift.TJSONProtocol): void;" << endl; + indent_down(); + } } else { f_service_ << js_namespace(tservice->get_program()) << service_name_ << "Processor = " - << "exports.Processor = function(handler) "; + << "exports.Processor"; } - scope_up(f_service_); + bool is_subclass_service = tservice->get_extends() != NULL; - f_service_ << indent() << "this._handler = handler;" << endl; + // ES6 Constructor + if (gen_es6_) { + if (is_subclass_service) { + f_service_ << " = class extends " << tservice->get_extends()->get_name() << "Processor {" << endl; + } else { + f_service_ << " = class {" << endl; + } + indent_up(); + indent(f_service_) << "constructor(handler) {" << endl; + } else { + f_service_ << " = function(handler) {" << endl; + } - scope_down(f_service_); - f_service_ << ";" << endl; + indent_up(); + if (gen_es6_ && is_subclass_service) { + indent(f_service_) << "super(handler);" << endl; + } + indent(f_service_) << "this._handler = handler;" << endl; + indent_down(); - if (tservice->get_extends() != NULL) { + // Done with constructor + if (gen_es6_) { + indent(f_service_) << "}" << endl; + } else { + indent(f_service_) << "};" << endl; + } + + // ES5 service inheritance + if (!gen_es6_ && is_subclass_service) { indent(f_service_) << "Thrift.inherits(" << js_namespace(tservice->get_program()) << service_name_ << "Processor, " << tservice->get_extends()->get_name() << "Processor);" << endl; } // Generate the server implementation - indent(f_service_) << js_namespace(tservice->get_program()) << service_name_ - << "Processor.prototype.process = function(input, output) "; + if (gen_es6_) { + indent(f_service_) << "process (input, output) {" << endl; + } else { + indent(f_service_) << js_namespace(tservice->get_program()) << service_name_ + << "Processor.prototype.process = function(input, output) {" << endl; + } - scope_up(f_service_); + indent_up(); - f_service_ << indent() << "var r = input.readMessageBegin();" << endl << indent() + indent(f_service_) << js_const_type_ << "r = input.readMessageBegin();" << endl << indent() << "if (this['process_' + r.fname]) {" << endl << indent() << " return this['process_' + r.fname].call(this, r.rseqid, input, output);" << endl << indent() << "} else {" << endl << indent() << " input.skip(Thrift.Type.STRUCT);" << endl << indent() << " input.readMessageEnd();" << endl << indent() - << " var x = new " + << " " << js_const_type_ << "x = new " "Thrift.TApplicationException(Thrift.TApplicationExceptionType.UNKNOWN_METHOD, " "'Unknown function ' + r.fname);" << endl << indent() << " output.writeMessageBegin(r.fname, Thrift.MessageType.EXCEPTION, r.rseqid);" @@ -1062,13 +1243,26 @@ void t_js_generator::generate_service_processor(t_service* tservice) { << " output.writeMessageEnd();" << endl << indent() << " output.flush();" << endl << indent() << "}" << endl; - scope_down(f_service_); - f_service_ << ";" << endl; + indent_down(); + if (gen_es6_) { + indent(f_service_) << "}" << endl; + } else { + indent(f_service_) << "};" << endl; + } // Generate the process subfunctions for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { generate_process_function(tservice, *f_iter); } + + // Close off the processor class definition + if (gen_es6_) { + indent_down(); + indent(f_service_) << "};" << endl; + } + if (gen_node_ && gen_ts_) { + f_service_ts_ << "}" << endl; + } } /** @@ -1077,17 +1271,26 @@ void t_js_generator::generate_service_processor(t_service* tservice) { * @param tfunction The function to write a dispatcher for */ void t_js_generator::generate_process_function(t_service* tservice, t_function* tfunction) { - indent(f_service_) << js_namespace(tservice->get_program()) << service_name_ - << "Processor.prototype.process_" + tfunction->get_name() - + " = function(seqid, input, output) "; + if (gen_es6_) { + indent(f_service_) << "process_" + tfunction->get_name() + " (seqid, input, output) {" << endl; + } else { + indent(f_service_) << js_namespace(tservice->get_program()) << service_name_ + << "Processor.prototype.process_" + tfunction->get_name() + + " = function(seqid, input, output) {" << endl; + } + if (gen_ts_) { + indent_up(); + f_service_ts_ << ts_indent() << "process_" << tfunction->get_name() << "(seqid: number, input: Thrift.TJSONProtocol, output: Thrift.TJSONProtocol): void;" << endl; + indent_down(); + } - scope_up(f_service_); + indent_up(); string argsname = js_namespace(program_) + service_name_ + "_" + tfunction->get_name() + "_args"; string resultname = js_namespace(program_) + service_name_ + "_" + tfunction->get_name() + "_result"; - f_service_ << indent() << "var args = new " << argsname << "();" << endl << indent() + indent(f_service_) << js_const_type_ << "args = new " << argsname << "();" << endl << indent() << "args.read(input);" << endl << indent() << "input.readMessageEnd();" << endl; // Generate the function call @@ -1110,33 +1313,57 @@ void t_js_generator::generate_process_function(t_service* tservice, t_function* } f_service_ << ");" << endl; - scope_down(f_service_); - f_service_ << ";" << endl; + indent_down(); + + if (gen_es6_) { + indent(f_service_) << "}" << endl; + } else { + indent(f_service_) << "};" << endl; + } return; } - f_service_ << indent() << "if (this._handler." << tfunction->get_name() + // Promise style invocation + indent(f_service_) << "if (this._handler." << tfunction->get_name() << ".length === " << fields.size() << ") {" << endl; indent_up(); - indent(f_service_) << "Q.fcall(this._handler." << tfunction->get_name(); - for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { - f_service_ << ", args." << (*f_iter)->get_name(); + if (gen_es6_) { + indent(f_service_) << "Promise.resolve(this._handler." << tfunction->get_name() << ".bind(this._handler)(" << endl; + } else { + string maybeComma = (fields.size() > 0 ? "," : ""); + indent(f_service_) << "Q.fcall(this._handler." << tfunction->get_name() << ".bind(this._handler)" + << maybeComma << endl; } - f_service_ << ")" << endl; indent_up(); - indent(f_service_) << ".then(function(result) {" << endl; + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { + string maybeComma = (f_iter != fields.end() - 1 ? "," : ""); + indent(f_service_) << "args." << (*f_iter)->get_name() << maybeComma << endl; + } + indent_down(); + + if (gen_es6_) { + indent(f_service_) << ")).then(result => {" << endl; + } else { + indent(f_service_) << ").then(function(result) {" << endl; + } + indent_up(); - f_service_ << indent() << "var result_obj = new " << resultname << "({success: result});" << endl + f_service_ << indent() << js_const_type_ << "result_obj = new " << resultname << "({success: result});" << endl << indent() << "output.writeMessageBegin(\"" << tfunction->get_name() << "\", Thrift.MessageType.REPLY, seqid);" << endl << indent() << "result_obj.write(output);" << endl << indent() << "output.writeMessageEnd();" << endl << indent() << "output.flush();" << endl; indent_down(); - indent(f_service_) << "}, function (err) {" << endl; + + if (gen_es6_) { + indent(f_service_) << "}).catch(err => {" << endl; + } else { + indent(f_service_) << "}).catch(function (err) {" << endl; + } indent_up(); - indent(f_service_) << "var result;" << endl; + indent(f_service_) << js_let_type_ << "result;" << endl; bool has_exception = false; t_struct* exceptions = tfunction->get_xceptions(); @@ -1184,7 +1411,9 @@ void t_js_generator::generate_process_function(t_service* tservice, t_function* indent_down(); indent(f_service_) << "});" << endl; indent_down(); - indent_down(); + // End promise style invocation + + // Callback style invocation indent(f_service_) << "} else {" << endl; indent_up(); indent(f_service_) << "this._handler." << tfunction->get_name() << "("; @@ -1193,9 +1422,13 @@ void t_js_generator::generate_process_function(t_service* tservice, t_function* f_service_ << "args." << (*f_iter)->get_name() << ", "; } - f_service_ << "function (err, result) {" << endl; + if (gen_es6_) { + f_service_ << "(err, result) => {" << endl; + } else { + f_service_ << "function (err, result) {" << endl; + } indent_up(); - indent(f_service_) << "var result_obj;" << endl; + indent(f_service_) << js_let_type_ << "result_obj;" << endl; indent(f_service_) << "if ((err === null || typeof err === 'undefined')"; if (has_exception) { @@ -1228,8 +1461,15 @@ void t_js_generator::generate_process_function(t_service* tservice, t_function* indent(f_service_) << "});" << endl; indent_down(); indent(f_service_) << "}" << endl; + // End callback style invocation + indent_down(); - indent(f_service_) << "};" << endl; + + if (gen_es6_) { + indent(f_service_) << "}" << endl; + } else { + indent(f_service_) << "};" << endl; + } } /** @@ -1303,33 +1543,73 @@ void t_js_generator::generate_service_rest(t_service* tservice) { * @param tservice The service to generate a server for. */ void t_js_generator::generate_service_client(t_service* tservice) { + + bool is_subclass_service = tservice->get_extends() != NULL; + if (gen_node_) { - string prefix = has_js_namespace(tservice->get_program()) ? js_namespace(tservice->get_program()) : "var "; - f_service_ << prefix << service_name_ << "Client = " - << "exports.Client = function(output, pClass) {" << endl; + string prefix = has_js_namespace(tservice->get_program()) ? js_namespace(tservice->get_program()) : js_const_type_; + f_service_ << prefix << service_name_ << "Client = " << "exports.Client"; + if (gen_ts_) { + f_service_ts_ << ts_print_doc(tservice) << ts_indent() << ts_declare() << "class " + << "Client "; + if (tservice->get_extends() != NULL) { + f_service_ts_ << "extends " << tservice->get_extends()->get_name() << "Client "; + } + f_service_ts_ << "{" << endl; + } } else { f_service_ << js_namespace(tservice->get_program()) << service_name_ - << "Client = function(input, output) {" << endl; + << "Client"; if (gen_ts_) { f_service_ts_ << ts_print_doc(tservice) << ts_indent() << ts_declare() << "class " << service_name_ << "Client "; - if (tservice->get_extends() != NULL) { + if (is_subclass_service) { f_service_ts_ << "extends " << tservice->get_extends()->get_name() << "Client "; } f_service_ts_ << "{" << endl; } } + // ES6 Constructor + if (gen_es6_) { + if (is_subclass_service) { + f_service_ << " = class extends " << js_namespace(tservice->get_extends()->get_program()) + << tservice->get_extends()->get_name() << "Client {" << endl; + } else { + f_service_ << " = class {" << endl; + } + indent_up(); + if (gen_node_) { + indent(f_service_) << "constructor(output, pClass) {" << endl; + } else { + indent(f_service_) << "constructor(input, output) {" << endl; + } + } else { + if (gen_node_) { + f_service_ << " = function(output, pClass) {" << endl; + } else { + f_service_ << " = function(input, output) {" << endl; + } + } + indent_up(); if (gen_node_) { - f_service_ << indent() << " this.output = output;" << endl << indent() - << " this.pClass = pClass;" << endl << indent() << " this._seqid = 0;" << endl - << indent() << " this._reqs = {};" << endl; + indent(f_service_) << "this.output = output;" << endl; + indent(f_service_) << "this.pClass = pClass;" << endl; + indent(f_service_) << "this._seqid = 0;" << endl; + indent(f_service_) << "this._reqs = {};" << endl; + if (gen_ts_) { + f_service_ts_ << ts_indent() << "private input: Thrift.TJSONProtocol;" << endl << ts_indent() + << "private output: Thrift.TJSONProtocol;" << endl << ts_indent() << "private seqid: number;" + << endl << endl << ts_indent() + << "constructor(input: Thrift.TJSONProtocol, output?: Thrift.TJSONProtocol);" + << endl; + } } else { - f_service_ << indent() << " this.input = input;" << endl << indent() - << " this.output = (!output) ? input : output;" << endl << indent() - << " this.seqid = 0;" << endl; + indent(f_service_) << "this.input = input;" << endl; + indent(f_service_) << "this.output = (!output) ? input : output;" << endl; + indent(f_service_) << "this.seqid = 0;" << endl; if (gen_ts_) { f_service_ts_ << ts_indent() << "input: Thrift.TJSONProtocol;" << endl << ts_indent() << "output: Thrift.TJSONProtocol;" << endl << ts_indent() << "seqid: number;" @@ -1341,27 +1621,36 @@ void t_js_generator::generate_service_client(t_service* tservice) { indent_down(); - f_service_ << indent() << "};" << endl; - - if (tservice->get_extends() != NULL) { - indent(f_service_) << "Thrift.inherits(" << js_namespace(tservice->get_program()) - << service_name_ << "Client, " - << js_namespace(tservice->get_extends()->get_program()) - << tservice->get_extends()->get_name() << "Client);" << endl; + if (gen_es6_) { + indent(f_service_) << "}" << endl; } else { - // init prototype - indent(f_service_) << js_namespace(tservice->get_program()) << service_name_ - << "Client.prototype = {};" << endl; + indent(f_service_) << "};" << endl; + if (is_subclass_service) { + indent(f_service_) << "Thrift.inherits(" << js_namespace(tservice->get_program()) + << service_name_ << "Client, " + << js_namespace(tservice->get_extends()->get_program()) + << tservice->get_extends()->get_name() << "Client);" << endl; + } else { + // init prototype + indent(f_service_) << js_namespace(tservice->get_program()) << service_name_ + << "Client.prototype = {};" << endl; + } } // utils for multiplexed services if (gen_node_) { - indent(f_service_) << js_namespace(tservice->get_program()) << service_name_ - << "Client.prototype.seqid = function() { return this._seqid; };" << endl - << js_namespace(tservice->get_program()) << service_name_ - << "Client.prototype.new_seqid = function() { return this._seqid += 1; };" - << endl; + if (gen_es6_) { + indent(f_service_) << "seqid () { return this._seqid; }" << endl; + indent(f_service_) << "new_seqid () { return this._seqid += 1; }" << endl; + } else { + indent(f_service_) << js_namespace(tservice->get_program()) << service_name_ + << "Client.prototype.seqid = function() { return this._seqid; };" << endl + << js_namespace(tservice->get_program()) << service_name_ + << "Client.prototype.new_seqid = function() { return this._seqid += 1; };" + << endl; + } } + // Generate client method implementations vector functions = tservice->get_functions(); vector::const_iterator f_iter; @@ -1373,24 +1662,46 @@ void t_js_generator::generate_service_client(t_service* tservice) { string arglist = argument_list(arg_struct); // Open function - f_service_ << js_namespace(tservice->get_program()) << service_name_ << "Client.prototype." - << function_signature(*f_iter, "", true) << " {" << endl; + f_service_ << endl; + if (gen_es6_) { + indent(f_service_) << funname << " (" << arglist << ") {" << endl; + } else { + indent(f_service_) << js_namespace(tservice->get_program()) << service_name_ << "Client.prototype." + << function_signature(*f_iter, "", !gen_es6_) << " {" << endl; + } indent_up(); if (gen_ts_) { - f_service_ts_ << ts_print_doc(*f_iter) << - // function definition without callback - ts_indent() << ts_function_signature(*f_iter, false) << endl << ts_print_doc(*f_iter) << - // overload with callback - ts_indent() << ts_function_signature(*f_iter, true) << endl; + // function definition without callback + f_service_ts_ << ts_print_doc(*f_iter) << ts_indent() << ts_function_signature(*f_iter, false, false) << endl; + if (!gen_es6_) { + // overload with callback + f_service_ts_ << ts_print_doc(*f_iter) << ts_indent() << ts_function_signature(*f_iter, true, false) << endl; + } else { + // overload with callback + f_service_ts_ << ts_print_doc(*f_iter) << ts_indent() << ts_function_signature(*f_iter, true, true) << endl; + } } - if (gen_node_) { // Node.js output ./gen-nodejs + if (gen_es6_ && gen_node_) { + indent(f_service_) << "this._seqid = this.new_seqid();" << endl; + indent(f_service_) << js_const_type_ << "self = this;" << endl << indent() + << "return new Promise((resolve, reject) => {" << endl; + indent_up(); + indent(f_service_) << "self._reqs[self.seqid()] = (error, result) => {" << endl; + indent_up(); + indent(f_service_) << "return error ? reject(error) : resolve(result);" << endl; + indent_down(); + indent(f_service_) << "};" << endl; + indent(f_service_) << "self.send_" << funname << "(" << arglist << ");" << endl; + indent_down(); + indent(f_service_) << "});" << endl; + } else if (gen_node_) { // Node.js output ./gen-nodejs f_service_ << indent() << "this._seqid = this.new_seqid();" << endl << indent() << "if (callback === undefined) {" << endl; indent_up(); - f_service_ << indent() << "var _defer = Q.defer();" << endl << indent() + f_service_ << indent() << js_const_type_ << "_defer = Q.defer();" << endl << indent() << "this._reqs[this.seqid()] = function(error, result) {" << endl; indent_up(); indent(f_service_) << "if (error) {" << endl; @@ -1413,6 +1724,19 @@ void t_js_generator::generate_service_client(t_service* tservice) { << "this.send_" << funname << "(" << arglist << ");" << endl; indent_down(); indent(f_service_) << "}" << endl; + } else if (gen_es6_) { + f_service_ << indent() << js_const_type_ << "self = this;" << endl << indent() + << "return new Promise((resolve, reject) => {" << endl; + indent_up(); + f_service_ << indent() << "self.send_" << funname << "(" << arglist + << (arglist.empty() ? "" : ", ") << "(error, result) => {" << endl; + indent_up(); + indent(f_service_) << "return error ? reject(error) : resolve(result);" << endl; + indent_down(); + f_service_ << indent() << "});" << endl; + indent_down(); + f_service_ << indent() << "});" << endl; + } else if (gen_jquery_) { // jQuery output ./gen-js f_service_ << indent() << "if (callback === undefined) {" << endl; indent_up(); @@ -1427,7 +1751,7 @@ void t_js_generator::generate_service_client(t_service* tservice) { indent_down(); f_service_ << indent() << "} else {" << endl; indent_up(); - f_service_ << indent() << "var postData = this.send_" << funname << "(" << arglist + f_service_ << indent() << js_const_type_ << "postData = this.send_" << funname << "(" << arglist << (arglist.empty() ? "" : ", ") << "true);" << endl; f_service_ << indent() << "return this.output.getTransport()" << endl; indent_up(); @@ -1452,17 +1776,30 @@ void t_js_generator::generate_service_client(t_service* tservice) { indent_down(); - f_service_ << "};" << endl << endl; + if (gen_es6_) { + indent(f_service_) << "}" << endl << endl; + } else { + indent(f_service_) << "};" << endl << endl; + } // Send function - f_service_ << js_namespace(tservice->get_program()) << service_name_ << "Client.prototype.send_" - << function_signature(*f_iter, "", !gen_node_) << " {" << endl; + if (gen_es6_) { + if (gen_node_) { + indent(f_service_) << "send_" << funname << " (" << arglist << ") {" << endl; + } else { + // ES6 js still uses callbacks here. Should refactor this to promise style later.. + indent(f_service_) << "send_" << funname << " (" << argument_list(arg_struct, true) << ") {" << endl; + } + } else { + indent(f_service_) << js_namespace(tservice->get_program()) << service_name_ << "Client.prototype.send_" + << function_signature(*f_iter, "", !gen_node_) << " {" << endl; + } indent_up(); std::string outputVar; if (gen_node_) { - f_service_ << indent() << "var output = new this.pClass(this.output);" << endl; + f_service_ << indent() << js_const_type_ << "output = new this.pClass(this.output);" << endl; outputVar = "output"; } else { outputVar = "this.output"; @@ -1473,8 +1810,30 @@ void t_js_generator::generate_service_client(t_service* tservice) { std::string messageType = (*f_iter)->is_oneway() ? "Thrift.MessageType.ONEWAY" : "Thrift.MessageType.CALL"; + // Build args + if (fields.size() > 0){ + f_service_ << indent() << js_const_type_ << "params = {" << endl; + indent_up(); + for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) { + indent(f_service_) << (*fld_iter)->get_name() << ": " << (*fld_iter)->get_name(); + if (fld_iter != fields.end()-1) { + f_service_ << "," << endl; + } else { + f_service_ << endl; + } + } + indent_down(); + indent(f_service_) << "};" << endl; + indent(f_service_) << js_const_type_ << "args = new " << argsname << "(params);" << endl; + } else { + indent(f_service_) << js_const_type_ << "args = new " << argsname << "();" << endl; + } + + + // Serialize the request header within try/catch + indent(f_service_) << "try {" << endl; + indent_up(); - // Serialize the request header if (gen_node_) { f_service_ << indent() << outputVar << ".writeMessageBegin('" << (*f_iter)->get_name() << "', " << messageType << ", this.seqid());" << endl; @@ -1483,34 +1842,62 @@ void t_js_generator::generate_service_client(t_service* tservice) { << "', " << messageType << ", this.seqid);" << endl; } - f_service_ << indent() << "var args = new " << argsname << "();" << endl; - - for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) { - f_service_ << indent() << "args." << (*fld_iter)->get_name() << " = " - << (*fld_iter)->get_name() << ";" << endl; - } // Write to the stream f_service_ << indent() << "args.write(" << outputVar << ");" << endl << indent() << outputVar << ".writeMessageEnd();" << endl; if (gen_node_) { - f_service_ << indent() << "return this.output.flush();" << endl; + if((*f_iter)->is_oneway()) { + f_service_ << indent() << "this.output.flush();" << endl; + f_service_ << indent() << js_const_type_ << "callback = this._reqs[this.seqid()] || function() {};" << endl; + f_service_ << indent() << "delete this._reqs[this.seqid()];" << endl; + f_service_ << indent() << "callback(null);" << endl; + } else { + f_service_ << indent() << "return this.output.flush();" << endl; + } } else { if (gen_jquery_) { f_service_ << indent() << "return this.output.getTransport().flush(callback);" << endl; + } else if (gen_es6_) { + f_service_ << indent() << js_const_type_ << "self = this;" << endl; + if((*f_iter)->is_oneway()) { + f_service_ << indent() << "this.output.getTransport().flush(true, null);" << endl; + f_service_ << indent() << "callback();" << endl; + } else { + f_service_ << indent() << "this.output.getTransport().flush(true, () => {" << endl; + indent_up(); + f_service_ << indent() << js_let_type_ << "error = null, result = null;" << endl; + f_service_ << indent() << "try {" << endl; + f_service_ << indent() << " result = self.recv_" << funname << "();" << endl; + f_service_ << indent() << "} catch (e) {" << endl; + f_service_ << indent() << " error = e;" << endl; + f_service_ << indent() << "}" << endl; + f_service_ << indent() << "callback(error, result);" << endl; + indent_down(); + f_service_ << indent() << "});" << endl; + } } else { f_service_ << indent() << "if (callback) {" << endl; - f_service_ << indent() << " var self = this;" << endl; - f_service_ << indent() << " this.output.getTransport().flush(true, function() {" << endl; - f_service_ << indent() << " var result = null;" << endl; - f_service_ << indent() << " try {" << endl; - f_service_ << indent() << " result = self.recv_" << funname << "();" << endl; - f_service_ << indent() << " } catch (e) {" << endl; - f_service_ << indent() << " result = e;" << endl; - f_service_ << indent() << " }" << endl; - f_service_ << indent() << " callback(result);" << endl; - f_service_ << indent() << " });" << endl; + indent_up(); + if((*f_iter)->is_oneway()) { + f_service_ << indent() << "this.output.getTransport().flush(true, null);" << endl; + f_service_ << indent() << "callback();" << endl; + } else { + f_service_ << indent() << js_const_type_ << "self = this;" << endl; + f_service_ << indent() << "this.output.getTransport().flush(true, function() {" << endl; + indent_up(); + f_service_ << indent() << js_let_type_ << "result = null;" << endl; + f_service_ << indent() << "try {" << endl; + f_service_ << indent() << " result = self.recv_" << funname << "();" << endl; + f_service_ << indent() << "} catch (e) {" << endl; + f_service_ << indent() << " result = e;" << endl; + f_service_ << indent() << "}" << endl; + f_service_ << indent() << "callback(result);" << endl; + indent_down(); + f_service_ << indent() << "});" << endl; + } + indent_down(); f_service_ << indent() << "} else {" << endl; f_service_ << indent() << " return this.output.getTransport().flush();" << endl; f_service_ << indent() << "}" << endl; @@ -1518,27 +1905,61 @@ void t_js_generator::generate_service_client(t_service* tservice) { } indent_down(); + f_service_ << indent() << "}" << endl; - f_service_ << "};" << endl; + // Reset the transport and delete registered callback if there was a serialization error + f_service_ << indent() << "catch (e) {" << endl; + indent_up(); + if (gen_node_) { + f_service_ << indent() << "delete this._reqs[this.seqid()];" << endl; + f_service_ << indent() << "if (typeof " << outputVar << ".reset === 'function') {" << endl; + f_service_ << indent() << " " << outputVar << ".reset();" << endl; + f_service_ << indent() << "}" << endl; + } else { + f_service_ << indent() << "if (typeof " << outputVar << ".getTransport().reset === 'function') {" << endl; + f_service_ << indent() << " " << outputVar << ".getTransport().reset();" << endl; + f_service_ << indent() << "}" << endl; + } + f_service_ << indent() << "throw e;" << endl; + indent_down(); + f_service_ << indent() << "}" << endl; + indent_down(); + + // Close send function + if (gen_es6_) { + indent(f_service_) << "}" << endl; + } else { + indent(f_service_) << "};" << endl; + } + + // Receive function if (!(*f_iter)->is_oneway()) { std::string resultname = js_namespace(tservice->get_program()) + service_name_ + "_" + (*f_iter)->get_name() + "_result"; + f_service_ << endl; + // Open receive function if (gen_node_) { - // Open function - f_service_ << endl << js_namespace(tservice->get_program()) << service_name_ - << "Client.prototype.recv_" << (*f_iter)->get_name() - << " = function(input,mtype,rseqid) {" << endl; + if (gen_es6_) { + indent(f_service_) << "recv_" << (*f_iter)->get_name() << " (input, mtype, rseqid) {" << endl; + } else { + indent(f_service_) << js_namespace(tservice->get_program()) << service_name_ + << "Client.prototype.recv_" << (*f_iter)->get_name() + << " = function(input,mtype,rseqid) {" << endl; + } } else { - t_struct noargs(program_); + if (gen_es6_) { + indent(f_service_) << "recv_" << (*f_iter)->get_name() << " () {" << endl; + } else { + t_struct noargs(program_); - t_function recv_function((*f_iter)->get_returntype(), - string("recv_") + (*f_iter)->get_name(), - &noargs); - // Open function - f_service_ << endl << js_namespace(tservice->get_program()) << service_name_ - << "Client.prototype." << function_signature(&recv_function) << " {" << endl; + t_function recv_function((*f_iter)->get_returntype(), + string("recv_") + (*f_iter)->get_name(), + &noargs); + indent(f_service_) << js_namespace(tservice->get_program()) << service_name_ + << "Client.prototype." << function_signature(&recv_function) << " {" << endl; + } } indent_up(); @@ -1551,21 +1972,23 @@ void t_js_generator::generate_service_client(t_service* tservice) { } if (gen_node_) { - f_service_ << indent() << "var callback = this._reqs[rseqid] || function() {};" << endl + f_service_ << indent() << js_const_type_ << "callback = this._reqs[rseqid] || function() {};" << endl << indent() << "delete this._reqs[rseqid];" << endl; } else { - f_service_ << indent() << "var ret = this.input.readMessageBegin();" << endl << indent() - << "var fname = ret.fname;" << endl << indent() << "var mtype = ret.mtype;" - << endl << indent() << "var rseqid = ret.rseqid;" << endl; + f_service_ << indent() << js_const_type_ << "ret = this.input.readMessageBegin();" << endl + << indent() << js_const_type_ << "mtype = ret.mtype;" << endl; } - f_service_ << indent() << "if (mtype == Thrift.MessageType.EXCEPTION) {" << endl << indent() - << " var x = new Thrift.TApplicationException();" << endl << indent() - << " x.read(" << inputVar << ");" << endl << indent() << " " << inputVar - << ".readMessageEnd();" << endl << indent() << " " << render_recv_throw("x") - << endl << indent() << "}" << endl; + f_service_ << indent() << "if (mtype == Thrift.MessageType.EXCEPTION) {" << endl; - f_service_ << indent() << "var result = new " << resultname << "();" << endl << indent() + indent_up(); + f_service_ << indent() << js_const_type_ << "x = new Thrift.TApplicationException();" << endl + << indent() << "x.read(" << inputVar << ");" << endl + << indent() << inputVar << ".readMessageEnd();" << endl + << indent() << render_recv_throw("x") << endl; + scope_down(f_service_); + + f_service_ << indent() << js_const_type_ << "result = new " << resultname << "();" << endl << indent() << "result.read(" << inputVar << ");" << endl; f_service_ << indent() << inputVar << ".readMessageEnd();" << endl << endl; @@ -1594,15 +2017,24 @@ void t_js_generator::generate_service_client(t_service* tservice) { } } - // Close function + // Close receive function indent_down(); - f_service_ << "};" << endl; + if (gen_es6_) { + indent(f_service_) << "}" << endl; + } else { + indent(f_service_) << "};" << endl; + } } } + // Finish class definitions if (gen_ts_) { f_service_ts_ << ts_indent() << "}" << endl; } + if (gen_es6_) { + indent_down(); + f_service_ << "};" << endl; + } } std::string t_js_generator::render_recv_throw(std::string var) { @@ -1624,7 +2056,7 @@ std::string t_js_generator::render_recv_return(std::string var) { /** * Deserializes a field of any type. */ -void t_js_generator::generate_deserialize_field(ofstream& out, +void t_js_generator::generate_deserialize_field(ostream& out, t_field* tfield, string prefix, bool inclass) { @@ -1651,7 +2083,7 @@ void t_js_generator::generate_deserialize_field(ofstream& out, throw "compiler error: cannot serialize void field in a struct: " + name; break; case t_base_type::TYPE_STRING: - out << (((t_base_type*)type)->is_binary() ? "readBinary()" : "readString()"); + out << (type->is_binary() ? "readBinary()" : "readString()"); break; case t_base_type::TYPE_BOOL: out << "readBool()"; @@ -1696,54 +2128,42 @@ void t_js_generator::generate_deserialize_field(ofstream& out, * buffer for deserialization, and that there is a variable protocol which * is a reference to a TProtocol serialization object. */ -void t_js_generator::generate_deserialize_struct(ofstream& out, t_struct* tstruct, string prefix) { +void t_js_generator::generate_deserialize_struct(ostream& out, t_struct* tstruct, string prefix) { out << indent() << prefix << " = new " << js_type_namespace(tstruct->get_program()) << tstruct->get_name() << "();" << endl << indent() << prefix << ".read(input);" << endl; } -void t_js_generator::generate_deserialize_container(ofstream& out, t_type* ttype, string prefix) { +void t_js_generator::generate_deserialize_container(ostream& out, t_type* ttype, string prefix) { string size = tmp("_size"); - string ktype = tmp("_ktype"); - string vtype = tmp("_vtype"); - string etype = tmp("_etype"); string rtmp3 = tmp("_rtmp3"); t_field fsize(g_type_i32, size); - t_field fktype(g_type_i8, ktype); - t_field fvtype(g_type_i8, vtype); - t_field fetype(g_type_i8, etype); - - out << indent() << "var " << size << " = 0;" << endl; - out << indent() << "var " << rtmp3 << ";" << endl; // Declare variables, read header if (ttype->is_map()) { - out << indent() << prefix << " = {};" << endl << indent() << "var " << ktype << " = 0;" << endl - << indent() << "var " << vtype << " = 0;" << endl; + out << indent() << prefix << " = {};" << endl; - out << indent() << rtmp3 << " = input.readMapBegin();" << endl; - out << indent() << ktype << " = " << rtmp3 << ".ktype;" << endl; - out << indent() << vtype << " = " << rtmp3 << ".vtype;" << endl; - out << indent() << size << " = " << rtmp3 << ".size;" << endl; + out << indent() << js_const_type_ << rtmp3 << " = input.readMapBegin();" << endl; + out << indent() << js_const_type_ << size << " = " << rtmp3 << ".size || 0;" << endl; } else if (ttype->is_set()) { - out << indent() << prefix << " = [];" << endl << indent() << "var " << etype << " = 0;" << endl - << indent() << rtmp3 << " = input.readSetBegin();" << endl << indent() << etype << " = " - << rtmp3 << ".etype;" << endl << indent() << size << " = " << rtmp3 << ".size;" << endl; + out << indent() << prefix << " = [];" << endl + << indent() << js_const_type_ << rtmp3 << " = input.readSetBegin();" << endl + << indent() << js_const_type_ << size << " = " << rtmp3 << ".size || 0;" << endl; } else if (ttype->is_list()) { - out << indent() << prefix << " = [];" << endl << indent() << "var " << etype << " = 0;" << endl - << indent() << rtmp3 << " = input.readListBegin();" << endl << indent() << etype << " = " - << rtmp3 << ".etype;" << endl << indent() << size << " = " << rtmp3 << ".size;" << endl; + out << indent() << prefix << " = [];" << endl + << indent() << js_const_type_ << rtmp3 << " = input.readListBegin();" << endl + << indent() << js_const_type_ << size << " = " << rtmp3 << ".size || 0;" << endl; } // For loop iterates over elements string i = tmp("_i"); - indent(out) << "for (var " << i << " = 0; " << i << " < " << size << "; ++" << i << ")" << endl; + indent(out) << "for (" << js_let_type_ << i << " = 0; " << i << " < " << size << "; ++" << i << ") {" << endl; - scope_up(out); + indent_up(); if (ttype->is_map()) { if (!gen_node_) { @@ -1775,7 +2195,7 @@ void t_js_generator::generate_deserialize_container(ofstream& out, t_type* ttype /** * Generates code to deserialize a map */ -void t_js_generator::generate_deserialize_map_element(ofstream& out, t_map* tmap, string prefix) { +void t_js_generator::generate_deserialize_map_element(ostream& out, t_map* tmap, string prefix) { string key = tmp("key"); string val = tmp("val"); t_field fkey(tmap->get_key_type(), key); @@ -1790,24 +2210,24 @@ void t_js_generator::generate_deserialize_map_element(ofstream& out, t_map* tmap indent(out) << prefix << "[" << key << "] = " << val << ";" << endl; } -void t_js_generator::generate_deserialize_set_element(ofstream& out, t_set* tset, string prefix) { +void t_js_generator::generate_deserialize_set_element(ostream& out, t_set* tset, string prefix) { string elem = tmp("elem"); t_field felem(tset->get_elem_type(), elem); - indent(out) << "var " << elem << " = null;" << endl; + indent(out) << js_let_type_ << elem << " = null;" << endl; generate_deserialize_field(out, &felem); indent(out) << prefix << ".push(" << elem << ");" << endl; } -void t_js_generator::generate_deserialize_list_element(ofstream& out, +void t_js_generator::generate_deserialize_list_element(ostream& out, t_list* tlist, string prefix) { string elem = tmp("elem"); t_field felem(tlist->get_elem_type(), elem); - indent(out) << "var " << elem << " = null;" << endl; + indent(out) << js_let_type_ << elem << " = null;" << endl; generate_deserialize_field(out, &felem); @@ -1820,7 +2240,7 @@ void t_js_generator::generate_deserialize_list_element(ofstream& out, * @param tfield The field to serialize * @param prefix Name to prepend to field name */ -void t_js_generator::generate_serialize_field(ofstream& out, t_field* tfield, string prefix) { +void t_js_generator::generate_serialize_field(ostream& out, t_field* tfield, string prefix) { t_type* type = get_true_type(tfield->get_type()); // Do nothing for void types @@ -1849,7 +2269,7 @@ void t_js_generator::generate_serialize_field(ofstream& out, t_field* tfield, st throw "compiler error: cannot serialize void field in a struct: " + name; break; case t_base_type::TYPE_STRING: - out << (((t_base_type*)type)->is_binary() ? "writeBinary(" : "writeString(") << name << ")"; + out << (type->is_binary() ? "writeBinary(" : "writeString(") << name << ")"; break; case t_base_type::TYPE_BOOL: out << "writeBool(" << name << ")"; @@ -1891,7 +2311,7 @@ void t_js_generator::generate_serialize_field(ofstream& out, t_field* tfield, st * @param tstruct The struct to serialize * @param prefix String prefix to attach to all fields */ -void t_js_generator::generate_serialize_struct(ofstream& out, t_struct* tstruct, string prefix) { +void t_js_generator::generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix) { (void)tstruct; indent(out) << prefix << ".write(output);" << endl; } @@ -1899,7 +2319,7 @@ void t_js_generator::generate_serialize_struct(ofstream& out, t_struct* tstruct, /** * Writes out a container */ -void t_js_generator::generate_serialize_container(ofstream& out, t_type* ttype, string prefix) { +void t_js_generator::generate_serialize_container(ostream& out, t_type* ttype, string prefix) { if (ttype->is_map()) { indent(out) << "output.writeMapBegin(" << type_to_enum(((t_map*)ttype)->get_key_type()) << ", " << type_to_enum(((t_map*)ttype)->get_val_type()) << ", " @@ -1917,21 +2337,21 @@ void t_js_generator::generate_serialize_container(ofstream& out, t_type* ttype, if (ttype->is_map()) { string kiter = tmp("kiter"); string viter = tmp("viter"); - indent(out) << "for (var " << kiter << " in " << prefix << ")" << endl; - scope_up(out); - indent(out) << "if (" << prefix << ".hasOwnProperty(" << kiter << "))" << endl; - scope_up(out); - indent(out) << "var " << viter << " = " << prefix << "[" << kiter << "];" << endl; + indent(out) << "for (" << js_let_type_ << kiter << " in " << prefix << ") {" << endl; + indent_up(); + indent(out) << "if (" << prefix << ".hasOwnProperty(" << kiter << ")) {" << endl; + indent_up(); + indent(out) << js_let_type_ << viter << " = " << prefix << "[" << kiter << "];" << endl; generate_serialize_map_element(out, (t_map*)ttype, kiter, viter); scope_down(out); scope_down(out); } else if (ttype->is_set()) { string iter = tmp("iter"); - indent(out) << "for (var " << iter << " in " << prefix << ")" << endl; - scope_up(out); - indent(out) << "if (" << prefix << ".hasOwnProperty(" << iter << "))" << endl; - scope_up(out); + indent(out) << "for (" << js_let_type_ << iter << " in " << prefix << ") {" << endl; + indent_up(); + indent(out) << "if (" << prefix << ".hasOwnProperty(" << iter << ")) {" << endl; + indent_up(); indent(out) << iter << " = " << prefix << "[" << iter << "];" << endl; generate_serialize_set_element(out, (t_set*)ttype, iter); scope_down(out); @@ -1939,10 +2359,10 @@ void t_js_generator::generate_serialize_container(ofstream& out, t_type* ttype, } else if (ttype->is_list()) { string iter = tmp("iter"); - indent(out) << "for (var " << iter << " in " << prefix << ")" << endl; - scope_up(out); - indent(out) << "if (" << prefix << ".hasOwnProperty(" << iter << "))" << endl; - scope_up(out); + indent(out) << "for (" << js_let_type_ << iter << " in " << prefix << ") {" << endl; + indent_up(); + indent(out) << "if (" << prefix << ".hasOwnProperty(" << iter << ")) {" << endl; + indent_up(); indent(out) << iter << " = " << prefix << "[" << iter << "];" << endl; generate_serialize_list_element(out, (t_list*)ttype, iter); scope_down(out); @@ -1962,7 +2382,7 @@ void t_js_generator::generate_serialize_container(ofstream& out, t_type* ttype, * Serializes the members of a map. * */ -void t_js_generator::generate_serialize_map_element(ofstream& out, +void t_js_generator::generate_serialize_map_element(ostream& out, t_map* tmap, string kiter, string viter) { @@ -1976,7 +2396,7 @@ void t_js_generator::generate_serialize_map_element(ofstream& out, /** * Serializes the members of a set. */ -void t_js_generator::generate_serialize_set_element(ofstream& out, t_set* tset, string iter) { +void t_js_generator::generate_serialize_set_element(ostream& out, t_set* tset, string iter) { t_field efield(tset->get_elem_type(), iter); generate_serialize_field(out, &efield); } @@ -1984,7 +2404,7 @@ void t_js_generator::generate_serialize_set_element(ofstream& out, t_set* tset, /** * Serializes the members of a list. */ -void t_js_generator::generate_serialize_list_element(ofstream& out, t_list* tlist, string iter) { +void t_js_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string iter) { t_field efield(tlist->get_elem_type(), iter); generate_serialize_field(out, &efield); } @@ -1998,7 +2418,7 @@ string t_js_generator::declare_field(t_field* tfield, bool init, bool obj) { string result = "this." + tfield->get_name(); if (!obj) { - result = "var " + tfield->get_name(); + result = js_let_type_ + tfield->get_name(); } if (init) { @@ -2202,7 +2622,7 @@ string t_js_generator::ts_get_type(t_type* type) { * @param bool in-/exclude the callback argument * @return String of rendered function definition */ -std::string t_js_generator::ts_function_signature(t_function* tfunction, bool include_callback) { +std::string t_js_generator::ts_function_signature(t_function* tfunction, bool include_callback, bool optional_callback) { string str; const vector& fields = tfunction->get_arglist()->get_members(); vector::const_iterator f_iter; @@ -2218,15 +2638,42 @@ std::string t_js_generator::ts_function_signature(t_function* tfunction, bool in } if (include_callback) { - str += "callback: Function): "; + string callback_optional_string = optional_callback ? "?" : ""; + if (gen_node_) { + t_struct* exceptions = tfunction->get_xceptions(); + string exception_types; + if (exceptions) { + const vector& members = exceptions->get_members(); + for (vector::const_iterator it = members.begin(); it != members.end(); ++it) { + t_type* t = get_true_type((*it)->get_type()); + if (it == members.begin()) { + exception_types = t->get_name(); + } else { + exception_types += " | " + t->get_name(); + } + } + } + if (exception_types == "") { + str += "callback" + callback_optional_string + ": (error: void, response: " + ts_get_type(tfunction->get_returntype()) + ")=>void): "; + } else { + str += "callback" + callback_optional_string + ": (error: " + exception_types + ", response: " + ts_get_type(tfunction->get_returntype()) + ")=>void): "; + } + } else { + str += "callback" + callback_optional_string + ": (data: " + ts_get_type(tfunction->get_returntype()) + ")=>void): "; + } if (gen_jquery_) { - str += "JQueryXHR;"; + str += "JQueryPromise<" + ts_get_type(tfunction->get_returntype()) +">;"; } else { str += "void;"; } } else { - str += "): " + ts_get_type(tfunction->get_returntype()) + ";"; + if (gen_es6_) { + str += "): Promise<" + ts_get_type(tfunction->get_returntype()) + ">;"; + } + else { + str += "): " + ts_get_type(tfunction->get_returntype()) + ";"; + } } return str; @@ -2270,4 +2717,5 @@ THRIFT_REGISTER_GENERATOR(js, " jquery: Generate jQuery compatible code.\n" " node: Generate node.js compatible code.\n" " ts: Generate TypeScript definition files.\n" - " with_ns: Create global namespace objects when using node.js\n") + " with_ns: Create global namespace objects when using node.js\n" + " es6: Create ES6 code with Promises\n") diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_json_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_json_generator.cc index 36e9216..cd53612 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_json_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_json_generator.cc @@ -89,7 +89,7 @@ public: private: bool should_merge_includes_; - std::ofstream f_json_; + ofstream_with_content_based_conditional_update f_json_; std::stack comma_needed_; template @@ -264,6 +264,15 @@ void t_json_generator::write_type_spec(t_type* ttype) { write_string(get_type_name(ttype)); + if (ttype->annotations_.size() > 0) { + write_key_and("annotations"); + start_object(); + for (map::iterator it = ttype->annotations_.begin(); it != ttype->annotations_.end(); ++it) { + write_key_and_string(it->first, it->second); + } + end_object(); + } + if (ttype->is_struct() || ttype->is_xception()) { write_key_and_string("class", get_qualified_name(ttype)); } else if (ttype->is_map()) { @@ -273,10 +282,14 @@ void t_json_generator::write_type_spec(t_type* ttype) { write_key_and_string("valueTypeId", get_type_name(vtype)); write_type_spec_object("keyType", ktype); write_type_spec_object("valueType", vtype); - } else if (ttype->is_list() || ttype->is_set()) { + } else if (ttype->is_list()) { t_type* etype = ((t_list*)ttype)->get_elem_type(); write_key_and_string("elemTypeId", get_type_name(etype)); write_type_spec_object("elemType", etype); + } else if (ttype->is_set()) { + t_type* etype = ((t_set*)ttype)->get_elem_type(); + write_key_and_string("elemTypeId", get_type_name(etype)); + write_type_spec_object("elemType", etype); } } @@ -441,6 +454,14 @@ void t_json_generator::generate_typedef(t_typedef* ttypedef) { if (ttypedef->has_doc()) { write_key_and_string("doc", ttypedef->get_doc()); } + if (ttypedef->annotations_.size() > 0) { + write_key_and("annotations"); + start_object(); + for (map::iterator it = ttypedef->annotations_.begin(); it != ttypedef->annotations_.end(); ++it) { + write_key_and_string(it->first, it->second); + } + end_object(); + } end_object(); } @@ -489,8 +510,8 @@ void t_json_generator::write_const_value(t_const_value* value, bool should_force case t_const_value::CV_MAP: { start_object(NO_INDENT); - std::map map = value->get_map(); - std::map::iterator mit; + std::map map = value->get_map(); + std::map::iterator mit; for (mit = map.begin(); mit != map.end(); ++mit) { write_comma_if_needed(); f_json_ << indent(); @@ -540,6 +561,15 @@ void t_json_generator::generate_enum(t_enum* tenum) { write_key_and_string("doc", tenum->get_doc()); } + if (tenum->annotations_.size() > 0) { + write_key_and("annotations"); + start_object(); + for (map::iterator it = tenum->annotations_.begin(); it != tenum->annotations_.end(); ++it) { + write_key_and_string(it->first, it->second); + } + end_object(); + } + write_key_and("members"); start_array(); vector values = tenum->get_constants(); @@ -570,6 +600,15 @@ void t_json_generator::generate_struct(t_struct* tstruct) { write_key_and_string("doc", tstruct->get_doc()); } + if (tstruct->annotations_.size() > 0) { + write_key_and("annotations"); + start_object(); + for (map::iterator it = tstruct->annotations_.begin(); it != tstruct->annotations_.end(); ++it) { + write_key_and_string(it->first, it->second); + } + end_object(); + } + write_key_and_bool("isException", tstruct->is_xception()); write_key_and_bool("isUnion", tstruct->is_union()); @@ -601,6 +640,15 @@ void t_json_generator::generate_service(t_service* tservice) { write_key_and_string("doc", tservice->get_doc()); } + if (tservice->annotations_.size() > 0) { + write_key_and("annotations"); + start_object(); + for (map::iterator it = tservice->annotations_.begin(); it != tservice->annotations_.end(); ++it) { + write_key_and_string(it->first, it->second); + } + end_object(); + } + write_key_and("functions"); start_array(); vector functions = tservice->get_functions(); @@ -629,6 +677,15 @@ void t_json_generator::generate_function(t_function* tfunc) { write_key_and_string("doc", tfunc->get_doc()); } + if (tfunc->annotations_.size() > 0) { + write_key_and("annotations"); + start_object(); + for (map::iterator it = tfunc->annotations_.begin(); it != tfunc->annotations_.end(); ++it) { + write_key_and_string(it->first, it->second); + } + end_object(); + } + write_key_and("arguments"); start_array(); vector members = tfunc->get_arglist()->get_members(); @@ -666,6 +723,15 @@ void t_json_generator::generate_field(t_field* field) { write_key_and_string("doc", field->get_doc()); } + if (field->annotations_.size() > 0) { + write_key_and("annotations"); + start_object(); + for (map::iterator it = field->annotations_.begin(); it != field->annotations_.end(); ++it) { + write_key_and_string(it->first, it->second); + } + end_object(); + } + write_key_and("required"); switch (field->get_req()) { case t_field::T_REQUIRED: diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_lua_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_lua_generator.cc index 97b8aa3..adee896 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_lua_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_lua_generator.cc @@ -21,7 +21,7 @@ #include "thrift/platform.h" #include "thrift/generate/t_oop_generator.h" -using std::ofstream; +using std::ostream; using std::string; using std::vector; using std::map; @@ -80,65 +80,65 @@ private: /** * Struct-level generation functions */ - void generate_lua_struct_definition(std::ofstream& out, + void generate_lua_struct_definition(std::ostream& out, t_struct* tstruct, bool is_xception = false); - void generate_lua_struct_reader(std::ofstream& out, t_struct* tstruct); - void generate_lua_struct_writer(std::ofstream& out, t_struct* tstruct); + void generate_lua_struct_reader(std::ostream& out, t_struct* tstruct); + void generate_lua_struct_writer(std::ostream& out, t_struct* tstruct); /** * Service-level generation functions */ - void generate_service_client(std::ofstream& out, t_service* tservice); - void generate_service_interface(std::ofstream& out, t_service* tservice); - void generate_service_processor(std::ofstream& out, t_service* tservice); - void generate_process_function(std::ofstream& out, t_service* tservice, t_function* tfunction); - void generate_service_helpers(ofstream& out, t_service* tservice); - void generate_function_helpers(ofstream& out, t_function* tfunction); + void generate_service_client(std::ostream& out, t_service* tservice); + void generate_service_interface(std::ostream& out, t_service* tservice); + void generate_service_processor(std::ostream& out, t_service* tservice); + void generate_process_function(std::ostream& out, t_service* tservice, t_function* tfunction); + void generate_service_helpers(ostream& out, t_service* tservice); + void generate_function_helpers(ostream& out, t_function* tfunction); /** * Deserialization (Read) */ - void generate_deserialize_field(std::ofstream& out, + void generate_deserialize_field(std::ostream& out, t_field* tfield, bool local, std::string prefix = ""); - void generate_deserialize_struct(std::ofstream& out, + void generate_deserialize_struct(std::ostream& out, t_struct* tstruct, bool local, std::string prefix = ""); - void generate_deserialize_container(std::ofstream& out, + void generate_deserialize_container(std::ostream& out, t_type* ttype, bool local, std::string prefix = ""); - void generate_deserialize_set_element(std::ofstream& out, t_set* tset, std::string prefix = ""); + void generate_deserialize_set_element(std::ostream& out, t_set* tset, std::string prefix = ""); - void generate_deserialize_map_element(std::ofstream& out, t_map* tmap, std::string prefix = ""); + void generate_deserialize_map_element(std::ostream& out, t_map* tmap, std::string prefix = ""); - void generate_deserialize_list_element(std::ofstream& out, + void generate_deserialize_list_element(std::ostream& out, t_list* tlist, std::string prefix = ""); /** * Serialization (Write) */ - void generate_serialize_field(std::ofstream& out, t_field* tfield, std::string prefix = ""); + void generate_serialize_field(std::ostream& out, t_field* tfield, std::string prefix = ""); - void generate_serialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); + void generate_serialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); - void generate_serialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); + void generate_serialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); - void generate_serialize_map_element(std::ofstream& out, + void generate_serialize_map_element(std::ostream& out, t_map* tmap, std::string kiter, std::string viter); - void generate_serialize_set_element(std::ofstream& out, t_set* tmap, std::string iter); + void generate_serialize_set_element(std::ostream& out, t_set* tmap, std::string iter); - void generate_serialize_list_element(std::ofstream& out, t_list* tlist, std::string iter); + void generate_serialize_list_element(std::ostream& out, t_list* tlist, std::string iter); /** * Helper rendering functions @@ -159,9 +159,9 @@ private: /** * File streams */ - std::ofstream f_types_; - std::ofstream f_consts_; - std::ofstream f_service_; + ofstream_with_content_based_conditional_update f_types_; + ofstream_with_content_based_conditional_update f_consts_; + ofstream_with_content_based_conditional_update f_service_; }; /** @@ -276,8 +276,8 @@ string t_lua_generator::render_const_value(t_type* type, t_const_value* value) { const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end();) { t_type* field_type = NULL; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { @@ -308,8 +308,8 @@ string t_lua_generator::render_const_value(t_type* type, t_const_value* value) { t_type* ktype = ((t_map*)type)->get_key_type(); t_type* vtype = ((t_map*)type)->get_val_type(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end();) { indent(out) << "[" << render_const_value(ktype, v_iter->first) << "] = " << render_const_value(vtype, v_iter->second); @@ -366,7 +366,7 @@ void t_lua_generator::generate_xception(t_struct* txception) { /** * Generate a thrift struct or exception (lua table) */ -void t_lua_generator::generate_lua_struct_definition(ofstream& out, +void t_lua_generator::generate_lua_struct_definition(ostream& out, t_struct* tstruct, bool is_exception) { vector::const_iterator m_iter; @@ -402,7 +402,7 @@ void t_lua_generator::generate_lua_struct_definition(ofstream& out, /** * Generate a struct/exception reader */ -void t_lua_generator::generate_lua_struct_reader(ofstream& out, t_struct* tstruct) { +void t_lua_generator::generate_lua_struct_reader(ostream& out, t_struct* tstruct) { const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; @@ -459,7 +459,7 @@ void t_lua_generator::generate_lua_struct_reader(ofstream& out, t_struct* tstruc /** * Generate a struct/exception writer */ -void t_lua_generator::generate_lua_struct_writer(ofstream& out, t_struct* tstruct) { +void t_lua_generator::generate_lua_struct_writer(ostream& out, t_struct* tstruct) { const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; @@ -527,7 +527,7 @@ void t_lua_generator::generate_service(t_service* tservice) { f_service_.close(); } -void t_lua_generator::generate_service_interface(ofstream& out, t_service* tservice) { +void t_lua_generator::generate_service_interface(ostream& out, t_service* tservice) { string classname = tservice->get_name() + "Iface"; t_service* extends_s = tservice->get_extends(); @@ -541,7 +541,7 @@ void t_lua_generator::generate_service_interface(ofstream& out, t_service* tserv out << " __type = '" << classname << "'" << endl << "}" << endl << endl; } -void t_lua_generator::generate_service_client(ofstream& out, t_service* tservice) { +void t_lua_generator::generate_service_client(ostream& out, t_service* tservice) { string classname = tservice->get_name() + "Client"; t_service* extends_s = tservice->get_extends(); @@ -637,14 +637,14 @@ void t_lua_generator::generate_service_client(ofstream& out, t_service* tservice } } -void t_lua_generator::generate_service_processor(ofstream& out, t_service* tservice) { +void t_lua_generator::generate_service_processor(ostream& out, t_service* tservice) { string classname = tservice->get_name() + "Processor"; t_service* extends_s = tservice->get_extends(); // Define processor table out << endl << classname << " = __TObject.new("; if (extends_s != NULL) { - out << extends_s << "Processor" << endl; + out << extends_s->get_name() << "Processor" << endl; } else { out << "__TProcessor" << endl; } @@ -680,7 +680,7 @@ void t_lua_generator::generate_service_processor(ofstream& out, t_service* tserv } } -void t_lua_generator::generate_process_function(ofstream& out, +void t_lua_generator::generate_process_function(ostream& out, t_service* tservice, t_function* tfunction) { string classname = tservice->get_name() + "Processor"; @@ -731,7 +731,7 @@ void t_lua_generator::generate_process_function(ofstream& out, } // Service helpers -void t_lua_generator::generate_service_helpers(ofstream& out, t_service* tservice) { +void t_lua_generator::generate_service_helpers(ostream& out, t_service* tservice) { vector functions = tservice->get_functions(); vector::iterator f_iter; @@ -743,7 +743,7 @@ void t_lua_generator::generate_service_helpers(ofstream& out, t_service* tservic } } -void t_lua_generator::generate_function_helpers(ofstream& out, t_function* tfunction) { +void t_lua_generator::generate_function_helpers(ostream& out, t_function* tfunction) { if (!tfunction->is_oneway()) { t_struct result(program_, tfunction->get_name() + "_result"); t_field success(tfunction->get_returntype(), "success", 0); @@ -764,7 +764,7 @@ void t_lua_generator::generate_function_helpers(ofstream& out, t_function* tfunc /** * Deserialize (Read) */ -void t_lua_generator::generate_deserialize_field(ofstream& out, +void t_lua_generator::generate_deserialize_field(ostream& out, t_field* tfield, bool local, string prefix) { @@ -825,7 +825,7 @@ void t_lua_generator::generate_deserialize_field(ofstream& out, } } -void t_lua_generator::generate_deserialize_struct(ofstream& out, +void t_lua_generator::generate_deserialize_struct(ostream& out, t_struct* tstruct, bool local, string prefix) { @@ -833,7 +833,7 @@ void t_lua_generator::generate_deserialize_struct(ofstream& out, << endl << indent() << prefix << ":read(iprot)" << endl; } -void t_lua_generator::generate_deserialize_container(ofstream& out, +void t_lua_generator::generate_deserialize_container(ostream& out, t_type* ttype, bool local, string prefix) { @@ -883,7 +883,7 @@ void t_lua_generator::generate_deserialize_container(ofstream& out, } } -void t_lua_generator::generate_deserialize_map_element(ofstream& out, t_map* tmap, string prefix) { +void t_lua_generator::generate_deserialize_map_element(ostream& out, t_map* tmap, string prefix) { // A map is represented by a table indexable by any lua type string key = tmp("_key"); string val = tmp("_val"); @@ -896,7 +896,7 @@ void t_lua_generator::generate_deserialize_map_element(ofstream& out, t_map* tma indent(out) << prefix << "[" << key << "] = " << val << endl; } -void t_lua_generator::generate_deserialize_set_element(ofstream& out, t_set* tset, string prefix) { +void t_lua_generator::generate_deserialize_set_element(ostream& out, t_set* tset, string prefix) { // A set is represented by a table indexed by the value string elem = tmp("_elem"); t_field felem(tset->get_elem_type(), elem); @@ -906,7 +906,7 @@ void t_lua_generator::generate_deserialize_set_element(ofstream& out, t_set* tse indent(out) << prefix << "[" << elem << "] = " << elem << endl; } -void t_lua_generator::generate_deserialize_list_element(ofstream& out, +void t_lua_generator::generate_deserialize_list_element(ostream& out, t_list* tlist, string prefix) { // A list is represented by a table indexed by integer values @@ -922,7 +922,7 @@ void t_lua_generator::generate_deserialize_list_element(ofstream& out, /** * Serialize (Write) */ -void t_lua_generator::generate_serialize_field(ofstream& out, t_field* tfield, string prefix) { +void t_lua_generator::generate_serialize_field(ostream& out, t_field* tfield, string prefix) { t_type* type = get_true_type(tfield->get_type()); string name = prefix + tfield->get_name(); @@ -979,12 +979,12 @@ void t_lua_generator::generate_serialize_field(ofstream& out, t_field* tfield, s } } -void t_lua_generator::generate_serialize_struct(ofstream& out, t_struct* tstruct, string prefix) { +void t_lua_generator::generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix) { (void)tstruct; indent(out) << prefix << ":write(oprot)" << endl; } -void t_lua_generator::generate_serialize_container(ofstream& out, t_type* ttype, string prefix) { +void t_lua_generator::generate_serialize_container(ostream& out, t_type* ttype, string prefix) { // Begin writing if (ttype->is_map()) { indent(out) << "oprot:writeMapBegin(" << type_to_enum(((t_map*)ttype)->get_key_type()) << ", " @@ -1034,7 +1034,7 @@ void t_lua_generator::generate_serialize_container(ofstream& out, t_type* ttype, } } -void t_lua_generator::generate_serialize_map_element(ofstream& out, +void t_lua_generator::generate_serialize_map_element(ostream& out, t_map* tmap, string kiter, string viter) { @@ -1045,12 +1045,12 @@ void t_lua_generator::generate_serialize_map_element(ofstream& out, generate_serialize_field(out, &vfield, ""); } -void t_lua_generator::generate_serialize_set_element(ofstream& out, t_set* tset, string iter) { +void t_lua_generator::generate_serialize_set_element(ostream& out, t_set* tset, string iter) { t_field efield(tset->get_elem_type(), iter); generate_serialize_field(out, &efield, ""); } -void t_lua_generator::generate_serialize_list_element(ofstream& out, t_list* tlist, string iter) { +void t_lua_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string iter) { t_field efield(tlist->get_elem_type(), iter); generate_serialize_field(out, &efield, ""); } diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_netcore_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_netcore_generator.cc new file mode 100644 index 0000000..d2e7da0 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_netcore_generator.cc @@ -0,0 +1,3117 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + * + * Contains some contributions under the Thrift Software License. + * Please see doc/old-thrift-license.txt in the Thrift distribution for + * details. + */ + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "thrift/platform.h" +#include "thrift/generate/t_oop_generator.h" +#include "thrift/generate/t_netcore_generator.h" + +using std::map; +using std::ostream; +using std::ostringstream; +using std::string; +using std::stringstream; +using std::vector; + +//TODO: check for indentation +//TODO: Do we need seqId_ in generation? + +t_netcore_generator::t_netcore_generator(t_program* program, const map& parsed_options, const string& option_string) + : t_oop_generator(program) +{ + (void)option_string; + + nullable_ = false; + hashcode_ = false; + union_ = false; + serialize_ = false; + wcf_ = false; + wcf_namespace_.clear(); + + map::const_iterator iter; + + for (iter = parsed_options.begin(); iter != parsed_options.end(); ++iter) + { + if (iter->first.compare("nullable") == 0) + { + nullable_ = true; + } + else if (iter->first.compare("hashcode") == 0) + { + hashcode_ = true; + } + else if (iter->first.compare("union") == 0) + { + union_ = true; + } + else if (iter->first.compare("serial") == 0) + { + serialize_ = true; + wcf_namespace_ = iter->second; // since there can be only one namespace + } + else if (iter->first.compare("wcf") == 0) + { + wcf_ = true; + wcf_namespace_ = iter->second; + } + else + { + throw "unknown option netcore:" + iter->first; + } + } + + out_dir_base_ = "gen-netcore"; +} + +static string correct_function_name_for_async(string const& function_name) +{ + string const async_end = "Async"; + size_t i = function_name.find(async_end); + if (i != string::npos) + { + return function_name + async_end; + } + + return function_name; +} + +/** +* \brief Search and replace "_args" substring in struct name if exist (for C# class naming) +* \param struct_name +* \return Modified struct name ("Struct_args" -> "StructArgs") or original name +*/ +static string check_and_correct_struct_name(const string& struct_name) +{ + string args_end = "_args"; + size_t i = struct_name.find(args_end); + if (i != string::npos) + { + string new_struct_name = struct_name; + new_struct_name.replace(i, args_end.length(), "Args"); + return new_struct_name; + } + + string result_end = "_result"; + size_t j = struct_name.find(result_end); + if (j != string::npos) + { + string new_struct_name = struct_name; + new_struct_name.replace(j, result_end.length(), "Result"); + return new_struct_name; + } + + return struct_name; +} + +static bool field_has_default(t_field* tfield) { return tfield->get_value() != NULL; } + +static bool field_is_required(t_field* tfield) { return tfield->get_req() == t_field::T_REQUIRED; } + +static bool type_can_be_null(t_type* ttype) +{ + while (ttype->is_typedef()) + { + ttype = static_cast(ttype)->get_type(); + } + + return ttype->is_container() || ttype->is_struct() || ttype->is_xception() || ttype->is_string(); +} + +bool t_netcore_generator::is_wcf_enabled() const { return wcf_; } + +bool t_netcore_generator::is_nullable_enabled() const { return nullable_; } + +bool t_netcore_generator::is_hashcode_enabled() const { return hashcode_; } + +bool t_netcore_generator::is_serialize_enabled() const { return serialize_; } + +bool t_netcore_generator::is_union_enabled() const { return union_; } + +map t_netcore_generator::get_keywords_list() const +{ + return netcore_keywords; +} + +void t_netcore_generator::init_generator() +{ + MKDIR(get_out_dir().c_str()); + + // for usage of csharp namespaces in thrift files (from files for csharp) + namespace_name_ = program_->get_namespace("netcore"); + if (namespace_name_.empty()) + { + namespace_name_ = program_->get_namespace("netcore"); + } + + string dir = namespace_name_; + string subdir = get_out_dir().c_str(); + string::size_type loc; + + while ((loc = dir.find(".")) != string::npos) + { + subdir = subdir + "/" + dir.substr(0, loc); + MKDIR(subdir.c_str()); + dir = dir.substr(loc + 1); + } + if (dir.size() > 0) + { + subdir = subdir + "/" + dir; + MKDIR(subdir.c_str()); + } + + namespace_dir_ = subdir; + init_keywords(); + + while (!member_mapping_scopes.empty()) + { + cleanup_member_name_mapping(member_mapping_scopes.back().scope_member); + } + + pverbose(".NET Core options:\n"); + pverbose("- nullable ... %s\n", (nullable_ ? "ON" : "off")); + pverbose("- union ...... %s\n", (union_ ? "ON" : "off")); + pverbose("- hashcode ... %s\n", (hashcode_ ? "ON" : "off")); + pverbose("- serialize .. %s\n", (serialize_ ? "ON" : "off")); + pverbose("- wcf ........ %s\n", (wcf_ ? "ON" : "off")); +} + +string t_netcore_generator::normalize_name(string name) +{ + string tmp(name); + transform(tmp.begin(), tmp.end(), tmp.begin(), static_cast(tolower)); + + // un-conflict keywords by prefixing with "@" + if (netcore_keywords.find(tmp) != netcore_keywords.end()) + { + return "@" + name; + } + + // no changes necessary + return name; +} + +void t_netcore_generator::init_keywords() +{ + netcore_keywords.clear(); + + // C# keywords + netcore_keywords["abstract"] = 1; + netcore_keywords["as"] = 1; + netcore_keywords["base"] = 1; + netcore_keywords["bool"] = 1; + netcore_keywords["break"] = 1; + netcore_keywords["byte"] = 1; + netcore_keywords["case"] = 1; + netcore_keywords["catch"] = 1; + netcore_keywords["char"] = 1; + netcore_keywords["checked"] = 1; + netcore_keywords["class"] = 1; + netcore_keywords["const"] = 1; + netcore_keywords["continue"] = 1; + netcore_keywords["decimal"] = 1; + netcore_keywords["default"] = 1; + netcore_keywords["delegate"] = 1; + netcore_keywords["do"] = 1; + netcore_keywords["double"] = 1; + netcore_keywords["else"] = 1; + netcore_keywords["enum"] = 1; + netcore_keywords["event"] = 1; + netcore_keywords["explicit"] = 1; + netcore_keywords["extern"] = 1; + netcore_keywords["false"] = 1; + netcore_keywords["finally"] = 1; + netcore_keywords["fixed"] = 1; + netcore_keywords["float"] = 1; + netcore_keywords["for"] = 1; + netcore_keywords["foreach"] = 1; + netcore_keywords["goto"] = 1; + netcore_keywords["if"] = 1; + netcore_keywords["implicit"] = 1; + netcore_keywords["in"] = 1; + netcore_keywords["int"] = 1; + netcore_keywords["interface"] = 1; + netcore_keywords["internal"] = 1; + netcore_keywords["is"] = 1; + netcore_keywords["lock"] = 1; + netcore_keywords["long"] = 1; + netcore_keywords["namespace"] = 1; + netcore_keywords["new"] = 1; + netcore_keywords["null"] = 1; + netcore_keywords["object"] = 1; + netcore_keywords["operator"] = 1; + netcore_keywords["out"] = 1; + netcore_keywords["override"] = 1; + netcore_keywords["params"] = 1; + netcore_keywords["private"] = 1; + netcore_keywords["protected"] = 1; + netcore_keywords["public"] = 1; + netcore_keywords["readonly"] = 1; + netcore_keywords["ref"] = 1; + netcore_keywords["return"] = 1; + netcore_keywords["sbyte"] = 1; + netcore_keywords["sealed"] = 1; + netcore_keywords["short"] = 1; + netcore_keywords["sizeof"] = 1; + netcore_keywords["stackalloc"] = 1; + netcore_keywords["static"] = 1; + netcore_keywords["string"] = 1; + netcore_keywords["struct"] = 1; + netcore_keywords["switch"] = 1; + netcore_keywords["this"] = 1; + netcore_keywords["throw"] = 1; + netcore_keywords["true"] = 1; + netcore_keywords["try"] = 1; + netcore_keywords["typeof"] = 1; + netcore_keywords["uint"] = 1; + netcore_keywords["ulong"] = 1; + netcore_keywords["unchecked"] = 1; + netcore_keywords["unsafe"] = 1; + netcore_keywords["ushort"] = 1; + netcore_keywords["using"] = 1; + netcore_keywords["virtual"] = 1; + netcore_keywords["void"] = 1; + netcore_keywords["volatile"] = 1; + netcore_keywords["while"] = 1; + + // C# contextual keywords + netcore_keywords["add"] = 1; + netcore_keywords["alias"] = 1; + netcore_keywords["ascending"] = 1; + netcore_keywords["async"] = 1; + netcore_keywords["await"] = 1; + netcore_keywords["descending"] = 1; + netcore_keywords["dynamic"] = 1; + netcore_keywords["from"] = 1; + netcore_keywords["get"] = 1; + netcore_keywords["global"] = 1; + netcore_keywords["group"] = 1; + netcore_keywords["into"] = 1; + netcore_keywords["join"] = 1; + netcore_keywords["let"] = 1; + netcore_keywords["orderby"] = 1; + netcore_keywords["partial"] = 1; + netcore_keywords["remove"] = 1; + netcore_keywords["select"] = 1; + netcore_keywords["set"] = 1; + netcore_keywords["value"] = 1; + netcore_keywords["var"] = 1; + netcore_keywords["where"] = 1; + netcore_keywords["yield"] = 1; + + netcore_keywords["when"] = 1; +} + +void t_netcore_generator::start_netcore_namespace(ostream& out) +{ + if (!namespace_name_.empty()) + { + out << "namespace " << namespace_name_ << endl; + scope_up(out); + } +} + +void t_netcore_generator::end_netcore_namespace(ostream& out) +{ + if (!namespace_name_.empty()) + { + scope_down(out); + } +} + +string t_netcore_generator::netcore_type_usings() const +{ + string namespaces = + "using System;\n" + "using System.Collections;\n" + "using System.Collections.Generic;\n" + "using System.Text;\n" + "using System.IO;\n" + "using System.Threading;\n" + "using System.Threading.Tasks;\n" + "using Thrift;\n" + "using Thrift.Collections;\n"; + + if (wcf_) + { + namespaces += "using System.ServiceModel;\n"; + namespaces += "using System.Runtime.Serialization;\n"; + } + + return namespaces + endl; +} + +string t_netcore_generator::netcore_thrift_usings() const +{ + string namespaces = + "using Thrift.Protocols;\n" + "using Thrift.Protocols.Entities;\n" + "using Thrift.Protocols.Utilities;\n" + "using Thrift.Transports;\n" + "using Thrift.Transports.Client;\n" + "using Thrift.Transports.Server;\n"; + + return namespaces + endl; +} + +void t_netcore_generator::close_generator() +{ +} + +void t_netcore_generator::generate_typedef(t_typedef* ttypedef) +{ + (void)ttypedef; +} + +void t_netcore_generator::generate_enum(t_enum* tenum) +{ + int ic = indent_count(); + string f_enum_name = namespace_dir_ + "/" + tenum->get_name() + ".cs"; + + ofstream_with_content_based_conditional_update f_enum; + f_enum.open(f_enum_name.c_str()); + + generate_enum(f_enum, tenum); + + f_enum.close(); + indent_validate(ic, "generate_enum"); +} + +void t_netcore_generator::generate_enum(ostream& out, t_enum* tenum) +{ + out << autogen_comment() << endl; + + start_netcore_namespace(out); + generate_netcore_doc(out, tenum); + + out << indent() << "public enum " << tenum->get_name() << endl; + scope_up(out); + + vector constants = tenum->get_constants(); + vector::iterator c_iter; + + for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) + { + generate_netcore_doc(out, *c_iter); + int value = (*c_iter)->get_value(); + out << indent() << (*c_iter)->get_name() << " = " << value << "," << endl; + } + + scope_down(out); + end_netcore_namespace(out); +} + +void t_netcore_generator::generate_consts(vector consts) +{ + if (consts.empty()) + { + return; + } + + string f_consts_name = namespace_dir_ + '/' + program_name_ + ".Constants.cs"; + ofstream_with_content_based_conditional_update f_consts; + f_consts.open(f_consts_name.c_str()); + + generate_consts(f_consts, consts); + + f_consts.close(); +} + +void t_netcore_generator::generate_consts(ostream& out, vector consts) +{ + if (consts.empty()) + { + return; + } + + out << autogen_comment() << netcore_type_usings() << endl; + + start_netcore_namespace(out); + + out << indent() << "public static class " << make_valid_csharp_identifier(program_name_) << "Constants" << endl; + + scope_up(out); + + vector::iterator c_iter; + bool need_static_constructor = false; + for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) + { + generate_netcore_doc(out, *c_iter); + if (print_const_value(out, (*c_iter)->get_name(), (*c_iter)->get_type(), (*c_iter)->get_value(), false)) + { + need_static_constructor = true; + } + } + + if (need_static_constructor) + { + print_const_constructor(out, consts); + } + + scope_down(out); + end_netcore_namespace(out); +} + +void t_netcore_generator::print_const_def_value(ostream& out, string name, t_type* type, t_const_value* value) +{ + if (type->is_struct() || type->is_xception()) + { + const vector& fields = static_cast(type)->get_members(); + const map& val = value->get_map(); + vector::const_iterator f_iter; + map::const_iterator v_iter; + prepare_member_name_mapping(static_cast(type)); + + for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) + { + t_field* field = NULL; + + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) + { + if ((*f_iter)->get_name() == v_iter->first->get_string()) + { + field = *f_iter; + } + } + + if (field == NULL) + { + throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string(); + } + + t_type* field_type = field->get_type(); + + string val = render_const_value(out, name, field_type, v_iter->second); + out << indent() << name << "." << prop_name(field) << " = " << val << ";" << endl; + } + + cleanup_member_name_mapping(static_cast(type)); + } + else if (type->is_map()) + { + t_type* ktype = static_cast(type)->get_key_type(); + t_type* vtype = static_cast(type)->get_val_type(); + const map& val = value->get_map(); + map::const_iterator v_iter; + for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) + { + string key = render_const_value(out, name, ktype, v_iter->first); + string val = render_const_value(out, name, vtype, v_iter->second); + out << indent() << name << "[" << key << "]" << " = " << val << ";" << endl; + } + } + else if (type->is_list() || type->is_set()) + { + t_type* etype; + if (type->is_list()) + { + etype = static_cast(type)->get_elem_type(); + } + else + { + etype = static_cast(type)->get_elem_type(); + } + + const vector& val = value->get_list(); + vector::const_iterator v_iter; + for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) + { + string val = render_const_value(out, name, etype, *v_iter); + out << indent() << name << ".Add(" << val << ");" << endl; + } + } +} + +void t_netcore_generator::print_const_constructor(ostream& out, vector consts) +{ + out << indent() << "static " << make_valid_csharp_identifier(program_name_).c_str() << "Constants()" << endl; + scope_up(out); + + vector::iterator c_iter; + for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) + { + string name = (*c_iter)->get_name(); + t_type* type = (*c_iter)->get_type(); + t_const_value* value = (*c_iter)->get_value(); + + print_const_def_value(out, name, type, value); + } + scope_down(out); +} + +bool t_netcore_generator::print_const_value(ostream& out, string name, t_type* type, t_const_value* value, bool in_static, bool defval, bool needtype) +{ + out << indent(); + bool need_static_construction = !in_static; + while (type->is_typedef()) + { + type = static_cast(type)->get_type(); + } + + if (!defval || needtype) + { + out << (in_static ? "" : type->is_base_type() ? "public const " : "public static ") << type_name(type) << " "; + } + + if (type->is_base_type()) + { + string v2 = render_const_value(out, name, type, value); + out << normalize_name(name) << " = " << v2 << ";" << endl; + need_static_construction = false; + } + else if (type->is_enum()) + { + out << name << " = " << type_name(type, false, true) << "." << value->get_identifier_name() << ";" << endl; + need_static_construction = false; + } + else if (type->is_struct() || type->is_xception()) + { + out << name << " = new " << type_name(type) << "();" << endl; + } + else if (type->is_map()) + { + out << name << " = new " << type_name(type, true, true) << "();" << endl; + } + else if (type->is_list() || type->is_set()) + { + out << name << " = new " << type_name(type) << "();" << endl; + } + + if (defval && !type->is_base_type() && !type->is_enum()) + { + print_const_def_value(out, name, type, value); + } + + return need_static_construction; +} + +string t_netcore_generator::render_const_value(ostream& out, string name, t_type* type, t_const_value* value) +{ + (void)name; + ostringstream render; + + if (type->is_base_type()) + { + t_base_type::t_base tbase = static_cast(type)->get_base(); + switch (tbase) + { + case t_base_type::TYPE_STRING: + render << '"' << get_escaped_string(value) << '"'; + break; + case t_base_type::TYPE_BOOL: + render << ((value->get_integer() > 0) ? "true" : "false"); + break; + case t_base_type::TYPE_I8: + case t_base_type::TYPE_I16: + case t_base_type::TYPE_I32: + case t_base_type::TYPE_I64: + render << value->get_integer(); + break; + case t_base_type::TYPE_DOUBLE: + if (value->get_type() == t_const_value::CV_INTEGER) + { + render << value->get_integer(); + } + else + { + render << value->get_double(); + } + break; + default: + throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase); + } + } + else if (type->is_enum()) + { + render << type->get_name() << "." << value->get_identifier_name(); + } + else + { + string t = tmp("tmp"); + print_const_value(out, t, type, value, true, true, true); + render << t; + } + + return render.str(); +} + +void t_netcore_generator::generate_struct(t_struct* tstruct) +{ + if (union_ && tstruct->is_union()) + { + generate_netcore_union(tstruct); + } + else + { + generate_netcore_struct(tstruct, false); + } +} + +void t_netcore_generator::generate_xception(t_struct* txception) +{ + generate_netcore_struct(txception, true); +} + +void t_netcore_generator::generate_netcore_struct(t_struct* tstruct, bool is_exception) +{ + int ic = indent_count(); + + string f_struct_name = namespace_dir_ + "/" + (tstruct->get_name()) + ".cs"; + ofstream_with_content_based_conditional_update f_struct; + + f_struct.open(f_struct_name.c_str()); + + f_struct << autogen_comment() << netcore_type_usings() << netcore_thrift_usings() << endl; + + generate_netcore_struct_definition(f_struct, tstruct, is_exception); + + f_struct.close(); + + indent_validate(ic, "generate_netcore_struct"); +} + +void t_netcore_generator::generate_netcore_struct_definition(ostream& out, t_struct* tstruct, bool is_exception, bool in_class, bool is_result) +{ + if (!in_class) + { + start_netcore_namespace(out); + } + + out << endl; + + generate_netcore_doc(out, tstruct); + prepare_member_name_mapping(tstruct); + + if ((serialize_ || wcf_) && !is_exception) + { + out << indent() << "[DataContract(Namespace=\"" << wcf_namespace_ << "\")]" << endl; + } + + bool is_final = tstruct->annotations_.find("final") != tstruct->annotations_.end(); + + string sharp_struct_name = check_and_correct_struct_name(normalize_name(tstruct->get_name())); + + out << indent() << "public " << (is_final ? "sealed " : "") << "partial class " << sharp_struct_name << " : "; + + if (is_exception) + { + out << "TException, "; + } + + out << "TBase" << endl + << indent() << "{" << endl; + indent_up(); + + const vector& members = tstruct->get_members(); + vector::const_iterator m_iter; + + // make private members with public Properties + for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) + { + // if the field is requied, then we use auto-properties + if (!field_is_required((*m_iter)) && (!nullable_ || field_has_default((*m_iter)))) + { + out << indent() << "private " << declare_field(*m_iter, false, "_") << endl; + } + } + out << endl; + + bool has_non_required_fields = false; + bool has_non_required_default_value_fields = false; + bool has_required_fields = false; + for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) + { + generate_netcore_doc(out, *m_iter); + generate_property(out, *m_iter, true, true); + bool is_required = field_is_required((*m_iter)); + bool has_default = field_has_default((*m_iter)); + if (is_required) + { + has_required_fields = true; + } + else + { + if (has_default) + { + has_non_required_default_value_fields = true; + } + has_non_required_fields = true; + } + } + + bool generate_isset = (nullable_ && has_non_required_default_value_fields) || (!nullable_ && has_non_required_fields); + if (generate_isset) + { + out << endl; + if (serialize_ || wcf_) + { + out << indent() << "[DataMember(Order = 1)]" << endl; + } + out << indent() << "public Isset __isset;" << endl; + if (serialize_ || wcf_) + { + out << indent() << "[DataContract]" << endl; + } + + out << indent() << "public struct Isset" << endl + << indent() << "{" << endl; + indent_up(); + + for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) + { + bool is_required = field_is_required((*m_iter)); + bool has_default = field_has_default((*m_iter)); + // if it is required, don't need Isset for that variable + // if it is not required, if it has a default value, we need to generate Isset + // if we are not nullable, then we generate Isset + if (!is_required && (!nullable_ || has_default)) + { + if (serialize_ || wcf_) + { + out << indent() << "[DataMember]" << endl; + } + out << indent() << "public bool " << normalize_name((*m_iter)->get_name()) << ";" << endl; + } + } + + indent_down(); + out << indent() << "}" << endl << endl; + + if (generate_isset && (serialize_ || wcf_)) + { + out << indent() << "#region XmlSerializer support" << endl << endl; + + for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) + { + bool is_required = field_is_required(*m_iter); + bool has_default = field_has_default(*m_iter); + // if it is required, don't need Isset for that variable + // if it is not required, if it has a default value, we need to generate Isset + // if we are not nullable, then we generate Isset + if (!is_required && (!nullable_ || has_default)) + { + out << indent() << "public bool ShouldSerialize" << prop_name(*m_iter) << "()" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "return __isset." << normalize_name((*m_iter)->get_name()) << ";" << endl; + indent_down(); + out << indent() << "}" << endl << endl; + } + } + + out << indent() << "#endregion XmlSerializer support" << endl << endl; + } + } + + // We always want a default, no argument constructor for Reading + out << indent() << "public " << sharp_struct_name << "()" << endl + << indent() << "{" << endl; + indent_up(); + + for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) + { + t_type* t = (*m_iter)->get_type(); + while (t->is_typedef()) + { + t = static_cast(t)->get_type(); + } + if ((*m_iter)->get_value() != NULL) + { + if (field_is_required((*m_iter))) + { + print_const_value(out, "this." + prop_name(*m_iter), t, (*m_iter)->get_value(), true, true); + } + else + { + print_const_value(out, "this._" + (*m_iter)->get_name(), t, (*m_iter)->get_value(), true, true); + // Optionals with defaults are marked set + out << indent() << "this.__isset." << normalize_name((*m_iter)->get_name()) << " = true;" << endl; + } + } + } + indent_down(); + out << indent() << "}" << endl << endl; + + if (has_required_fields) + { + out << indent() << "public " << sharp_struct_name << "("; + bool first = true; + for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) + { + if (field_is_required(*m_iter)) + { + if (first) + { + first = false; + } + else + { + out << ", "; + } + out << type_name((*m_iter)->get_type()) << " " << (*m_iter)->get_name(); + } + } + out << ") : this()" << endl + << indent() << "{" << endl; + indent_up(); + + for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) + { + if (field_is_required(*m_iter)) + { + out << indent() << "this." << prop_name(*m_iter) << " = " << (*m_iter)->get_name() << ";" << endl; + } + } + + indent_down(); + out << indent() << "}" << endl << endl; + } + + generate_netcore_struct_reader(out, tstruct); + if (is_result) + { + generate_netcore_struct_result_writer(out, tstruct); + } + else + { + generate_netcore_struct_writer(out, tstruct); + } + if (hashcode_) + { + generate_netcore_struct_equals(out, tstruct); + generate_netcore_struct_hashcode(out, tstruct); + } + generate_netcore_struct_tostring(out, tstruct); + + indent_down(); + out << indent() << "}" << endl << endl; + + // generate a corresponding WCF fault to wrap the exception + if ((serialize_ || wcf_) && is_exception) + { + generate_netcore_wcffault(out, tstruct); + } + + cleanup_member_name_mapping(tstruct); + if (!in_class) + { + end_netcore_namespace(out); + } +} + +void t_netcore_generator::generate_netcore_wcffault(ostream& out, t_struct* tstruct) +{ + out << endl; + out << indent() << "[DataContract]" << endl; + + bool is_final = tstruct->annotations_.find("final") != tstruct->annotations_.end(); + + out << indent() << "public " << (is_final ? "sealed " : "") << "partial class " << tstruct->get_name() << "Fault" << endl + << indent() << "{" << endl; + indent_up(); + + const vector& members = tstruct->get_members(); + vector::const_iterator m_iter; + + // make private members with public Properties + for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) + { + out << indent() << "private " << declare_field(*m_iter, false, "_") << endl; + } + out << endl; + + for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) + { + generate_property(out, *m_iter, true, false); + } + + indent_down(); + out << indent() << "}" << endl << endl; +} + +void t_netcore_generator::generate_netcore_struct_reader(ostream& out, t_struct* tstruct) +{ + out << indent() << "public async Task ReadAsync(TProtocol iprot, CancellationToken cancellationToken)" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "iprot.IncrementRecursionDepth();" << endl + << indent() << "try" << endl + << indent() << "{" << endl; + indent_up(); + + const vector& fields = tstruct->get_members(); + vector::const_iterator f_iter; + + // Required variables aren't in __isset, so we need tmp vars to check them + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) + { + if (field_is_required(*f_iter)) + { + out << indent() << "bool isset_" << (*f_iter)->get_name() << " = false;" << endl; + } + } + + out << indent() << "TField field;" << endl + << indent() << "await iprot.ReadStructBeginAsync(cancellationToken);" << endl + << indent() << "while (true)" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "field = await iprot.ReadFieldBeginAsync(cancellationToken);" << endl + << indent() << "if (field.Type == TType.Stop)" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "break;" << endl; + indent_down(); + out << indent() << "}" << endl << endl + << indent() << "switch (field.ID)" << endl + << indent() << "{" << endl; + indent_up(); + + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) + { + bool is_required = field_is_required(*f_iter); + out << indent() << "case " << (*f_iter)->get_key() << ":" << endl; + indent_up(); + out << indent() << "if (field.Type == " << type_to_enum((*f_iter)->get_type()) << ")" << endl + << indent() << "{" << endl; + indent_up(); + + generate_deserialize_field(out, *f_iter); + if (is_required) + { + out << indent() << "isset_" << (*f_iter)->get_name() << " = true;" << endl; + } + + indent_down(); + out << indent() << "}" << endl + << indent() << "else" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken);" << endl; + indent_down(); + out << indent() << "}" << endl + << indent() << "break;" << endl; + indent_down(); + } + + out << indent() << "default: " << endl; + indent_up(); + out << indent() << "await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken);" << endl + << indent() << "break;" << endl; + indent_down(); + indent_down(); + out << indent() << "}" << endl + << endl + << indent() << "await iprot.ReadFieldEndAsync(cancellationToken);" << endl; + indent_down(); + out << indent() << "}" << endl + << endl + << indent() << "await iprot.ReadStructEndAsync(cancellationToken);" << endl; + + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) + { + if (field_is_required((*f_iter))) + { + out << indent() << "if (!isset_" << (*f_iter)->get_name() << ")" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "throw new TProtocolException(TProtocolException.INVALID_DATA);" << endl; + indent_down(); + out << indent() << "}" << endl; + } + } + + indent_down(); + out << indent() << "}" << endl; + out << indent() << "finally" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "iprot.DecrementRecursionDepth();" << endl; + indent_down(); + out << indent() << "}" << endl; + indent_down(); + out << indent() << "}" << endl << endl; +} + +void t_netcore_generator::generate_netcore_struct_writer(ostream& out, t_struct* tstruct) +{ + out << indent() << "public async Task WriteAsync(TProtocol oprot, CancellationToken cancellationToken)" << endl + << indent() << "{" << endl; + indent_up(); + + out << indent() << "oprot.IncrementRecursionDepth();" << endl + << indent() << "try" << endl + << indent() << "{" << endl; + indent_up(); + + string name = tstruct->get_name(); + const vector& fields = tstruct->get_sorted_members(); + vector::const_iterator f_iter; + + out << indent() << "var struc = new TStruct(\"" << name << "\");" << endl + << indent() << "await oprot.WriteStructBeginAsync(struc, cancellationToken);" << endl; + + if (fields.size() > 0) + { + out << indent() << "var field = new TField();" << endl; + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) + { + bool is_required = field_is_required(*f_iter); + bool has_default = field_has_default(*f_iter); + if (nullable_ && !has_default && !is_required) + { + out << indent() << "if (" << prop_name(*f_iter) << " != null)" << endl + << indent() << "{" << endl; + indent_up(); + } + else if (!is_required) + { + bool null_allowed = type_can_be_null((*f_iter)->get_type()); + if (null_allowed) + { + out << indent() << "if (" << prop_name(*f_iter) << " != null && __isset." << normalize_name((*f_iter)->get_name()) << ")" << endl + << indent() << "{" << endl; + indent_up(); + } + else + { + out << indent() << "if (__isset." << normalize_name((*f_iter)->get_name()) << ")" << endl + << indent() << "{" << endl; + indent_up(); + } + } + out << indent() << "field.Name = \"" << (*f_iter)->get_name() << "\";" << endl + << indent() << "field.Type = " << type_to_enum((*f_iter)->get_type()) << ";" << endl + << indent() << "field.ID = " << (*f_iter)->get_key() << ";" << endl + << indent() << "await oprot.WriteFieldBeginAsync(field, cancellationToken);" << endl; + + generate_serialize_field(out, *f_iter); + + out << indent() << "await oprot.WriteFieldEndAsync(cancellationToken);" << endl; + if (!is_required) + { + indent_down(); + out << indent() << "}" << endl; + } + } + } + + out << indent() << "await oprot.WriteFieldStopAsync(cancellationToken);" << endl + << indent() << "await oprot.WriteStructEndAsync(cancellationToken);" << endl; + indent_down(); + out << indent() << "}" << endl + << indent() << "finally" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "oprot.DecrementRecursionDepth();" << endl; + indent_down(); + out << indent() << "}" << endl; + indent_down(); + out << indent() << "}" << endl << endl; +} + +void t_netcore_generator::generate_netcore_struct_result_writer(ostream& out, t_struct* tstruct) +{ + out << indent() << "public async Task WriteAsync(TProtocol oprot, CancellationToken cancellationToken)" << endl + << indent() << "{" << endl; + indent_up(); + + out << indent() << "oprot.IncrementRecursionDepth();" << endl + << indent() << "try" << endl + << indent() << "{" << endl; + indent_up(); + + string name = tstruct->get_name(); + const vector& fields = tstruct->get_sorted_members(); + vector::const_iterator f_iter; + + out << indent() << "var struc = new TStruct(\"" << name << "\");" << endl + << indent() << "await oprot.WriteStructBeginAsync(struc, cancellationToken);" << endl; + + if (fields.size() > 0) + { + out << indent() << "var field = new TField();" << endl; + bool first = true; + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) + { + if (first) + { + first = false; + out << endl << indent() << "if"; + } + else + { + out << indent() << "else if"; + } + + if (nullable_) + { + out << "(this." << prop_name((*f_iter)) << " != null)" << endl + << indent() << "{" << endl; + } + else + { + out << "(this.__isset." << normalize_name((*f_iter)->get_name()) << ")" << endl + << indent() << "{" << endl; + } + indent_up(); + + bool null_allowed = !nullable_ && type_can_be_null((*f_iter)->get_type()); + if (null_allowed) + { + out << indent() << "if (" << prop_name(*f_iter) << " != null)" << endl + << indent() << "{" << endl; + indent_up(); + } + + out << indent() << "field.Name = \"" << prop_name(*f_iter) << "\";" << endl + << indent() << "field.Type = " << type_to_enum((*f_iter)->get_type()) << ";" << endl + << indent() << "field.ID = " << (*f_iter)->get_key() << ";" << endl + << indent() << "await oprot.WriteFieldBeginAsync(field, cancellationToken);" << endl; + + generate_serialize_field(out, *f_iter); + + out << indent() << "await oprot.WriteFieldEndAsync(cancellationToken);" << endl; + + if (null_allowed) + { + indent_down(); + out << indent() << "}" << endl; + } + + indent_down(); + out << indent() << "}" << endl; + } + } + + out << indent() << "await oprot.WriteFieldStopAsync(cancellationToken);" << endl + << indent() << "await oprot.WriteStructEndAsync(cancellationToken);" << endl; + indent_down(); + out << indent() << "}" << endl + << indent() << "finally" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "oprot.DecrementRecursionDepth();" << endl; + indent_down(); + out << indent() << "}" << endl; + indent_down(); + out << indent() << "}" << endl << endl; +} + +void t_netcore_generator::generate_netcore_struct_tostring(ostream& out, t_struct* tstruct) +{ + out << indent() << "public override string ToString()" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "var sb = new StringBuilder(\"" << tstruct->get_name() << "(\");" << endl; + + const vector& fields = tstruct->get_members(); + vector::const_iterator f_iter; + + bool useFirstFlag = false; + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) + { + if (!field_is_required((*f_iter))) + { + out << indent() << "bool __first = true;" << endl; + useFirstFlag = true; + } + break; + } + + bool had_required = false; // set to true after first required field has been processed + + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) + { + bool is_required = field_is_required((*f_iter)); + bool has_default = field_has_default((*f_iter)); + if (nullable_ && !has_default && !is_required) + { + out << indent() << "if (" << prop_name((*f_iter)) << " != null)" << endl + << indent() << "{" << endl; + indent_up(); + } + else if (!is_required) + { + bool null_allowed = type_can_be_null((*f_iter)->get_type()); + if (null_allowed) + { + out << indent() << "if (" << prop_name((*f_iter)) << " != null && __isset." << normalize_name((*f_iter)->get_name()) << ")" << endl + << indent() << "{" << endl; + indent_up(); + } + else + { + out << indent() << "if (__isset." << normalize_name((*f_iter)->get_name()) << ")" << endl + << indent() << "{" << endl; + indent_up(); + } + } + + if (useFirstFlag && (!had_required)) + { + out << indent() << "if(!__first) { sb.Append(\", \"); }" << endl; + if (!is_required) + { + out << indent() << "__first = false;" << endl; + } + out << indent() << "sb.Append(\"" << prop_name(*f_iter) << ": \");" << endl; + } + else + { + out << indent() << "sb.Append(\", " << prop_name(*f_iter) << ": \");" << endl; + } + + t_type* ttype = (*f_iter)->get_type(); + if (ttype->is_xception() || ttype->is_struct()) + { + out << indent() << "sb.Append(" << prop_name(*f_iter) << "== null ? \"\" : " << prop_name(*f_iter) << ".ToString());" << endl; + } + else + { + out << indent() << "sb.Append(" << prop_name(*f_iter) << ");" << endl; + } + + if (!is_required) + { + indent_down(); + out << indent() << "}" << endl; + } + else + { + had_required = true; // now __first must be false, so we don't need to check it anymore + } + } + + out << indent() << "sb.Append(\")\");" << endl + << indent() << "return sb.ToString();" << endl; + indent_down(); + out << indent() << "}" << endl; +} + +void t_netcore_generator::generate_netcore_union(t_struct* tunion) +{ + int ic = indent_count(); + + string f_union_name = namespace_dir_ + "/" + (tunion->get_name()) + ".cs"; + ofstream_with_content_based_conditional_update f_union; + + f_union.open(f_union_name.c_str()); + + f_union << autogen_comment() << netcore_type_usings() << netcore_thrift_usings() << endl; + + generate_netcore_union_definition(f_union, tunion); + + f_union.close(); + + indent_validate(ic, "generate_netcore_union."); +} + +void t_netcore_generator::generate_netcore_union_definition(ostream& out, t_struct* tunion) +{ + // Let's define the class first + start_netcore_namespace(out); + + out << indent() << "public abstract partial class " << tunion->get_name() << " : TAbstractBase" << endl + << indent() << "{" << endl; + indent_up(); + + out << indent() << "public abstract Task WriteAsync(TProtocol tProtocol, CancellationToken cancellationToken);" << endl + << indent() << "public readonly bool Isset;" << endl + << indent() << "public abstract object Data { get; }" << endl + << indent() << "protected " << tunion->get_name() << "(bool isset)" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "Isset = isset;" << endl; + indent_down(); + out << indent() << "}" << endl << endl; + + out << indent() << "public class ___undefined : " << tunion->get_name() << endl + << indent() << "{" << endl; + indent_up(); + + out << indent() << "public override object Data { get { return null; } }" << endl + << indent() << "public ___undefined() : base(false) {}" << endl << endl; + + out << indent() << "public override Task WriteAsync(TProtocol oprot, CancellationToken cancellationToken)" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "throw new TProtocolException( TProtocolException.INVALID_DATA, \"Cannot persist an union type which is not set.\");" << endl; + indent_down(); + out << indent() << "}" << endl << endl; + indent_down(); + out << indent() << "}" << endl << endl; + + const vector& fields = tunion->get_members(); + vector::const_iterator f_iter; + + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) + { + generate_netcore_union_class(out, tunion, (*f_iter)); + } + + generate_netcore_union_reader(out, tunion); + + indent_down(); + out << indent() << "}" << endl << endl; + + end_netcore_namespace(out); +} + +void t_netcore_generator::generate_netcore_union_class(ostream& out, t_struct* tunion, t_field* tfield) +{ + out << indent() << "public class " << tfield->get_name() << " : " << tunion->get_name() << endl + << indent() << "{" << endl; + indent_up(); + + out << indent() << "private " << type_name(tfield->get_type()) << " _data;" << endl + << indent() << "public override object Data { get { return _data; } }" << endl + << indent() << "public " << tfield->get_name() << "(" << type_name(tfield->get_type()) << " data) : base(true)" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "this._data = data;" << endl; + indent_down(); + out << indent() << "}" << endl; + + out << indent() << "public override async Task WriteAsync(TProtocol oprot, CancellationToken cancellationToken) {" << endl; + indent_up(); + + out << indent() << "oprot.IncrementRecursionDepth();" << endl + << indent() << "try" << endl + << indent() << "{" << endl; + indent_up(); + + out << indent() << "var struc = new TStruct(\"" << tunion->get_name() << "\");" << endl + << indent() << "await oprot.WriteStructBeginAsync(struc, cancellationToken);" << endl; + + out << indent() << "var field = new TField();" << endl + << indent() << "field.Name = \"" << tfield->get_name() << "\";" << endl + << indent() << "field.Type = " << type_to_enum(tfield->get_type()) << ";" << endl + << indent() << "field.ID = " << tfield->get_key() << ";" << endl + << indent() << "await oprot.WriteFieldBeginAsync(field, cancellationToken);" << endl; + + generate_serialize_field(out, tfield, "_data", true, true); + + out << indent() << "await oprot.WriteFieldEndAsync(cancellationToken);" << endl + << indent() << "await oprot.WriteFieldStopAsync(cancellationToken);" << endl + << indent() << "await oprot.WriteStructEndAsync(cancellationToken);" << endl; + indent_down(); + out << indent() << "}" << endl + << indent() << "finally" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "oprot.DecrementRecursionDepth();" << endl; + indent_down(); + out << indent() << "}" << endl; + out << indent() << "}" << endl; + indent_down(); + out << indent() << "}" << endl << endl; +} + +void t_netcore_generator::generate_netcore_struct_equals(ostream& out, t_struct* tstruct) +{ + out << indent() << "public override bool Equals(object that)" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "var other = that as " << check_and_correct_struct_name(normalize_name(tstruct->get_name())) << ";" << endl + << indent() << "if (other == null) return false;" << endl + << indent() << "if (ReferenceEquals(this, other)) return true;" << endl; + + const vector& fields = tstruct->get_members(); + vector::const_iterator f_iter; + + bool first = true; + + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) + { + if (first) + { + first = false; + out << indent() << "return "; + indent_up(); + } + else + { + out << endl; + out << indent() << "&& "; + } + if (!field_is_required((*f_iter)) && !(nullable_ && !field_has_default((*f_iter)))) + { + out << "((__isset." << normalize_name((*f_iter)->get_name()) << " == other.__isset." + << normalize_name((*f_iter)->get_name()) << ") && ((!__isset." + << normalize_name((*f_iter)->get_name()) << ") || ("; + } + t_type* ttype = (*f_iter)->get_type(); + if (ttype->is_container() || ttype->is_binary()) + { + out << "TCollections.Equals("; + } + else + { + out << "System.Object.Equals("; + } + out << prop_name((*f_iter)) << ", other." << prop_name((*f_iter)) << ")"; + if (!field_is_required((*f_iter)) && !(nullable_ && !field_has_default((*f_iter)))) + { + out << ")))"; + } + } + if (first) + { + out << indent() << "return true;" << endl; + } + else + { + out << ";" << endl; + indent_down(); + } + + indent_down(); + out << indent() << "}" << endl << endl; +} + +void t_netcore_generator::generate_netcore_struct_hashcode(ostream& out, t_struct* tstruct) +{ + out << indent() << "public override int GetHashCode() {" << endl; + indent_up(); + + out << indent() << "int hashcode = 0;" << endl; + out << indent() << "unchecked {" << endl; + indent_up(); + + const vector& fields = tstruct->get_members(); + vector::const_iterator f_iter; + + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) + { + t_type* ttype = (*f_iter)->get_type(); + out << indent() << "hashcode = (hashcode * 397) ^ "; + if (field_is_required((*f_iter))) + { + out << "("; + } + else if (nullable_) + { + out << "(" << prop_name((*f_iter)) << " == null ? 0 : "; + } + else + { + out << "(!__isset." << normalize_name((*f_iter)->get_name()) << " ? 0 : "; + } + if (ttype->is_container()) + { + out << "(TCollections.GetHashCode(" << prop_name((*f_iter)) << "))"; + } + else + { + out << "(" << prop_name((*f_iter)) << ".GetHashCode())"; + } + out << ");" << endl; + } + + indent_down(); + out << indent() << "}" << endl; + out << indent() << "return hashcode;" << endl; + + indent_down(); + out << indent() << "}" << endl << endl; +} + +void t_netcore_generator::generate_service(t_service* tservice) +{ + int ic = indent_count(); + + string f_service_name = namespace_dir_ + "/" + service_name_ + ".cs"; + ofstream_with_content_based_conditional_update f_service; + f_service.open(f_service_name.c_str()); + + f_service << autogen_comment() << netcore_type_usings() << netcore_thrift_usings() << endl; + + start_netcore_namespace(f_service); + + f_service << indent() << "public partial class " << normalize_name(service_name_) << endl + << indent() << "{" << endl; + indent_up(); + + generate_service_interface(f_service, tservice); + generate_service_client(f_service, tservice); + generate_service_server(f_service, tservice); + generate_service_helpers(f_service, tservice); + + indent_down(); + f_service << indent() << "}" << endl; + + end_netcore_namespace(f_service); + f_service.close(); + + indent_validate(ic, "generate_service."); +} + +void t_netcore_generator::generate_service_interface(ostream& out, t_service* tservice) +{ + string extends = ""; + string extends_iface = ""; + if (tservice->get_extends() != NULL) + { + extends = type_name(tservice->get_extends()); + extends_iface = " : " + extends + ".IAsync"; + } + + //out << endl << endl; + + generate_netcore_doc(out, tservice); + + if (wcf_) + { + out << indent() << "[ServiceContract(Namespace=\"" << wcf_namespace_ << "\")]" << endl; + } + + out << indent() << "public interface IAsync" << extends_iface << endl + << indent() << "{" << endl; + + indent_up(); + vector functions = tservice->get_functions(); + vector::iterator f_iter; + for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) + { + generate_netcore_doc(out, *f_iter); + + // if we're using WCF, add the corresponding attributes + if (wcf_) + { + out << indent() << "[OperationContract]" << endl; + + const vector& xceptions = (*f_iter)->get_xceptions()->get_members(); + vector::const_iterator x_iter; + for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) + { + out << indent() << "[FaultContract(typeof(" + type_name((*x_iter)->get_type(), false, false) + "Fault))]" << endl; + } + } + + out << indent() << function_signature_async(*f_iter) << ";" << endl << endl; + } + indent_down(); + out << indent() << "}" << endl << endl; +} + +void t_netcore_generator::generate_service_helpers(ostream& out, t_service* tservice) +{ + vector functions = tservice->get_functions(); + vector::iterator f_iter; + + for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) + { + t_struct* ts = (*f_iter)->get_arglist(); + generate_netcore_struct_definition(out, ts, false, true); + generate_function_helpers(out, *f_iter); + } +} + +void t_netcore_generator::generate_service_client(ostream& out, t_service* tservice) +{ + string extends = ""; + string extends_client = ""; + if (tservice->get_extends() != NULL) + { + extends = type_name(tservice->get_extends()); + extends_client = extends + ".Client, "; + } + else + { + extends_client = "TBaseClient, IDisposable, "; + } + + out << endl; + + generate_netcore_doc(out, tservice); + + out << indent() << "public class Client : " << extends_client << "IAsync" << endl + << indent() << "{" << endl; + indent_up(); + + out << indent() << "public Client(TProtocol protocol) : this(protocol, protocol)" << endl + << indent() << "{" << endl + << indent() << "}" << endl + << endl + << indent() << "public Client(TProtocol inputProtocol, TProtocol outputProtocol) : base(inputProtocol, outputProtocol)" + << indent() << "{" << endl + << indent() << "}" << endl; + + vector functions = tservice->get_functions(); + vector::const_iterator functions_iterator; + + for (functions_iterator = functions.begin(); functions_iterator != functions.end(); ++functions_iterator) + { + string function_name = correct_function_name_for_async((*functions_iterator)->get_name()); + + // async + out << indent() << "public async " << function_signature_async(*functions_iterator, "") << endl + << indent() << "{" << endl; + indent_up(); + + string argsname = (*functions_iterator)->get_name() + "Args"; + + out << indent() << "await OutputProtocol.WriteMessageBeginAsync(new TMessage(\"" << function_name + << "\", " << ((*functions_iterator)->is_oneway() ? "TMessageType.Oneway" : "TMessageType.Call") << ", SeqId), cancellationToken);" << endl + << indent() << endl + << indent() << "var args = new " << argsname << "();" << endl; + + t_struct* arg_struct = (*functions_iterator)->get_arglist(); + prepare_member_name_mapping(arg_struct); + const vector& fields = arg_struct->get_members(); + vector::const_iterator fld_iter; + + for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) + { + out << indent() << "args." << prop_name(*fld_iter) << " = " << normalize_name((*fld_iter)->get_name()) << ";" << endl; + } + + out << indent() << endl + << indent() << "await args.WriteAsync(OutputProtocol, cancellationToken);" << endl + << indent() << "await OutputProtocol.WriteMessageEndAsync(cancellationToken);" << endl + << indent() << "await OutputProtocol.Transport.FlushAsync(cancellationToken);" << endl; + + if (!(*functions_iterator)->is_oneway()) + { + string resultname = (*functions_iterator)->get_name() + "Result"; + t_struct noargs(program_); + t_struct* xs = (*functions_iterator)->get_xceptions(); + prepare_member_name_mapping(xs, xs->get_members(), resultname); + + out << indent() << endl + << indent() << "var msg = await InputProtocol.ReadMessageBeginAsync(cancellationToken);" << endl + << indent() << "if (msg.Type == TMessageType.Exception)" << endl + << indent() << "{" << endl; + indent_up(); + + out << indent() << "var x = await TApplicationException.ReadAsync(InputProtocol, cancellationToken);" << endl + << indent() << "await InputProtocol.ReadMessageEndAsync(cancellationToken);" << endl + << indent() << "throw x;" << endl; + indent_down(); + + out << indent() << "}" << endl + << endl + << indent() << "var result = new " << resultname << "();" << endl + << indent() << "await result.ReadAsync(InputProtocol, cancellationToken);" << endl + << indent() << "await InputProtocol.ReadMessageEndAsync(cancellationToken);" << endl; + + if (!(*functions_iterator)->get_returntype()->is_void()) + { + if (nullable_) + { + if (type_can_be_null((*functions_iterator)->get_returntype())) + { + out << indent() << "if (result.Success != null)" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "return result.Success;" << endl; + indent_down(); + out << indent() << "}" << endl; + } + else + { + out << indent() << "if (result.Success.HasValue)" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "return result.Success.Value;" << endl; + indent_down(); + out << indent() << "}" << endl; + } + } + else + { + out << indent() << "if (result.__isset.success)" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "return result.Success;" << endl; + indent_down(); + out << indent() << "}" << endl; + } + } + + const vector& xceptions = xs->get_members(); + vector::const_iterator x_iter; + for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) + { + if (nullable_) + { + out << indent() << "if (result." << prop_name(*x_iter) << " != null)" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "throw result." << prop_name(*x_iter) << ";" << endl; + indent_down(); + out << indent() << "}" << endl; + } + else + { + out << indent() << "if (result.__isset." << normalize_name((*x_iter)->get_name()) << ")" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "throw result." << prop_name(*x_iter) << ";" << endl; + indent_down(); + out << indent() << "}" << endl; + } + } + + if ((*functions_iterator)->get_returntype()->is_void()) + { + out << indent() << "return;" << endl; + } + else + { + out << indent() << "throw new TApplicationException(TApplicationException.ExceptionType.MissingResult, \"" + << function_name << " failed: unknown result\");" << endl; + } + + cleanup_member_name_mapping((*functions_iterator)->get_xceptions()); + indent_down(); + out << indent() << "}" << endl << endl; + } + else + { + indent_down(); + out << indent() << "}" << endl; + } + } + + indent_down(); + out << indent() << "}" << endl << endl; +} + +void t_netcore_generator::generate_service_server(ostream& out, t_service* tservice) +{ + vector functions = tservice->get_functions(); + vector::iterator f_iter; + + string extends = ""; + string extends_processor = ""; + if (tservice->get_extends() != NULL) + { + extends = type_name(tservice->get_extends()); + extends_processor = extends + ".AsyncProcessor, "; + } + + out << indent() << "public class AsyncProcessor : " << extends_processor << "ITAsyncProcessor" << endl + << indent() << "{" << endl; + + indent_up(); + + out << indent() << "private IAsync _iAsync;" << endl + << endl + << indent() << "public AsyncProcessor(IAsync iAsync)"; + + if (!extends.empty()) + { + out << " : base(iAsync)"; + } + + out << endl + << indent() << "{" << endl; + indent_up(); + + out << indent() << "if (iAsync == null) throw new ArgumentNullException(nameof(iAsync));" << endl + << endl + << indent() << "_iAsync = iAsync;" << endl; + + for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) + { + string function_name = (*f_iter)->get_name(); + out << indent() << "processMap_[\"" << correct_function_name_for_async(function_name) << "\"] = " << function_name << "_ProcessAsync;" << endl; + } + + indent_down(); + out << indent() << "}" << endl + << endl; + + if (extends.empty()) + { + out << indent() << "protected delegate Task ProcessFunction(int seqid, TProtocol iprot, TProtocol oprot, CancellationToken cancellationToken);" << endl; + } + + if (extends.empty()) + { + out << indent() << "protected Dictionary processMap_ = new Dictionary();" << endl; + } + + out << endl; + + if (extends.empty()) + { + out << indent() << "public async Task ProcessAsync(TProtocol iprot, TProtocol oprot)" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "return await ProcessAsync(iprot, oprot, CancellationToken.None);" << endl; + indent_down(); + out << indent() << "}" << endl << endl; + + out << indent() << "public async Task ProcessAsync(TProtocol iprot, TProtocol oprot, CancellationToken cancellationToken)" << endl; + } + else + { + out << indent() << "public new async Task ProcessAsync(TProtocol iprot, TProtocol oprot)" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "return await ProcessAsync(iprot, oprot, CancellationToken.None);" << endl; + indent_down(); + out << indent() << "}" << endl << endl; + + out << indent() << "public new async Task ProcessAsync(TProtocol iprot, TProtocol oprot, CancellationToken cancellationToken)" << endl; + } + + out << indent() << "{" << endl; + indent_up(); + out << indent() << "try" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "var msg = await iprot.ReadMessageBeginAsync(cancellationToken);" << endl + << endl + << indent() << "ProcessFunction fn;" << endl + << indent() << "processMap_.TryGetValue(msg.Name, out fn);" << endl + << endl + << indent() << "if (fn == null)" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "await TProtocolUtil.SkipAsync(iprot, TType.Struct, cancellationToken);" << endl + << indent() << "await iprot.ReadMessageEndAsync(cancellationToken);" << endl + << indent() << "var x = new TApplicationException (TApplicationException.ExceptionType.UnknownMethod, \"Invalid method name: '\" + msg.Name + \"'\");" << endl + << indent() << "await oprot.WriteMessageBeginAsync(new TMessage(msg.Name, TMessageType.Exception, msg.SeqID), cancellationToken);" << endl + << indent() << "await x.WriteAsync(oprot, cancellationToken);" << endl + << indent() << "await oprot.WriteMessageEndAsync(cancellationToken);" << endl + << indent() << "await oprot.Transport.FlushAsync(cancellationToken);" << endl + << indent() << "return true;" << endl; + indent_down(); + out << indent() << "}" << endl + << endl + << indent() << "await fn(msg.SeqID, iprot, oprot, cancellationToken);" << endl + << endl; + indent_down(); + out << indent() << "}" << endl; + out << indent() << "catch (IOException)" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "return false;" << endl; + indent_down(); + out << indent() << "}" << endl + << endl + << indent() << "return true;" << endl; + indent_down(); + out << indent() << "}" << endl << endl; + + for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) + { + generate_process_function_async(out, tservice, *f_iter); + } + + indent_down(); + out << indent() << "}" << endl << endl; +} + +void t_netcore_generator::generate_function_helpers(ostream& out, t_function* tfunction) +{ + if (tfunction->is_oneway()) + { + return; + } + + t_struct result(program_, tfunction->get_name() + "_result"); + t_field success(tfunction->get_returntype(), "success", 0); + if (!tfunction->get_returntype()->is_void()) + { + result.append(&success); + } + + t_struct* xs = tfunction->get_xceptions(); + const vector& fields = xs->get_members(); + vector::const_iterator f_iter; + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) + { + result.append(*f_iter); + } + + generate_netcore_struct_definition(out, &result, false, true, true); +} + +void t_netcore_generator::generate_process_function_async(ostream& out, t_service* tservice, t_function* tfunction) +{ + (void)tservice; + out << indent() << "public async Task " << tfunction->get_name() + << "_ProcessAsync(int seqid, TProtocol iprot, TProtocol oprot, CancellationToken cancellationToken)" << endl + << indent() << "{" << endl; + indent_up(); + + string argsname = tfunction->get_name() + "Args"; + string resultname = tfunction->get_name() + "Result"; + + out << indent() << "var args = new " << argsname << "();" << endl + << indent() << "await args.ReadAsync(iprot, cancellationToken);" << endl + << indent() << "await iprot.ReadMessageEndAsync(cancellationToken);" << endl; + + if (!tfunction->is_oneway()) + { + out << indent() << "var result = new " << resultname << "();" << endl; + } + + out << indent() << "try" << endl + << indent() << "{" << endl; + indent_up(); + + t_struct* xs = tfunction->get_xceptions(); + const vector& xceptions = xs->get_members(); + + if (xceptions.size() > 0) + { + out << indent() << "try" << endl + << indent() << "{" << endl; + indent_up(); + } + + t_struct* arg_struct = tfunction->get_arglist(); + const vector& fields = arg_struct->get_members(); + vector::const_iterator f_iter; + + out << indent(); + if (!tfunction->is_oneway() && !tfunction->get_returntype()->is_void()) + { + out << "result.Success = "; + } + + out << "await _iAsync." << normalize_name(tfunction->get_name()) << "Async("; + + bool first = true; + prepare_member_name_mapping(arg_struct); + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) + { + if (first) + { + first = false; + } + else + { + out << ", "; + } + + out << "args." << prop_name(*f_iter); + if (nullable_ && !type_can_be_null((*f_iter)->get_type())) + { + out << ".Value"; + } + } + + cleanup_member_name_mapping(arg_struct); + + if (!first) + { + out << ", "; + } + + out << "cancellationToken);" << endl; + + vector::const_iterator x_iter; + + prepare_member_name_mapping(xs, xs->get_members(), resultname); + if (xceptions.size() > 0) + { + indent_down(); + out << indent() << "}" << endl; + + for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) + { + out << indent() << "catch (" << type_name((*x_iter)->get_type(), false, false) << " " << (*x_iter)->get_name() << ")" << endl + << indent() << "{" << endl; + + if (!tfunction->is_oneway()) + { + indent_up(); + out << indent() << "result." << prop_name(*x_iter) << " = " << (*x_iter)->get_name() << ";" << endl; + indent_down(); + } + out << indent() << "}" << endl; + } + } + + if (!tfunction->is_oneway()) + { + out << indent() << "await oprot.WriteMessageBeginAsync(new TMessage(\"" + << correct_function_name_for_async(tfunction->get_name()) << "\", TMessageType.Reply, seqid), cancellationToken); " << endl + << indent() << "await result.WriteAsync(oprot, cancellationToken);" << endl; + } + indent_down(); + + cleanup_member_name_mapping(xs); + + out << indent() << "}" << endl + << indent() << "catch (TTransportException)" << endl + << indent() << "{" << endl + << indent() << " throw;" << endl + << indent() << "}" << endl + << indent() << "catch (Exception ex)" << endl + << indent() << "{" << endl; + indent_up(); + + out << indent() << "Console.Error.WriteLine(\"Error occurred in processor:\");" << endl + << indent() << "Console.Error.WriteLine(ex.ToString());" << endl; + + if (tfunction->is_oneway()) + { + indent_down(); + out << indent() << "}" << endl; + } + else + { + out << indent() << "var x = new TApplicationException(TApplicationException.ExceptionType.InternalError,\" Internal error.\");" << endl + << indent() << "await oprot.WriteMessageBeginAsync(new TMessage(\"" << correct_function_name_for_async(tfunction->get_name()) + << "\", TMessageType.Exception, seqid), cancellationToken);" << endl + << indent() << "await x.WriteAsync(oprot, cancellationToken);" << endl; + indent_down(); + + out << indent() << "}" << endl + << indent() << "await oprot.WriteMessageEndAsync(cancellationToken);" << endl + << indent() << "await oprot.Transport.FlushAsync(cancellationToken);" << endl; + } + + indent_down(); + out << indent() << "}" << endl << endl; +} + +void t_netcore_generator::generate_netcore_union_reader(ostream& out, t_struct* tunion) +{ + // Thanks to THRIFT-1768, we don't need to check for required fields in the union + const vector& fields = tunion->get_members(); + vector::const_iterator f_iter; + + out << indent() << "public static async Task<" << tunion->get_name() << "> ReadAsync(TProtocol iprot, CancellationToken cancellationToken)" << endl; + scope_up(out); + + out << indent() << "iprot.IncrementRecursionDepth();" << endl; + out << indent() << "try" << endl; + scope_up(out); + + out << indent() << tunion->get_name() << " retval;" << endl; + out << indent() << "await iprot.ReadStructBeginAsync(cancellationToken);" << endl; + out << indent() << "TField field = await iprot.ReadFieldBeginAsync(cancellationToken);" << endl; + // we cannot have the first field be a stop -- we must have a single field defined + out << indent() << "if (field.Type == TType.Stop)" << endl; + scope_up(out); + out << indent() << "await iprot.ReadFieldEndAsync(cancellationToken);" << endl; + out << indent() << "retval = new ___undefined();" << endl; + scope_down(out); + out << indent() << "else" << endl; + scope_up(out); + out << indent() << "switch (field.ID)" << endl; + scope_up(out); + + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) + { + out << indent() << "case " << (*f_iter)->get_key() << ":" << endl; + indent_up(); + out << indent() << "if (field.Type == " << type_to_enum((*f_iter)->get_type()) << ") {" << endl; + indent_up(); + + out << indent() << type_name((*f_iter)->get_type()) << " temp;" << endl; + generate_deserialize_field(out, (*f_iter), "temp", true); + out << indent() << "retval = new " << (*f_iter)->get_name() << "(temp);" << endl; + + indent_down(); + out << indent() << "} else { " << endl << indent() << " await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken);" + << endl << indent() << " retval = new ___undefined();" << endl << indent() << "}" << endl + << indent() << "break;" << endl; + indent_down(); + } + + out << indent() << "default: " << endl; + indent_up(); + out << indent() << "await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken);" << endl << indent() + << "retval = new ___undefined();" << endl; + out << indent() << "break;" << endl; + indent_down(); + + scope_down(out); + + out << indent() << "await iprot.ReadFieldEndAsync(cancellationToken);" << endl; + + out << indent() << "if ((await iprot.ReadFieldBeginAsync(cancellationToken)).Type != TType.Stop)" << endl; + scope_up(out); + out << indent() << "throw new TProtocolException(TProtocolException.INVALID_DATA);" << endl; + scope_down(out); + + // end of else for TStop + scope_down(out); + out << indent() << "await iprot.ReadStructEndAsync(cancellationToken);" << endl; + out << indent() << "return retval;" << endl; + indent_down(); + + scope_down(out); + out << indent() << "finally" << endl; + scope_up(out); + out << indent() << "iprot.DecrementRecursionDepth();" << endl; + scope_down(out); + + out << indent() << "}" << endl << endl; +} + +void t_netcore_generator::generate_deserialize_field(ostream& out, t_field* tfield, string prefix, bool is_propertyless) +{ + t_type* type = tfield->get_type(); + while (type->is_typedef()) + { + type = static_cast(type)->get_type(); + } + + if (type->is_void()) + { + throw "CANNOT GENERATE DESERIALIZE CODE FOR void TYPE: " + prefix + tfield->get_name(); + } + + string name = prefix + (is_propertyless ? "" : prop_name(tfield)); + + if (type->is_struct() || type->is_xception()) + { + generate_deserialize_struct(out, static_cast(type), name); + } + else if (type->is_container()) + { + generate_deserialize_container(out, type, name); + } + else if (type->is_base_type() || type->is_enum()) + { + out << indent() << name << " = "; + + if (type->is_enum()) + { + out << "(" << type_name(type, false, true) << ")"; + } + + out << "await iprot."; + + if (type->is_base_type()) + { + t_base_type::t_base tbase = static_cast(type)->get_base(); + switch (tbase) + { + case t_base_type::TYPE_VOID: + throw "compiler error: cannot serialize void field in a struct: " + name; + break; + case t_base_type::TYPE_STRING: + if (type->is_binary()) + { + out << "ReadBinaryAsync(cancellationToken);"; + } + else + { + out << "ReadStringAsync(cancellationToken);"; + } + break; + case t_base_type::TYPE_BOOL: + out << "ReadBoolAsync(cancellationToken);"; + break; + case t_base_type::TYPE_I8: + out << "ReadByteAsync(cancellationToken);"; + break; + case t_base_type::TYPE_I16: + out << "ReadI16Async(cancellationToken);"; + break; + case t_base_type::TYPE_I32: + out << "ReadI32Async(cancellationToken);"; + break; + case t_base_type::TYPE_I64: + out << "ReadI64Async(cancellationToken);"; + break; + case t_base_type::TYPE_DOUBLE: + out << "ReadDoubleAsync(cancellationToken);"; + break; + default: + throw "compiler error: no C# name for base type " + t_base_type::t_base_name(tbase); + } + } + else if (type->is_enum()) + { + out << "ReadI32Async(cancellationToken);"; + } + out << endl; + } + else + { + printf("DO NOT KNOW HOW TO DESERIALIZE FIELD '%s' TYPE '%s'\n", tfield->get_name().c_str(), type_name(type).c_str()); + } +} + +void t_netcore_generator::generate_deserialize_struct(ostream& out, t_struct* tstruct, string prefix) +{ + if (union_ && tstruct->is_union()) + { + out << indent() << prefix << " = await " << type_name(tstruct) << ".ReadAsync(iprot, cancellationToken);" << endl; + } + else + { + out << indent() << prefix << " = new " << type_name(tstruct) << "();" << endl + << indent() << "await " << prefix << ".ReadAsync(iprot, cancellationToken);" << endl; + } +} + +void t_netcore_generator::generate_deserialize_container(ostream& out, t_type* ttype, string prefix) +{ + out << indent() << "{" << endl; + indent_up(); + + string obj; + + if (ttype->is_map()) + { + obj = tmp("_map"); + } + else if (ttype->is_set()) + { + obj = tmp("_set"); + } + else if (ttype->is_list()) + { + obj = tmp("_list"); + } + + out << indent() << prefix << " = new " << type_name(ttype, false, true) << "();" << endl; + if (ttype->is_map()) + { + out << indent() << "TMap " << obj << " = await iprot.ReadMapBeginAsync(cancellationToken);" << endl; + } + else if (ttype->is_set()) + { + out << indent() << "TSet " << obj << " = await iprot.ReadSetBeginAsync(cancellationToken);" << endl; + } + else if (ttype->is_list()) + { + out << indent() << "TList " << obj << " = await iprot.ReadListBeginAsync(cancellationToken);" << endl; + } + + string i = tmp("_i"); + out << indent() << "for(int " << i << " = 0; " << i << " < " << obj << ".Count; ++" << i << ")" << endl + << indent() << "{" << endl; + indent_up(); + + if (ttype->is_map()) + { + generate_deserialize_map_element(out, static_cast(ttype), prefix); + } + else if (ttype->is_set()) + { + generate_deserialize_set_element(out, static_cast(ttype), prefix); + } + else if (ttype->is_list()) + { + generate_deserialize_list_element(out, static_cast(ttype), prefix); + } + + indent_down(); + out << indent() << "}" << endl; + + if (ttype->is_map()) + { + out << indent() << "await iprot.ReadMapEndAsync(cancellationToken);" << endl; + } + else if (ttype->is_set()) + { + out << indent() << "await iprot.ReadSetEndAsync(cancellationToken);" << endl; + } + else if (ttype->is_list()) + { + out << indent() << "await iprot.ReadListEndAsync(cancellationToken);" << endl; + } + + indent_down(); + out << indent() << "}" << endl; +} + +void t_netcore_generator::generate_deserialize_map_element(ostream& out, t_map* tmap, string prefix) +{ + string key = tmp("_key"); + string val = tmp("_val"); + + t_field fkey(tmap->get_key_type(), key); + t_field fval(tmap->get_val_type(), val); + + out << indent() << declare_field(&fkey) << endl; + out << indent() << declare_field(&fval) << endl; + + generate_deserialize_field(out, &fkey); + generate_deserialize_field(out, &fval); + + out << indent() << prefix << "[" << key << "] = " << val << ";" << endl; +} + +void t_netcore_generator::generate_deserialize_set_element(ostream& out, t_set* tset, string prefix) +{ + string elem = tmp("_elem"); + t_field felem(tset->get_elem_type(), elem); + + out << indent() << declare_field(&felem) << endl; + + generate_deserialize_field(out, &felem); + + out << indent() << prefix << ".Add(" << elem << ");" << endl; +} + +void t_netcore_generator::generate_deserialize_list_element(ostream& out, t_list* tlist, string prefix) +{ + string elem = tmp("_elem"); + t_field felem(tlist->get_elem_type(), elem); + + out << indent() << declare_field(&felem) << endl; + + generate_deserialize_field(out, &felem); + + out << indent() << prefix << ".Add(" << elem << ");" << endl; +} + +void t_netcore_generator::generate_serialize_field(ostream& out, t_field* tfield, string prefix, bool is_element, bool is_propertyless) +{ + t_type* type = tfield->get_type(); + while (type->is_typedef()) + { + type = static_cast(type)->get_type(); + } + + string name = prefix + (is_propertyless ? "" : prop_name(tfield)); + + if (type->is_void()) + { + throw "CANNOT GENERATE SERIALIZE CODE FOR void TYPE: " + name; + } + + if (type->is_struct() || type->is_xception()) + { + generate_serialize_struct(out, static_cast(type), name); + } + else if (type->is_container()) + { + generate_serialize_container(out, type, name); + } + else if (type->is_base_type() || type->is_enum()) + { + out << indent() << "await oprot."; + + string nullable_name = nullable_ && !is_element && !field_is_required(tfield) ? name + ".Value" : name; + + if (type->is_base_type()) + { + t_base_type::t_base tbase = static_cast(type)->get_base(); + switch (tbase) + { + case t_base_type::TYPE_VOID: + throw "compiler error: cannot serialize void field in a struct: " + name; + case t_base_type::TYPE_STRING: + if (type->is_binary()) + { + out << "WriteBinaryAsync("; + } + else + { + out << "WriteStringAsync("; + } + out << name << ", cancellationToken);"; + break; + case t_base_type::TYPE_BOOL: + out << "WriteBoolAsync(" << nullable_name << ", cancellationToken);"; + break; + case t_base_type::TYPE_I8: + out << "WriteByteAsync(" << nullable_name << ", cancellationToken);"; + break; + case t_base_type::TYPE_I16: + out << "WriteI16Async(" << nullable_name << ", cancellationToken);"; + break; + case t_base_type::TYPE_I32: + out << "WriteI32Async(" << nullable_name << ", cancellationToken);"; + break; + case t_base_type::TYPE_I64: + out << "WriteI64Async(" << nullable_name << ", cancellationToken);"; + break; + case t_base_type::TYPE_DOUBLE: + out << "WriteDoubleAsync(" << nullable_name << ", cancellationToken);"; + break; + default: + throw "compiler error: no C# name for base type " + t_base_type::t_base_name(tbase); + } + } + else if (type->is_enum()) + { + out << "WriteI32Async((int)" << nullable_name << ", cancellationToken);"; + } + out << endl; + } + else + { + printf("DO NOT KNOW HOW TO SERIALIZE '%s%s' TYPE '%s'\n", prefix.c_str(), tfield->get_name().c_str(), type_name(type).c_str()); + } +} + +void t_netcore_generator::generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix) +{ + (void)tstruct; + out << indent() << "await " << prefix << ".WriteAsync(oprot, cancellationToken);" << endl; +} + +void t_netcore_generator::generate_serialize_container(ostream& out, t_type* ttype, string prefix) +{ + out << indent() << "{" << endl; + indent_up(); + + if (ttype->is_map()) + { + out << indent() << "await oprot.WriteMapBeginAsync(new TMap(" << type_to_enum(static_cast(ttype)->get_key_type()) + << ", " << type_to_enum(static_cast(ttype)->get_val_type()) << ", " << prefix + << ".Count), cancellationToken);" << endl; + } + else if (ttype->is_set()) + { + out << indent() << "await oprot.WriteSetBeginAsync(new TSet(" << type_to_enum(static_cast(ttype)->get_elem_type()) + << ", " << prefix << ".Count), cancellationToken);" << endl; + } + else if (ttype->is_list()) + { + out << indent() << "await oprot.WriteListBeginAsync(new TList(" + << type_to_enum(static_cast(ttype)->get_elem_type()) << ", " << prefix << ".Count), cancellationToken);" + << endl; + } + + string iter = tmp("_iter"); + if (ttype->is_map()) + { + out << indent() << "foreach (" << type_name(static_cast(ttype)->get_key_type()) << " " << iter + << " in " << prefix << ".Keys)"; + } + else if (ttype->is_set()) + { + out << indent() << "foreach (" << type_name(static_cast(ttype)->get_elem_type()) << " " << iter + << " in " << prefix << ")"; + } + else if (ttype->is_list()) + { + out << indent() << "foreach (" << type_name(static_cast(ttype)->get_elem_type()) << " " << iter + << " in " << prefix << ")"; + } + + out << endl; + out << indent() << "{" << endl; + indent_up(); + + if (ttype->is_map()) + { + generate_serialize_map_element(out, static_cast(ttype), iter, prefix); + } + else if (ttype->is_set()) + { + generate_serialize_set_element(out, static_cast(ttype), iter); + } + else if (ttype->is_list()) + { + generate_serialize_list_element(out, static_cast(ttype), iter); + } + + indent_down(); + out << indent() << "}" << endl; + + if (ttype->is_map()) + { + out << indent() << "await oprot.WriteMapEndAsync(cancellationToken);" << endl; + } + else if (ttype->is_set()) + { + out << indent() << "await oprot.WriteSetEndAsync(cancellationToken);" << endl; + } + else if (ttype->is_list()) + { + out << indent() << "await oprot.WriteListEndAsync(cancellationToken);" << endl; + } + + indent_down(); + out << indent() << "}" << endl; +} + +void t_netcore_generator::generate_serialize_map_element(ostream& out, t_map* tmap, string iter, string map) +{ + t_field kfield(tmap->get_key_type(), iter); + generate_serialize_field(out, &kfield, "", true); + t_field vfield(tmap->get_val_type(), map + "[" + iter + "]"); + generate_serialize_field(out, &vfield, "", true); +} + +void t_netcore_generator::generate_serialize_set_element(ostream& out, t_set* tset, string iter) +{ + t_field efield(tset->get_elem_type(), iter); + generate_serialize_field(out, &efield, "", true); +} + +void t_netcore_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string iter) +{ + t_field efield(tlist->get_elem_type(), iter); + generate_serialize_field(out, &efield, "", true); +} + +void t_netcore_generator::generate_property(ostream& out, t_field* tfield, bool isPublic, bool generateIsset) +{ + generate_netcore_property(out, tfield, isPublic, generateIsset, "_"); +} + +void t_netcore_generator::generate_netcore_property(ostream& out, t_field* tfield, bool isPublic, bool generateIsset, string fieldPrefix) +{ + if ((serialize_ || wcf_) && isPublic) + { + out << indent() << "[DataMember(Order = 0)]" << endl; + } + bool has_default = field_has_default(tfield); + bool is_required = field_is_required(tfield); + if ((nullable_ && !has_default) || is_required) + { + out << indent() << (isPublic ? "public " : "private ") << type_name(tfield->get_type(), false, false, true, is_required) << " " << prop_name(tfield) << " { get; set; }" << endl; + } + else + { + out << indent() << (isPublic ? "public " : "private ") << type_name(tfield->get_type(), false, false, true) << " " << prop_name(tfield) << endl + << indent() << "{" << endl; + indent_up(); + + out << indent() << "get" << endl + << indent() << "{" << endl; + indent_up(); + + bool use_nullable = false; + if (nullable_) + { + t_type* ttype = tfield->get_type(); + while (ttype->is_typedef()) + { + ttype = static_cast(ttype)->get_type(); + } + if (ttype->is_base_type()) + { + use_nullable = static_cast(ttype)->get_base() != t_base_type::TYPE_STRING; + } + } + + out << indent() << "return " << fieldPrefix + tfield->get_name() << ";" << endl; + indent_down(); + out << indent() << "}" << endl + << indent() << "set" << endl + << indent() << "{" << endl; + indent_up(); + + if (use_nullable) + { + if (generateIsset) + { + out << indent() << "__isset." << normalize_name(tfield->get_name()) << " = value.HasValue;" << endl; + } + out << indent() << "if (value.HasValue) this." << fieldPrefix + tfield->get_name() << " = value.Value;" << endl; + } + else + { + if (generateIsset) + { + out << indent() << "__isset." << normalize_name(tfield->get_name()) << " = true;" << endl; + } + out << indent() << "this." << fieldPrefix + tfield->get_name() << " = value;" << endl; + } + + indent_down(); + out << indent() << "}" << endl; + indent_down(); + out << indent() << "}" << endl; + } + out << endl; +} + +string t_netcore_generator::make_valid_csharp_identifier(string const& fromName) +{ + string str = fromName; + if (str.empty()) + { + return str; + } + + // tests rely on this + assert(('A' < 'Z') && ('a' < 'z') && ('0' < '9')); + + // if the first letter is a number, we add an additional underscore in front of it + char c = str.at(0); + if (('0' <= c) && (c <= '9')) + { + str = "_" + str; + } + + // following chars: letter, number or underscore + for (size_t i = 0; i < str.size(); ++i) + { + c = str.at(i); + if (('A' > c || c > 'Z') && ('a' > c || c > 'z') && ('0' > c || c > '9') && '_' != c) + { + str.replace(i, 1, "_"); + } + } + + return str; +} + +void t_netcore_generator::cleanup_member_name_mapping(void* scope) +{ + if (member_mapping_scopes.empty()) + { + throw "internal error: cleanup_member_name_mapping() no scope active"; + } + + member_mapping_scope& active = member_mapping_scopes.back(); + if (active.scope_member != scope) + { + throw "internal error: cleanup_member_name_mapping() called for wrong struct"; + } + + member_mapping_scopes.pop_back(); +} + +string t_netcore_generator::get_mapped_member_name(string name) +{ + if (!member_mapping_scopes.empty()) + { + member_mapping_scope& active = member_mapping_scopes.back(); + map::iterator iter = active.mapping_table.find(name); + if (active.mapping_table.end() != iter) + { + return iter->second; + } + } + + pverbose("no mapping for member %s\n", name.c_str()); + return name; +} + +void t_netcore_generator::prepare_member_name_mapping(t_struct* tstruct) +{ + prepare_member_name_mapping(tstruct, tstruct->get_members(), tstruct->get_name()); +} + +void t_netcore_generator::prepare_member_name_mapping(void* scope, const vector& members, const string& structname) +{ + // begin new scope + member_mapping_scopes.push_back(member_mapping_scope()); + member_mapping_scope& active = member_mapping_scopes.back(); + active.scope_member = scope; + + // current C# generator policy: + // - prop names are always rendered with an Uppercase first letter + // - struct names are used as given + std::set used_member_names; + vector::const_iterator iter; + + // prevent name conflicts with struct (CS0542 error) + used_member_names.insert(structname); + + // prevent name conflicts with known methods (THRIFT-2942) + used_member_names.insert("Read"); + used_member_names.insert("Write"); + + for (iter = members.begin(); iter != members.end(); ++iter) + { + string oldname = (*iter)->get_name(); + string newname = prop_name(*iter, true); + while (true) + { + // new name conflicts with another member + if (used_member_names.find(newname) != used_member_names.end()) + { + pverbose("struct %s: member %s conflicts with another member\n", structname.c_str(), newname.c_str()); + newname += '_'; + continue; + } + + // add always, this helps us to detect edge cases like + // different spellings ("foo" and "Foo") within the same struct + pverbose("struct %s: member mapping %s => %s\n", structname.c_str(), oldname.c_str(), newname.c_str()); + active.mapping_table[oldname] = newname; + used_member_names.insert(newname); + break; + } + } +} + +string t_netcore_generator::prop_name(t_field* tfield, bool suppress_mapping) +{ + string name(tfield->get_name()); + if (suppress_mapping) + { + name[0] = toupper(name[0]); + } + else + { + name = get_mapped_member_name(name); + } + return name; +} + +string t_netcore_generator::type_name(t_type* ttype, bool in_container, bool in_init, bool in_param, bool is_required) +{ + (void)in_init; + + while (ttype->is_typedef()) + { + ttype = static_cast(ttype)->get_type(); + } + + if (ttype->is_base_type()) + { + return base_type_name(static_cast(ttype), in_container, in_param, is_required); + } + + if (ttype->is_map()) + { + t_map* tmap = static_cast(ttype); + return "Dictionary<" + type_name(tmap->get_key_type(), true) + ", " + type_name(tmap->get_val_type(), true) + ">"; + } + + if (ttype->is_set()) + { + t_set* tset = static_cast(ttype); + return "THashSet<" + type_name(tset->get_elem_type(), true) + ">"; + } + + if (ttype->is_list()) + { + t_list* tlist = static_cast(ttype); + return "List<" + type_name(tlist->get_elem_type(), true) + ">"; + } + + t_program* program = ttype->get_program(); + string postfix = (!is_required && nullable_ && in_param && ttype->is_enum()) ? "?" : ""; + if (program != NULL && program != program_) + { + string ns = program->get_namespace("netcore"); + if (!ns.empty()) + { + return ns + "." + normalize_name(ttype->get_name()) + postfix; + } + } + + return normalize_name(ttype->get_name()) + postfix; +} + +string t_netcore_generator::base_type_name(t_base_type* tbase, bool in_container, bool in_param, bool is_required) +{ + (void)in_container; + string postfix = (!is_required && nullable_ && in_param) ? "?" : ""; + switch (tbase->get_base()) + { + case t_base_type::TYPE_VOID: + return "void"; + case t_base_type::TYPE_STRING: + { + if (tbase->is_binary()) + { + return "byte[]"; + } + return "string"; + } + case t_base_type::TYPE_BOOL: + return "bool" + postfix; + case t_base_type::TYPE_I8: + return "sbyte" + postfix; + case t_base_type::TYPE_I16: + return "short" + postfix; + case t_base_type::TYPE_I32: + return "int" + postfix; + case t_base_type::TYPE_I64: + return "long" + postfix; + case t_base_type::TYPE_DOUBLE: + return "double" + postfix; + default: + throw "compiler error: no C# name for base type " + t_base_type::t_base_name(tbase->get_base()); + } +} + +string t_netcore_generator::declare_field(t_field* tfield, bool init, string prefix) +{ + string result = type_name(tfield->get_type()) + " " + prefix + tfield->get_name(); + if (init) + { + t_type* ttype = tfield->get_type(); + while (ttype->is_typedef()) + { + ttype = static_cast(ttype)->get_type(); + } + if (ttype->is_base_type() && field_has_default(tfield)) + { + std::ofstream dummy; + result += " = " + render_const_value(dummy, tfield->get_name(), ttype, tfield->get_value()); + } + else if (ttype->is_base_type()) + { + t_base_type::t_base tbase = static_cast(ttype)->get_base(); + switch (tbase) + { + case t_base_type::TYPE_VOID: + throw "NO T_VOID CONSTRUCT"; + case t_base_type::TYPE_STRING: + result += " = null"; + break; + case t_base_type::TYPE_BOOL: + result += " = false"; + break; + case t_base_type::TYPE_I8: + case t_base_type::TYPE_I16: + case t_base_type::TYPE_I32: + case t_base_type::TYPE_I64: + result += " = 0"; + break; + case t_base_type::TYPE_DOUBLE: + result += " = (double)0"; + break; + } + } + else if (ttype->is_enum()) + { + result += " = (" + type_name(ttype, false, true) + ")0"; + } + else if (ttype->is_container()) + { + result += " = new " + type_name(ttype, false, true) + "()"; + } + else + { + result += " = new " + type_name(ttype, false, true) + "()"; + } + } + return result + ";"; +} + +string t_netcore_generator::function_signature(t_function* tfunction, string prefix) +{ + t_type* ttype = tfunction->get_returntype(); + return type_name(ttype) + " " + normalize_name(prefix + tfunction->get_name()) + "(" + argument_list(tfunction->get_arglist()) + ")"; +} + +string t_netcore_generator::function_signature_async(t_function* tfunction, string prefix) +{ + t_type* ttype = tfunction->get_returntype(); + string task = "Task"; + if (!ttype->is_void()) + { + task += "<" + type_name(ttype) + ">"; + } + + string result = task + " " + normalize_name(prefix + tfunction->get_name()) + "Async("; + string args = argument_list(tfunction->get_arglist()); + result += args; + if (!args.empty()) + { + result += ", "; + } + result += "CancellationToken cancellationToken)"; + + return result; +} + +string t_netcore_generator::argument_list(t_struct* tstruct) +{ + string result = ""; + const vector& fields = tstruct->get_members(); + vector::const_iterator f_iter; + bool first = true; + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) + { + if (first) + { + first = false; + } + else + { + result += ", "; + } + result += type_name((*f_iter)->get_type()) + " " + normalize_name((*f_iter)->get_name()); + } + return result; +} + +string t_netcore_generator::type_to_enum(t_type* type) +{ + while (type->is_typedef()) + { + type = static_cast(type)->get_type(); + } + + if (type->is_base_type()) + { + t_base_type::t_base tbase = static_cast(type)->get_base(); + switch (tbase) + { + case t_base_type::TYPE_VOID: + throw "NO T_VOID CONSTRUCT"; + case t_base_type::TYPE_STRING: + return "TType.String"; + case t_base_type::TYPE_BOOL: + return "TType.Bool"; + case t_base_type::TYPE_I8: + return "TType.Byte"; + case t_base_type::TYPE_I16: + return "TType.I16"; + case t_base_type::TYPE_I32: + return "TType.I32"; + case t_base_type::TYPE_I64: + return "TType.I64"; + case t_base_type::TYPE_DOUBLE: + return "TType.Double"; + } + } + else if (type->is_enum()) + { + return "TType.I32"; + } + else if (type->is_struct() || type->is_xception()) + { + return "TType.Struct"; + } + else if (type->is_map()) + { + return "TType.Map"; + } + else if (type->is_set()) + { + return "TType.Set"; + } + else if (type->is_list()) + { + return "TType.List"; + } + + throw "INVALID TYPE IN type_to_enum: " + type->get_name(); +} + +void t_netcore_generator::generate_netcore_docstring_comment(ostream& out, string contents) +{ + docstring_comment(out, "/// " + endl, "/// ", contents, "/// " + endl); +} + +void t_netcore_generator::generate_netcore_doc(ostream& out, t_field* field) +{ + if (field->get_type()->is_enum()) + { + string combined_message = field->get_doc() + endl + "get_type()) + "\"/>"; + generate_netcore_docstring_comment(out, combined_message); + } + else + { + generate_netcore_doc(out, static_cast(field)); + } +} + +void t_netcore_generator::generate_netcore_doc(ostream& out, t_doc* tdoc) +{ + if (tdoc->has_doc()) + { + generate_netcore_docstring_comment(out, tdoc->get_doc()); + } +} + +void t_netcore_generator::generate_netcore_doc(ostream& out, t_function* tfunction) +{ + if (tfunction->has_doc()) + { + stringstream ps; + const vector& fields = tfunction->get_arglist()->get_members(); + vector::const_iterator p_iter; + for (p_iter = fields.begin(); p_iter != fields.end(); ++p_iter) + { + t_field* p = *p_iter; + ps << endl << "get_name() << "\">"; + if (p->has_doc()) + { + string str = p->get_doc(); + str.erase(remove(str.begin(), str.end(), '\n'), str.end()); + ps << str; + } + ps << ""; + } + + docstring_comment(out, + "", + "/// ", + "" + endl + tfunction->get_doc() + "" + ps.str(), + ""); + } +} + +void t_netcore_generator::docstring_comment(ostream& out, const string& comment_start, const string& line_prefix, const string& contents, const string& comment_end) +{ + if (comment_start != "") + { + out << indent() << comment_start; + } + + stringstream docs(contents, std::ios_base::in); + + while (!(docs.eof() || docs.fail())) + { + char line[1024]; + docs.getline(line, 1024); + + // Just prnt a newline when the line & prefix are empty. + if (strlen(line) == 0 && line_prefix == "" && !docs.eof()) + { + out << endl; + } + else if (strlen(line) > 0 || !docs.eof()) + { // skip the empty last line + out << indent() << line_prefix << line << endl; + } + } + if (comment_end != "") + { + out << indent() << comment_end; + } +} + +string t_netcore_generator::get_enum_class_name(t_type* type) +{ + string package = ""; + t_program* program = type->get_program(); + if (program != NULL && program != program_) + { + package = program->get_namespace("netcore") + "."; + } + return package + type->get_name(); +} + +THRIFT_REGISTER_GENERATOR( + netcore, + "C#", + " wcf: Adds bindings for WCF to generated classes.\n" + " serial: Add serialization support to generated classes.\n" + " nullable: Use nullable types for properties.\n" + " hashcode: Generate a hashcode and equals implementation for classes.\n" + " union: Use new union typing, which includes a static read function for union types.\n" +) diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_netcore_generator.h b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_netcore_generator.h new file mode 100644 index 0000000..6efc922 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_netcore_generator.h @@ -0,0 +1,137 @@ +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "thrift/platform.h" +#include "thrift/generate/t_oop_generator.h" + +using std::map; +using std::ostream; +using std::ostringstream; +using std::string; +using std::stringstream; +using std::vector; + +static const string endl = "\n"; // avoid ostream << std::endl flushes + +class t_netcore_generator : public t_oop_generator +{ + + struct member_mapping_scope + { + public: + member_mapping_scope() : scope_member(0) { } + void* scope_member; + map mapping_table; + }; + +public: + t_netcore_generator(t_program* program, const map& parsed_options, const string& option_string); + + bool is_wcf_enabled() const; + bool is_nullable_enabled() const; + bool is_hashcode_enabled() const; + bool is_serialize_enabled() const; + bool is_union_enabled() const; + map get_keywords_list() const; + + // overrides + void init_generator(); + void close_generator(); + void generate_consts(vector consts); + void generate_consts(ostream& out, vector consts); + void generate_typedef(t_typedef* ttypedef); + void generate_enum(t_enum* tenum); + void generate_enum(ostream& out, t_enum* tenum); + void generate_struct(t_struct* tstruct); + void generate_xception(t_struct* txception); + void generate_service(t_service* tservice); + + void generate_property(ostream& out, t_field* tfield, bool isPublic, bool generateIsset); + void generate_netcore_property(ostream& out, t_field* tfield, bool isPublic, bool includeIsset = true, string fieldPrefix = ""); + bool print_const_value(ostream& out, string name, t_type* type, t_const_value* value, bool in_static, bool defval = false, bool needtype = false); + string render_const_value(ostream& out, string name, t_type* type, t_const_value* value); + void print_const_constructor(ostream& out, vector consts); + void print_const_def_value(ostream& out, string name, t_type* type, t_const_value* value); + void generate_netcore_struct(t_struct* tstruct, bool is_exception); + void generate_netcore_union(t_struct* tunion); + void generate_netcore_struct_definition(ostream& out, t_struct* tstruct, bool is_xception = false, bool in_class = false, bool is_result = false); + void generate_netcore_union_definition(ostream& out, t_struct* tunion); + void generate_netcore_union_class(ostream& out, t_struct* tunion, t_field* tfield); + void generate_netcore_wcffault(ostream& out, t_struct* tstruct); + void generate_netcore_struct_reader(ostream& out, t_struct* tstruct); + void generate_netcore_struct_result_writer(ostream& out, t_struct* tstruct); + void generate_netcore_struct_writer(ostream& out, t_struct* tstruct); + void generate_netcore_struct_tostring(ostream& out, t_struct* tstruct); + void generate_netcore_struct_equals(ostream& out, t_struct* tstruct); + void generate_netcore_struct_hashcode(ostream& out, t_struct* tstruct); + void generate_netcore_union_reader(ostream& out, t_struct* tunion); + void generate_function_helpers(ostream& out, t_function* tfunction); + void generate_service_interface(ostream& out, t_service* tservice); + void generate_service_helpers(ostream& out, t_service* tservice); + void generate_service_client(ostream& out, t_service* tservice); + void generate_service_server(ostream& out, t_service* tservice); + void generate_process_function_async(ostream& out, t_service* tservice, t_function* function); + void generate_deserialize_field(ostream& out, t_field* tfield, string prefix = "", bool is_propertyless = false); + void generate_deserialize_struct(ostream& out, t_struct* tstruct, string prefix = ""); + void generate_deserialize_container(ostream& out, t_type* ttype, string prefix = ""); + void generate_deserialize_set_element(ostream& out, t_set* tset, string prefix = ""); + void generate_deserialize_map_element(ostream& out, t_map* tmap, string prefix = ""); + void generate_deserialize_list_element(ostream& out, t_list* list, string prefix = ""); + void generate_serialize_field(ostream& out, t_field* tfield, string prefix = "", bool is_element = false, bool is_propertyless = false); + void generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix = ""); + void generate_serialize_container(ostream& out, t_type* ttype, string prefix = ""); + void generate_serialize_map_element(ostream& out, t_map* tmap, string iter, string map); + void generate_serialize_set_element(ostream& out, t_set* tmap, string iter); + void generate_serialize_list_element(ostream& out, t_list* tlist, string iter); + void generate_netcore_doc(ostream& out, t_field* field); + void generate_netcore_doc(ostream& out, t_doc* tdoc); + void generate_netcore_doc(ostream& out, t_function* tdoc); + void generate_netcore_docstring_comment(ostream& out, string contents); + void docstring_comment(ostream& out, const string& comment_start, const string& line_prefix, const string& contents, const string& comment_end); + void start_netcore_namespace(ostream& out); + void end_netcore_namespace(ostream& out); + + string netcore_type_usings() const; + string netcore_thrift_usings() const; + + string type_name(t_type* ttype, bool in_countainer = false, bool in_init = false, bool in_param = false, bool is_required = false); + string base_type_name(t_base_type* tbase, bool in_container = false, bool in_param = false, bool is_required = false); + string declare_field(t_field* tfield, bool init = false, string prefix = ""); + string function_signature_async(t_function* tfunction, string prefix = ""); + string function_signature(t_function* tfunction, string prefix = ""); + string argument_list(t_struct* tstruct); + string type_to_enum(t_type* ttype); + string prop_name(t_field* tfield, bool suppress_mapping = false); + string get_enum_class_name(t_type* type); + +private: + string namespace_name_; + string namespace_dir_; + + bool nullable_; + bool union_; + bool hashcode_; + bool serialize_; + bool wcf_; + + string wcf_namespace_; + map netcore_keywords; + vector member_mapping_scopes; + + void init_keywords(); + string normalize_name(string name); + string make_valid_csharp_identifier(string const& fromName); + void prepare_member_name_mapping(t_struct* tstruct); + void prepare_member_name_mapping(void* scope, const vector& members, const string& structname); + void cleanup_member_name_mapping(void* scope); + string get_mapped_member_name(string oldname); +}; diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_ocaml_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_ocaml_generator.cc index 594219a..0ec81ba 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_ocaml_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_ocaml_generator.cc @@ -32,7 +32,7 @@ using std::ios; using std::map; -using std::ofstream; +using std::ostream; using std::ostringstream; using std::string; using std::stringstream; @@ -90,16 +90,16 @@ public: */ void generate_ocaml_struct(t_struct* tstruct, bool is_exception); - void generate_ocaml_struct_definition(std::ofstream& out, + void generate_ocaml_struct_definition(std::ostream& out, t_struct* tstruct, bool is_xception = false); - void generate_ocaml_struct_member(std::ofstream& out, string tname, t_field* tmember); - void generate_ocaml_struct_sig(std::ofstream& out, t_struct* tstruct, bool is_exception); - void generate_ocaml_struct_reader(std::ofstream& out, t_struct* tstruct); - void generate_ocaml_struct_writer(std::ofstream& out, t_struct* tstruct); + void generate_ocaml_struct_member(std::ostream& out, string tname, t_field* tmember); + void generate_ocaml_struct_sig(std::ostream& out, t_struct* tstruct, bool is_exception); + void generate_ocaml_struct_reader(std::ostream& out, t_struct* tstruct); + void generate_ocaml_struct_writer(std::ostream& out, t_struct* tstruct); void generate_ocaml_function_helpers(t_function* tfunction); - void generate_ocaml_method_copy(std::ofstream& out, const vector& members); - void generate_ocaml_member_copy(std::ofstream& out, t_field* member); + void generate_ocaml_method_copy(std::ostream& out, const vector& members); + void generate_ocaml_member_copy(std::ostream& out, t_field* member); /** * Service-level generation functions @@ -115,33 +115,33 @@ public: * Serialization constructs */ - void generate_deserialize_field(std::ofstream& out, t_field* tfield, std::string prefix); + void generate_deserialize_field(std::ostream& out, t_field* tfield, std::string prefix); - void generate_deserialize_struct(std::ofstream& out, t_struct* tstruct); + void generate_deserialize_struct(std::ostream& out, t_struct* tstruct); - void generate_deserialize_container(std::ofstream& out, t_type* ttype); + void generate_deserialize_container(std::ostream& out, t_type* ttype); - void generate_deserialize_set_element(std::ofstream& out, t_set* tset); + void generate_deserialize_set_element(std::ostream& out, t_set* tset); - void generate_deserialize_list_element(std::ofstream& out, + void generate_deserialize_list_element(std::ostream& out, t_list* tlist, std::string prefix = ""); - void generate_deserialize_type(std::ofstream& out, t_type* type); + void generate_deserialize_type(std::ostream& out, t_type* type); - void generate_serialize_field(std::ofstream& out, t_field* tfield, std::string name = ""); + void generate_serialize_field(std::ostream& out, t_field* tfield, std::string name = ""); - void generate_serialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); + void generate_serialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); - void generate_serialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); + void generate_serialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); - void generate_serialize_map_element(std::ofstream& out, + void generate_serialize_map_element(std::ostream& out, t_map* tmap, std::string kiter, std::string viter); - void generate_serialize_set_element(std::ofstream& out, t_set* tmap, std::string iter); + void generate_serialize_set_element(std::ostream& out, t_set* tmap, std::string iter); - void generate_serialize_list_element(std::ofstream& out, t_list* tlist, std::string iter); + void generate_serialize_list_element(std::ostream& out, t_list* tlist, std::string iter); /** * Helper rendering functions @@ -161,12 +161,12 @@ private: * File streams */ - std::ofstream f_types_; - std::ofstream f_consts_; - std::ofstream f_service_; + ofstream_with_content_based_conditional_update f_types_; + ofstream_with_content_based_conditional_update f_consts_; + ofstream_with_content_based_conditional_update f_service_; - std::ofstream f_types_i_; - std::ofstream f_service_i_; + ofstream_with_content_based_conditional_update f_types_i_; + ofstream_with_content_based_conditional_update f_service_i_; }; /* @@ -401,8 +401,8 @@ string t_ocaml_generator::render_const_value(t_type* type, t_const_value* value) indent_up(); const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { t_type* field_type = NULL; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { @@ -425,8 +425,8 @@ string t_ocaml_generator::render_const_value(t_type* type, t_const_value* value) } else if (type->is_map()) { t_type* ktype = ((t_map*)type)->get_key_type(); t_type* vtype = ((t_map*)type)->get_val_type(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; string hm = tmp("_hm"); out << endl; indent_up(); @@ -499,7 +499,7 @@ void t_ocaml_generator::generate_ocaml_struct(t_struct* tstruct, bool is_excepti generate_ocaml_struct_sig(f_types_i_, tstruct, is_exception); } -void t_ocaml_generator::generate_ocaml_method_copy(ofstream& out, const vector& members) { +void t_ocaml_generator::generate_ocaml_method_copy(ostream& out, const vector& members) { vector::const_iterator m_iter; /* Create a copy of the current object */ @@ -555,7 +555,7 @@ string t_ocaml_generator::struct_member_copy_of(t_type* type, string what) { return what; } -void t_ocaml_generator::generate_ocaml_member_copy(ofstream& out, t_field* tmember) { +void t_ocaml_generator::generate_ocaml_member_copy(ostream& out, t_field* tmember) { string mname = decapitalize(tmember->get_name()); t_type* type = get_true_type(tmember->get_type()); @@ -576,7 +576,7 @@ void t_ocaml_generator::generate_ocaml_member_copy(ofstream& out, t_field* tmemb * * @param tstruct The struct definition */ -void t_ocaml_generator::generate_ocaml_struct_definition(ofstream& out, +void t_ocaml_generator::generate_ocaml_struct_definition(ostream& out, t_struct* tstruct, bool is_exception) { const vector& members = tstruct->get_members(); @@ -611,7 +611,7 @@ void t_ocaml_generator::generate_ocaml_struct_definition(ofstream& out, * @param tname Name of the parent structure for the member * @param tmember Member definition */ -void t_ocaml_generator::generate_ocaml_struct_member(ofstream& out, +void t_ocaml_generator::generate_ocaml_struct_member(ostream& out, string tname, t_field* tmember) { string x = tmp("_x"); @@ -713,7 +713,7 @@ bool t_ocaml_generator::struct_member_default_cheaply_comparable(t_field* tmembe * * @param tstruct The struct definition */ -void t_ocaml_generator::generate_ocaml_struct_sig(ofstream& out, +void t_ocaml_generator::generate_ocaml_struct_sig(ostream& out, t_struct* tstruct, bool is_exception) { const vector& members = tstruct->get_members(); @@ -752,7 +752,7 @@ void t_ocaml_generator::generate_ocaml_struct_sig(ofstream& out, /** * Generates the read method for a struct */ -void t_ocaml_generator::generate_ocaml_struct_reader(ofstream& out, t_struct* tstruct) { +void t_ocaml_generator::generate_ocaml_struct_reader(ostream& out, t_struct* tstruct) { const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; string sname = type_name(tstruct); @@ -812,7 +812,7 @@ void t_ocaml_generator::generate_ocaml_struct_reader(ofstream& out, t_struct* ts indent_down(); } -void t_ocaml_generator::generate_ocaml_struct_writer(ofstream& out, t_struct* tstruct) { +void t_ocaml_generator::generate_ocaml_struct_writer(ostream& out, t_struct* tstruct) { string name = tstruct->get_name(); const vector& fields = tstruct->get_sorted_members(); vector::const_iterator f_iter; @@ -1309,7 +1309,7 @@ void t_ocaml_generator::generate_process_function(t_service* tservice, t_functio /** * Deserializes a field of any type. */ -void t_ocaml_generator::generate_deserialize_field(ofstream& out, t_field* tfield, string prefix) { +void t_ocaml_generator::generate_deserialize_field(ostream& out, t_field* tfield, string prefix) { t_type* type = tfield->get_type(); string name = decapitalize(tfield->get_name()); @@ -1321,7 +1321,7 @@ void t_ocaml_generator::generate_deserialize_field(ofstream& out, t_field* tfiel /** * Deserializes a field of any type. */ -void t_ocaml_generator::generate_deserialize_type(ofstream& out, t_type* type) { +void t_ocaml_generator::generate_deserialize_type(ostream& out, t_type* type) { type = get_true_type(type); if (type->is_void()) { @@ -1374,7 +1374,7 @@ void t_ocaml_generator::generate_deserialize_type(ofstream& out, t_type* type) { /** * Generates an unserializer for a struct, calling read() */ -void t_ocaml_generator::generate_deserialize_struct(ofstream& out, t_struct* tstruct) { +void t_ocaml_generator::generate_deserialize_struct(ostream& out, t_struct* tstruct) { string prefix = ""; t_program* program = tstruct->get_program(); if (program != NULL && program != program_) { @@ -1388,7 +1388,7 @@ void t_ocaml_generator::generate_deserialize_struct(ofstream& out, t_struct* tst * Serialize a container by writing out the header followed by * data and then a footer. */ -void t_ocaml_generator::generate_deserialize_container(ofstream& out, t_type* ttype) { +void t_ocaml_generator::generate_deserialize_container(ostream& out, t_type* ttype) { string size = tmp("_size"); string ktype = tmp("_ktype"); string vtype = tmp("_vtype"); @@ -1454,7 +1454,7 @@ void t_ocaml_generator::generate_deserialize_container(ofstream& out, t_type* tt * @param tfield The field to serialize * @param prefix Name to prepend to field name */ -void t_ocaml_generator::generate_serialize_field(ofstream& out, t_field* tfield, string name) { +void t_ocaml_generator::generate_serialize_field(ostream& out, t_field* tfield, string name) { t_type* type = get_true_type(tfield->get_type()); // Do nothing for void types @@ -1523,12 +1523,12 @@ void t_ocaml_generator::generate_serialize_field(ofstream& out, t_field* tfield, * @param tstruct The struct to serialize * @param prefix String prefix to attach to all fields */ -void t_ocaml_generator::generate_serialize_struct(ofstream& out, t_struct* tstruct, string prefix) { +void t_ocaml_generator::generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix) { (void)tstruct; indent(out) << prefix << "#write(oprot)"; } -void t_ocaml_generator::generate_serialize_container(ofstream& out, t_type* ttype, string prefix) { +void t_ocaml_generator::generate_serialize_container(ostream& out, t_type* ttype, string prefix) { if (ttype->is_map()) { indent(out) << "oprot#writeMapBegin(" << type_to_enum(((t_map*)ttype)->get_key_type()) << ","; out << type_to_enum(((t_map*)ttype)->get_val_type()) << ","; @@ -1579,7 +1579,7 @@ void t_ocaml_generator::generate_serialize_container(ofstream& out, t_type* ttyp * Serializes the members of a map. * */ -void t_ocaml_generator::generate_serialize_map_element(ofstream& out, +void t_ocaml_generator::generate_serialize_map_element(ostream& out, t_map* tmap, string kiter, string viter) { @@ -1593,7 +1593,7 @@ void t_ocaml_generator::generate_serialize_map_element(ofstream& out, /** * Serializes the members of a set. */ -void t_ocaml_generator::generate_serialize_set_element(ofstream& out, t_set* tset, string iter) { +void t_ocaml_generator::generate_serialize_set_element(ostream& out, t_set* tset, string iter) { t_field efield(tset->get_elem_type(), iter); generate_serialize_field(out, &efield); } @@ -1601,7 +1601,7 @@ void t_ocaml_generator::generate_serialize_set_element(ofstream& out, t_set* tse /** * Serializes the members of a list. */ -void t_ocaml_generator::generate_serialize_list_element(ofstream& out, t_list* tlist, string iter) { +void t_ocaml_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string iter) { t_field efield(tlist->get_elem_type(), iter); generate_serialize_field(out, &efield); } diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_oop_generator.h b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_oop_generator.h index 8fb580d..f8da547 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_oop_generator.h +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_oop_generator.h @@ -65,11 +65,11 @@ public: return package + type->get_name(); } - virtual void generate_java_docstring_comment(std::ofstream& out, std::string contents) { + virtual void generate_java_docstring_comment(std::ostream& out, std::string contents) { generate_docstring_comment(out, "/**\n", " * ", contents, " */\n"); } - virtual void generate_java_doc(std::ofstream& out, t_field* field) { + virtual void generate_java_doc(std::ostream& out, t_field* field) { if (field->get_type()->is_enum()) { std::string combined_message = field->get_doc() + "\n@see " + get_enum_class_name(field->get_type()); @@ -82,7 +82,7 @@ public: /** * Emits a JavaDoc comment if the provided object has a doc in Thrift */ - virtual void generate_java_doc(std::ofstream& out, t_doc* tdoc) { + virtual void generate_java_doc(std::ostream& out, t_doc* tdoc) { if (tdoc->has_doc()) { generate_java_docstring_comment(out, tdoc->get_doc()); } @@ -91,7 +91,7 @@ public: /** * Emits a JavaDoc comment if the provided function object has a doc in Thrift */ - virtual void generate_java_doc(std::ofstream& out, t_function* tfunction) { + virtual void generate_java_doc(std::ostream& out, t_function* tfunction) { if (tfunction->has_doc()) { std::stringstream ss; ss << tfunction->get_doc(); diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_perl_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_perl_generator.cc index bfe08f9..8924a76 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_perl_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_perl_generator.cc @@ -31,7 +31,7 @@ #include "thrift/generate/t_oop_generator.h" using std::map; -using std::ofstream; +using std::ostream; using std::ostringstream; using std::string; using std::stringstream; @@ -48,7 +48,7 @@ public: t_perl_generator(t_program* program, const std::map& parsed_options, const std::string& option_string) - : t_oop_generator(program) { + : t_oop_generator(program), f_types_use_includes_emitted_(false) { (void)option_string; std::map::const_iterator iter; @@ -87,11 +87,11 @@ public: */ void generate_perl_struct(t_struct* tstruct, bool is_exception); - void generate_perl_struct_definition(std::ofstream& out, + void generate_perl_struct_definition(std::ostream& out, t_struct* tstruct, bool is_xception = false); - void generate_perl_struct_reader(std::ofstream& out, t_struct* tstruct); - void generate_perl_struct_writer(std::ofstream& out, t_struct* tstruct); + void generate_perl_struct_reader(std::ostream& out, t_struct* tstruct); + void generate_perl_struct_writer(std::ostream& out, t_struct* tstruct); void generate_perl_function_helpers(t_function* tfunction); /** @@ -104,42 +104,43 @@ public: void generate_service_client(t_service* tservice); void generate_service_processor(t_service* tservice); void generate_process_function(t_service* tservice, t_function* tfunction); + void generate_use_includes(std::ostream& os, bool& done, t_type *type, bool selfish); /** * Serialization constructs */ - void generate_deserialize_field(std::ofstream& out, + void generate_deserialize_field(std::ostream& out, t_field* tfield, std::string prefix = "", bool inclass = false); - void generate_deserialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); + void generate_deserialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); - void generate_deserialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); + void generate_deserialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); - void generate_deserialize_set_element(std::ofstream& out, t_set* tset, std::string prefix = ""); + void generate_deserialize_set_element(std::ostream& out, t_set* tset, std::string prefix = ""); - void generate_deserialize_map_element(std::ofstream& out, t_map* tmap, std::string prefix = ""); + void generate_deserialize_map_element(std::ostream& out, t_map* tmap, std::string prefix = ""); - void generate_deserialize_list_element(std::ofstream& out, + void generate_deserialize_list_element(std::ostream& out, t_list* tlist, std::string prefix = ""); - void generate_serialize_field(std::ofstream& out, t_field* tfield, std::string prefix = ""); + void generate_serialize_field(std::ostream& out, t_field* tfield, std::string prefix = ""); - void generate_serialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); + void generate_serialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); - void generate_serialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); + void generate_serialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); - void generate_serialize_map_element(std::ofstream& out, + void generate_serialize_map_element(std::ostream& out, t_map* tmap, std::string kiter, std::string viter); - void generate_serialize_set_element(std::ofstream& out, t_set* tmap, std::string iter); + void generate_serialize_set_element(std::ostream& out, t_set* tmap, std::string iter); - void generate_serialize_list_element(std::ofstream& out, t_list* tlist, std::string iter); + void generate_serialize_list_element(std::ostream& out, t_list* tlist, std::string iter); /** * Helper rendering functions @@ -207,10 +208,12 @@ private: /** * File streams */ - std::ofstream f_types_; - std::ofstream f_consts_; - std::ofstream f_helpers_; - std::ofstream f_service_; + ofstream_with_content_based_conditional_update f_types_; + ofstream_with_content_based_conditional_update f_consts_; + ofstream_with_content_based_conditional_update f_helpers_; + ofstream_with_content_based_conditional_update f_service_; + + bool f_types_use_includes_emitted_; }; /** @@ -252,10 +255,12 @@ void t_perl_generator::init_generator() { string t_perl_generator::perl_includes() { string inc; - inc = "require 5.6.0;\n"; + inc = "use 5.10.0;\n"; inc += "use strict;\n"; inc += "use warnings;\n"; - inc += "use Thrift;\n\n"; + inc += "use Thrift::Exception;\n"; + inc += "use Thrift::MessageType;\n"; + inc += "use Thrift::Type;\n\n"; return inc; } @@ -349,12 +354,13 @@ string t_perl_generator::render_const_value(t_type* type, t_const_value* value) } else if (type->is_enum()) { out << value->get_integer(); } else if (type->is_struct() || type->is_xception()) { - out << "new " << perl_namespace(type->get_program()) << type->get_name() << "({" << endl; + out << perl_namespace(type->get_program()) << type->get_name() << "->new({" << endl; indent_up(); + const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { t_type* field_type = NULL; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { @@ -365,29 +371,30 @@ string t_perl_generator::render_const_value(t_type* type, t_const_value* value) if (field_type == NULL) { throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string(); } - out << render_const_value(g_type_string, v_iter->first); + indent(out) << render_const_value(g_type_string, v_iter->first); out << " => "; out << render_const_value(field_type, v_iter->second); out << ","; out << endl; } - - out << "})"; + indent_down(); + indent(out) << "})"; } else if (type->is_map()) { t_type* ktype = ((t_map*)type)->get_key_type(); t_type* vtype = ((t_map*)type)->get_val_type(); out << "{" << endl; + indent_up(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { - out << render_const_value(ktype, v_iter->first); + indent(out) << render_const_value(ktype, v_iter->first); out << " => "; out << render_const_value(vtype, v_iter->second); out << "," << endl; } - - out << "}"; + indent_down(); + indent(out) << "}"; } else if (type->is_list() || type->is_set()) { t_type* etype; if (type->is_list()) { @@ -396,17 +403,20 @@ string t_perl_generator::render_const_value(t_type* type, t_const_value* value) etype = ((t_set*)type)->get_elem_type(); } out << "[" << endl; + indent_up(); + const vector& val = value->get_list(); vector::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { - out << render_const_value(etype, *v_iter); + indent(out) << render_const_value(etype, *v_iter); if (type->is_set()) { out << " => 1"; } out << "," << endl; } - out << "]"; + indent_down(); + indent(out) << "]"; } return out.str(); } @@ -432,6 +442,7 @@ void t_perl_generator::generate_xception(t_struct* txception) { * Structs can be normal or exceptions. */ void t_perl_generator::generate_perl_struct(t_struct* tstruct, bool is_exception) { + generate_use_includes(f_types_, f_types_use_includes_emitted_, tstruct, false); generate_perl_struct_definition(f_types_, tstruct, is_exception); } @@ -442,7 +453,7 @@ void t_perl_generator::generate_perl_struct(t_struct* tstruct, bool is_exception * * @param tstruct The struct definition */ -void t_perl_generator::generate_perl_struct_definition(ofstream& out, +void t_perl_generator::generate_perl_struct_definition(ostream& out, t_struct* tstruct, bool is_exception) { const vector& members = tstruct->get_members(); @@ -520,7 +531,7 @@ void t_perl_generator::generate_perl_struct_definition(ofstream& out, /** * Generates the read() method for a struct */ -void t_perl_generator::generate_perl_struct_reader(ofstream& out, t_struct* tstruct) { +void t_perl_generator::generate_perl_struct_reader(ostream& out, t_struct* tstruct) { const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; @@ -535,14 +546,14 @@ void t_perl_generator::generate_perl_struct_reader(ofstream& out, t_struct* tstr indent(out) << "$xfer += $input->readStructBegin(\\$fname);" << endl; // Loop over reading in fields - indent(out) << "while (1) " << endl; + indent(out) << "while (1)" << endl; scope_up(out); indent(out) << "$xfer += $input->readFieldBegin(\\$fname, \\$ftype, \\$fid);" << endl; // Check for field STOP marker and break - indent(out) << "if ($ftype == TType::STOP) {" << endl; + indent(out) << "if ($ftype == Thrift::TType::STOP) {" << endl; indent_up(); indent(out) << "last;" << endl; indent_down(); @@ -590,7 +601,7 @@ void t_perl_generator::generate_perl_struct_reader(ofstream& out, t_struct* tstr /** * Generates the write() method for a struct */ -void t_perl_generator::generate_perl_struct_writer(ofstream& out, t_struct* tstruct) { +void t_perl_generator::generate_perl_struct_writer(ostream& out, t_struct* tstruct) { string name = tstruct->get_name(); const vector& fields = tstruct->get_sorted_members(); vector::const_iterator f_iter; @@ -629,6 +640,31 @@ void t_perl_generator::generate_perl_struct_writer(ofstream& out, t_struct* tstr out << indent() << "}" << endl << endl; } +/** + * Generates use clauses for included entities + * + * @param os The output stream + * @param done A flag reference to debounce the action + * @param type The type being processed + * @param selfish Flag to indicate if the current namespace types should be "use"d as well. + */ +void t_perl_generator::generate_use_includes(std::ostream& os, bool& done, t_type *type, bool selfish) { + t_program *current = type->get_program(); + if (current && !done) { + std::vector& currInc = current->get_includes(); + std::vector::size_type numInc = currInc.size(); + if (selfish) { + os << "use " << perl_namespace(current) << "Types;" << endl; + } + for (std::vector::size_type i = 0; i < numInc; ++i) { + t_program* incProgram = currInc.at(i); + os << "use " << perl_namespace(incProgram) << "Types;" << endl; + } + os << endl; + done = true; + } +} + /** * Generates a thrift service. * @@ -638,11 +674,10 @@ void t_perl_generator::generate_service(t_service* tservice) { string f_service_name = get_namespace_out_dir() + service_name_ + ".pm"; f_service_.open(f_service_name.c_str()); - f_service_ << - /// "package "<get_program()) << "Types;" << endl; + bool done = false; + generate_use_includes(f_service_, done, tservice, true); t_service* extends_s = tservice->get_extends(); if (extends_s != NULL) { @@ -721,11 +756,11 @@ void t_perl_generator::generate_service_processor(t_service* tservice) { << "if (!$self->can($methodname)) {" << endl; indent_up(); - f_service_ << indent() << "$input->skip(TType::STRUCT);" << endl << indent() + f_service_ << indent() << "$input->skip(Thrift::TType::STRUCT);" << endl << indent() << "$input->readMessageEnd();" << endl << indent() - << "my $x = new TApplicationException('Function '.$fname.' not implemented.', " - "TApplicationException::UNKNOWN_METHOD);" << endl << indent() - << "$output->writeMessageBegin($fname, TMessageType::EXCEPTION, $rseqid);" << endl + << "my $x = Thrift::TApplicationException->new('Function '.$fname.' not implemented.', " + "Thrift::TApplicationException::UNKNOWN_METHOD);" << endl << indent() + << "$output->writeMessageBegin($fname, Thrift::TMessageType::EXCEPTION, $rseqid);" << endl << indent() << "$x->write($output);" << endl << indent() << "$output->writeMessageEnd();" << endl << indent() << "$output->getTransport()->flush();" << endl << indent() << "return;" << endl; @@ -763,7 +798,7 @@ void t_perl_generator::generate_process_function(t_service* tservice, t_function string resultname = perl_namespace(tservice->get_program()) + service_name_ + "_" + tfunction->get_name() + "_result"; - f_service_ << indent() << "my $args = new " << argsname << "();" << endl << indent() + f_service_ << indent() << "my $args = " << argsname << "->new();" << endl << indent() << "$args->read($input);" << endl; f_service_ << indent() << "$input->readMessageEnd();" << endl; @@ -774,7 +809,7 @@ void t_perl_generator::generate_process_function(t_service* tservice, t_function // Declare result for non oneway function if (!tfunction->is_oneway()) { - f_service_ << indent() << "my $result = new " << resultname << "();" << endl; + f_service_ << indent() << "my $result = " << resultname << "->new();" << endl; } // Try block for a function with exceptions @@ -823,8 +858,8 @@ void t_perl_generator::generate_process_function(t_service* tservice, t_function f_service_ << indent() << "if ($@) {" << endl; indent_up(); f_service_ << indent() << "$@ =~ s/^\\s+|\\s+$//g;" << endl - << indent() << "my $err = new TApplicationException(\"Unexpected Exception: \" . $@, TApplicationException::INTERNAL_ERROR);" << endl - << indent() << "$output->writeMessageBegin('" << tfunction->get_name() << "', TMessageType::EXCEPTION, $seqid);" << endl + << indent() << "my $err = Thrift::TApplicationException->new(\"Unexpected Exception: \" . $@, Thrift::TApplicationException::INTERNAL_ERROR);" << endl + << indent() << "$output->writeMessageBegin('" << tfunction->get_name() << "', Thrift::TMessageType::EXCEPTION, $seqid);" << endl << indent() << "$err->write($output);" << endl << indent() << "$output->writeMessageEnd();" << endl << indent() << "$output->getTransport()->flush();" << endl @@ -843,7 +878,7 @@ void t_perl_generator::generate_process_function(t_service* tservice, t_function } // Serialize the reply - f_service_ << indent() << "$output->writeMessageBegin('" << tfunction->get_name() << "', TMessageType::REPLY, $seqid);" << endl + f_service_ << indent() << "$output->writeMessageBegin('" << tfunction->get_name() << "', Thrift::TMessageType::REPLY, $seqid);" << endl << indent() << "$result->write($output);" << endl << indent() << "$output->writeMessageEnd();" << endl << indent() << "$output->getTransport()->flush();" << endl; @@ -1068,10 +1103,10 @@ void t_perl_generator::generate_service_client(t_service* tservice) { // Serialize the request header f_service_ << indent() << "$self->{output}->writeMessageBegin('" << (*f_iter)->get_name() - << "', " << ((*f_iter)->is_oneway() ? "TMessageType::ONEWAY" : "TMessageType::CALL") + << "', " << ((*f_iter)->is_oneway() ? "Thrift::TMessageType::ONEWAY" : "Thrift::TMessageType::CALL") << ", $self->{seqid});" << endl; - f_service_ << indent() << "my $args = new " << argsname << "();" << endl; + f_service_ << indent() << "my $args = " << argsname << "->new();" << endl; for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) { f_service_ << indent() << "$args->{" << (*fld_iter)->get_name() << "} = $" @@ -1104,13 +1139,13 @@ void t_perl_generator::generate_service_client(t_service* tservice) { << indent() << "my $mtype = 0;" << endl << endl; f_service_ << indent() << "$self->{input}->readMessageBegin(\\$fname, \\$mtype, \\$rseqid);" - << endl << indent() << "if ($mtype == TMessageType::EXCEPTION) {" << endl - << indent() << " my $x = new TApplicationException();" << endl << indent() + << endl << indent() << "if ($mtype == Thrift::TMessageType::EXCEPTION) {" << endl + << indent() << " my $x = Thrift::TApplicationException->new();" << endl << indent() << " $x->read($self->{input});" << endl << indent() << " $self->{input}->readMessageEnd();" << endl << indent() << " die $x;" << endl << indent() << "}" << endl; - f_service_ << indent() << "my $result = new " << resultname << "();" << endl << indent() + f_service_ << indent() << "my $result = " << resultname << "->new();" << endl << indent() << "$result->read($self->{input});" << endl; f_service_ << indent() << "$self->{input}->readMessageEnd();" << endl << endl; @@ -1148,7 +1183,7 @@ void t_perl_generator::generate_service_client(t_service* tservice) { /** * Deserializes a field of any type. */ -void t_perl_generator::generate_deserialize_field(ofstream& out, +void t_perl_generator::generate_deserialize_field(ostream& out, t_field* tfield, string prefix, bool inclass) { @@ -1221,15 +1256,15 @@ void t_perl_generator::generate_deserialize_field(ofstream& out, * buffer for deserialization, and that there is a variable protocol which * is a reference to a TProtocol serialization object. */ -void t_perl_generator::generate_deserialize_struct(ofstream& out, +void t_perl_generator::generate_deserialize_struct(ostream& out, t_struct* tstruct, string prefix) { - out << indent() << "$" << prefix << " = new " << perl_namespace(tstruct->get_program()) - << tstruct->get_name() << "();" << endl << indent() << "$xfer += $" << prefix + out << indent() << "$" << prefix << " = " << perl_namespace(tstruct->get_program()) + << tstruct->get_name() << "->new();" << endl << indent() << "$xfer += $" << prefix << "->read($input);" << endl; } -void t_perl_generator::generate_deserialize_container(ofstream& out, t_type* ttype, string prefix) { +void t_perl_generator::generate_deserialize_container(ostream& out, t_type* ttype, string prefix) { scope_up(out); string size = tmp("_size"); @@ -1297,7 +1332,7 @@ void t_perl_generator::generate_deserialize_container(ofstream& out, t_type* tty /** * Generates code to deserialize a map */ -void t_perl_generator::generate_deserialize_map_element(ofstream& out, t_map* tmap, string prefix) { +void t_perl_generator::generate_deserialize_map_element(ostream& out, t_map* tmap, string prefix) { string key = tmp("key"); string val = tmp("val"); t_field fkey(tmap->get_key_type(), key); @@ -1312,7 +1347,7 @@ void t_perl_generator::generate_deserialize_map_element(ofstream& out, t_map* tm indent(out) << "$" << prefix << "->{$" << key << "} = $" << val << ";" << endl; } -void t_perl_generator::generate_deserialize_set_element(ofstream& out, t_set* tset, string prefix) { +void t_perl_generator::generate_deserialize_set_element(ostream& out, t_set* tset, string prefix) { string elem = tmp("elem"); t_field felem(tset->get_elem_type(), elem); @@ -1323,7 +1358,7 @@ void t_perl_generator::generate_deserialize_set_element(ofstream& out, t_set* ts indent(out) << "$" << prefix << "->{$" << elem << "} = 1;" << endl; } -void t_perl_generator::generate_deserialize_list_element(ofstream& out, +void t_perl_generator::generate_deserialize_list_element(ostream& out, t_list* tlist, string prefix) { string elem = tmp("elem"); @@ -1342,7 +1377,7 @@ void t_perl_generator::generate_deserialize_list_element(ofstream& out, * @param tfield The field to serialize * @param prefix Name to prepend to field name */ -void t_perl_generator::generate_serialize_field(ofstream& out, t_field* tfield, string prefix) { +void t_perl_generator::generate_serialize_field(ostream& out, t_field* tfield, string prefix) { t_type* type = get_true_type(tfield->get_type()); // Do nothing for void types @@ -1413,7 +1448,7 @@ void t_perl_generator::generate_serialize_field(ofstream& out, t_field* tfield, * @param tstruct The struct to serialize * @param prefix String prefix to attach to all fields */ -void t_perl_generator::generate_serialize_struct(ofstream& out, t_struct* tstruct, string prefix) { +void t_perl_generator::generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix) { (void)tstruct; indent(out) << "$xfer += $" << prefix << "->write($output);" << endl; } @@ -1421,7 +1456,7 @@ void t_perl_generator::generate_serialize_struct(ofstream& out, t_struct* tstruc /** * Writes out a container */ -void t_perl_generator::generate_serialize_container(ofstream& out, t_type* ttype, string prefix) { +void t_perl_generator::generate_serialize_container(ostream& out, t_type* ttype, string prefix) { scope_up(out); if (ttype->is_map()) { @@ -1485,7 +1520,7 @@ void t_perl_generator::generate_serialize_container(ofstream& out, t_type* ttype * Serializes the members of a map. * */ -void t_perl_generator::generate_serialize_map_element(ofstream& out, +void t_perl_generator::generate_serialize_map_element(ostream& out, t_map* tmap, string kiter, string viter) { @@ -1499,7 +1534,7 @@ void t_perl_generator::generate_serialize_map_element(ofstream& out, /** * Serializes the members of a set. */ -void t_perl_generator::generate_serialize_set_element(ofstream& out, t_set* tset, string iter) { +void t_perl_generator::generate_serialize_set_element(ostream& out, t_set* tset, string iter) { t_field efield(tset->get_elem_type(), iter); generate_serialize_field(out, &efield); } @@ -1507,7 +1542,7 @@ void t_perl_generator::generate_serialize_set_element(ofstream& out, t_set* tset /** * Serializes the members of a list. */ -void t_perl_generator::generate_serialize_list_element(ofstream& out, t_list* tlist, string iter) { +void t_perl_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string iter) { t_field efield(tlist->get_elem_type(), iter); generate_serialize_field(out, &efield); } @@ -1551,7 +1586,7 @@ string t_perl_generator::declare_field(t_field* tfield, bool init, bool obj) { result += " = []"; } else if (type->is_struct() || type->is_xception()) { if (obj) { - result += " = new " + perl_namespace(type->get_program()) + type->get_name() + "()"; + result += " = " + perl_namespace(type->get_program()) + type->get_name() + "->new()"; } else { result += " = undef"; } @@ -1616,30 +1651,30 @@ string t_perl_generator::type_to_enum(t_type* type) { case t_base_type::TYPE_VOID: throw "NO T_VOID CONSTRUCT"; case t_base_type::TYPE_STRING: - return "TType::STRING"; + return "Thrift::TType::STRING"; case t_base_type::TYPE_BOOL: - return "TType::BOOL"; + return "Thrift::TType::BOOL"; case t_base_type::TYPE_I8: - return "TType::BYTE"; + return "Thrift::TType::BYTE"; case t_base_type::TYPE_I16: - return "TType::I16"; + return "Thrift::TType::I16"; case t_base_type::TYPE_I32: - return "TType::I32"; + return "Thrift::TType::I32"; case t_base_type::TYPE_I64: - return "TType::I64"; + return "Thrift::TType::I64"; case t_base_type::TYPE_DOUBLE: - return "TType::DOUBLE"; + return "Thrift::TType::DOUBLE"; } } else if (type->is_enum()) { - return "TType::I32"; + return "Thrift::TType::I32"; } else if (type->is_struct() || type->is_xception()) { - return "TType::STRUCT"; + return "Thrift::TType::STRUCT"; } else if (type->is_map()) { - return "TType::MAP"; + return "Thrift::TType::MAP"; } else if (type->is_set()) { - return "TType::SET"; + return "Thrift::TType::SET"; } else if (type->is_list()) { - return "TType::LIST"; + return "Thrift::TType::LIST"; } throw "INVALID TYPE IN type_to_enum: " + type->get_name(); diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_php_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_php_generator.cc index 515e165..50a4415 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_php_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_php_generator.cc @@ -29,7 +29,7 @@ #include "thrift/generate/t_oop_generator.h" using std::map; -using std::ofstream; +using std::ostream; using std::ostringstream; using std::string; using std::stringstream; @@ -62,7 +62,7 @@ public: validate_ = false; json_serializable_ = false; nsglobal_ = ""; // by default global namespace is empty - psr4_ = false; + classmap_ = false; for (iter = parsed_options.begin(); iter != parsed_options.end(); ++iter) { if (iter->first.compare("inlined") == 0) { binary_inline_ = true; @@ -78,8 +78,14 @@ public: json_serializable_ = true; } else if (iter->first.compare("nsglobal") == 0) { nsglobal_ = iter->second; + } else if (iter->first.compare("classmap") == 0) { + classmap_ = true; } else if (iter->first.compare("psr4") == 0) { - psr4_ = true; + if(classmap_){ + throw "psr4 and classmap are mutually exclusive."; + } else { + pwarning(0, "psr4 is default option! needn't add psr4 option!\n"); + } } else { throw "unknown option php:" + iter->first; } @@ -93,6 +99,10 @@ public: escape_['$'] = "\\$"; } + virtual std::string indent_str() const { + return " "; + } + static bool is_valid_namespace(const std::string& sub_namespace); /** @@ -120,26 +130,26 @@ public: */ void generate_php_struct(t_struct* tstruct, bool is_exception); - void generate_php_struct_definition(std::ofstream& out, + void generate_php_struct_definition(std::ostream& out, t_struct* tstruct, bool is_xception = false, bool is_result = false); - void generate_php_struct_reader(std::ofstream& out, t_struct* tstruct, bool is_result); - void generate_php_struct_writer(std::ofstream& out, t_struct* tstruct, bool is_result); + void generate_php_struct_reader(std::ostream& out, t_struct* tstruct, bool is_result); + void generate_php_struct_writer(std::ostream& out, t_struct* tstruct, bool is_result); void generate_php_function_helpers(t_service* tservice, t_function* tfunction); - void generate_php_struct_required_validator(ofstream& out, + void generate_php_struct_required_validator(ostream& out, t_struct* tstruct, std::string method_name, bool write_mode); - void generate_php_struct_read_validator(ofstream& out, t_struct* tstruct); - void generate_php_struct_write_validator(ofstream& out, t_struct* tstruct); - void generate_php_struct_json_serialize(ofstream& out, t_struct* tstruct, bool is_result); + void generate_php_struct_read_validator(ostream& out, t_struct* tstruct); + void generate_php_struct_write_validator(ostream& out, t_struct* tstruct); + void generate_php_struct_json_serialize(ostream& out, t_struct* tstruct, bool is_result); bool needs_php_write_validator(t_struct* tstruct, bool is_result); bool needs_php_read_validator(t_struct* tstruct, bool is_result); int get_php_num_required_fields(const vector& fields, bool write_mode); - void generate_php_type_spec(std::ofstream& out, t_type* t); - void generate_php_struct_spec(std::ofstream& out, t_struct* tstruct); + void generate_php_type_spec(std::ostream& out, t_type* t); + void generate_php_struct_spec(std::ostream& out, t_struct* tstruct); /** * Service-level generation functions @@ -150,53 +160,53 @@ public: void generate_service_rest(t_service* tservice); void generate_service_client(t_service* tservice); void generate_service_processor(t_service* tservice); - void generate_process_function(std::ofstream& out, t_service* tservice, t_function* tfunction); - void generate_service_header(t_service* tservice, std::ofstream& file); - void generate_program_header(std::ofstream& file); + void generate_process_function(std::ostream& out, t_service* tservice, t_function* tfunction); + void generate_service_header(t_service* tservice, std::ostream& file); + void generate_program_header(std::ostream& file); /** * Serialization constructs */ - void generate_deserialize_field(std::ofstream& out, + void generate_deserialize_field(std::ostream& out, t_field* tfield, std::string prefix = "", bool inclass = false); - void generate_deserialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); + void generate_deserialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); - void generate_deserialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); + void generate_deserialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); - void generate_deserialize_set_element(std::ofstream& out, t_set* tset, std::string prefix = ""); + void generate_deserialize_set_element(std::ostream& out, t_set* tset, std::string prefix = ""); - void generate_deserialize_map_element(std::ofstream& out, t_map* tmap, std::string prefix = ""); + void generate_deserialize_map_element(std::ostream& out, t_map* tmap, std::string prefix = ""); - void generate_deserialize_list_element(std::ofstream& out, + void generate_deserialize_list_element(std::ostream& out, t_list* tlist, std::string prefix = ""); - void generate_serialize_field(std::ofstream& out, t_field* tfield, std::string prefix = ""); + void generate_serialize_field(std::ostream& out, t_field* tfield, std::string prefix = ""); - void generate_serialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); + void generate_serialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); - void generate_serialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); + void generate_serialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); - void generate_serialize_map_element(std::ofstream& out, + void generate_serialize_map_element(std::ostream& out, t_map* tmap, std::string kiter, std::string viter); - void generate_serialize_set_element(std::ofstream& out, t_set* tmap, std::string iter); + void generate_serialize_set_element(std::ostream& out, t_set* tmap, std::string iter); - void generate_serialize_list_element(std::ofstream& out, t_list* tlist, std::string iter); + void generate_serialize_list_element(std::ostream& out, t_list* tlist, std::string iter); - void generate_php_doc(std::ofstream& out, t_doc* tdoc); + void generate_php_doc(std::ostream& out, t_doc* tdoc); - void generate_php_doc(std::ofstream& out, t_field* tfield); + void generate_php_doc(std::ostream& out, t_field* tfield); - void generate_php_doc(std::ofstream& out, t_function* tfunction); + void generate_php_doc(std::ostream& out, t_function* tfunction); - void generate_php_docstring_comment(std::ofstream& out, string contents); + void generate_php_docstring_comment(std::ostream& out, string contents); /** * Helper rendering functions @@ -210,6 +220,17 @@ public: std::string type_to_enum(t_type* ttype); std::string type_to_phpdoc(t_type* ttype); + bool php_is_scalar(t_type *ttype) { + ttype = ttype->get_true_type(); + if(ttype->is_base_type()) { + return true; + } else if(ttype->is_enum()) { + return true; + } else { + return false; + } + } + std::string php_namespace_base(const t_program* p) { std::string ns = p->get_namespace("php"); const char* delimiter = "\\"; @@ -336,8 +357,8 @@ private: /** * File streams */ - std::ofstream f_types_; - std::ofstream f_service_; + ofstream_with_content_based_conditional_update f_types_; + ofstream_with_content_based_conditional_update f_service_; std::string package_dir_; /** @@ -361,9 +382,9 @@ private: bool oop_; /** - * Whether to hold each class in separate file to allow PSR4-autoloading + * Whether to generate old-style PHP file to use classmap autoloading */ - bool psr4_; + bool classmap_; /** * Whether to generate validator code @@ -404,8 +425,8 @@ void t_php_generator::init_generator() { MKDIR(package_dir_.c_str()); } - // Prepare output file for all the types in non-psr4 mode - if (!psr4_) { + // Prepare output file for all the types in classmap mode + if (classmap_) { // Make output file string f_types_name = package_dir_ + "Types.php"; f_types_.open(f_types_name.c_str()); @@ -431,16 +452,15 @@ string t_php_generator::php_includes() { "use stdClass;\n"; } - return includes + "\n"; + return includes; } /** * Close up (or down) some filez. */ void t_php_generator::close_generator() { - if (!psr4_) { + if (classmap_) { // Close types file - f_types_ << endl; f_types_.close(); } } @@ -457,10 +477,11 @@ void t_php_generator::generate_typedef(t_typedef* ttypedef) { /** * Generates service header contains namespace suffix and includes inside file specified */ -void t_php_generator::generate_service_header(t_service* tservice, std::ofstream& file) { +void t_php_generator::generate_service_header(t_service* tservice, std::ostream& file) { file << "get_program()).empty()) { - file << "namespace " << php_namespace_suffix(tservice->get_program()) << ";" << endl; + file << "namespace " << php_namespace_suffix(tservice->get_program()) << ";" << endl + << endl; } file << autogen_comment() << php_includes(); @@ -470,10 +491,11 @@ void t_php_generator::generate_service_header(t_service* tservice, std::ofstream /** * Generates program header contains namespace suffix and includes inside file specified */ -void t_php_generator::generate_program_header(std::ofstream& file) { +void t_php_generator::generate_program_header(std::ostream& file) { file << "get_name() + ".php"; f_enum.open(f_enum_name.c_str()); generate_program_header(f_enum); @@ -501,26 +523,31 @@ void t_php_generator::generate_enum(t_enum* tenum) { // code but you can't do things like an 'extract' on it, which is a bit of // a downer. generate_php_doc(f_enum, tenum); - f_enum << "final class " << tenum->get_name() << " {" << endl; + f_enum << "final class " << tenum->get_name() << endl + << "{" << endl; indent_up(); for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) { int value = (*c_iter)->get_value(); generate_php_doc(f_enum, *c_iter); - indent(f_enum) << "const " << (*c_iter)->get_name() << " = " << value << ";" << endl; + indent(f_enum) << "const " << (*c_iter)->get_name() << " = " << value << ";" << endl + << endl; } indent(f_enum) << "static public $__names = array(" << endl; + + indent_up(); for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) { int value = (*c_iter)->get_value(); - indent(f_enum) << " " << value << " => '" << (*c_iter)->get_name() << "'," << endl; + indent(f_enum) << value << " => '" << (*c_iter)->get_name() << "'," << endl; } + indent_down(); indent(f_enum) << ");" << endl; indent_down(); f_enum << "}" << endl << endl; - if (psr4_) { + if (!classmap_) { f_enum.close(); } } @@ -536,13 +563,14 @@ void t_php_generator::generate_consts(vector consts) { // Create class only if needed if (consts.size() > 0) { - std::ofstream& f_consts = f_types_; - if (psr4_) { + ofstream_with_content_based_conditional_update& f_consts = f_types_; + if (!classmap_) { string f_consts_name = package_dir_ + "Constant.php"; f_consts.open(f_consts_name.c_str()); generate_program_header(f_consts); } - f_consts << "final class Constant extends \\Thrift\\Type\\TConstant {" << endl; + f_consts << "final class Constant extends \\Thrift\\Type\\TConstant"<< endl + << "{" << endl; indent_up(); @@ -559,7 +587,8 @@ void t_php_generator::generate_consts(vector consts) { f_consts << endl; - indent(f_consts) << "static protected function init_" << name << "() {" << endl; + f_consts << indent() << "protected static function init_" << name << "()" < consts) { } indent_down(); - f_consts << "}" << endl << endl; - if (psr4_) { + f_consts << "}" << endl; + if (!classmap_) { f_consts.close(); } } @@ -619,8 +648,8 @@ string t_php_generator::render_const_value(t_type* type, t_const_value* value) { indent_up(); const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { t_type* field_type = NULL; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { @@ -644,8 +673,8 @@ string t_php_generator::render_const_value(t_type* type, t_const_value* value) { t_type* vtype = ((t_map*)type)->get_val_type(); out << "array(" << endl; indent_up(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { out << indent(); out << render_const_value(ktype, v_iter->first); @@ -701,19 +730,19 @@ void t_php_generator::generate_xception(t_struct* txception) { * Structs can be normal or exceptions. */ void t_php_generator::generate_php_struct(t_struct* tstruct, bool is_exception) { - std::ofstream& f_struct = f_types_; - if (psr4_) { + ofstream_with_content_based_conditional_update& f_struct = f_types_; + if (!classmap_) { string f_struct_name = package_dir_ + tstruct->get_name() + ".php"; f_struct.open(f_struct_name.c_str()); generate_program_header(f_struct); } generate_php_struct_definition(f_struct, tstruct, is_exception); - if (psr4_) { + if (!classmap_) { f_struct.close(); } } -void t_php_generator::generate_php_type_spec(ofstream& out, t_type* t) { +void t_php_generator::generate_php_type_spec(ostream& out, t_type* t) { t = get_true_type(t); indent(out) << "'type' => " << type_to_enum(t) << "," << endl; @@ -759,11 +788,8 @@ void t_php_generator::generate_php_type_spec(ofstream& out, t_type* t) { * Generates the struct specification structure, which fully qualifies enough * type information to generalize serialization routines. */ -void t_php_generator::generate_php_struct_spec(ofstream& out, t_struct* tstruct) { - indent(out) << "if (!isset(self::$_TSPEC)) {" << endl; - indent_up(); - - indent(out) << "self::$_TSPEC = array(" << endl; +void t_php_generator::generate_php_struct_spec(ostream& out, t_struct* tstruct) { + indent(out) << "static public $_TSPEC = array(" << endl; indent_up(); const vector& members = tstruct->get_members(); @@ -773,15 +799,14 @@ void t_php_generator::generate_php_struct_spec(ofstream& out, t_struct* tstruct) indent(out) << (*m_iter)->get_key() << " => array(" << endl; indent_up(); out << indent() << "'var' => '" << (*m_iter)->get_name() << "'," << endl; + out << indent() << "'isRequired' => " << ((*m_iter)->get_req() == t_field::T_REQUIRED ? "true" : "false") << "," << endl; generate_php_type_spec(out, t); - indent(out) << ")," << endl; indent_down(); + indent(out) << ")," << endl; } indent_down(); - indent(out) << " );" << endl; - indent_down(); - indent(out) << "}" << endl; + indent(out) << ");" << endl << endl; } /** @@ -791,7 +816,7 @@ void t_php_generator::generate_php_struct_spec(ofstream& out, t_struct* tstruct) * * @param tstruct The struct definition */ -void t_php_generator::generate_php_struct_definition(ofstream& out, +void t_php_generator::generate_php_struct_definition(ostream& out, t_struct* tstruct, bool is_exception, bool is_result) { @@ -810,10 +835,13 @@ void t_php_generator::generate_php_struct_definition(ofstream& out, if (json_serializable_) { out << " implements JsonSerializable"; } - out << " {" << endl; + out << endl + << "{" << endl; indent_up(); - indent(out) << "static $_TSPEC;" << endl << endl; + out << indent() << "static public $isValidate = " << (validate_ ? "true" : "false") << ";" << endl << endl; + + generate_php_struct_spec(out, tstruct); for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { string dval = "null"; @@ -828,12 +856,11 @@ void t_php_generator::generate_php_struct_definition(ofstream& out, out << endl; // Generate constructor from array - string param = (members.size() > 0) ? "$vals=null" : ""; - out << indent() << "public function __construct(" << param << ") {" << endl; + string param = (members.size() > 0) ? "$vals = null" : ""; + out << indent() << "public function __construct(" << param << ")"<< endl + << indent() << "{" << endl; indent_up(); - generate_php_struct_spec(out, tstruct); - if (members.size() > 0) { for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { t_type* t = get_true_type((*m_iter)->get_type()); @@ -848,9 +875,14 @@ void t_php_generator::generate_php_struct_definition(ofstream& out, out << indent() << "parent::__construct(self::$_TSPEC, $vals);" << endl; } else { for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { - out << indent() << "if (isset($vals['" << (*m_iter)->get_name() << "'])) {" << endl - << indent() << " $this->" << (*m_iter)->get_name() << " = $vals['" - << (*m_iter)->get_name() << "'];" << endl << indent() << "}" << endl; + out << indent() << "if (isset($vals['" << (*m_iter)->get_name() << "'])) {" << endl; + + indent_up(); + out << indent() << "$this->" << (*m_iter)->get_name() << " = $vals['" + << (*m_iter)->get_name() << "'];" << endl; + + indent_down(); + out << indent() << "}" << endl; } } indent_down(); @@ -859,29 +891,40 @@ void t_php_generator::generate_php_struct_definition(ofstream& out, scope_down(out); out << endl; - out << indent() << "public function getName() {" << endl << indent() << " return '" - << tstruct->get_name() << "';" << endl << indent() << "}" << endl << endl; + out << indent() << "public function getName()" << endl + << indent() << "{" << endl; + indent_up(); + out << indent() << "return '" << tstruct->get_name() << "';" << endl; + + indent_down(); + out << indent() << "}" << endl << endl; + + out << endl; generate_php_struct_reader(out, tstruct, is_result); + out << endl; generate_php_struct_writer(out, tstruct, is_result); if (needs_php_read_validator(tstruct, is_result)) { + out << endl; generate_php_struct_read_validator(out, tstruct); } if (needs_php_write_validator(tstruct, is_result)) { + out << endl; generate_php_struct_write_validator(out, tstruct); } if (json_serializable_) { + out << endl; generate_php_struct_json_serialize(out, tstruct, is_result); } indent_down(); - out << indent() << "}" << endl << endl; + out << indent() << "}" << endl; } /** * Generates the read() method for a struct */ -void t_php_generator::generate_php_struct_reader(ofstream& out, t_struct* tstruct, bool is_result) { +void t_php_generator::generate_php_struct_reader(ostream& out, t_struct* tstruct, bool is_result) { const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; @@ -912,9 +955,9 @@ void t_php_generator::generate_php_struct_reader(ofstream& out, t_struct* tstruc } // Loop over reading in fields - indent(out) << "while (true)" << endl; + indent(out) << "while (true) {" << endl; - scope_up(out); + indent_up(); // Read beginning field marker if (binary_inline_) { @@ -936,9 +979,9 @@ void t_php_generator::generate_php_struct_reader(ofstream& out, t_struct* tstruc } // Switch statement on the field we are reading - indent(out) << "switch ($fid)" << endl; + indent(out) << "switch ($fid) {" << endl; - scope_up(out); + indent_up(); // Generate deserialization code for known cases for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { @@ -949,25 +992,31 @@ void t_php_generator::generate_php_struct_reader(ofstream& out, t_struct* tstruc generate_deserialize_field(out, *f_iter, "this->"); indent_down(); out << indent() << "} else {" << endl; + + indent_up(); if (binary_inline_) { - indent(out) << " $xfer += " - << "TProtocol::skipBinary($input, $ftype);" << endl; + indent(out) << "$xfer += TProtocol::skipBinary($input, $ftype);" << endl; } else { - indent(out) << " $xfer += $input->skip($ftype);" << endl; + indent(out) << "$xfer += $input->skip($ftype);" << endl; } + + indent_down(); out << indent() << "}" << endl << indent() << "break;" << endl; indent_down(); } // In the default case we skip the field indent(out) << "default:" << endl; + + indent_up(); if (binary_inline_) { - indent(out) << " $xfer += " + indent(out) << "$xfer += " << "TProtocol::skipBinary($input, $ftype);" << endl; } else { - indent(out) << " $xfer += $input->skip($ftype);" << endl; + indent(out) << "$xfer += $input->skip($ftype);" << endl; } - indent(out) << " break;" << endl; + indent(out) << "break;" << endl; + indent_down(); scope_down(out); @@ -989,22 +1038,23 @@ void t_php_generator::generate_php_struct_reader(ofstream& out, t_struct* tstruc indent(out) << "return $xfer;" << endl; indent_down(); - out << indent() << "}" << endl << endl; + out << indent() << "}" << endl; } /** * Generates the write() method for a struct */ -void t_php_generator::generate_php_struct_writer(ofstream& out, t_struct* tstruct, bool is_result) { +void t_php_generator::generate_php_struct_writer(ostream& out, t_struct* tstruct, bool is_result) { string name = tstruct->get_name(); const vector& fields = tstruct->get_sorted_members(); vector::const_iterator f_iter; if (binary_inline_) { - indent(out) << "public function write(&$output) {" << endl; + indent(out) << "public function write(&$output)" << endl; } else { - indent(out) << "public function write($output) {" << endl; + indent(out) << "public function write($output)" << endl; } + indent(out) << "{" << endl; indent_up(); if (needs_php_write_validator(tstruct, is_result)) { @@ -1079,18 +1129,18 @@ void t_php_generator::generate_php_struct_writer(ofstream& out, t_struct* tstruc out << indent() << "return $xfer;" << endl; indent_down(); - out << indent() << "}" << endl << endl; + out << indent() << "}" << endl; } -void t_php_generator::generate_php_struct_read_validator(ofstream& out, t_struct* tstruct) { +void t_php_generator::generate_php_struct_read_validator(ostream& out, t_struct* tstruct) { generate_php_struct_required_validator(out, tstruct, "_validateForRead", false); } -void t_php_generator::generate_php_struct_write_validator(ofstream& out, t_struct* tstruct) { +void t_php_generator::generate_php_struct_write_validator(ostream& out, t_struct* tstruct) { generate_php_struct_required_validator(out, tstruct, "_validateForWrite", true); } -void t_php_generator::generate_php_struct_required_validator(ofstream& out, +void t_php_generator::generate_php_struct_required_validator(ostream& out, t_struct* tstruct, std::string method_name, bool write_mode) { @@ -1117,10 +1167,10 @@ void t_php_generator::generate_php_struct_required_validator(ofstream& out, } indent_down(); - indent(out) << "}" << endl << endl; + indent(out) << "}" << endl; } -void t_php_generator::generate_php_struct_json_serialize(ofstream& out, +void t_php_generator::generate_php_struct_json_serialize(ostream& out, t_struct* tstruct, bool is_result) { indent(out) << "public function jsonSerialize() {" << endl; @@ -1166,7 +1216,7 @@ void t_php_generator::generate_php_struct_json_serialize(ofstream& out, indent(out) << "return $json;" << endl; indent_down(); - indent(out) << "}" << endl << endl; + indent(out) << "}" << endl; } int t_php_generator::get_php_num_required_fields(const vector& fields, bool write_mode) { @@ -1200,7 +1250,7 @@ bool t_php_generator::needs_php_read_validator(t_struct* tstruct, bool is_result * @param tservice The service definition */ void t_php_generator::generate_service(t_service* tservice) { - if(!psr4_) { + if(classmap_) { string f_service_name = package_dir_ + service_name_ + ".php"; f_service_.open(f_service_name.c_str()); generate_service_header(tservice, f_service_); @@ -1217,7 +1267,7 @@ void t_php_generator::generate_service(t_service* tservice) { generate_service_processor(tservice); } - if(!psr4_) { + if(classmap_) { // Close service file f_service_ << endl; f_service_.close(); @@ -1230,8 +1280,8 @@ void t_php_generator::generate_service(t_service* tservice) { * @param tservice The service to generate a server for. */ void t_php_generator::generate_service_processor(t_service* tservice) { - std::ofstream& f_service_processor = f_service_; - if (psr4_) { + ofstream_with_content_based_conditional_update& f_service_processor = f_service_; + if (!classmap_) { string f_service_processor_name = package_dir_ + service_name_ + "Processor.php"; f_service_processor.open(f_service_processor_name.c_str()); generate_service_header(tservice, f_service_processor); @@ -1250,23 +1300,30 @@ void t_php_generator::generate_service_processor(t_service* tservice) { } // Generate the header portion - f_service_processor << "class " << service_name_ << "Processor" << extends_processor << " {" << endl; + f_service_processor << "class " << service_name_ << "Processor" << extends_processor << endl + << "{" << endl; indent_up(); if (extends.empty()) { f_service_processor << indent() << "protected $handler_ = null;" << endl; } - f_service_processor << indent() << "public function __construct($handler) {" << endl; + f_service_processor << indent() << "public function __construct($handler)"<< endl + << indent() << "{" << endl; + + indent_up(); if (extends.empty()) { - f_service_processor << indent() << " $this->handler_ = $handler;" << endl; + f_service_processor << indent() << "$this->handler_ = $handler;" << endl; } else { - f_service_processor << indent() << " parent::__construct($handler);" << endl; + f_service_processor << indent() << "parent::__construct($handler);" << endl; } + + indent_down(); f_service_processor << indent() << "}" << endl << endl; // Generate the server implementation - indent(f_service_processor) << "public function process($input, $output) {" << endl; + f_service_processor << indent() << "public function process($input, $output)" << endl + << indent() << "{" << endl; indent_up(); f_service_processor << indent() << "$rseqid = 0;" << endl << indent() << "$fname = null;" << endl @@ -1284,11 +1341,12 @@ void t_php_generator::generate_service_processor(t_service* tservice) { } // HOT: check for method implementation - f_service_processor << indent() << "$methodname = 'process_'.$fname;" << endl << indent() - << "if (!method_exists($this, $methodname)) {" << endl; + f_service_processor << indent() << "$methodname = 'process_'.$fname;" << endl + << indent() << "if (!method_exists($this, $methodname)) {" << endl; + + indent_up(); if (binary_inline_) { - f_service_processor << indent() << " throw new \\Exception('Function '.$fname.' not implemented.');" - << endl; + f_service_processor << indent() << "throw new \\Exception('Function '.$fname.' not implemented.');" << endl; } else { f_service_processor << indent() << " $input->skip(" << "TType::STRUCT);" << endl << indent() << " $input->readMessageEnd();" << endl @@ -1301,9 +1359,12 @@ void t_php_generator::generate_service_processor(t_service* tservice) { << endl << indent() << " $output->getTransport()->flush();" << endl << indent() << " return;" << endl; } - f_service_processor << indent() << "}" << endl << indent() - << "$this->$methodname($rseqid, $input, $output);" << endl << indent() - << "return true;" << endl; + + indent_down(); + f_service_processor << indent() << "}" << endl + << indent() << "$this->$methodname($rseqid, $input, $output);" << endl + << indent() << "return true;" << endl; + indent_down(); f_service_processor << indent() << "}" << endl << endl; @@ -1315,7 +1376,7 @@ void t_php_generator::generate_service_processor(t_service* tservice) { indent_down(); f_service_processor << "}" << endl; - if (psr4_) { + if (!classmap_) { f_service_processor.close(); } } @@ -1325,10 +1386,10 @@ void t_php_generator::generate_service_processor(t_service* tservice) { * * @param tfunction The function to write a dispatcher for */ -void t_php_generator::generate_process_function(std::ofstream& out, t_service* tservice, t_function* tfunction) { +void t_php_generator::generate_process_function(std::ostream& out, t_service* tservice, t_function* tfunction) { // Open function - indent(out) << "protected function process_" << tfunction->get_name() - << "($seqid, $input, $output) {" << endl; + out << indent() << "protected function process_" << tfunction->get_name() << "($seqid, $input, $output)" << endl + << indent() << "{" << endl; indent_up(); string argsname = php_namespace(tservice->get_program()) + service_name_ + "_" @@ -1336,8 +1397,32 @@ void t_php_generator::generate_process_function(std::ofstream& out, t_service* t string resultname = php_namespace(tservice->get_program()) + service_name_ + "_" + tfunction->get_name() + "_result"; - out << indent() << "$args = new " << argsname << "();" << endl << indent() - << "$args->read($input);" << endl; + out << indent() << "$bin_accel = ($input instanceof " + << "TBinaryProtocolAccelerated) && function_exists('thrift_protocol_read_binary_after_message_begin');" + << endl; + out << indent() << "if ($bin_accel) {" << endl; + indent_up(); + + out << indent() << "$args = thrift_protocol_read_binary_after_message_begin(" <isStrictRead()" <read($input);" << endl; + + indent_down(); + out << indent() << "}" << endl; + if (!binary_inline_) { out << indent() << "$input->readMessageEnd();" << endl; } @@ -1408,16 +1493,25 @@ void t_php_generator::generate_process_function(std::ofstream& out, t_service* t << "TBinaryProtocolAccelerated) && function_exists('thrift_protocol_write_binary');" << endl; - out << indent() << "if ($bin_accel)" << endl; - scope_up(out); + out << indent() << "if ($bin_accel) {" << endl; + indent_up(); - out << indent() << "thrift_protocol_write_binary($output, '" << tfunction->get_name() - << "', " - << "TMessageType::REPLY, $result, $seqid, $output->isStrictWrite());" << endl; + out << indent() << "thrift_protocol_write_binary(" << endl; - scope_down(out); - out << indent() << "else" << endl; - scope_up(out); + indent_up(); + out << indent() << "$output,"<get_name()<< "'," <isStrictWrite()"< functions = tservice->get_functions(); vector::iterator f_iter; - std::ofstream& f_struct_definition = f_service_; - if (!psr4_) { + ofstream_with_content_based_conditional_update& f_struct_definition = f_service_; + if (classmap_) { f_struct_definition << "// HELPER FUNCTIONS AND STRUCTURES" << endl << endl; } @@ -1460,14 +1554,14 @@ void t_php_generator::generate_service_helpers(t_service* tservice) { string name = ts->get_name(); ts->set_name(service_name_ + "_" + name); - if (psr4_) { + if (!classmap_) { string f_struct_definition_name = package_dir_ + service_name_ + "_" + name + ".php"; f_struct_definition.open(f_struct_definition_name.c_str()); generate_service_header(tservice, f_struct_definition); } generate_php_struct_definition(f_struct_definition, ts); - if (psr4_) { + if (!classmap_) { f_struct_definition.close(); } @@ -1496,14 +1590,14 @@ void t_php_generator::generate_php_function_helpers(t_service* tservice, t_funct result.append(*f_iter); } - std::ofstream& f_struct_helper = f_service_; - if (psr4_) { + ofstream_with_content_based_conditional_update& f_struct_helper = f_service_; + if (!classmap_) { string f_struct_helper_name = package_dir_ + result.get_name() + ".php"; f_struct_helper.open(f_struct_helper_name.c_str()); generate_service_header(tservice, f_struct_helper); } generate_php_struct_definition(f_struct_helper, &result, false, true); - if (psr4_) { + if (!classmap_) { f_struct_helper.close(); } } @@ -1515,8 +1609,8 @@ void t_php_generator::generate_php_function_helpers(t_service* tservice, t_funct * @param tservice The service to generate a header definition for */ void t_php_generator::generate_service_interface(t_service* tservice) { - std::ofstream& f_service_interface = f_service_; - if (psr4_) { + ofstream_with_content_based_conditional_update& f_service_interface = f_service_; + if (!classmap_) { string f_service_interface_name = package_dir_ + service_name_ + "If.php"; f_service_interface.open(f_service_interface_name.c_str()); generate_service_header(tservice, f_service_interface); @@ -1531,8 +1625,9 @@ void t_php_generator::generate_service_interface(t_service* tservice) { + tservice->get_extends()->get_name() + "If"; } generate_php_doc(f_service_interface, tservice); - f_service_interface << "interface " << php_namespace_declaration(tservice) << "If" << extends_if << " {" - << endl; + f_service_interface << "interface " << php_namespace_declaration(tservice) << "If" << extends_if << endl + << "{" << endl; + indent_up(); vector functions = tservice->get_functions(); vector::iterator f_iter; @@ -1541,11 +1636,10 @@ void t_php_generator::generate_service_interface(t_service* tservice) { indent(f_service_interface) << "public function " << function_signature(*f_iter) << ";" << endl; } indent_down(); - f_service_interface << "}" << endl << endl; + f_service_interface << "}" << endl; // Close service interface file - f_service_interface << endl; - if (psr4_) { + if (!classmap_) { f_service_interface.close(); } } @@ -1554,8 +1648,8 @@ void t_php_generator::generate_service_interface(t_service* tservice) { * Generates a REST interface */ void t_php_generator::generate_service_rest(t_service* tservice) { - std::ofstream& f_service_rest = f_service_; - if (psr4_) { + ofstream_with_content_based_conditional_update& f_service_rest = f_service_; + if (!classmap_) { string f_service_rest_name = package_dir_ + service_name_ + "Rest.php"; f_service_rest.open(f_service_rest_name.c_str()); generate_service_header(tservice, f_service_rest); @@ -1569,7 +1663,8 @@ void t_php_generator::generate_service_rest(t_service* tservice) { extends_if = " extends " + php_namespace(tservice->get_extends()->get_program()) + tservice->get_extends()->get_name() + "Rest"; } - f_service_rest << "class " << service_name_ << "Rest" << extends_if << " {" << endl; + f_service_rest << "class " << service_name_ << "Rest" << extends_if << endl + << "{" << endl; indent_up(); if (extends.empty()) { @@ -1623,7 +1718,7 @@ void t_php_generator::generate_service_rest(t_service* tservice) { // Close service rest file f_service_rest << endl; - if (psr4_) { + if (!classmap_) { f_service_rest.close(); } } @@ -1634,8 +1729,8 @@ void t_php_generator::generate_service_rest(t_service* tservice) { * @param tservice The service to generate a server for. */ void t_php_generator::generate_service_client(t_service* tservice) { - std::ofstream& f_service_client = f_service_; - if (psr4_) { + ofstream_with_content_based_conditional_update& f_service_client = f_service_; + if (!classmap_) { string f_service_client_name = package_dir_ + service_name_ + "Client.php"; f_service_client.open(f_service_client_name.c_str()); generate_service_header(tservice, f_service_client); @@ -1650,8 +1745,8 @@ void t_php_generator::generate_service_client(t_service* tservice) { } f_service_client << "class " << php_namespace_declaration(tservice) << "Client" << extends_client - << " implements " << php_namespace(tservice->get_program()) << service_name_ << "If {" - << endl; + << " implements " << php_namespace(tservice->get_program()) << service_name_ << "If" << endl + <<"{"<< endl; indent_up(); // Private members @@ -1662,13 +1757,18 @@ void t_php_generator::generate_service_client(t_service* tservice) { } // Constructor function - f_service_client << indent() << "public function __construct($input, $output=null) {" << endl; + f_service_client << indent() << "public function __construct($input, $output = null)" << endl + << indent() << "{" << endl; + + indent_up(); if (!extends.empty()) { - f_service_client << indent() << " parent::__construct($input, $output);" << endl; + f_service_client << indent() << "parent::__construct($input, $output);" << endl; } else { - f_service_client << indent() << " $this->input_ = $input;" << endl << indent() - << " $this->output_ = $output ? $output : $input;" << endl; + f_service_client << indent() << "$this->input_ = $input;" << endl + << indent() << "$this->output_ = $output ? $output : $input;" << endl; } + + indent_down(); f_service_client << indent() << "}" << endl << endl; // Generate client method implementations @@ -1680,6 +1780,8 @@ void t_php_generator::generate_service_client(t_service* tservice) { vector::const_iterator fld_iter; string funname = (*f_iter)->get_name(); + f_service_client << endl; + // Open function indent(f_service_client) << "public function " << function_signature(*f_iter) << endl; scope_up(f_service_client); @@ -1723,18 +1825,27 @@ void t_php_generator::generate_service_client(t_service* tservice) { << "TBinaryProtocolAccelerated) && function_exists('thrift_protocol_write_binary');" << endl; - f_service_client << indent() << "if ($bin_accel)" << endl; - scope_up(f_service_client); + f_service_client << indent() << "if ($bin_accel) {" << endl; + indent_up(); string messageType = (*f_iter)->is_oneway() ? "TMessageType::ONEWAY" : "TMessageType::CALL"; - f_service_client << indent() << "thrift_protocol_write_binary($this->output_, '" - << (*f_iter)->get_name() << "', " << messageType - << ", $args, $this->seqid_, $this->output_->isStrictWrite());" << endl; + f_service_client << indent() << "thrift_protocol_write_binary(" << endl; - scope_down(f_service_client); - f_service_client << indent() << "else" << endl; - scope_up(f_service_client); + indent_up(); + f_service_client << indent() << "$this->output_," << endl + << indent() << "'" << (*f_iter)->get_name() << "'," << endl + << indent() << messageType << "," << endl + << indent() << "$args," << endl + << indent() << "$this->seqid_," << endl + << indent() << "$this->output_->isStrictWrite()" << endl; + + indent_down(); + f_service_client << indent() << ");" << endl; + + indent_down(); + f_service_client << indent() << "} else {" << endl; + indent_up(); // Serialize the request header if (binary_inline_) { @@ -1779,14 +1890,26 @@ void t_php_generator::generate_service_client(t_service* tservice) { << "TBinaryProtocolAccelerated)" << " && function_exists('thrift_protocol_read_binary');" << endl; - f_service_client << indent() - << "if ($bin_accel) $result = thrift_protocol_read_binary($this->input_, '" - << resultname << "', $this->input_->isStrictRead());" << endl; - f_service_client << indent() << "else" << endl; - scope_up(f_service_client); + f_service_client << indent() << "if ($bin_accel) {" << endl; - f_service_client << indent() << "$rseqid = 0;" << endl << indent() << "$fname = null;" << endl - << indent() << "$mtype = 0;" << endl << endl; + indent_up(); + f_service_client << indent() << "$result = thrift_protocol_read_binary(" << endl; + + indent_up(); + f_service_client << indent() << "$this->input_," << endl + << indent() << "'" << resultname << "'," << endl + << indent() << "$this->input_->isStrictRead()" << endl; + + indent_down(); + f_service_client << indent() << ");" << endl; + + indent_down(); + f_service_client << indent() << "} else {" << endl; + + indent_up(); + f_service_client << indent() << "$rseqid = 0;" << endl + << indent() << "$fname = null;" << endl + << indent() << "$mtype = 0;" << endl << endl; if (binary_inline_) { t_field ffname(g_type_string, "fname"); @@ -1800,16 +1923,20 @@ void t_php_generator::generate_service_client(t_service* tservice) { generate_deserialize_field(f_service_client, &ffname, "", true); generate_deserialize_field(f_service_client, &fseqid, "", true); } else { - f_service_client << indent() << "$this->input_->readMessageBegin($fname, $mtype, $rseqid);" - << endl << indent() << "if ($mtype == " - << "TMessageType::EXCEPTION) {" << endl << indent() << " $x = new " - << "TApplicationException();" << endl << indent() << " $x->read($this->input_);" - << endl << indent() << " $this->input_->readMessageEnd();" << endl << indent() - << " throw $x;" << endl << indent() << "}" << endl; + f_service_client << indent() << "$this->input_->readMessageBegin($fname, $mtype, $rseqid);" << endl + << indent() << "if ($mtype == TMessageType::EXCEPTION) {" << endl; + + indent_up(); + f_service_client << indent() << "$x = new TApplicationException();" << endl + << indent() << "$x->read($this->input_);" << endl + << indent() << "$this->input_->readMessageEnd();" << endl + << indent() << "throw $x;" << endl; + indent_down(); + f_service_client << indent() << "}" << endl; } - f_service_client << indent() << "$result = new " << resultname << "();" << endl << indent() - << "$result->read($this->input_);" << endl; + f_service_client << indent() << "$result = new " << resultname << "();" << endl + << indent() << "$result->read($this->input_);" << endl; if (!binary_inline_) { f_service_client << indent() << "$this->input_->readMessageEnd();" << endl; @@ -1819,17 +1946,26 @@ void t_php_generator::generate_service_client(t_service* tservice) { // Careful, only return result if not a void function if (!(*f_iter)->get_returntype()->is_void()) { - f_service_client << indent() << "if ($result->success !== null) {" << endl << indent() - << " return $result->success;" << endl << indent() << "}" << endl; + f_service_client << indent() << "if ($result->success !== null) {" << endl; + + indent_up(); + f_service_client << indent() << "return $result->success;" << endl; + + indent_down(); + f_service_client << indent() << "}" << endl; } t_struct* xs = (*f_iter)->get_xceptions(); const std::vector& xceptions = xs->get_members(); vector::const_iterator x_iter; for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) { - f_service_client << indent() << "if ($result->" << (*x_iter)->get_name() << " !== null) {" << endl - << indent() << " throw $result->" << (*x_iter)->get_name() << ";" << endl - << indent() << "}" << endl; + f_service_client << indent() << "if ($result->" << (*x_iter)->get_name() << " !== null) {" << endl; + + indent_up(); + f_service_client << indent() << "throw $result->" << (*x_iter)->get_name() << ";" << endl; + + indent_down(); + f_service_client << indent() << "}" << endl; } // Careful, only return _result if not a void function @@ -1842,16 +1978,14 @@ void t_php_generator::generate_service_client(t_service* tservice) { // Close function scope_down(f_service_client); - f_service_client << endl; } } indent_down(); - f_service_client << "}" << endl << endl; + f_service_client << "}" << endl; // Close service client file - f_service_client << endl; - if (psr4_) { + if (!classmap_) { f_service_client.close(); } } @@ -1859,7 +1993,7 @@ void t_php_generator::generate_service_client(t_service* tservice) { /** * Deserializes a field of any type. */ -void t_php_generator::generate_deserialize_field(ofstream& out, +void t_php_generator::generate_deserialize_field(ostream& out, t_field* tfield, string prefix, bool inclass) { @@ -1991,13 +2125,13 @@ void t_php_generator::generate_deserialize_field(ofstream& out, * buffer for deserialization, and that there is a variable protocol which * is a reference to a TProtocol serialization object. */ -void t_php_generator::generate_deserialize_struct(ofstream& out, t_struct* tstruct, string prefix) { +void t_php_generator::generate_deserialize_struct(ostream& out, t_struct* tstruct, string prefix) { out << indent() << "$" << prefix << " = new " << php_namespace(tstruct->get_program()) << tstruct->get_name() << "();" << endl << indent() << "$xfer += $" << prefix << "->read($input);" << endl; } -void t_php_generator::generate_deserialize_container(ofstream& out, t_type* ttype, string prefix) { +void t_php_generator::generate_deserialize_container(ostream& out, t_type* ttype, string prefix) { string size = tmp("_size"); string ktype = tmp("_ktype"); string vtype = tmp("_vtype"); @@ -2045,9 +2179,9 @@ void t_php_generator::generate_deserialize_container(ofstream& out, t_type* ttyp // For loop iterates over elements string i = tmp("_i"); - indent(out) << "for ($" << i << " = 0; $" << i << " < $" << size << "; ++$" << i << ")" << endl; + indent(out) << "for ($" << i << " = 0; $" << i << " < $" << size << "; ++$" << i << ") {" << endl; - scope_up(out); + indent_up(); if (ttype->is_map()) { generate_deserialize_map_element(out, (t_map*)ttype, prefix); @@ -2074,7 +2208,7 @@ void t_php_generator::generate_deserialize_container(ofstream& out, t_type* ttyp /** * Generates code to deserialize a map */ -void t_php_generator::generate_deserialize_map_element(ofstream& out, t_map* tmap, string prefix) { +void t_php_generator::generate_deserialize_map_element(ostream& out, t_map* tmap, string prefix) { string key = tmp("key"); string val = tmp("val"); t_field fkey(tmap->get_key_type(), key); @@ -2089,7 +2223,7 @@ void t_php_generator::generate_deserialize_map_element(ofstream& out, t_map* tma indent(out) << "$" << prefix << "[$" << key << "] = $" << val << ";" << endl; } -void t_php_generator::generate_deserialize_set_element(ofstream& out, t_set* tset, string prefix) { +void t_php_generator::generate_deserialize_set_element(ostream& out, t_set* tset, string prefix) { string elem = tmp("elem"); t_field felem(tset->get_elem_type(), elem); @@ -2097,14 +2231,15 @@ void t_php_generator::generate_deserialize_set_element(ofstream& out, t_set* tse generate_deserialize_field(out, &felem); - indent(out) << "if (is_scalar($" << elem << ")) {" << endl; - indent(out) << " $" << prefix << "[$" << elem << "] = true;" << endl; - indent(out) << "} else {" << endl; - indent(out) << " $" << prefix << " []= $" << elem << ";" << endl; - indent(out) << "}" << endl; + t_type* elem_type = tset->get_elem_type(); + if(php_is_scalar(elem_type)) { + indent(out) << "$" << prefix << "[$" << elem << "] = true;" << endl; + } else { + indent(out) << "$" << prefix << "[] = $" << elem << ";" << endl; + } } -void t_php_generator::generate_deserialize_list_element(ofstream& out, +void t_php_generator::generate_deserialize_list_element(ostream& out, t_list* tlist, string prefix) { string elem = tmp("elem"); @@ -2123,7 +2258,7 @@ void t_php_generator::generate_deserialize_list_element(ofstream& out, * @param tfield The field to serialize * @param prefix Name to prepend to field name */ -void t_php_generator::generate_serialize_field(ofstream& out, t_field* tfield, string prefix) { +void t_php_generator::generate_serialize_field(ostream& out, t_field* tfield, string prefix) { t_type* type = get_true_type(tfield->get_type()); // Do nothing for void types @@ -2228,7 +2363,7 @@ void t_php_generator::generate_serialize_field(ofstream& out, t_field* tfield, s * @param tstruct The struct to serialize * @param prefix String prefix to attach to all fields */ -void t_php_generator::generate_serialize_struct(ofstream& out, t_struct* tstruct, string prefix) { +void t_php_generator::generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix) { (void)tstruct; indent(out) << "$xfer += $" << prefix << "->write($output);" << endl; } @@ -2236,9 +2371,7 @@ void t_php_generator::generate_serialize_struct(ofstream& out, t_struct* tstruct /** * Writes out a container */ -void t_php_generator::generate_serialize_container(ofstream& out, t_type* ttype, string prefix) { - scope_up(out); - +void t_php_generator::generate_serialize_container(ostream& out, t_type* ttype, string prefix) { if (ttype->is_map()) { if (binary_inline_) { out << indent() << "$output .= pack('c', " << type_to_enum(((t_map*)ttype)->get_key_type()) @@ -2274,37 +2407,35 @@ void t_php_generator::generate_serialize_container(ofstream& out, t_type* ttype, } } - scope_up(out); - if (ttype->is_map()) { string kiter = tmp("kiter"); string viter = tmp("viter"); indent(out) << "foreach ($" << prefix << " as " - << "$" << kiter << " => $" << viter << ")" << endl; - scope_up(out); + << "$" << kiter << " => $" << viter << ") {" << endl; + indent_up(); generate_serialize_map_element(out, (t_map*)ttype, kiter, viter); scope_down(out); } else if (ttype->is_set()) { string iter = tmp("iter"); string iter_val = tmp("iter"); - indent(out) << "foreach ($" << prefix << " as $" << iter << " => $" << iter_val << ")" << endl; - scope_up(out); - indent(out) << "if (is_scalar($" << iter_val << ")) {" << endl; - generate_serialize_set_element(out, (t_set*)ttype, iter); - indent(out) << "} else {" << endl; - generate_serialize_set_element(out, (t_set*)ttype, iter_val); - indent(out) << "}" << endl; + indent(out) << "foreach ($" << prefix << " as $" << iter << " => $" << iter_val << ") {" << endl; + indent_up(); + + t_type* elem_type = ((t_set*)ttype)->get_elem_type(); + if(php_is_scalar(elem_type)) { + generate_serialize_set_element(out, (t_set*)ttype, iter); + } else { + generate_serialize_set_element(out, (t_set*)ttype, iter_val); + } scope_down(out); } else if (ttype->is_list()) { string iter = tmp("iter"); - indent(out) << "foreach ($" << prefix << " as $" << iter << ")" << endl; - scope_up(out); + indent(out) << "foreach ($" << prefix << " as $" << iter << ") {" << endl; + indent_up(); generate_serialize_list_element(out, (t_list*)ttype, iter); scope_down(out); } - scope_down(out); - if (!binary_inline_) { if (ttype->is_map()) { indent(out) << "$output->writeMapEnd();" << endl; @@ -2314,15 +2445,13 @@ void t_php_generator::generate_serialize_container(ofstream& out, t_type* ttype, indent(out) << "$output->writeListEnd();" << endl; } } - - scope_down(out); } /** * Serializes the members of a map. * */ -void t_php_generator::generate_serialize_map_element(ofstream& out, +void t_php_generator::generate_serialize_map_element(ostream& out, t_map* tmap, string kiter, string viter) { @@ -2336,7 +2465,7 @@ void t_php_generator::generate_serialize_map_element(ofstream& out, /** * Serializes the members of a set. */ -void t_php_generator::generate_serialize_set_element(ofstream& out, t_set* tset, string iter) { +void t_php_generator::generate_serialize_set_element(ostream& out, t_set* tset, string iter) { t_field efield(tset->get_elem_type(), iter); generate_serialize_field(out, &efield, ""); } @@ -2344,7 +2473,7 @@ void t_php_generator::generate_serialize_set_element(ofstream& out, t_set* tset, /** * Serializes the members of a list. */ -void t_php_generator::generate_serialize_list_element(ofstream& out, t_list* tlist, string iter) { +void t_php_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string iter) { t_field efield(tlist->get_elem_type(), iter); generate_serialize_field(out, &efield, ""); } @@ -2352,14 +2481,14 @@ void t_php_generator::generate_serialize_list_element(ofstream& out, t_list* tli /** * Emits a PHPDoc comment for the given contents */ -void t_php_generator::generate_php_docstring_comment(ofstream& out, string contents) { +void t_php_generator::generate_php_docstring_comment(ostream& out, string contents) { generate_docstring_comment(out, "/**\n", " * ", contents, " */\n"); } /** * Emits a PHPDoc comment if the provided object has a doc in Thrift */ -void t_php_generator::generate_php_doc(ofstream& out, t_doc* tdoc) { +void t_php_generator::generate_php_doc(ostream& out, t_doc* tdoc) { if (tdoc->has_doc()) { generate_php_docstring_comment(out, tdoc->get_doc()); } @@ -2368,7 +2497,7 @@ void t_php_generator::generate_php_doc(ofstream& out, t_doc* tdoc) { /** * Emits a PHPDoc comment for a field */ -void t_php_generator::generate_php_doc(ofstream& out, t_field* field) { +void t_php_generator::generate_php_doc(ostream& out, t_field* field) { stringstream ss; // prepend free-style doc if available @@ -2386,7 +2515,7 @@ void t_php_generator::generate_php_doc(ofstream& out, t_field* field) { /** * Emits a PHPDoc comment for a function */ -void t_php_generator::generate_php_doc(ofstream& out, t_function* function) { +void t_php_generator::generate_php_doc(ostream& out, t_function* function) { stringstream ss; if (function->has_doc()) { ss << function->get_doc() << endl; @@ -2649,7 +2778,7 @@ THRIFT_REGISTER_GENERATOR( " inlined: Generate PHP inlined files\n" " server: Generate PHP server stubs\n" " oop: Generate PHP with object oriented subclasses\n" - " psr4: Generate each PHP class in separate file (allows PSR4 autoloading)\n" + " classmap: Generate old-style PHP files (use classmap autoloading)\n" " rest: Generate PHP REST processors\n" " nsglobal=NAME: Set global namespace\n" " validate: Generate PHP validator methods\n" diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_py_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_py_generator.cc index 1d11144..f0a153c 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_py_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_py_generator.cc @@ -19,7 +19,9 @@ #include #include +#include #include +#include #include #include @@ -32,7 +34,7 @@ #include "thrift/generate/t_generator.h" using std::map; -using std::ofstream; +using std::ostream; using std::ostringstream; using std::string; using std::stringstream; @@ -49,15 +51,15 @@ public: t_py_generator(t_program* program, const std::map& parsed_options, const std::string& option_string) - : t_generator(program) { + : t_generator (program) { std::map::const_iterator iter; - gen_newstyle_ = true; gen_utf8strings_ = true; gen_dynbase_ = false; gen_slots_ = false; gen_tornado_ = false; + gen_zope_interface_ = false; gen_twisted_ = false; gen_dynamic_ = false; coding_ = ""; @@ -105,8 +107,11 @@ public: } else if( iter->first.compare("dynimport") == 0) { gen_dynbase_ = true; import_dynbase_ = (iter->second); + } else if( iter->first.compare("zope.interface") == 0) { + gen_zope_interface_ = true; } else if( iter->first.compare("twisted") == 0) { gen_twisted_ = true; + gen_zope_interface_ = true; } else if( iter->first.compare("tornado") == 0) { gen_tornado_ = true; } else if( iter->first.compare("coding") == 0) { @@ -150,6 +155,7 @@ public: void generate_enum(t_enum* tenum); void generate_const(t_const* tconst); void generate_struct(t_struct* tstruct); + void generate_forward_declaration(t_struct* tstruct); void generate_xception(t_struct* txception); void generate_service(t_service* tservice); @@ -160,12 +166,13 @@ public: */ void generate_py_struct(t_struct* tstruct, bool is_exception); - void generate_py_struct_definition(std::ofstream& out, + void generate_py_thrift_spec(std::ostream& out, t_struct* tstruct, bool is_exception); + void generate_py_struct_definition(std::ostream& out, t_struct* tstruct, bool is_xception = false); - void generate_py_struct_reader(std::ofstream& out, t_struct* tstruct); - void generate_py_struct_writer(std::ofstream& out, t_struct* tstruct); - void generate_py_struct_required_validator(std::ofstream& out, t_struct* tstruct); + void generate_py_struct_reader(std::ostream& out, t_struct* tstruct); + void generate_py_struct_writer(std::ostream& out, t_struct* tstruct); + void generate_py_struct_required_validator(std::ostream& out, t_struct* tstruct); void generate_py_function_helpers(t_function* tfunction); /** @@ -183,47 +190,47 @@ public: * Serialization constructs */ - void generate_deserialize_field(std::ofstream& out, + void generate_deserialize_field(std::ostream& out, t_field* tfield, std::string prefix = ""); - void generate_deserialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); + void generate_deserialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); - void generate_deserialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); + void generate_deserialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); - void generate_deserialize_set_element(std::ofstream& out, t_set* tset, std::string prefix = ""); + void generate_deserialize_set_element(std::ostream& out, t_set* tset, std::string prefix = ""); - void generate_deserialize_map_element(std::ofstream& out, t_map* tmap, std::string prefix = ""); + void generate_deserialize_map_element(std::ostream& out, t_map* tmap, std::string prefix = ""); - void generate_deserialize_list_element(std::ofstream& out, + void generate_deserialize_list_element(std::ostream& out, t_list* tlist, std::string prefix = ""); - void generate_serialize_field(std::ofstream& out, t_field* tfield, std::string prefix = ""); + void generate_serialize_field(std::ostream& out, t_field* tfield, std::string prefix = ""); - void generate_serialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = ""); + void generate_serialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); - void generate_serialize_container(std::ofstream& out, t_type* ttype, std::string prefix = ""); + void generate_serialize_container(std::ostream& out, t_type* ttype, std::string prefix = ""); - void generate_serialize_map_element(std::ofstream& out, + void generate_serialize_map_element(std::ostream& out, t_map* tmap, std::string kiter, std::string viter); - void generate_serialize_set_element(std::ofstream& out, t_set* tmap, std::string iter); + void generate_serialize_set_element(std::ostream& out, t_set* tmap, std::string iter); - void generate_serialize_list_element(std::ofstream& out, t_list* tlist, std::string iter); + void generate_serialize_list_element(std::ostream& out, t_list* tlist, std::string iter); - void generate_python_docstring(std::ofstream& out, t_struct* tstruct); + void generate_python_docstring(std::ostream& out, t_struct* tstruct); - void generate_python_docstring(std::ofstream& out, t_function* tfunction); + void generate_python_docstring(std::ostream& out, t_function* tfunction); - void generate_python_docstring(std::ofstream& out, + void generate_python_docstring(std::ostream& out, t_doc* tdoc, t_struct* tstruct, const char* subheader); - void generate_python_docstring(std::ofstream& out, t_doc* tdoc); + void generate_python_docstring(std::ostream& out, t_doc* tdoc); /** * Helper rendering functions @@ -288,6 +295,11 @@ private: std::string copy_options_; + /** + * True if we should generate code for use with zope.interface. + */ + bool gen_zope_interface_; + /** * True if we should generate Twisted-friendly RPC services. */ @@ -315,12 +327,21 @@ private: * File streams */ - std::ofstream f_types_; - std::ofstream f_consts_; - std::ofstream f_service_; + ofstream_with_content_based_conditional_update f_types_; + ofstream_with_content_based_conditional_update f_consts_; + ofstream_with_content_based_conditional_update f_service_; std::string package_dir_; std::string module_; + +protected: + virtual std::set lang_keywords() const { + std::string keywords[] = { "False", "None", "True", "and", "as", "assert", "break", "class", + "continue", "def", "del", "elif", "else", "except", "exec", "finally", "for", "from", + "global", "if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass", "print", + "raise", "return", "try", "while", "with", "yield" }; + return std::set(keywords, keywords + sizeof(keywords)/sizeof(keywords[0]) ); + } }; /** @@ -362,7 +383,7 @@ void t_py_generator::init_generator() { f_consts_.open(f_consts_name.c_str()); string f_init_name = package_dir_ + "/__init__.py"; - ofstream f_init; + ofstream_with_content_based_conditional_update f_init; f_init.open(f_init_name.c_str()); f_init << "__all__ = ['ttypes', 'constants'"; vector services = program_->get_services(); @@ -380,6 +401,8 @@ void t_py_generator::init_generator() { << "from thrift.transport import TTransport" << endl << import_dynbase_; + f_types_ << "all_structs = []" << endl; + f_consts_ << py_autogen_comment() << endl << py_imports() << endl << @@ -419,7 +442,11 @@ string t_py_generator::py_imports() { ss << "from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, " "TApplicationException" << endl - << "from thrift.protocol.TProtocol import TProtocolException"; + << "from thrift.protocol.TProtocol import TProtocolException" + << endl + << "from thrift.TRecursive import fix_spec" + << endl; + if (gen_utf8strings_) { ss << endl << "import sys"; } @@ -430,6 +457,11 @@ string t_py_generator::py_imports() { * Closes the type files */ void t_py_generator::close_generator() { + + // Fix thrift_spec definitions for recursive structs. + f_types_ << "fix_spec(all_structs)" << endl; + f_types_ << "del all_structs" << endl; + // Close types file f_types_.close(); f_consts_.close(); @@ -519,9 +551,9 @@ string t_py_generator::render_const_value(t_type* type, t_const_value* value) { break; case t_base_type::TYPE_DOUBLE: if (value->get_type() == t_const_value::CV_INTEGER) { - out << value->get_integer(); + out << "float(" << value->get_integer() << ")"; } else { - out << value->get_double(); + out << emit_double_as_string(value->get_double()); } break; default: @@ -534,8 +566,8 @@ string t_py_generator::render_const_value(t_type* type, t_const_value* value) { indent_up(); const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { t_type* field_type = NULL; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { @@ -559,8 +591,8 @@ string t_py_generator::render_const_value(t_type* type, t_const_value* value) { } out << "{" << endl; indent_up(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { indent(out) << render_const_value(ktype, v_iter->first) << ": " << render_const_value(vtype, v_iter->second) << "," << endl; @@ -610,11 +642,21 @@ string t_py_generator::render_const_value(t_type* type, t_const_value* value) { return out.str(); } +/** + * Generates the "forward declarations" for python structs. + * These are actually full class definitions so that calls to generate_struct + * can add the thrift_spec field. This is needed so that all thrift_spec + * definitions are grouped at the end of the file to enable co-recursive structs. + */ +void t_py_generator::generate_forward_declaration(t_struct* tstruct) { + generate_py_struct(tstruct, tstruct->is_xception()); +} + /** * Generates a python struct */ void t_py_generator::generate_struct(t_struct* tstruct) { - generate_py_struct(tstruct, false); + generate_py_thrift_spec(f_types_, tstruct, false); } /** @@ -624,7 +666,7 @@ void t_py_generator::generate_struct(t_struct* tstruct) { * @param txception The struct definition */ void t_py_generator::generate_xception(t_struct* txception) { - generate_py_struct(txception, true); + generate_py_thrift_spec(f_types_, txception, true); } /** @@ -634,12 +676,60 @@ void t_py_generator::generate_py_struct(t_struct* tstruct, bool is_exception) { generate_py_struct_definition(f_types_, tstruct, is_exception); } + +/** + * Generate the thrift_spec for a struct + * For example, + * all_structs.append(Recursive) + * Recursive.thrift_spec = ( + * None, # 0 + * (1, TType.LIST, 'Children', (TType.STRUCT, (Recursive, None), False), None, ), # 1 + * ) + */ +void t_py_generator::generate_py_thrift_spec(ostream& out, + t_struct* tstruct, + bool /*is_exception*/) { + const vector& sorted_members = tstruct->get_sorted_members(); + vector::const_iterator m_iter; + + // Add struct definition to list so thrift_spec can be fixed for recursive structures. + indent(out) << "all_structs.append(" << tstruct->get_name() << ")" << endl; + + if (sorted_members.empty() || (sorted_members[0]->get_key() >= 0)) { + indent(out) << tstruct->get_name() << ".thrift_spec = (" << endl; + indent_up(); + + int sorted_keys_pos = 0; + for (m_iter = sorted_members.begin(); m_iter != sorted_members.end(); ++m_iter) { + + for (; sorted_keys_pos != (*m_iter)->get_key(); sorted_keys_pos++) { + indent(out) << "None, # " << sorted_keys_pos << endl; + } + + indent(out) << "(" << (*m_iter)->get_key() << ", " << type_to_enum((*m_iter)->get_type()) + << ", " + << "'" << (*m_iter)->get_name() << "'" + << ", " << type_to_spec_args((*m_iter)->get_type()) << ", " + << render_field_default_value(*m_iter) << ", " + << ")," + << " # " << sorted_keys_pos << endl; + + sorted_keys_pos++; + } + + indent_down(); + indent(out) << ")" << endl; + } else { + indent(out) << tstruct->get_name() << ".thrift_spec = ()" << endl; + } +} + /** * Generates a struct definition for a thrift data type. * * @param tstruct The struct definition */ -void t_py_generator::generate_py_struct_definition(ofstream& out, +void t_py_generator::generate_py_struct_definition(ostream& out, t_struct* tstruct, bool is_exception) { const vector& members = tstruct->get_members(); @@ -702,43 +792,14 @@ void t_py_generator::generate_py_struct_definition(ofstream& out, // for structures with no members. // TODO(dreiss): Test encoding of structs where some inner structs // don't have thrift_spec. - if (sorted_members.empty() || (sorted_members[0]->get_key() >= 0)) { - indent(out) << "thrift_spec = (" << endl; - indent_up(); - - int sorted_keys_pos = 0; - for (m_iter = sorted_members.begin(); m_iter != sorted_members.end(); ++m_iter) { - - for (; sorted_keys_pos != (*m_iter)->get_key(); sorted_keys_pos++) { - indent(out) << "None, # " << sorted_keys_pos << endl; - } - - indent(out) << "(" << (*m_iter)->get_key() << ", " << type_to_enum((*m_iter)->get_type()) - << ", " - << "'" << (*m_iter)->get_name() << "'" - << ", " << type_to_spec_args((*m_iter)->get_type()) << ", " - << render_field_default_value(*m_iter) << ", " - << ")," - << " # " << sorted_keys_pos << endl; - - sorted_keys_pos++; - } - - indent_down(); - indent(out) << ")" << endl; - } else { - indent(out) << "thrift_spec = None" << endl; - } if (members.size() > 0) { out << endl; out << indent() << "def __init__(self,"; for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { - // This fills in default values, as opposed to nulls out << " " << declare_argument(*m_iter) << ","; } - out << "):" << endl; indent_up(); @@ -867,7 +928,7 @@ void t_py_generator::generate_py_struct_definition(ofstream& out, /** * Generates the read method for a struct */ -void t_py_generator::generate_py_struct_reader(ofstream& out, t_struct* tstruct) { +void t_py_generator::generate_py_struct_reader(ostream& out, t_struct* tstruct) { const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; @@ -887,14 +948,28 @@ void t_py_generator::generate_py_struct_reader(ofstream& out, t_struct* tstruct) indent_up(); if (is_immutable(tstruct)) { - indent(out) << "return iprot._fast_decode(None, iprot, (cls, cls.thrift_spec))" << endl; + indent(out) << "return iprot._fast_decode(None, iprot, [cls, cls.thrift_spec])" << endl; } else { - indent(out) << "iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec))" << endl; + indent(out) << "iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec])" << endl; indent(out) << "return" << endl; } indent_down(); indent(out) << "iprot.readStructBegin()" << endl; + + if (is_immutable(tstruct)) { + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { + t_field* tfield = *f_iter; + std::ostringstream result; + result << tfield->get_name() << " = "; + if (tfield->get_value() != NULL) { + result << render_field_default_value(tfield); + } else { + result << "None"; + } + indent(out) << result.str() << endl; + } + } // Loop over reading in fields indent(out) << "while True:" << endl; @@ -958,7 +1033,7 @@ void t_py_generator::generate_py_struct_reader(ofstream& out, t_struct* tstruct) out << endl; } -void t_py_generator::generate_py_struct_writer(ofstream& out, t_struct* tstruct) { +void t_py_generator::generate_py_struct_writer(ostream& out, t_struct* tstruct) { string name = tstruct->get_name(); const vector& fields = tstruct->get_sorted_members(); vector::const_iterator f_iter; @@ -970,7 +1045,7 @@ void t_py_generator::generate_py_struct_writer(ofstream& out, t_struct* tstruct) indent_up(); indent(out) - << "oprot.trans.write(oprot._fast_encode(self, (self.__class__, self.thrift_spec)))" + << "oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec]))" << endl; indent(out) << "return" << endl; indent_down(); @@ -1004,7 +1079,7 @@ void t_py_generator::generate_py_struct_writer(ofstream& out, t_struct* tstruct) generate_py_struct_required_validator(out, tstruct); } -void t_py_generator::generate_py_struct_required_validator(ofstream& out, t_struct* tstruct) { +void t_py_generator::generate_py_struct_required_validator(ostream& out, t_struct* tstruct) { indent(out) << "def validate(self):" << endl; indent_up(); @@ -1049,16 +1124,20 @@ void t_py_generator::generate_service(t_service* tservice) { << "from thrift.Thrift import TProcessor" << endl << "from thrift.transport import TTransport" << endl << import_dynbase_; + if (gen_zope_interface_) { + f_service_ << "from zope.interface import Interface, implementer" << endl; + } if (gen_twisted_) { - f_service_ << "from zope.interface import Interface, implements" << endl - << "from twisted.internet import defer" << endl + f_service_ << "from twisted.internet import defer" << endl << "from thrift.transport import TTwisted" << endl; } else if (gen_tornado_) { f_service_ << "from tornado import gen" << endl; f_service_ << "from tornado import concurrent" << endl; } + f_service_ << "all_structs = []" << endl; + // Generate the three main parts of the service generate_service_interface(tservice); generate_service_client(tservice); @@ -1067,6 +1146,8 @@ void t_py_generator::generate_service(t_service* tservice) { generate_service_remote(tservice); // Close service file + f_service_ << "fix_spec(all_structs)" << endl + << "del all_structs" << endl << endl; f_service_.close(); } @@ -1084,6 +1165,7 @@ void t_py_generator::generate_service_helpers(t_service* tservice) { for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { t_struct* ts = (*f_iter)->get_arglist(); generate_py_struct_definition(f_service_, ts, false); + generate_py_thrift_spec(f_service_, ts, false); generate_py_function_helpers(*f_iter); } } @@ -1108,6 +1190,7 @@ void t_py_generator::generate_py_function_helpers(t_function* tfunction) { result.append(*f_iter); } generate_py_struct_definition(f_service_, &result, false); + generate_py_thrift_spec(f_service_, &result, false); } } @@ -1123,7 +1206,7 @@ void t_py_generator::generate_service_interface(t_service* tservice) { extends = type_name(tservice->get_extends()); extends_if = "(" + extends + ".Iface)"; } else { - if (gen_twisted_) { + if (gen_zope_interface_) { extends_if = "(Interface)"; } else if (gen_newstyle_ || gen_dynamic_ || gen_tornado_) { extends_if = "(object)"; @@ -1166,22 +1249,22 @@ void t_py_generator::generate_service_client(t_service* tservice) { string extends_client = ""; if (tservice->get_extends() != NULL) { extends = type_name(tservice->get_extends()); - if (gen_twisted_) { + if (gen_zope_interface_) { extends_client = "(" + extends + ".Client)"; } else { extends_client = extends + ".Client, "; } } else { - if (gen_twisted_ && (gen_newstyle_ || gen_dynamic_)) { + if (gen_zope_interface_ && (gen_newstyle_ || gen_dynamic_)) { extends_client = "(object)"; } } f_service_ << endl << endl; - if (gen_twisted_) { - f_service_ << "class Client" << extends_client << ":" << endl - << indent_str() << "implements(Iface)" << endl + if (gen_zope_interface_) { + f_service_ << "@implementer(Iface)" << endl + << "class Client" << extends_client << ":" << endl << endl; } else { f_service_ << "class Client(" << extends_client << "Iface):" << endl; @@ -1454,12 +1537,13 @@ void t_py_generator::generate_service_client(t_service* tservice) { const std::vector& xceptions = xs->get_members(); vector::const_iterator x_iter; for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) { - f_service_ << indent() << "if result." << (*x_iter)->get_name() << " is not None:" << endl; + const string& xname = (*x_iter)->get_name(); + f_service_ << indent() << "if result." << xname << " is not None:" << endl; if (gen_twisted_) { - f_service_ << indent() << indent_str() << "return d.errback(result." << (*x_iter)->get_name() << ")" + f_service_ << indent() << indent_str() << "return d.errback(result." << xname << ")" << endl; } else { - f_service_ << indent() << indent_str() << "raise result." << (*x_iter)->get_name() << "" << endl; + f_service_ << indent() << indent_str() << "raise result." << xname << "" << endl; } } @@ -1508,7 +1592,7 @@ void t_py_generator::generate_service_remote(t_service* tservice) { vector::iterator f_iter; string f_remote_name = package_dir_ + "/" + service_name_ + "-remote"; - ofstream f_remote; + ofstream_with_content_based_conditional_update f_remote; f_remote.open(f_remote_name.c_str()); f_remote << @@ -1719,9 +1803,9 @@ void t_py_generator::generate_service_server(t_service* tservice) { f_service_ << endl << endl; // Generate the header portion - if (gen_twisted_) { - f_service_ << "class Processor(" << extends_processor << "TProcessor):" << endl - << indent_str() << "implements(Iface)" << endl << endl; + if (gen_zope_interface_) { + f_service_ << "@implementer(Iface)" << endl + << "class Processor(" << extends_processor << "TProcessor):" << endl; } else { f_service_ << "class Processor(" << extends_processor << "Iface, TProcessor):" << endl; } @@ -1731,7 +1815,7 @@ void t_py_generator::generate_service_server(t_service* tservice) { indent(f_service_) << "def __init__(self, handler):" << endl; indent_up(); if (extends.empty()) { - if (gen_twisted_) { + if (gen_zope_interface_) { f_service_ << indent() << "self._handler = Iface(handler)" << endl; } else { f_service_ << indent() << "self._handler = handler" << endl; @@ -1739,7 +1823,7 @@ void t_py_generator::generate_service_server(t_service* tservice) { f_service_ << indent() << "self._processMap = {}" << endl; } else { - if (gen_twisted_) { + if (gen_zope_interface_) { f_service_ << indent() << extends << ".Processor.__init__(self, Iface(handler))" << endl; } else { f_service_ << indent() << extends << ".Processor.__init__(self, handler)" << endl; @@ -1839,8 +1923,6 @@ void t_py_generator::generate_process_function(t_service* tservice, t_function* } if (gen_twisted_) { - // TODO: Propagate arbitrary exception raised by handler to client as does plain "py" - // Generate the function call t_struct* arg_struct = tfunction->get_arglist(); const std::vector& fields = arg_struct->get_members(); @@ -1859,78 +1941,97 @@ void t_py_generator::generate_process_function(t_service* tservice, t_function* } f_service_ << ")" << endl; - // Shortcut out here for oneway functions if (tfunction->is_oneway()) { - f_service_ << indent() << "return d" << endl; - indent_down(); - f_service_ << endl; - return; - } - - f_service_ << indent() << "d.addCallback(self.write_results_success_" << tfunction->get_name() - << ", result, seqid, oprot)" << endl; - - if (xceptions.size() > 0) { - f_service_ << indent() << "d.addErrback(self.write_results_exception_" + f_service_ << indent() << "d.addErrback(self.handle_exception_" << tfunction->get_name() + << ", seqid)" << endl; + } else { + f_service_ << indent() << "d.addCallback(self.write_results_success_" << tfunction->get_name() + << ", result, seqid, oprot)" << endl + << indent() << "d.addErrback(self.write_results_exception_" << tfunction->get_name() << ", result, seqid, oprot)" << endl; } - - f_service_ << indent() << "return d" << endl; + f_service_ << indent() << "return d" << endl << endl; indent_down(); - f_service_ << endl; - indent(f_service_) << "def write_results_success_" << tfunction->get_name() - << "(self, success, result, seqid, oprot):" << endl; - indent_up(); - f_service_ << indent() << "result.success = success" << endl << indent() - << "oprot.writeMessageBegin(\"" << tfunction->get_name() - << "\", TMessageType.REPLY, seqid)" << endl << indent() << "result.write(oprot)" - << endl << indent() << "oprot.writeMessageEnd()" << endl << indent() - << "oprot.trans.flush()" << endl; - indent_down(); - - // Try block for a function with exceptions - if (!tfunction->is_oneway() && xceptions.size() > 0) { - f_service_ << endl; - indent(f_service_) << "def write_results_exception_" << tfunction->get_name() - << "(self, error, result, seqid, oprot):" << endl; + if (tfunction->is_oneway()) { + indent(f_service_) << "def handle_exception_" << tfunction->get_name() + << "(self, error, seqid):" << endl; + } else { + indent(f_service_) << "def write_results_success_" << tfunction->get_name() + << "(self, success, result, seqid, oprot):" << endl; indent_up(); - f_service_ << indent() << "try:" << endl; - - // Kinda absurd - f_service_ << indent() << indent_str() << "error.raiseException()" << endl; - for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) { - f_service_ << - indent() << "except " << type_name((*x_iter)->get_type()) << " as " << (*x_iter)->get_name() << ":" << endl; - if (!tfunction->is_oneway()) { - indent_up(); - f_service_ << indent() << "result." << (*x_iter)->get_name() << " = " - << (*x_iter)->get_name() << endl; - indent_down(); - } else { - f_service_ << indent() << "pass" << endl; - } + if (!tfunction->get_returntype()->is_void()) { + f_service_ << indent() << "result.success = success" << endl; } f_service_ << indent() << "oprot.writeMessageBegin(\"" << tfunction->get_name() - << "\", TMessageType.REPLY, seqid)" << endl << indent() << "result.write(oprot)" - << endl << indent() << "oprot.writeMessageEnd()" << endl << indent() - << "oprot.trans.flush()" << endl; + << "\", TMessageType.REPLY, seqid)" << endl + << indent() << "result.write(oprot)" << endl + << indent() << "oprot.writeMessageEnd()" << endl + << indent() << "oprot.trans.flush()" << endl + << endl; indent_down(); + + indent(f_service_) << "def write_results_exception_" << tfunction->get_name() + << "(self, error, result, seqid, oprot):" << endl; } + indent_up(); + if (!tfunction->is_oneway()) { + f_service_ << indent() << "msg_type = TMessageType.REPLY" << endl; + } + f_service_ << indent() << "try:" << endl; + + // Kinda absurd + f_service_ << indent() << indent_str() << "error.raiseException()" << endl; + if (!tfunction->is_oneway()) { + for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) { + const string& xname = (*x_iter)->get_name(); + f_service_ << indent() << "except " << type_name((*x_iter)->get_type()) << " as " << xname + << ":" << endl; + indent_up(); + f_service_ << indent() << "result." << xname << " = " << xname << endl; + indent_down(); + } + } + f_service_ << indent() << "except TTransport.TTransportException:" << endl + << indent() << indent_str() << "raise" << endl; + if (!tfunction->is_oneway()) { + f_service_ << indent() << "except TApplicationException as ex:" << endl + << indent() << indent_str() + << "logging.exception('TApplication exception in handler')" << endl + << indent() << indent_str() << "msg_type = TMessageType.EXCEPTION" << endl + << indent() << indent_str() << "result = ex" << endl + << indent() << "except Exception:" << endl + << indent() << indent_str() + << "logging.exception('Unexpected exception in handler')" << endl + << indent() << indent_str() << "msg_type = TMessageType.EXCEPTION" << endl + << indent() << indent_str() + << "result = TApplicationException(TApplicationException.INTERNAL_ERROR, " + "'Internal error')" + << endl + << indent() << "oprot.writeMessageBegin(\"" << tfunction->get_name() + << "\", msg_type, seqid)" << endl + << indent() << "result.write(oprot)" << endl + << indent() << "oprot.writeMessageEnd()" << endl + << indent() << "oprot.trans.flush()" << endl; + } else { + f_service_ << indent() << "except Exception:" << endl + << indent() << indent_str() + << "logging.exception('Exception in oneway handler')" << endl; + } + indent_down(); } else if (gen_tornado_) { - // TODO: Propagate arbitrary exception raised by handler to client as does plain "py" - // Generate the function call t_struct* arg_struct = tfunction->get_arglist(); const std::vector& fields = arg_struct->get_members(); vector::const_iterator f_iter; - if (xceptions.size() > 0) { - f_service_ << indent() << "try:" << endl; - indent_up(); + if (!tfunction->is_oneway()) { + indent(f_service_) << "msg_type = TMessageType.REPLY" << endl; } + f_service_ << indent() << "try:" << endl; + indent_up(); f_service_ << indent(); if (!tfunction->is_oneway() && !tfunction->get_returntype()->is_void()) { f_service_ << "result.success = "; @@ -1947,27 +2048,43 @@ void t_py_generator::generate_process_function(t_service* tservice, t_function* } f_service_ << "))" << endl; - if (!tfunction->is_oneway() && xceptions.size() > 0) { - indent_down(); + indent_down(); + if (!tfunction->is_oneway()) { for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) { - f_service_ << indent() << "except " << type_name((*x_iter)->get_type()) << " as " - << (*x_iter)->get_name() << ":" << endl; - if (!tfunction->is_oneway()) { - indent_up(); - f_service_ << indent() << "result." << (*x_iter)->get_name() << " = " - << (*x_iter)->get_name() << endl; - indent_down(); - } else { - f_service_ << indent() << "pass" << endl; - } + const string& xname = (*x_iter)->get_name(); + f_service_ << indent() << "except " << type_name((*x_iter)->get_type()) << " as " << xname + << ":" << endl + << indent() << indent_str() << "result." << xname << " = " << xname << endl; } } + f_service_ << indent() << "except TTransport.TTransportException:" << endl + << indent() << indent_str() << "raise" << endl; + if (!tfunction->is_oneway()) { + f_service_ << indent() << "except TApplicationException as ex:" << endl + << indent() << indent_str() + << "logging.exception('TApplication exception in handler')" << endl + << indent() << indent_str() << "msg_type = TMessageType.EXCEPTION" << endl + << indent() << indent_str() << "result = ex" << endl + << indent() << "except Exception:" << endl + << indent() << indent_str() + << "logging.exception('Unexpected exception in handler')" << endl + << indent() << indent_str() << "msg_type = TMessageType.EXCEPTION" << endl + << indent() << indent_str() + << "result = TApplicationException(TApplicationException.INTERNAL_ERROR, " + "'Internal error')" + << endl; + } else { + f_service_ << indent() << "except Exception:" << endl + << indent() << indent_str() + << "logging.exception('Exception in oneway handler')" << endl; + } if (!tfunction->is_oneway()) { f_service_ << indent() << "oprot.writeMessageBegin(\"" << tfunction->get_name() - << "\", TMessageType.REPLY, seqid)" << endl << indent() << "result.write(oprot)" - << endl << indent() << "oprot.writeMessageEnd()" << endl << indent() - << "oprot.trans.flush()" << endl; + << "\", msg_type, seqid)" << endl + << indent() << "result.write(oprot)" << endl + << indent() << "oprot.writeMessageEnd()" << endl + << indent() << "oprot.trans.flush()" << endl; } // Close function @@ -2000,43 +2117,46 @@ void t_py_generator::generate_process_function(t_service* tservice, t_function* } f_service_ << ")" << endl; if (!tfunction->is_oneway()) { - f_service_ << indent() << "msg_type = TMessageType.REPLY" << endl; + f_service_ << indent() << "msg_type = TMessageType.REPLY" << endl; } indent_down(); f_service_ << indent() - << "except (TTransport.TTransportException, KeyboardInterrupt, SystemExit):" << endl + << "except TTransport.TTransportException:" << endl << indent() << indent_str() << "raise" << endl; if (!tfunction->is_oneway()) { for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) { - f_service_ << indent() << "except " << type_name((*x_iter)->get_type()) << " as " - << (*x_iter)->get_name() << ":" << endl; - if (!tfunction->is_oneway()) { - indent_up(); - f_service_ << indent() << "msg_type = TMessageType.REPLY" << endl; - f_service_ << indent() << "result." << (*x_iter)->get_name() << " = " - << (*x_iter)->get_name() << endl; - indent_down(); - } else { - f_service_ << indent() << "pass" << endl; - } + const string& xname = (*x_iter)->get_name(); + f_service_ << indent() << "except " << type_name((*x_iter)->get_type()) << " as " << xname + << ":" << endl; + indent_up(); + f_service_ << indent() << "msg_type = TMessageType.REPLY" << endl; + f_service_ << indent() << "result." << xname << " = " << xname << endl; + indent_down(); } - f_service_ << indent() << "except Exception as ex:" << endl + f_service_ << indent() << "except TApplicationException as ex:" << endl + << indent() << indent_str() + << "logging.exception('TApplication exception in handler')" << endl << indent() << indent_str() << "msg_type = TMessageType.EXCEPTION" << endl - << indent() << indent_str() << "logging.exception(ex)" << endl - << indent() - << indent_str() << "result = TApplicationException(TApplicationException.INTERNAL_ERROR, " - "'Internal error')" << endl + << indent() << indent_str() << "result = ex" << endl + << indent() << "except Exception:" << endl + << indent() << indent_str() + << "logging.exception('Unexpected exception in handler')" << endl + << indent() << indent_str() << "msg_type = TMessageType.EXCEPTION" << endl + << indent() << indent_str() + << "result = TApplicationException(TApplicationException.INTERNAL_ERROR, " + "'Internal error')" + << endl << indent() << "oprot.writeMessageBegin(\"" << tfunction->get_name() << "\", msg_type, seqid)" << endl << indent() << "result.write(oprot)" << endl << indent() << "oprot.writeMessageEnd()" << endl << indent() << "oprot.trans.flush()" << endl; } else { - f_service_ << indent() << "except:" << endl - << indent() << indent_str() << "pass" << endl; + f_service_ << indent() << "except Exception:" << endl + << indent() << indent_str() << "logging.exception('Exception in oneway handler')" << endl; } // Close function @@ -2047,7 +2167,7 @@ void t_py_generator::generate_process_function(t_service* tservice, t_function* /** * Deserializes a field of any type. */ -void t_py_generator::generate_deserialize_field(ofstream& out, +void t_py_generator::generate_deserialize_field(ostream& out, t_field* tfield, string prefix) { t_type* type = get_true_type(tfield->get_type()); @@ -2071,7 +2191,7 @@ void t_py_generator::generate_deserialize_field(ofstream& out, case t_base_type::TYPE_VOID: throw "compiler error: cannot serialize void field in a struct: " + name; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { out << "readBinary()"; } else if(!gen_utf8strings_) { out << "readString()"; @@ -2115,7 +2235,7 @@ void t_py_generator::generate_deserialize_field(ofstream& out, /** * Generates an unserializer for a struct, calling read() */ -void t_py_generator::generate_deserialize_struct(ofstream& out, t_struct* tstruct, string prefix) { +void t_py_generator::generate_deserialize_struct(ostream& out, t_struct* tstruct, string prefix) { if (is_immutable(tstruct)) { out << indent() << prefix << " = " << type_name(tstruct) << ".read(iprot)" << endl; } else { @@ -2128,7 +2248,7 @@ void t_py_generator::generate_deserialize_struct(ofstream& out, t_struct* tstruc * Serialize a container by writing out the header followed by * data and then a footer. */ -void t_py_generator::generate_deserialize_container(ofstream& out, t_type* ttype, string prefix) { +void t_py_generator::generate_deserialize_container(ostream& out, t_type* ttype, string prefix) { string size = tmp("_size"); string ktype = tmp("_ktype"); string vtype = tmp("_vtype"); @@ -2190,7 +2310,7 @@ void t_py_generator::generate_deserialize_container(ofstream& out, t_type* ttype /** * Generates code to deserialize a map */ -void t_py_generator::generate_deserialize_map_element(ofstream& out, t_map* tmap, string prefix) { +void t_py_generator::generate_deserialize_map_element(ostream& out, t_map* tmap, string prefix) { string key = tmp("_key"); string val = tmp("_val"); t_field fkey(tmap->get_key_type(), key); @@ -2205,7 +2325,7 @@ void t_py_generator::generate_deserialize_map_element(ofstream& out, t_map* tmap /** * Write a set element */ -void t_py_generator::generate_deserialize_set_element(ofstream& out, t_set* tset, string prefix) { +void t_py_generator::generate_deserialize_set_element(ostream& out, t_set* tset, string prefix) { string elem = tmp("_elem"); t_field felem(tset->get_elem_type(), elem); @@ -2217,7 +2337,7 @@ void t_py_generator::generate_deserialize_set_element(ofstream& out, t_set* tset /** * Write a list element */ -void t_py_generator::generate_deserialize_list_element(ofstream& out, +void t_py_generator::generate_deserialize_list_element(ostream& out, t_list* tlist, string prefix) { string elem = tmp("_elem"); @@ -2234,7 +2354,7 @@ void t_py_generator::generate_deserialize_list_element(ofstream& out, * @param tfield The field to serialize * @param prefix Name to prepend to field name */ -void t_py_generator::generate_serialize_field(ofstream& out, t_field* tfield, string prefix) { +void t_py_generator::generate_serialize_field(ostream& out, t_field* tfield, string prefix) { t_type* type = get_true_type(tfield->get_type()); // Do nothing for void types @@ -2259,7 +2379,7 @@ void t_py_generator::generate_serialize_field(ofstream& out, t_field* tfield, st throw "compiler error: cannot serialize void field in a struct: " + name; break; case t_base_type::TYPE_STRING: - if (((t_base_type*)type)->is_binary()) { + if (type->is_binary()) { out << "writeBinary(" << name << ")"; } else if (!gen_utf8strings_) { out << "writeString(" << name << ")"; @@ -2306,12 +2426,12 @@ void t_py_generator::generate_serialize_field(ofstream& out, t_field* tfield, st * @param tstruct The struct to serialize * @param prefix String prefix to attach to all fields */ -void t_py_generator::generate_serialize_struct(ofstream& out, t_struct* tstruct, string prefix) { +void t_py_generator::generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix) { (void)tstruct; indent(out) << prefix << ".write(oprot)" << endl; } -void t_py_generator::generate_serialize_container(ofstream& out, t_type* ttype, string prefix) { +void t_py_generator::generate_serialize_container(ostream& out, t_type* ttype, string prefix) { if (ttype->is_map()) { indent(out) << "oprot.writeMapBegin(" << type_to_enum(((t_map*)ttype)->get_key_type()) << ", " << type_to_enum(((t_map*)ttype)->get_val_type()) << ", " @@ -2359,7 +2479,7 @@ void t_py_generator::generate_serialize_container(ofstream& out, t_type* ttype, * Serializes the members of a map. * */ -void t_py_generator::generate_serialize_map_element(ofstream& out, +void t_py_generator::generate_serialize_map_element(ostream& out, t_map* tmap, string kiter, string viter) { @@ -2373,7 +2493,7 @@ void t_py_generator::generate_serialize_map_element(ofstream& out, /** * Serializes the members of a set. */ -void t_py_generator::generate_serialize_set_element(ofstream& out, t_set* tset, string iter) { +void t_py_generator::generate_serialize_set_element(ostream& out, t_set* tset, string iter) { t_field efield(tset->get_elem_type(), iter); generate_serialize_field(out, &efield, ""); } @@ -2381,7 +2501,7 @@ void t_py_generator::generate_serialize_set_element(ofstream& out, t_set* tset, /** * Serializes the members of a list. */ -void t_py_generator::generate_serialize_list_element(ofstream& out, t_list* tlist, string iter) { +void t_py_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string iter) { t_field efield(tlist->get_elem_type(), iter); generate_serialize_field(out, &efield, ""); } @@ -2389,21 +2509,21 @@ void t_py_generator::generate_serialize_list_element(ofstream& out, t_list* tlis /** * Generates the docstring for a given struct. */ -void t_py_generator::generate_python_docstring(ofstream& out, t_struct* tstruct) { +void t_py_generator::generate_python_docstring(ostream& out, t_struct* tstruct) { generate_python_docstring(out, tstruct, tstruct, "Attributes"); } /** * Generates the docstring for a given function. */ -void t_py_generator::generate_python_docstring(ofstream& out, t_function* tfunction) { +void t_py_generator::generate_python_docstring(ostream& out, t_function* tfunction) { generate_python_docstring(out, tfunction, tfunction->get_arglist(), "Parameters"); } /** * Generates the docstring for a struct or function. */ -void t_py_generator::generate_python_docstring(ofstream& out, +void t_py_generator::generate_python_docstring(ostream& out, t_doc* tdoc, t_struct* tstruct, const char* subheader) { @@ -2441,7 +2561,7 @@ void t_py_generator::generate_python_docstring(ofstream& out, /** * Generates the docstring for a generic object. */ -void t_py_generator::generate_python_docstring(ofstream& out, t_doc* tdoc) { +void t_py_generator::generate_python_docstring(ostream& out, t_doc* tdoc) { if (tdoc->has_doc()) { generate_docstring_comment(out, "\"\"\"\n", "", tdoc->get_doc(), "\"\"\"\n"); } @@ -2456,7 +2576,7 @@ string t_py_generator::declare_argument(t_field* tfield) { std::ostringstream result; result << tfield->get_name() << "="; if (tfield->get_value() != NULL) { - result << "thrift_spec[" << tfield->get_key() << "][4]"; + result << render_field_default_value(tfield); } else { result << "None"; } @@ -2488,7 +2608,7 @@ string t_py_generator::function_signature(t_function* tfunction, bool interface) vector post; string signature = tfunction->get_name() + "("; - if (!(gen_twisted_ && interface)) { + if (!(gen_zope_interface_ && interface)) { pre.push_back("self"); } @@ -2599,7 +2719,7 @@ string t_py_generator::type_to_spec_args(t_type* ttype) { ttype = ((t_typedef*)ttype)->get_type(); } - if (ttype->is_base_type() && reinterpret_cast(ttype)->is_binary()) { + if (ttype->is_binary()) { return "'BINARY'"; } else if (gen_utf8strings_ && ttype->is_base_type() && reinterpret_cast(ttype)->is_string()) { @@ -2607,7 +2727,7 @@ string t_py_generator::type_to_spec_args(t_type* ttype) { } else if (ttype->is_base_type() || ttype->is_enum()) { return "None"; } else if (ttype->is_struct() || ttype->is_xception()) { - return "(" + type_name(ttype) + ", " + type_name(ttype) + ".thrift_spec)"; + return "[" + type_name(ttype) + ", None]"; } else if (ttype->is_map()) { return "(" + type_to_enum(((t_map*)ttype)->get_key_type()) + ", " + type_to_spec_args(((t_map*)ttype)->get_key_type()) + ", " @@ -2632,6 +2752,7 @@ string t_py_generator::type_to_spec_args(t_type* ttype) { THRIFT_REGISTER_GENERATOR( py, "Python", + " zope.interface: Generate code for use with zope.interface.\n" " twisted: Generate Twisted-friendly RPC services.\n" " tornado: Generate code for use with Tornado.\n" " no_utf8strings: Do not Encode/decode strings using utf8 in the generated code. Basically no effect for Python 3.\n" diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_rb_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_rb_generator.cc index 924f6f6..13ea249 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_rb_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_rb_generator.cc @@ -113,6 +113,7 @@ public: void generate_enum(t_enum* tenum); void generate_const(t_const* tconst); void generate_struct(t_struct* tstruct); + void generate_forward_declaration(t_struct* tstruct); void generate_union(t_struct* tunion); void generate_xception(t_struct* txception); void generate_service(t_service* tservice); @@ -123,6 +124,7 @@ public: * Struct generation code */ + void generate_rb_struct_declaration(t_rb_ofstream& out, t_struct* tstruct, bool is_exception); void generate_rb_struct(t_rb_ofstream& out, t_struct* tstruct, bool is_exception); void generate_rb_struct_required_validator(t_rb_ofstream& out, t_struct* tstruct); void generate_rb_union(t_rb_ofstream& out, t_struct* tstruct, bool is_exception); @@ -455,8 +457,8 @@ t_rb_ofstream& t_rb_generator::render_const_value(t_rb_ofstream& out, out.indent_up(); const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { t_type* field_type = NULL; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { @@ -478,8 +480,8 @@ t_rb_ofstream& t_rb_generator::render_const_value(t_rb_ofstream& out, t_type* vtype = ((t_map*)type)->get_val_type(); out << "{" << endl; out.indent_up(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { out.indent(); render_const_value(out, ktype, v_iter->first) << " => "; @@ -529,6 +531,29 @@ void t_rb_generator::generate_struct(t_struct* tstruct) { } } + +/** + * Generates the "forward declarations" for ruby structs. + * These are simply a declaration of each class with proper inheritance. + * The rest of the struct is still generated in generate_struct as has + * always been the case. These declarations allow thrift to generate valid + * ruby in cases where thrift structs rely on recursive definitions. + */ +void t_rb_generator::generate_forward_declaration(t_struct* tstruct) { + generate_rb_struct_declaration(f_types_, tstruct, tstruct->is_xception()); +} + +void t_rb_generator::generate_rb_struct_declaration(t_rb_ofstream& out, t_struct* tstruct, bool is_exception) { + out.indent() << "class " << type_name(tstruct); + if (tstruct->is_union()) { + out << " < ::Thrift::Union"; + } + if (is_exception) { + out << " < ::Thrift::Exception"; + } + out << "; end" << endl << endl; +} + /** * Generates a struct definition for a thrift exception. Basically the same * as a struct but extends the Exception class. diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_rs_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_rs_generator.cc new file mode 100644 index 0000000..9843d7a --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_rs_generator.cc @@ -0,0 +1,3339 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +#include +#include +#include + +#include "thrift/platform.h" +#include "thrift/generate/t_generator.h" + +using std::map; +using std::ofstream; +using std::ostringstream; +using std::string; +using std::vector; +using std::set; + +static const string endl("\n"); // avoid ostream << std::endl flushes +static const string SERVICE_RESULT_VARIABLE("result_value"); +static const string RESULT_STRUCT_SUFFIX("Result"); +static const string RUST_RESERVED_WORDS[] = { + "abstract", "alignof", "as", "become", + "box", "break", "const", "continue", + "crate", "do", "else", "enum", + "extern", "false", "final", "fn", + "for", "if", "impl", "in", + "let", "loop", "macro", "match", + "mod", "move", "mut", "offsetof", + "override", "priv", "proc", "pub", + "pure", "ref", "return", "Self", + "self", "sizeof", "static", "struct", + "super", "trait", "true", "type", + "typeof", "unsafe", "unsized", "use", + "virtual", "where", "while", "yield" +}; +const set RUST_RESERVED_WORDS_SET( + RUST_RESERVED_WORDS, + RUST_RESERVED_WORDS + sizeof(RUST_RESERVED_WORDS)/sizeof(RUST_RESERVED_WORDS[0]) +); + +static const string SYNC_CLIENT_GENERIC_BOUND_VARS(""); +static const string SYNC_CLIENT_GENERIC_BOUNDS("where IP: TInputProtocol, OP: TOutputProtocol"); + +// FIXME: extract common TMessageIdentifier function +// FIXME: have to_rust_type deal with Option + +class t_rs_generator : public t_generator { +public: + t_rs_generator( + t_program* program, + const std::map&, + const std::string& + ) : t_generator(program) { + gen_dir_ = get_out_dir(); + } + + /** + * Init and close methods + */ + + void init_generator(); + void close_generator(); + + /** + * Program-level generation functions + */ + + void generate_typedef(t_typedef* ttypedef); + void generate_enum(t_enum* tenum); + void generate_const(t_const* tconst); + void generate_struct(t_struct* tstruct); + void generate_xception(t_struct* txception); + void generate_service(t_service* tservice); + +private: + // struct type + // T_REGULAR: user-defined struct in the IDL + // T_ARGS: struct used to hold all service-call parameters + // T_RESULT: struct used to hold all service-call returns and exceptions + // T_EXCEPTION: user-defined exception in the IDL + enum e_struct_type { T_REGULAR, T_ARGS, T_RESULT, T_EXCEPTION }; + + // Directory to which generated code is written. + string gen_dir_; + + // File to which generated code is written. + ofstream_with_content_based_conditional_update f_gen_; + + // Write the common compiler attributes and module includes to the top of the auto-generated file. + void render_attributes_and_includes(); + + // Create the closure of Rust modules referenced by this service. + void compute_service_referenced_modules(t_service *tservice, set &referenced_modules); + + // Write the rust representation of an enum. + void render_enum_definition(t_enum* tenum, const string& enum_name); + + // Write the impl blocks associated with the traits necessary to convert an enum to/from an i32. + void render_enum_conversion(t_enum* tenum, const string& enum_name); + + // Write the impl block associated with the rust representation of an enum. This includes methods + // to write the enum to a protocol, read it from a protocol, etc. + void render_enum_impl(const string& enum_name); + + // Write a simple rust const value (ie. `pub const FOO: foo...`). + void render_const_value(const string& name, t_type* ttype, t_const_value* tvalue); + + // Write a constant list, set, map or struct. These constants require allocation and cannot be defined + // using a 'pub const'. As a result, I create a holder struct with a single `const_value` method that + // returns the initialized instance. + void render_const_value_holder(const string& name, t_type* ttype, t_const_value* tvalue); + + // Write the actual const value - the right side of a const definition. + void render_const_value(t_type* ttype, t_const_value* tvalue, bool is_owned = true); + + // Write a const struct (returned from `const_value` method). + void render_const_struct(t_type* ttype, t_const_value* tvalue); + + // Write a const list (returned from `const_value` method). + void render_const_list(t_type* ttype, t_const_value* tvalue); + + // Write a const set (returned from `const_value` method). + void render_const_set(t_type* ttype, t_const_value* tvalue); + + // Write a const map (returned from `const_value` method). + void render_const_map(t_type* ttype, t_const_value* tvalue); + + // Write the code to insert constant values into a rust vec or set. The + // `insert_function` is the rust function that we'll use to insert the elements. + void render_container_const_value( + const string& insert_function, + t_type* ttype, + t_const_value* tvalue + ); + + // Write the rust representation of a thrift struct to the generated file. Set `struct_type` to `T_ARGS` + // if rendering the struct used to pack arguments for a service call. When `struct_type` is `T_ARGS` the + // struct and its members have module visibility, and all fields are required. When `struct_type` is + // anything else the struct and its members have public visibility and fields have the visibility set + // in their definition. + void render_struct(const string& struct_name, t_struct* tstruct, t_rs_generator::e_struct_type struct_type); + + // Write the comment block preceding a type definition (and implementation). + void render_type_comment(const string& struct_name); + + // Write the rust representation of a thrift struct. Supports argument structs, result structs, + // user-defined structs and exception structs. The exact struct type to be generated is controlled + // by the `struct_type` parameter, which (among other things) modifies the visibility of the + // written struct and members, controls which trait implementations are generated. + void render_struct_definition( + const string& struct_name, + t_struct* tstruct, + t_rs_generator::e_struct_type struct_type + ); + + // Writes the impl block associated with the rust representation of a struct. At minimum this + // contains the methods to read from a protocol and write to a protocol. Additional methods may + // be generated depending on `struct_type`. + void render_struct_impl( + const string& struct_name, + t_struct* tstruct, + t_rs_generator::e_struct_type struct_type + ); + + // Generate a `fn new(...)` for a struct with name `struct_name` and type `t_struct`. The auto-generated + // code may include generic type parameters to make the constructor more ergonomic. `struct_type` controls + // the visibility of the generated constructor. + void render_struct_constructor( + const string& struct_name, + t_struct* tstruct, + t_rs_generator::e_struct_type struct_type + ); + + // Write the `ok_or` method added to all Thrift service call result structs. You can use this method + // to convert a struct into a `Result` and use it in a `try!` or combinator chain. + void render_result_struct_to_result_method(t_struct* tstruct); + + // Write the implementations for the `Error` and `Debug` traits. These traits are necessary for a + // user-defined exception to be properly handled as Rust errors. + void render_exception_struct_error_trait_impls(const string& struct_name, t_struct* tstruct); + + // Write the implementations for the `Default`. This trait allows you to specify only the fields you want + // and use `..Default::default()` to fill in the rest. + void render_struct_default_trait_impl(const string& struct_name, t_struct* tstruct); + + // Write the function that serializes a struct to its wire representation. If `struct_type` is `T_ARGS` + // then all fields are considered "required", if not, the default optionality is used. + void render_struct_sync_write(t_struct *tstruct, t_rs_generator::e_struct_type struct_type); + + // Helper function that serializes a single struct field to its wire representation. Unpacks the + // variable (since it may be optional) and serializes according to the optionality rules required by `req`. + // Variables in auto-generated code are passed by reference. Since this function may be called in + // contexts where the variable is *already* a reference you can set `field_var_is_ref` to `true` to avoid + // generating an extra, unnecessary `&` that the compiler will have to automatically dereference. + void render_struct_field_sync_write( + const string &field_var, + bool field_var_is_ref, + t_field *tfield, + t_field::e_req req); + + // Write the rust function that serializes a single type (i.e. a i32 etc.) to its wire representation. + // Variables in auto-generated code are passed by reference. Since this function may be called in + // contexts where the variable is *already* a reference you can set `type_var_is_ref` to `true` to avoid + // generating an extra, unnecessary `&` that the compiler will have to automatically dereference. + void render_type_sync_write(const string &type_var, bool type_var_is_ref, t_type *ttype); + + // Write a list to the output protocol. `list_variable` is the variable containing the list + // that will be written to the output protocol. + // Variables in auto-generated code are passed by reference. Since this function may be called in + // contexts where the variable is *already* a reference you can set `list_var_is_ref` to `true` to avoid + // generating an extra, unnecessary `&` that the compiler will have to automatically dereference. + void render_list_sync_write(const string &list_var, bool list_var_is_ref, t_list *tlist); + + // Write a set to the output protocol. `set_variable` is the variable containing the set that will + // be written to the output protocol. + // Variables in auto-generated code are passed by reference. Since this function may be called in + // contexts where the variable is *already* a reference you can set `set_var_is_ref` to `true` to avoid + // generating an extra, unnecessary `&` that the compiler will have to automatically dereference. + void render_set_sync_write(const string &set_var, bool set_var_is_ref, t_set *tset); + + // Write a map to the output protocol. `map_variable` is the variable containing the map that will + // be written to the output protocol. + // Variables in auto-generated code are passed by reference. Since this function may be called in + // contexts where the variable is *already* a reference you can set `map_var_is_ref` to `true` to avoid + // generating an extra, unnecessary `&` that the compiler will have to automatically dereference. + void render_map_sync_write(const string &map_var, bool map_var_is_ref, t_map *tset); + + // Return `true` if we need to dereference ths type when writing an element from a container. + // Iterations on rust containers are performed as follows: `for v in &values { ... }` + // where `v` has type `&RUST_TYPE` All defined functions take primitives by value, so, if the + // rendered code is calling such a function it has to dereference `v`. + bool needs_deref_on_container_write(t_type* ttype); + + // Return the variable (including all dereferences) required to write values from a rust container + // to the output protocol. For example, if you were iterating through a container and using the temp + // variable `v` to represent each element, then `ttype` is the type stored in the container and + // `base_var` is "v". The return value is the actual string you will have to use to properly reference + // the temp variable for writing to the output protocol. + string string_container_write_variable(t_type* ttype, const string& base_var); + + // Write the code to read bytes from the wire into the given `t_struct`. `struct_name` is the + // actual Rust name of the `t_struct`. If `struct_type` is `T_ARGS` then all struct fields are + // necessary. Otherwise, the field's default optionality is used. + void render_struct_sync_read(const string &struct_name, t_struct *tstruct, t_rs_generator::e_struct_type struct_type); + + // Write the rust function that deserializes a single type (i.e. i32 etc.) from its wire representation. + // Set `is_boxed` to `true` if the resulting value should be wrapped in a `Box::new(...)`. + void render_type_sync_read(const string &type_var, t_type *ttype, bool is_boxed = false); + + // Read the wire representation of a list and convert it to its corresponding rust implementation. + // The deserialized list is stored in `list_variable`. + void render_list_sync_read(t_list *tlist, const string &list_variable); + + // Read the wire representation of a set and convert it to its corresponding rust implementation. + // The deserialized set is stored in `set_variable`. + void render_set_sync_read(t_set *tset, const string &set_variable); + + // Read the wire representation of a map and convert it to its corresponding rust implementation. + // The deserialized map is stored in `map_variable`. + void render_map_sync_read(t_map *tmap, const string &map_variable); + + // Return a temporary variable used to store values when deserializing nested containers. + string struct_field_read_temp_variable(t_field* tfield); + + // Top-level function that calls the various render functions necessary to write the rust representation + // of a thrift union (i.e. an enum). + void render_union(t_struct* tstruct); + + // Write the enum corresponding to the Thrift union. + void render_union_definition(const string& union_name, t_struct* tstruct); + + // Write the enum impl (with read/write functions) for the Thrift union. + void render_union_impl(const string& union_name, t_struct* tstruct); + + // Write the `ENUM::write_to_out_protocol` function. + void render_union_sync_write(const string &union_name, t_struct *tstruct); + + // Write the `ENUM::read_from_in_protocol` function. + void render_union_sync_read(const string &union_name, t_struct *tstruct); + + // Top-level function that calls the various render functions necessary to write the rust representation + // of a Thrift client. + void render_sync_client(t_service* tservice); + + // Write the trait with the service-call methods for `tservice`. + void render_sync_client_trait(t_service *tservice); + + // Write the trait to be implemented by the client impl if end users can use it to make service calls. + void render_sync_client_marker_trait(t_service *tservice); + + // Write the code to create the Thrift service sync client struct and its matching 'impl' block. + void render_sync_client_definition_and_impl(const string& client_impl_name); + + // Write the code to create the `SyncClient::new` functions as well as any other functions + // callers would like to use on the Thrift service sync client. + void render_sync_client_lifecycle_functions(const string& client_struct); + + // Write the code to create the impl block for the `TThriftClient` trait. Since generated + // Rust Thrift clients perform all their operations using methods defined in this trait, we + // have to implement it for the client structs. + void render_sync_client_tthriftclient_impl(const string &client_impl_name); + + // Write the marker traits for any service(s) being extended, including the one for the current + // service itself (i.e. `tservice`) + void render_sync_client_marker_trait_impls(t_service *tservice, const string &impl_struct_name); + + // Generate a list of all the traits this Thrift client struct extends. + string sync_client_marker_traits_for_extension(t_service *tservice); + + // Top-level function that writes the code to make the Thrift service calls. + void render_sync_client_process_impl(t_service* tservice); + + // Write the actual function that calls out to the remote service and processes its response. + void render_sync_send_recv_wrapper(t_function* tfunc); + + // Write the `send` functionality for a Thrift service call represented by a `t_service->t_function`. + void render_sync_send(t_function* tfunc); + + // Write the `recv` functionality for a Thrift service call represented by a `t_service->t_function`. + // This method is only rendered if the function is *not* oneway. + void render_sync_recv(t_function* tfunc); + + void render_sync_processor(t_service *tservice); + + void render_sync_handler_trait(t_service *tservice); + void render_sync_processor_definition_and_impl(t_service *tservice); + void render_sync_process_delegation_functions(t_service *tservice); + void render_sync_process_function(t_function *tfunc, const string &handler_type); + void render_process_match_statements(t_service* tservice); + void render_sync_handler_succeeded(t_function *tfunc); + void render_sync_handler_failed(t_function *tfunc); + void render_sync_handler_failed_user_exception_branch(t_function *tfunc); + void render_sync_handler_failed_application_exception_branch(t_function *tfunc, const string &app_err_var); + void render_sync_handler_failed_default_exception_branch(t_function *tfunc); + void render_sync_handler_send_exception_response(t_function *tfunc, const string &err_var); + void render_service_call_structs(t_service* tservice); + void render_service_call_args_struct(t_function* tfunc); + void render_service_call_result_value_struct(t_function* tfunc); + + string handler_successful_return_struct(t_function* tfunc); + + // Writes the result of `render_thrift_error_struct` wrapped in an `Err(thrift::Error(...))`. + void render_thrift_error( + const string& error_kind, + const string& error_struct, + const string& sub_error_kind, + const string& error_message + ); + + // Write a thrift::Error variant struct. Error structs take the form: + // ``` + // pub struct error_struct { + // kind: sub_error_kind, + // message: error_message, + // } + // ``` + // A concrete example is: + // ``` + // pub struct ApplicationError { + // kind: ApplicationErrorKind::Unknown, + // message: "This is some error message", + // } + // ``` + void render_thrift_error_struct( + const string& error_struct, + const string& sub_error_kind, + const string& error_message + ); + + // Return a string containing all the unpacked service call args given a service call function + // `t_function`. Prepends the args with either `&mut self` or `&self` and includes the arg types + // in the returned string, for example: + // `fn foo(&mut self, field_0: String)`. + string rust_sync_service_call_declaration(t_function* tfunc, bool self_is_mutable); + + // Return a string containing all the unpacked service call args given a service call function + // `t_function`. Only includes the arg names, each of which is prefixed with the optional prefix + // `field_prefix`, for example: `self.field_0`. + string rust_sync_service_call_invocation(t_function* tfunc, const string& field_prefix = ""); + + // Return a string containing all fields in the struct `tstruct` for use in a function declaration. + // Each field is followed by its type, for example: `field_0: String`. + string struct_to_declaration(t_struct* tstruct, t_rs_generator::e_struct_type struct_type); + + // Return a string containing all fields in the struct `tstruct` for use in a function call, + // for example: `field_0: String`. + string struct_to_invocation(t_struct* tstruct, const string& field_prefix = ""); + + // Write the documentation for a struct, service-call or other documentation-annotated element. + void render_rustdoc(t_doc* tdoc); + + // Return `true` if the true type of `ttype` is a thrift double, `false` otherwise. + bool is_double(t_type* ttype); + + // Return a string representing the rust type given a `t_type`. + string to_rust_type(t_type* ttype, bool ordered_float = true); + + // Return a string representing the `const` rust type given a `t_type` + string to_rust_const_type(t_type* ttype, bool ordered_float = true); + + // Return a string representing the rift `protocol::TType` given a `t_type`. + string to_rust_field_type_enum(t_type* ttype); + + // Return the default value to be used when initializing a struct field which has `OPT_IN_REQ_OUT` + // optionality. + string opt_in_req_out_value(t_type* ttype); + + // Return `true` if we can write a const of the form `pub const FOO: ...`. + bool can_generate_simple_const(t_type* ttype); + + // Return `true` if we cannot write a standard Rust constant (because the type needs some allocation). + bool can_generate_const_holder(t_type* ttype); + + // Return `true` if this type is a void, and should be represented by the rust `()` type. + bool is_void(t_type* ttype); + + t_field::e_req actual_field_req(t_field* tfield, t_rs_generator::e_struct_type struct_type); + + // Return `true` if this `t_field::e_req` is either `t_field::T_OPTIONAL` or `t_field::T_OPT_IN_REQ_OUT` + // and needs to be wrapped by an `Option`, `false` otherwise. + bool is_optional(t_field::e_req req); + + // Return `true` if the service call has arguments, `false` otherwise. + bool has_args(t_function* tfunc); + + // Return `true` if a service call has non-`()` arguments, `false` otherwise. + bool has_non_void_args(t_function* tfunc); + + // Return `pub ` (notice trailing whitespace!) if the struct should be public, `` (empty string) otherwise. + string visibility_qualifier(t_rs_generator::e_struct_type struct_type); + + // Returns the namespace prefix for a given Thrift service. If the type is defined in the presently-computed + // Thrift program, then an empty string is returned. + string rust_namespace(t_service* tservice); + + // Returns the namespace prefix for a given Thrift type. If the type is defined in the presently-computed + // Thrift program, then an empty string is returned. + string rust_namespace(t_type* ttype); + + // Returns the camel-cased name for a Rust struct type. Handles the case where `tstruct->get_name()` is + // a reserved word. + string rust_struct_name(t_struct* tstruct); + + // Returns the snake-cased name for a Rust field or local variable. Handles the case where + // `tfield->get_name()` is a reserved word. + string rust_field_name(t_field* tstruct); + + // Returns the camel-cased name for a Rust union type. Handles the case where `tstruct->get_name()` is + // a reserved word. + string rust_union_field_name(t_field* tstruct); + + // Converts any variable name into a 'safe' variant that does not clash with any Rust reserved keywords. + string rust_safe_name(const string& name); + + // Return `true` if the name is a reserved Rust keyword, `false` otherwise. + bool is_reserved(const string& name); + + // Return the name of the function that users will invoke to make outgoing service calls. + string service_call_client_function_name(t_function* tfunc); + + // Return the name of the function that users will have to implement to handle incoming service calls. + string service_call_handler_function_name(t_function* tfunc); + + // Return the name of the struct used to pack the arguments for the thrift service call. + string service_call_args_struct_name(t_function* tfunc); + + // Return the name of the struct used to pack the return value + // and user-defined exceptions for the thrift service call. + string service_call_result_struct_name(t_function* tfunc); + + string rust_sync_client_marker_trait_name(t_service* tservice); + + // Return the trait name for the sync service client given a `t_service`. + string rust_sync_client_trait_name(t_service* tservice); + + // Return the name for the sync service client struct given a `t_service`. + string rust_sync_client_impl_name(t_service* tservice); + + // Return the trait name that users will have to implement for the server half of a Thrift service. + string rust_sync_handler_trait_name(t_service* tservice); + + // Return the struct name for the server half of a Thrift service. + string rust_sync_processor_name(t_service* tservice); + + // Return the struct name for the struct that contains all the service-call implementations for + // the server half of a Thrift service. + string rust_sync_processor_impl_name(t_service *tservice); + + // Return the variant name for an enum variant + string rust_enum_variant_name(const string& name); + + // Properly uppercase names for use in Rust. + string rust_upper_case(const string& name); + + // Snake-case field, parameter and function names and make them Rust friendly. + string rust_snake_case(const string& name); + + // Camel-case type/variant names and make them Rust friendly. + string rust_camel_case(const string& name); + + // Replace all instances of `search_string` with `replace_string` in `target`. + void string_replace(string& target, const string& search_string, const string& replace_string); +}; + +void t_rs_generator::init_generator() { + // make output directory for this thrift program + MKDIR(gen_dir_.c_str()); + + // create the file into which we're going to write the generated code + string f_gen_name = gen_dir_ + "/" + rust_snake_case(get_program()->get_name()) + ".rs"; + f_gen_.open(f_gen_name.c_str()); + + // header comment + f_gen_ << "// " << autogen_summary() << endl; + f_gen_ << "// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING" << endl; + f_gen_ << endl; + + render_attributes_and_includes(); +} + +void t_rs_generator::render_attributes_and_includes() { + // turn off some compiler/clippy warnings + + // code always includes BTreeMap/BTreeSet/OrderedFloat + f_gen_ << "#![allow(unused_imports)]" << endl; + // code might not include imports from crates + f_gen_ << "#![allow(unused_extern_crates)]" << endl; + // constructors take *all* struct parameters, which can trigger the "too many arguments" warning + // some auto-gen'd types can be deeply nested. clippy recommends factoring them out which is hard to autogen + f_gen_ << "#![cfg_attr(feature = \"cargo-clippy\", allow(too_many_arguments, type_complexity))]" << endl; + // prevent rustfmt from running against this file + // lines are too long, code is (thankfully!) not visual-indented, etc. + f_gen_ << "#![cfg_attr(rustfmt, rustfmt_skip)]" << endl; + f_gen_ << endl; + + // add standard includes + f_gen_ << "extern crate ordered_float;" << endl; + f_gen_ << "extern crate thrift;" << endl; + f_gen_ << "extern crate try_from;" << endl; + f_gen_ << endl; + f_gen_ << "use ordered_float::OrderedFloat;" << endl; + f_gen_ << "use std::cell::RefCell;" << endl; + f_gen_ << "use std::collections::{BTreeMap, BTreeSet};" << endl; + f_gen_ << "use std::convert::From;" << endl; + f_gen_ << "use std::default::Default;" << endl; + f_gen_ << "use std::error::Error;" << endl; + f_gen_ << "use std::fmt;" << endl; + f_gen_ << "use std::fmt::{Display, Formatter};" << endl; + f_gen_ << "use std::rc::Rc;" << endl; + f_gen_ << "use try_from::TryFrom;" << endl; + f_gen_ << endl; + f_gen_ << "use thrift::{ApplicationError, ApplicationErrorKind, ProtocolError, ProtocolErrorKind, TThriftClient};" << endl; + f_gen_ << "use thrift::protocol::{TFieldIdentifier, TListIdentifier, TMapIdentifier, TMessageIdentifier, TMessageType, TInputProtocol, TOutputProtocol, TSetIdentifier, TStructIdentifier, TType};" << endl; + f_gen_ << "use thrift::protocol::field_id;" << endl; + f_gen_ << "use thrift::protocol::verify_expected_message_type;" << endl; + f_gen_ << "use thrift::protocol::verify_expected_sequence_number;" << endl; + f_gen_ << "use thrift::protocol::verify_expected_service_call;" << endl; + f_gen_ << "use thrift::protocol::verify_required_field_exists;" << endl; + f_gen_ << "use thrift::server::TProcessor;" << endl; + f_gen_ << endl; + + // add all the program includes + // NOTE: this is more involved than you would expect because of service extension + // Basically, I have to find the closure of all the services and include their modules at the top-level + + set referenced_modules; + + // first, start by adding explicit thrift includes + const vector includes = get_program()->get_includes(); + vector::const_iterator includes_iter; + for(includes_iter = includes.begin(); includes_iter != includes.end(); ++includes_iter) { + referenced_modules.insert((*includes_iter)->get_name()); + } + + // next, recursively iterate through all the services and add the names of any programs they reference + const vector services = get_program()->get_services(); + vector::const_iterator service_iter; + for (service_iter = services.begin(); service_iter != services.end(); ++service_iter) { + compute_service_referenced_modules(*service_iter, referenced_modules); + } + + // finally, write all the "pub use..." declarations + if (!referenced_modules.empty()) { + set::iterator module_iter; + for (module_iter = referenced_modules.begin(); module_iter != referenced_modules.end(); ++module_iter) { + f_gen_ << "use " << rust_snake_case(*module_iter) << ";" << endl; + } + f_gen_ << endl; + } +} + +void t_rs_generator::compute_service_referenced_modules( + t_service *tservice, + set &referenced_modules +) { + t_service* extends = tservice->get_extends(); + if (extends) { + if (extends->get_program() != get_program()) { + referenced_modules.insert(extends->get_program()->get_name()); + } + compute_service_referenced_modules(extends, referenced_modules); + } +} + +void t_rs_generator::close_generator() { + f_gen_.close(); +} + +//----------------------------------------------------------------------------- +// +// Consts +// +// NOTE: consider using macros to generate constants +// +//----------------------------------------------------------------------------- + +// This is worse than it should be because constants +// aren't (sensibly) limited to scalar types +void t_rs_generator::generate_const(t_const* tconst) { + string name = tconst->get_name(); + t_type* ttype = tconst->get_type(); + t_const_value* tvalue = tconst->get_value(); + + if (can_generate_simple_const(ttype)) { + render_const_value(name, ttype, tvalue); + } else if (can_generate_const_holder(ttype)) { + render_const_value_holder(name, ttype, tvalue); + } else { + throw "cannot generate const for " + name; + } +} + +void t_rs_generator::render_const_value(const string& name, t_type* ttype, t_const_value* tvalue) { + if (!can_generate_simple_const(ttype)) { + throw "cannot generate simple rust constant for " + ttype->get_name(); + } + + f_gen_ << "pub const " << rust_upper_case(name) << ": " << to_rust_const_type(ttype) << " = "; + render_const_value(ttype, tvalue, false); + f_gen_ << ";" << endl; + f_gen_ << endl; +} + +void t_rs_generator::render_const_value_holder(const string& name, t_type* ttype, t_const_value* tvalue) { + if (!can_generate_const_holder(ttype)) { + throw "cannot generate constant holder for " + ttype->get_name(); + } + + string holder_name("Const" + rust_camel_case(name)); + + f_gen_ << indent() << "pub struct " << holder_name << ";" << endl; + f_gen_ << indent() << "impl " << holder_name << " {" << endl; + indent_up(); + + f_gen_ << indent() << "pub fn const_value() -> " << to_rust_type(ttype) << " {" << endl; + indent_up(); + render_const_value(ttype, tvalue); + indent_down(); + f_gen_ << indent() << "}" << endl; + + indent_down(); + f_gen_ << indent() << "}" << endl; + f_gen_ << endl; +} + +void t_rs_generator::render_const_value(t_type* ttype, t_const_value* tvalue, bool is_owned) { + if (ttype->is_base_type()) { + t_base_type* tbase_type = (t_base_type*)ttype; + switch (tbase_type->get_base()) { + case t_base_type::TYPE_STRING: + if (tbase_type->is_binary()) { + if (is_owned) { + f_gen_ << "\"" << tvalue->get_string() << "\""<< ".to_owned().into_bytes()"; + } else { + f_gen_ << "b\"" << tvalue->get_string() << "\""; + } + } else { + f_gen_ << "\"" << tvalue->get_string() << "\""; + if (is_owned) { + f_gen_ << ".to_owned()"; + } + } + break; + case t_base_type::TYPE_BOOL: + f_gen_ << (tvalue->get_integer() ? "true" : "false"); + break; + case t_base_type::TYPE_I8: + case t_base_type::TYPE_I16: + case t_base_type::TYPE_I32: + case t_base_type::TYPE_I64: + f_gen_ << tvalue->get_integer(); + break; + case t_base_type::TYPE_DOUBLE: + f_gen_ << "OrderedFloat::from(" << tvalue->get_double() << " as f64)"; + break; + default: + throw "cannot generate const value for " + t_base_type::t_base_name(tbase_type->get_base()); + } + } else if (ttype->is_typedef()) { + render_const_value(get_true_type(ttype), tvalue); + } else if (ttype->is_enum()) { + f_gen_ << indent() << "{" << endl; + indent_up(); + f_gen_ + << indent() + << to_rust_type(ttype) + << "::try_from(" + << tvalue->get_integer() + << ").expect(\"expecting valid const value\")" + << endl; + indent_down(); + f_gen_ << indent() << "}" << endl; + } else if (ttype->is_struct() || ttype->is_xception()) { + render_const_struct(ttype, tvalue); + } else if (ttype->is_container()) { + f_gen_ << indent() << "{" << endl; + indent_up(); + + if (ttype->is_list()) { + render_const_list(ttype, tvalue); + } else if (ttype->is_set()) { + render_const_set(ttype, tvalue); + } else if (ttype->is_map()) { + render_const_map(ttype, tvalue); + } else { + throw "cannot generate const container value for " + ttype->get_name(); + } + + indent_down(); + f_gen_ << indent() << "}" << endl; + } else { + throw "cannot generate const value for " + ttype->get_name(); + } +} + +void t_rs_generator::render_const_struct(t_type* ttype, t_const_value*) { + if (((t_struct*)ttype)->is_union()) { + f_gen_ << indent() << "{" << endl; + indent_up(); + f_gen_ << indent() << "unimplemented!()" << endl; + indent_down(); + f_gen_ << indent() << "}" << endl; + } else { + f_gen_ << indent() << "{" << endl; + indent_up(); + f_gen_ << indent() << "unimplemented!()" << endl; + indent_down(); + f_gen_ << indent() << "}" << endl; + } +} + +void t_rs_generator::render_const_list(t_type* ttype, t_const_value* tvalue) { + t_type* elem_type = ((t_list*)ttype)->get_elem_type(); + f_gen_ << indent() << "let mut l: Vec<" << to_rust_type(elem_type) << "> = Vec::new();" << endl; + const vector& elems = tvalue->get_list(); + vector::const_iterator elem_iter; + for(elem_iter = elems.begin(); elem_iter != elems.end(); ++elem_iter) { + t_const_value* elem_value = (*elem_iter); + render_container_const_value("l.push", elem_type, elem_value); + } + f_gen_ << indent() << "l" << endl; +} + +void t_rs_generator::render_const_set(t_type* ttype, t_const_value* tvalue) { + t_type* elem_type = ((t_set*)ttype)->get_elem_type(); + f_gen_ << indent() << "let mut s: BTreeSet<" << to_rust_type(elem_type) << "> = BTreeSet::new();" << endl; + const vector& elems = tvalue->get_list(); + vector::const_iterator elem_iter; + for(elem_iter = elems.begin(); elem_iter != elems.end(); ++elem_iter) { + t_const_value* elem_value = (*elem_iter); + render_container_const_value("s.insert", elem_type, elem_value); + } + f_gen_ << indent() << "s" << endl; +} + +void t_rs_generator::render_const_map(t_type* ttype, t_const_value* tvalue) { + t_type* key_type = ((t_map*)ttype)->get_key_type(); + t_type* val_type = ((t_map*)ttype)->get_val_type(); + f_gen_ + << indent() + << "let mut m: BTreeMap<" + << to_rust_type(key_type) << ", " << to_rust_type(val_type) + << "> = BTreeMap::new();" + << endl; + const map& elems = tvalue->get_map(); + map::const_iterator elem_iter; + for (elem_iter = elems.begin(); elem_iter != elems.end(); ++elem_iter) { + t_const_value* key_value = elem_iter->first; + t_const_value* val_value = elem_iter->second; + if (get_true_type(key_type)->is_base_type()) { + f_gen_ << indent() << "let k = "; + render_const_value(key_type, key_value); + f_gen_ << ";" << endl; + } else { + f_gen_ << indent() << "let k = {" << endl; + indent_up(); + render_const_value(key_type, key_value); + indent_down(); + f_gen_ << indent() << "};" << endl; + } + if (get_true_type(val_type)->is_base_type()) { + f_gen_ << indent() << "let v = "; + render_const_value(val_type, val_value); + f_gen_ << ";" << endl; + } else { + f_gen_ << indent() << "let v = {" << endl; + indent_up(); + render_const_value(val_type, val_value); + indent_down(); + f_gen_ << indent() << "};" << endl; + } + f_gen_ << indent() << "m.insert(k, v);" << endl; + } + f_gen_ << indent() << "m" << endl; +} + +void t_rs_generator::render_container_const_value( + const string& insert_function, + t_type* ttype, + t_const_value* tvalue +) { + if (get_true_type(ttype)->is_base_type()) { + f_gen_ << indent() << insert_function << "("; + render_const_value(ttype, tvalue); + f_gen_ << ");" << endl; + } else { + f_gen_ << indent() << insert_function << "(" << endl; + indent_up(); + render_const_value(ttype, tvalue); + indent_down(); + f_gen_ << indent() << ");" << endl; + } +} + +//----------------------------------------------------------------------------- +// +// Typedefs +// +//----------------------------------------------------------------------------- + +void t_rs_generator::generate_typedef(t_typedef* ttypedef) { + std::string actual_type = to_rust_type(ttypedef->get_type()); + f_gen_ << "pub type " << rust_safe_name(ttypedef->get_symbolic()) << " = " << actual_type << ";" << endl; + f_gen_ << endl; +} + +//----------------------------------------------------------------------------- +// +// Enums +// +//----------------------------------------------------------------------------- + +void t_rs_generator::generate_enum(t_enum* tenum) { + string enum_name(rust_camel_case(tenum->get_name())); + render_enum_definition(tenum, enum_name); + render_enum_impl(enum_name); + render_enum_conversion(tenum, enum_name); +} + +void t_rs_generator::render_enum_definition(t_enum* tenum, const string& enum_name) { + render_rustdoc((t_doc*) tenum); + f_gen_ << "#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]" << endl; + f_gen_ << "pub enum " << enum_name << " {" << endl; + indent_up(); + + vector constants = tenum->get_constants(); + vector::iterator constants_iter; + for (constants_iter = constants.begin(); constants_iter != constants.end(); ++constants_iter) { + t_enum_value* val = (*constants_iter); + render_rustdoc((t_doc*) val); + f_gen_ + << indent() + << rust_enum_variant_name(val->get_name()) + << " = " + << val->get_value() + << "," + << endl; + } + + indent_down(); + f_gen_ << "}" << endl; + f_gen_ << endl; +} + +void t_rs_generator::render_enum_impl(const string& enum_name) { + f_gen_ << "impl " << enum_name << " {" << endl; + indent_up(); + + f_gen_ + << indent() + << "pub fn write_to_out_protocol(&self, o_prot: &mut TOutputProtocol) -> thrift::Result<()> {" + << endl; + indent_up(); + f_gen_ << indent() << "o_prot.write_i32(*self as i32)" << endl; + indent_down(); + f_gen_ << indent() << "}" << endl; + + f_gen_ + << indent() + << "pub fn read_from_in_protocol(i_prot: &mut TInputProtocol) -> thrift::Result<" << enum_name << "> {" + << endl; + indent_up(); + + f_gen_ << indent() << "let enum_value = i_prot.read_i32()?;" << endl; + f_gen_ << indent() << enum_name << "::try_from(enum_value)"; + + indent_down(); + f_gen_ << indent() << "}" << endl; + + indent_down(); + f_gen_ << "}" << endl; + f_gen_ << endl; +} + +void t_rs_generator::render_enum_conversion(t_enum* tenum, const string& enum_name) { + f_gen_ << "impl TryFrom for " << enum_name << " {" << endl; + indent_up(); + + f_gen_ << indent() << "type Err = thrift::Error;"; + + f_gen_ << indent() << "fn try_from(i: i32) -> Result {" << endl; + indent_up(); + + f_gen_ << indent() << "match i {" << endl; + indent_up(); + + vector constants = tenum->get_constants(); + vector::iterator constants_iter; + for (constants_iter = constants.begin(); constants_iter != constants.end(); ++constants_iter) { + t_enum_value* val = (*constants_iter); + f_gen_ + << indent() + << val->get_value() + << " => Ok(" << enum_name << "::" << rust_enum_variant_name(val->get_name()) << ")," + << endl; + } + f_gen_ << indent() << "_ => {" << endl; + indent_up(); + render_thrift_error( + "Protocol", + "ProtocolError", + "ProtocolErrorKind::InvalidData", + "format!(\"cannot convert enum constant {} to " + enum_name + "\", i)" + ); + indent_down(); + f_gen_ << indent() << "}," << endl; + + indent_down(); + f_gen_ << indent() << "}" << endl; + + indent_down(); + f_gen_ << indent() << "}" << endl; + + indent_down(); + f_gen_ << "}" << endl; + f_gen_ << endl; +} + +//----------------------------------------------------------------------------- +// +// Structs, Unions and Exceptions +// +//----------------------------------------------------------------------------- + +void t_rs_generator::generate_xception(t_struct* txception) { + render_struct(rust_struct_name(txception), txception, t_rs_generator::T_EXCEPTION); +} + +void t_rs_generator::generate_struct(t_struct* tstruct) { + if (tstruct->is_union()) { + render_union(tstruct); + } else if (tstruct->is_struct()) { + render_struct(rust_struct_name(tstruct), tstruct, t_rs_generator::T_REGULAR); + } else { + throw "cannot generate struct for exception"; + } +} + +void t_rs_generator::render_struct( + const string& struct_name, + t_struct* tstruct, + t_rs_generator::e_struct_type struct_type +) { + render_type_comment(struct_name); + render_struct_definition(struct_name, tstruct, struct_type); + render_struct_impl(struct_name, tstruct, struct_type); + if (struct_type == t_rs_generator::T_REGULAR || struct_type == t_rs_generator::T_EXCEPTION) { + render_struct_default_trait_impl(struct_name, tstruct); + } + if (struct_type == t_rs_generator::T_EXCEPTION) { + render_exception_struct_error_trait_impls(struct_name, tstruct); + } +} + +void t_rs_generator::render_struct_definition( + const string& struct_name, + t_struct* tstruct, + t_rs_generator::e_struct_type struct_type +) { + render_rustdoc((t_doc*) tstruct); + f_gen_ << "#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]" << endl; + f_gen_ << visibility_qualifier(struct_type) << "struct " << struct_name << " {" << endl; + + // render the members + vector members = tstruct->get_sorted_members(); + if (!members.empty()) { + indent_up(); + + vector::iterator members_iter; + for(members_iter = members.begin(); members_iter != members.end(); ++members_iter) { + t_field* member = (*members_iter); + t_field::e_req member_req = actual_field_req(member, struct_type); + + string rust_type = to_rust_type(member->get_type()); + rust_type = is_optional(member_req) ? "Option<" + rust_type + ">" : rust_type; + + render_rustdoc((t_doc*) member); + f_gen_ + << indent() + << visibility_qualifier(struct_type) + << rust_field_name(member) << ": " << rust_type << "," + << endl; + } + + indent_down(); + } + + f_gen_ << "}" << endl; + f_gen_ << endl; +} + +void t_rs_generator::render_exception_struct_error_trait_impls(const string& struct_name, t_struct* tstruct) { + // error::Error trait + f_gen_ << "impl Error for " << struct_name << " {" << endl; + indent_up(); + f_gen_ << indent() << "fn description(&self) -> &str {" << endl; + indent_up(); + f_gen_ << indent() << "\"" << "remote service threw " << tstruct->get_name() << "\"" << endl; // use *original* name + indent_down(); + f_gen_ << indent() << "}" << endl; + indent_down(); + f_gen_ << "}" << endl; + f_gen_ << endl; + + // convert::From trait + f_gen_ << "impl From<" << struct_name << "> for thrift::Error {" << endl; + indent_up(); + f_gen_ << indent() << "fn from(e: " << struct_name << ") -> Self {" << endl; + indent_up(); + f_gen_ << indent() << "thrift::Error::User(Box::new(e))" << endl; + indent_down(); + f_gen_ << indent() << "}" << endl; + indent_down(); + f_gen_ << "}" << endl; + f_gen_ << endl; + + // fmt::Display trait + f_gen_ << "impl Display for " << struct_name << " {" << endl; + indent_up(); + f_gen_ << indent() << "fn fmt(&self, f: &mut Formatter) -> fmt::Result {" << endl; + indent_up(); + f_gen_ << indent() << "self.description().fmt(f)" << endl; + indent_down(); + f_gen_ << indent() << "}" << endl; + indent_down(); + f_gen_ << "}" << endl; + f_gen_ << endl; +} + +void t_rs_generator::render_struct_default_trait_impl(const string& struct_name, t_struct* tstruct) { + bool has_required_field = false; + + const vector& members = tstruct->get_sorted_members(); + vector::const_iterator members_iter; + for (members_iter = members.begin(); members_iter != members.end(); ++members_iter) { + t_field* member = *members_iter; + if (!is_optional(member->get_req())) { + has_required_field = true; + break; + } + } + + if (has_required_field) { + return; + } + + f_gen_ << "impl Default for " << struct_name << " {" << endl; + indent_up(); + f_gen_ << indent() << "fn default() -> Self {" << endl; + indent_up(); + + if (members.empty()) { + f_gen_ << indent() << struct_name << "{}" << endl; + } else { + f_gen_ << indent() << struct_name << "{" << endl; + indent_up(); + for (members_iter = members.begin(); members_iter != members.end(); ++members_iter) { + t_field *member = (*members_iter); + string member_name(rust_field_name(member)); + f_gen_ << indent() << member_name << ": " << opt_in_req_out_value(member->get_type()) << "," << endl; + } + indent_down(); + f_gen_ << indent() << "}" << endl; + } + + indent_down(); + f_gen_ << indent() << "}" << endl; + indent_down(); + f_gen_ << "}" << endl; + f_gen_ << endl; +} + +void t_rs_generator::render_struct_impl( + const string& struct_name, + t_struct* tstruct, + t_rs_generator::e_struct_type struct_type +) { + f_gen_ << "impl " << struct_name << " {" << endl; + indent_up(); + + if (struct_type == t_rs_generator::T_REGULAR || struct_type == t_rs_generator::T_EXCEPTION) { + render_struct_constructor(struct_name, tstruct, struct_type); + } + + render_struct_sync_read(struct_name, tstruct, struct_type); + render_struct_sync_write(tstruct, struct_type); + + if (struct_type == t_rs_generator::T_RESULT) { + render_result_struct_to_result_method(tstruct); + } + + indent_down(); + f_gen_ << "}" << endl; + f_gen_ << endl; +} + +void t_rs_generator::render_struct_constructor( + const string& struct_name, + t_struct* tstruct, + t_rs_generator::e_struct_type struct_type +) { + const vector& members = tstruct->get_sorted_members(); + vector::const_iterator members_iter; + + // build the convenience type parameters that allows us to pass unwrapped values to a constructor and + // have them automatically converted into Option + bool first_arg = true; + + ostringstream generic_type_parameters; + ostringstream generic_type_qualifiers; + for(members_iter = members.begin(); members_iter != members.end(); ++members_iter) { + t_field* member = (*members_iter); + t_field::e_req member_req = actual_field_req(member, struct_type); + + if (is_optional(member_req)) { + if (first_arg) { + first_arg = false; + } else { + generic_type_parameters << ", "; + generic_type_qualifiers << ", "; + } + generic_type_parameters << "F" << member->get_key(); + generic_type_qualifiers << "F" << member->get_key() << ": Intoget_type()) << ">>"; + } + } + + string type_parameter_string = generic_type_parameters.str(); + if (type_parameter_string.length() != 0) { + type_parameter_string = "<" + type_parameter_string + ">"; + } + + string type_qualifier_string = generic_type_qualifiers.str(); + if (type_qualifier_string.length() != 0) { + type_qualifier_string = "where " + type_qualifier_string + " "; + } + + // now build the actual constructor arg list + // when we're building this list we have to use the type parameters in place of the actual type names + // if necessary + ostringstream args; + first_arg = true; + for(members_iter = members.begin(); members_iter != members.end(); ++members_iter) { + t_field* member = (*members_iter); + t_field::e_req member_req = actual_field_req(member, struct_type); + string member_name(rust_field_name(member)); + + if (first_arg) { + first_arg = false; + } else { + args << ", "; + } + + if (is_optional(member_req)) { + args << member_name << ": " << "F" << member->get_key(); + } else { + args << member_name << ": " << to_rust_type(member->get_type()); + } + } + + string arg_string = args.str(); + + string visibility(visibility_qualifier(struct_type)); + f_gen_ + << indent() + << visibility + << "fn new" + << type_parameter_string + << "(" + << arg_string + << ") -> " + << struct_name + << " " + << type_qualifier_string + << "{" + << endl; + indent_up(); + + if (members.size() == 0) { + f_gen_ << indent() << struct_name << " {}" << endl; + } else { + f_gen_ << indent() << struct_name << " {" << endl; + indent_up(); + + for(members_iter = members.begin(); members_iter != members.end(); ++members_iter) { + t_field* member = (*members_iter); + t_field::e_req member_req = actual_field_req(member, struct_type); + string member_name(rust_field_name(member)); + + if (is_optional(member_req)) { + f_gen_ << indent() << member_name << ": " << member_name << ".into()," << endl; + } else { + f_gen_ << indent() << member_name << ": " << member_name << "," << endl; + } + } + + indent_down(); + f_gen_ << indent() << "}" << endl; + } + + indent_down(); + f_gen_ << indent() << "}" << endl; +} + +void t_rs_generator::render_result_struct_to_result_method(t_struct* tstruct) { + // we don't use the rust struct name in this method, just the service call name + string service_call_name = tstruct->get_name(); + + // check that we actually have a result + size_t index = service_call_name.find(RESULT_STRUCT_SUFFIX, 0); + if (index == std::string::npos) { + throw "result struct " + service_call_name + " missing result suffix"; + } else { + service_call_name.replace(index, 6, ""); + } + + const vector& members = tstruct->get_sorted_members(); + vector::const_iterator members_iter; + + // find out what the call's expected return type was + string rust_return_type = "()"; + for(members_iter = members.begin(); members_iter != members.end(); ++members_iter) { + t_field* member = (*members_iter); + if (member->get_name() == SERVICE_RESULT_VARIABLE) { // don't have to check safe name here + rust_return_type = to_rust_type(member->get_type()); + break; + } + } + + // NOTE: ideally I would generate the branches and render them separately + // I tried this however, and the resulting code was harder to understand + // maintaining a rendered branch count (while a little ugly) got me the + // rendering I wanted with code that was reasonably understandable + + f_gen_ << indent() << "fn ok_or(self) -> thrift::Result<" << rust_return_type << "> {" << endl; + indent_up(); + + int rendered_branch_count = 0; + + // render the exception branches + for(members_iter = members.begin(); members_iter != members.end(); ++members_iter) { + t_field* tfield = (*members_iter); + if (tfield->get_name() != SERVICE_RESULT_VARIABLE) { // don't have to check safe name here + string field_name("self." + rust_field_name(tfield)); + string branch_statement = rendered_branch_count == 0 ? "if" : "} else if"; + + f_gen_ << indent() << branch_statement << " " << field_name << ".is_some() {" << endl; + indent_up(); + f_gen_ << indent() << "Err(thrift::Error::User(Box::new(" << field_name << ".unwrap())))" << endl; + indent_down(); + + rendered_branch_count++; + } + } + + // render the return value branches + if (rust_return_type == "()") { + if (rendered_branch_count == 0) { + // we have the unit return and this service call has no user-defined + // exceptions. this means that we've a trivial return (happens with oneways) + f_gen_ << indent() << "Ok(())" << endl; + } else { + // we have the unit return, but there are user-defined exceptions + // if we've gotten this far then we have the default return (i.e. call successful) + f_gen_ << indent() << "} else {" << endl; + indent_up(); + f_gen_ << indent() << "Ok(())" << endl; + indent_down(); + f_gen_ << indent() << "}" << endl; + } + } else { + string branch_statement = rendered_branch_count == 0 ? "if" : "} else if"; + f_gen_ << indent() << branch_statement << " self." << SERVICE_RESULT_VARIABLE << ".is_some() {" << endl; + indent_up(); + f_gen_ << indent() << "Ok(self." << SERVICE_RESULT_VARIABLE << ".unwrap())" << endl; + indent_down(); + f_gen_ << indent() << "} else {" << endl; + indent_up(); + // if we haven't found a valid return value *or* a user exception + // then we're in trouble; return a default error + render_thrift_error( + "Application", + "ApplicationError", + "ApplicationErrorKind::MissingResult", + "\"no result received for " + service_call_name + "\"" + ); + indent_down(); + f_gen_ << indent() << "}" << endl; + } + + indent_down(); + f_gen_ << indent() << "}" << endl; +} + +void t_rs_generator::render_union(t_struct* tstruct) { + string union_name(rust_struct_name(tstruct)); + render_type_comment(union_name); + render_union_definition(union_name, tstruct); + render_union_impl(union_name, tstruct); +} + +void t_rs_generator::render_union_definition(const string& union_name, t_struct* tstruct) { + const vector& members = tstruct->get_sorted_members(); + if (members.empty()) { + throw "cannot generate rust enum with 0 members"; // may be valid thrift, but it's invalid rust + } + + f_gen_ << "#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]" << endl; + f_gen_ << "pub enum " << union_name << " {" << endl; + indent_up(); + + vector::const_iterator member_iter; + for(member_iter = members.begin(); member_iter != members.end(); ++member_iter) { + t_field* tfield = (*member_iter); + f_gen_ + << indent() + << rust_union_field_name(tfield) + << "(" << to_rust_type(tfield->get_type()) << ")," + << endl; + } + + indent_down(); + f_gen_ << "}" << endl; + f_gen_ << endl; +} + +void t_rs_generator::render_union_impl(const string& union_name, t_struct* tstruct) { + f_gen_ << "impl " << union_name << " {" << endl; + indent_up(); + + render_union_sync_read(union_name, tstruct); + render_union_sync_write(union_name, tstruct); + + indent_down(); + f_gen_ << "}" << endl; + f_gen_ << endl; +} + +//----------------------------------------------------------------------------- +// +// Sync Struct Write +// +//----------------------------------------------------------------------------- + +void t_rs_generator::render_struct_sync_write( + t_struct *tstruct, + t_rs_generator::e_struct_type struct_type +) { + f_gen_ + << indent() + << visibility_qualifier(struct_type) + << "fn write_to_out_protocol(&self, o_prot: &mut TOutputProtocol) -> thrift::Result<()> {" + << endl; + indent_up(); + + // write struct header to output protocol + // note: use the *original* struct name here + f_gen_ << indent() << "let struct_ident = TStructIdentifier::new(\"" + tstruct->get_name() + "\");" << endl; + f_gen_ << indent() << "o_prot.write_struct_begin(&struct_ident)?;" << endl; + + // write struct members to output protocol + vector members = tstruct->get_sorted_members(); + if (!members.empty()) { + vector::iterator members_iter; + for(members_iter = members.begin(); members_iter != members.end(); ++members_iter) { + t_field* member = (*members_iter); + t_field::e_req member_req = actual_field_req(member, struct_type); + string member_var("self." + rust_field_name(member)); + render_struct_field_sync_write(member_var, false, member, member_req); + } + } + + // write struct footer to output protocol + f_gen_ << indent() << "o_prot.write_field_stop()?;" << endl; + f_gen_ << indent() << "o_prot.write_struct_end()" << endl; + + indent_down(); + f_gen_ << indent() << "}" << endl; +} + +void t_rs_generator::render_union_sync_write(const string &union_name, t_struct *tstruct) { + f_gen_ + << indent() + << "pub fn write_to_out_protocol(&self, o_prot: &mut TOutputProtocol) -> thrift::Result<()> {" + << endl; + indent_up(); + + // write struct header to output protocol + // note: use the *original* struct name here + f_gen_ << indent() << "let struct_ident = TStructIdentifier::new(\"" + tstruct->get_name() + "\");" << endl; + f_gen_ << indent() << "o_prot.write_struct_begin(&struct_ident)?;" << endl; + + // write the enum field to the output protocol + vector members = tstruct->get_sorted_members(); + if (!members.empty()) { + f_gen_ << indent() << "match *self {" << endl; + indent_up(); + vector::iterator members_iter; + for(members_iter = members.begin(); members_iter != members.end(); ++members_iter) { + t_field* member = (*members_iter); + t_field::e_req member_req = t_field::T_REQUIRED; + t_type* ttype = member->get_type(); + string match_var((ttype->is_base_type() && !ttype->is_string()) ? "f" : "ref f"); + f_gen_ + << indent() + << union_name << "::" << rust_union_field_name(member) + << "(" << match_var << ") => {" + << endl; + indent_up(); + render_struct_field_sync_write("f", true, member, member_req); + indent_down(); + f_gen_ << indent() << "}," << endl; + } + indent_down(); + f_gen_ << indent() << "}" << endl; + } + + // write struct footer to output protocol + f_gen_ << indent() << "o_prot.write_field_stop()?;" << endl; + f_gen_ << indent() << "o_prot.write_struct_end()" << endl; + + indent_down(); + f_gen_ << indent() << "}" << endl; +} + +void t_rs_generator::render_struct_field_sync_write( + const string &field_var, + bool field_var_is_ref, + t_field *tfield, + t_field::e_req req +) { + t_type* field_type = tfield->get_type(); + t_type* actual_type = get_true_type(field_type); + + ostringstream field_stream; + field_stream + << "TFieldIdentifier::new(" + << "\"" << tfield->get_name() << "\"" << ", " // note: use *original* name + << to_rust_field_type_enum(field_type) << ", " + << tfield->get_key() << ")"; + string field_ident_string = field_stream.str(); + + if (is_optional(req)) { + string let_var((actual_type->is_base_type() && !actual_type->is_string()) ? "fld_var" : "ref fld_var"); + f_gen_ << indent() << "if let Some(" << let_var << ") = " << field_var << " {" << endl; + indent_up(); + f_gen_ << indent() << "o_prot.write_field_begin(&" << field_ident_string << ")?;" << endl; + render_type_sync_write("fld_var", true, field_type); + f_gen_ << indent() << "o_prot.write_field_end()?;" << endl; + f_gen_ << indent() << "()" << endl; // FIXME: remove this extraneous '()' + indent_down(); + f_gen_ << indent() << "} else {" << endl; // FIXME: remove else branch + indent_up(); + /* FIXME: rethink how I deal with OPT_IN_REQ_OUT + if (req == t_field::T_OPT_IN_REQ_OUT) { + f_gen_ << indent() << "let field_ident = " << field_ident_string << ";" << endl; + f_gen_ << indent() << "o_prot.write_field_begin(&field_ident)?;" << endl; + f_gen_ << indent() << "o_prot.write_field_end()?;" << endl; + }*/ + f_gen_ << indent() << "()" << endl; + indent_down(); + f_gen_ << indent() << "}" << endl; + } else { + f_gen_ << indent() << "o_prot.write_field_begin(&" << field_ident_string << ")?;" << endl; + render_type_sync_write(field_var, field_var_is_ref, tfield->get_type()); + f_gen_ << indent() << "o_prot.write_field_end()?;" << endl; + } +} + +void t_rs_generator::render_type_sync_write(const string &type_var, bool type_var_is_ref, t_type *ttype) { + if (ttype->is_base_type()) { + t_base_type* tbase_type = (t_base_type*)ttype; + switch (tbase_type->get_base()) { + case t_base_type::TYPE_VOID: + throw "cannot write field of type TYPE_VOID to output protocol"; + case t_base_type::TYPE_STRING: { + string ref(type_var_is_ref ? "" : "&"); + if (tbase_type->is_binary()) { + f_gen_ << indent() << "o_prot.write_bytes(" + ref + type_var + ")?;" << endl; + } else { + f_gen_ << indent() << "o_prot.write_string(" + ref + type_var + ")?;" << endl; + } + return; + } + case t_base_type::TYPE_BOOL: + f_gen_ << indent() << "o_prot.write_bool(" + type_var + ")?;" << endl; + return; + case t_base_type::TYPE_I8: + f_gen_ << indent() << "o_prot.write_i8(" + type_var + ")?;" << endl; + return; + case t_base_type::TYPE_I16: + f_gen_ << indent() << "o_prot.write_i16(" + type_var + ")?;" << endl; + return; + case t_base_type::TYPE_I32: + f_gen_ << indent() << "o_prot.write_i32(" + type_var + ")?;" << endl; + return; + case t_base_type::TYPE_I64: + f_gen_ << indent() << "o_prot.write_i64(" + type_var + ")?;" << endl; + return; + case t_base_type::TYPE_DOUBLE: + f_gen_ << indent() << "o_prot.write_double(" + type_var + ".into())?;" << endl; + return; + } + } else if (ttype->is_typedef()) { + t_typedef* ttypedef = (t_typedef*) ttype; + render_type_sync_write(type_var, type_var_is_ref, ttypedef->get_type()); + return; + } else if (ttype->is_enum() || ttype->is_struct() || ttype->is_xception()) { + f_gen_ << indent() << type_var + ".write_to_out_protocol(o_prot)?;" << endl; + return; + } else if (ttype->is_map()) { + render_map_sync_write(type_var, type_var_is_ref, (t_map *) ttype); + return; + } else if (ttype->is_set()) { + render_set_sync_write(type_var, type_var_is_ref, (t_set *) ttype); + return; + } else if (ttype->is_list()) { + render_list_sync_write(type_var, type_var_is_ref, (t_list *) ttype); + return; + } + + throw "cannot write unsupported type " + ttype->get_name(); +} + +void t_rs_generator::render_list_sync_write(const string &list_var, bool list_var_is_ref, t_list *tlist) { + t_type* elem_type = tlist->get_elem_type(); + + f_gen_ + << indent() + << "o_prot.write_list_begin(" + << "&TListIdentifier::new(" + << to_rust_field_type_enum(elem_type) << ", " + << list_var << ".len() as i32" << ")" + << ")?;" + << endl; + + string ref(list_var_is_ref ? "" : "&"); + f_gen_ << indent() << "for e in " << ref << list_var << " {" << endl; + indent_up(); + render_type_sync_write(string_container_write_variable(elem_type, "e"), true, elem_type); + f_gen_ << indent() << "o_prot.write_list_end()?;" << endl; + indent_down(); + f_gen_ << indent() << "}" << endl; +} + +void t_rs_generator::render_set_sync_write(const string &set_var, bool set_var_is_ref, t_set *tset) { + t_type* elem_type = tset->get_elem_type(); + + f_gen_ + << indent() + << "o_prot.write_set_begin(" + << "&TSetIdentifier::new(" + << to_rust_field_type_enum(elem_type) << ", " + << set_var << ".len() as i32" << ")" + << ")?;" + << endl; + + string ref(set_var_is_ref ? "" : "&"); + f_gen_ << indent() << "for e in " << ref << set_var << " {" << endl; + indent_up(); + render_type_sync_write(string_container_write_variable(elem_type, "e"), true, elem_type); + f_gen_ << indent() << "o_prot.write_set_end()?;" << endl; + indent_down(); + f_gen_ << indent() << "}" << endl; +} + +void t_rs_generator::render_map_sync_write(const string &map_var, bool map_var_is_ref, t_map *tmap) { + t_type* key_type = tmap->get_key_type(); + t_type* val_type = tmap->get_val_type(); + + f_gen_ + << indent() + << "o_prot.write_map_begin(" + << "&TMapIdentifier::new(" + << to_rust_field_type_enum(key_type) << ", " + << to_rust_field_type_enum(val_type) << ", " + << map_var << ".len() as i32)" + << ")?;" + << endl; + + string ref(map_var_is_ref ? "" : "&"); + f_gen_ << indent() << "for (k, v) in " << ref << map_var << " {" << endl; + indent_up(); + render_type_sync_write(string_container_write_variable(key_type, "k"), true, key_type); + render_type_sync_write(string_container_write_variable(val_type, "v"), true, val_type); + f_gen_ << indent() << "o_prot.write_map_end()?;" << endl; + indent_down(); + f_gen_ << indent() << "}" << endl; +} + +string t_rs_generator::string_container_write_variable(t_type* ttype, const string& base_var) { + bool type_needs_deref = needs_deref_on_container_write(ttype); + bool type_is_double = is_double(ttype); + + string write_variable; + + if (type_is_double && type_needs_deref) { + write_variable = "(*" + base_var + ")"; + } else if (type_needs_deref) { + write_variable = "*" + base_var; + } else { + write_variable = base_var; + } + + return write_variable; +} + +bool t_rs_generator::needs_deref_on_container_write(t_type* ttype) { + ttype = get_true_type(ttype); + return ttype->is_base_type() && !ttype->is_string(); +} + +//----------------------------------------------------------------------------- +// +// Sync Struct Read +// +//----------------------------------------------------------------------------- + +void t_rs_generator::render_struct_sync_read( + const string &struct_name, + t_struct *tstruct, t_rs_generator::e_struct_type struct_type +) { + f_gen_ + << indent() + << visibility_qualifier(struct_type) + << "fn read_from_in_protocol(i_prot: &mut TInputProtocol) -> thrift::Result<" << struct_name << "> {" + << endl; + + indent_up(); + + f_gen_ << indent() << "i_prot.read_struct_begin()?;" << endl; + + // create temporary variables: one for each field in the struct + const vector members = tstruct->get_sorted_members(); + vector::const_iterator members_iter; + for (members_iter = members.begin(); members_iter != members.end(); ++members_iter) { + t_field* member = (*members_iter); + t_field::e_req member_req = actual_field_req(member, struct_type); + + f_gen_ + << indent() + << "let mut " << struct_field_read_temp_variable(member) + << ": Option<" << to_rust_type(member->get_type()) << "> = "; + if (member_req == t_field::T_OPT_IN_REQ_OUT) { + f_gen_ << opt_in_req_out_value(member->get_type()) << ";"; + } else { + f_gen_ << "None;"; + } + f_gen_ << endl; + } + + // now loop through the fields we've received + f_gen_ << indent() << "loop {" << endl; // start loop + indent_up(); + + // break out if you've found the Stop field + f_gen_ << indent() << "let field_ident = i_prot.read_field_begin()?;" << endl; + f_gen_ << indent() << "if field_ident.field_type == TType::Stop {" << endl; + indent_up(); + f_gen_ << indent() << "break;" << endl; + indent_down(); + f_gen_ << indent() << "}" << endl; + + // now read all the fields found + f_gen_ << indent() << "let field_id = field_id(&field_ident)?;" << endl; + f_gen_ << indent() << "match field_id {" << endl; // start match + indent_up(); + + for (members_iter = members.begin(); members_iter != members.end(); ++members_iter) { + t_field* tfield = (*members_iter); + f_gen_ << indent() << tfield->get_key() << " => {" << endl; + indent_up(); + render_type_sync_read("val", tfield->get_type()); + f_gen_ << indent() << struct_field_read_temp_variable(tfield) << " = Some(val);" << endl; + indent_down(); + f_gen_ << indent() << "}," << endl; + } + + // default case (skip fields) + f_gen_ << indent() << "_ => {" << endl; + indent_up(); + f_gen_ << indent() << "i_prot.skip(field_ident.field_type)?;" << endl; + indent_down(); + f_gen_ << indent() << "}," << endl; + + indent_down(); + f_gen_ << indent() << "};" << endl; // finish match + f_gen_ << indent() << "i_prot.read_field_end()?;" << endl; + indent_down(); + f_gen_ << indent() << "}" << endl; // finish loop + f_gen_ << indent() << "i_prot.read_struct_end()?;" << endl; // read message footer from the wire + + // verify that all required fields exist + for (members_iter = members.begin(); members_iter != members.end(); ++members_iter) { + t_field* tfield = (*members_iter); + t_field::e_req req = actual_field_req(tfield, struct_type); + if (!is_optional(req)) { + f_gen_ + << indent() + << "verify_required_field_exists(" + << "\"" << struct_name << "." << rust_field_name(tfield) << "\"" + << ", " + << "&" << struct_field_read_temp_variable(tfield) + << ")?;" << endl; + } + } + + // construct the struct + if (members.size() == 0) { + f_gen_ << indent() << "let ret = " << struct_name << " {};" << endl; + } else { + f_gen_ << indent() << "let ret = " << struct_name << " {" << endl; + indent_up(); + + for (members_iter = members.begin(); members_iter != members.end(); ++members_iter) { + t_field* tfield = (*members_iter); + t_field::e_req req = actual_field_req(tfield, struct_type); + string field_name(rust_field_name(tfield)); + string field_key = struct_field_read_temp_variable(tfield); + if (is_optional(req)) { + f_gen_ << indent() << field_name << ": " << field_key << "," << endl; + } else { + f_gen_ + << indent() + << field_name + << ": " + << field_key + << ".expect(\"auto-generated code should have checked for presence of required fields\")" + << "," + << endl; + } + } + + indent_down(); + f_gen_ << indent() << "};" << endl; + } + + // return the constructed value + f_gen_ << indent() << "Ok(ret)" << endl; + + indent_down(); + f_gen_ << indent() << "}" << endl; +} + +void t_rs_generator::render_union_sync_read(const string &union_name, t_struct *tstruct) { + f_gen_ + << indent() + << "pub fn read_from_in_protocol(i_prot: &mut TInputProtocol) -> thrift::Result<" << union_name << "> {" + << endl; + indent_up(); + + // create temporary variables to hold the + // completed union as well as a count of fields read + f_gen_ << indent() << "let mut ret: Option<" << union_name << "> = None;" << endl; + f_gen_ << indent() << "let mut received_field_count = 0;" << endl; + + // read the struct preamble + f_gen_ << indent() << "i_prot.read_struct_begin()?;" << endl; + + // now loop through the fields we've received + f_gen_ << indent() << "loop {" << endl; // start loop + indent_up(); + + // break out if you've found the Stop field + f_gen_ << indent() << "let field_ident = i_prot.read_field_begin()?;" << endl; + f_gen_ << indent() << "if field_ident.field_type == TType::Stop {" << endl; + indent_up(); + f_gen_ << indent() << "break;" << endl; + indent_down(); + f_gen_ << indent() << "}" << endl; + + // now read all the fields found + f_gen_ << indent() << "let field_id = field_id(&field_ident)?;" << endl; + f_gen_ << indent() << "match field_id {" << endl; // start match + indent_up(); + + const vector members = tstruct->get_sorted_members(); + vector::const_iterator members_iter; + for (members_iter = members.begin(); members_iter != members.end(); ++members_iter) { + t_field* member = (*members_iter); + f_gen_ << indent() << member->get_key() << " => {" << endl; + indent_up(); + render_type_sync_read("val", member->get_type()); + f_gen_ << indent() << "if ret.is_none() {" << endl; + indent_up(); + f_gen_ + << indent() + << "ret = Some(" << union_name << "::" << rust_union_field_name(member) << "(val));" + << endl; + indent_down(); + f_gen_ << indent() << "}" << endl; + f_gen_ << indent() << "received_field_count += 1;" << endl; + indent_down(); + f_gen_ << indent() << "}," << endl; + } + + // default case (skip fields) + f_gen_ << indent() << "_ => {" << endl; + indent_up(); + f_gen_ << indent() << "i_prot.skip(field_ident.field_type)?;" << endl; + f_gen_ << indent() << "received_field_count += 1;" << endl; + indent_down(); + f_gen_ << indent() << "}," << endl; + + indent_down(); + f_gen_ << indent() << "};" << endl; // finish match + f_gen_ << indent() << "i_prot.read_field_end()?;" << endl; + indent_down(); + f_gen_ << indent() << "}" << endl; // finish loop + f_gen_ << indent() << "i_prot.read_struct_end()?;" << endl; // finish reading message from wire + + // return the value or an error + f_gen_ << indent() << "if received_field_count == 0 {" << endl; + indent_up(); + render_thrift_error( + "Protocol", + "ProtocolError", + "ProtocolErrorKind::InvalidData", + "\"received empty union from remote " + union_name + "\"" + ); + indent_down(); + f_gen_ << indent() << "} else if received_field_count > 1 {" << endl; + indent_up(); + render_thrift_error( + "Protocol", + "ProtocolError", + "ProtocolErrorKind::InvalidData", + "\"received multiple fields for union from remote " + union_name + "\"" + ); + indent_down(); + f_gen_ << indent() << "} else {" << endl; + indent_up(); + f_gen_ << indent() << "Ok(ret.expect(\"return value should have been constructed\"))" << endl; + indent_down(); + f_gen_ << indent() << "}" << endl; + + indent_down(); + f_gen_ << indent() << "}" << endl; +} + +// Construct the rust representation of all supported types from the wire. +void t_rs_generator::render_type_sync_read(const string &type_var, t_type *ttype, bool is_boxed) { + if (ttype->is_base_type()) { + t_base_type* tbase_type = (t_base_type*)ttype; + switch (tbase_type->get_base()) { + case t_base_type::TYPE_VOID: + throw "cannot read field of type TYPE_VOID from input protocol"; + case t_base_type::TYPE_STRING: + if (tbase_type->is_binary()) { + f_gen_ << indent() << "let " << type_var << " = i_prot.read_bytes()?;" << endl; + } else { + f_gen_ << indent() << "let " << type_var << " = i_prot.read_string()?;" << endl; + } + return; + case t_base_type::TYPE_BOOL: + f_gen_ << indent() << "let " << type_var << " = i_prot.read_bool()?;" << endl; + return; + case t_base_type::TYPE_I8: + f_gen_ << indent() << "let " << type_var << " = i_prot.read_i8()?;" << endl; + return; + case t_base_type::TYPE_I16: + f_gen_ << indent() << "let " << type_var << " = i_prot.read_i16()?;" << endl; + return; + case t_base_type::TYPE_I32: + f_gen_ << indent() << "let " << type_var << " = i_prot.read_i32()?;" << endl; + return; + case t_base_type::TYPE_I64: + f_gen_ << indent() << "let " << type_var << " = i_prot.read_i64()?;" << endl; + return; + case t_base_type::TYPE_DOUBLE: + f_gen_ << indent() << "let " << type_var << " = OrderedFloat::from(i_prot.read_double()?);" << endl; + return; + } + } else if (ttype->is_typedef()) { + // FIXME: not a fan of separate `is_boxed` parameter + // This is problematic because it's an optional parameter, and only comes + // into play once. The core issue is that I lose an important piece of type + // information (whether the type is a fwd ref) by unwrapping the typedef'd + // type and making the recursive call using it. I can't modify or wrap the + // generated string after the fact because it's written directly into the file, + // so I have to pass this parameter along. Going with this approach because it + // seems like the lowest-cost option to easily support recursive types. + t_typedef* ttypedef = (t_typedef*)ttype; + render_type_sync_read(type_var, ttypedef->get_type(), ttypedef->is_forward_typedef()); + return; + } else if (ttype->is_enum() || ttype->is_struct() || ttype->is_xception()) { + string read_call(to_rust_type(ttype) + "::read_from_in_protocol(i_prot)?"); + read_call = is_boxed ? "Box::new(" + read_call + ")" : read_call; + f_gen_ + << indent() + << "let " << type_var << " = " << read_call << ";" + << endl; + return; + } else if (ttype->is_map()) { + render_map_sync_read((t_map *) ttype, type_var); + return; + } else if (ttype->is_set()) { + render_set_sync_read((t_set *) ttype, type_var); + return; + } else if (ttype->is_list()) { + render_list_sync_read((t_list *) ttype, type_var); + return; + } + + throw "cannot read unsupported type " + ttype->get_name(); +} + +// Construct the rust representation of a list from the wire. +void t_rs_generator::render_list_sync_read(t_list *tlist, const string &list_var) { + t_type* elem_type = tlist->get_elem_type(); + + f_gen_ << indent() << "let list_ident = i_prot.read_list_begin()?;" << endl; + f_gen_ + << indent() + << "let mut " << list_var << ": " << to_rust_type((t_type*) tlist) + << " = Vec::with_capacity(list_ident.size as usize);" + << endl; + f_gen_ << indent() << "for _ in 0..list_ident.size {" << endl; + + indent_up(); + + string list_elem_var = tmp("list_elem_"); + render_type_sync_read(list_elem_var, elem_type); + f_gen_ << indent() << list_var << ".push(" << list_elem_var << ");" << endl; + + indent_down(); + + f_gen_ << indent() << "}" << endl; + f_gen_ << indent() << "i_prot.read_list_end()?;" << endl; +} + +// Construct the rust representation of a set from the wire. +void t_rs_generator::render_set_sync_read(t_set *tset, const string &set_var) { + t_type* elem_type = tset->get_elem_type(); + + f_gen_ << indent() << "let set_ident = i_prot.read_set_begin()?;" << endl; + f_gen_ + << indent() + << "let mut " << set_var << ": " << to_rust_type((t_type*) tset) + << " = BTreeSet::new();" + << endl; + f_gen_ << indent() << "for _ in 0..set_ident.size {" << endl; + + indent_up(); + + string set_elem_var = tmp("set_elem_"); + render_type_sync_read(set_elem_var, elem_type); + f_gen_ << indent() << set_var << ".insert(" << set_elem_var << ");" << endl; + + indent_down(); + + f_gen_ << indent() << "}" << endl; + f_gen_ << indent() << "i_prot.read_set_end()?;" << endl; +} + +// Construct the rust representation of a map from the wire. +void t_rs_generator::render_map_sync_read(t_map *tmap, const string &map_var) { + t_type* key_type = tmap->get_key_type(); + t_type* val_type = tmap->get_val_type(); + + f_gen_ << indent() << "let map_ident = i_prot.read_map_begin()?;" << endl; + f_gen_ + << indent() + << "let mut " << map_var << ": " << to_rust_type((t_type*) tmap) + << " = BTreeMap::new();" + << endl; + f_gen_ << indent() << "for _ in 0..map_ident.size {" << endl; + + indent_up(); + + string key_elem_var = tmp("map_key_"); + render_type_sync_read(key_elem_var, key_type); + string val_elem_var = tmp("map_val_"); + render_type_sync_read(val_elem_var, val_type); + f_gen_ << indent() << map_var << ".insert(" << key_elem_var << ", " << val_elem_var << ");" << endl; + + indent_down(); + + f_gen_ << indent() << "}" << endl; + f_gen_ << indent() << "i_prot.read_map_end()?;" << endl; +} + +string t_rs_generator::struct_field_read_temp_variable(t_field* tfield) { + std::ostringstream foss; + foss << "f_" << tfield->get_key(); + return foss.str(); +} + +//----------------------------------------------------------------------------- +// +// Sync Client +// +//----------------------------------------------------------------------------- + +void t_rs_generator::generate_service(t_service* tservice) { + render_sync_client(tservice); + render_sync_processor(tservice); + render_service_call_structs(tservice); +} + +void t_rs_generator::render_service_call_structs(t_service* tservice) { + const std::vector functions = tservice->get_functions(); + std::vector::const_iterator func_iter; + + // thrift args for service calls are packed + // into a struct that's transmitted over the wire, so + // generate structs for those too + // + // thrift returns are *also* packed into a struct + // that's passed over the wire, so, generate the struct + // for that too. Note that this result struct *also* + // contains the exceptions as well + for(func_iter = functions.begin(); func_iter != functions.end(); ++func_iter) { + t_function* tfunc = (*func_iter); + render_service_call_args_struct(tfunc); + if (!tfunc->is_oneway()) { + render_service_call_result_value_struct(tfunc); + } + } +} + +void t_rs_generator::render_sync_client(t_service* tservice) { + string client_impl_name(rust_sync_client_impl_name(tservice)); + + render_type_comment(tservice->get_name() + " service client"); // note: use *original* name + render_sync_client_trait(tservice); + render_sync_client_marker_trait(tservice); + render_sync_client_definition_and_impl(client_impl_name); + render_sync_client_tthriftclient_impl(client_impl_name); + render_sync_client_marker_trait_impls(tservice, client_impl_name); f_gen_ << endl; + render_sync_client_process_impl(tservice); +} + +void t_rs_generator::render_sync_client_trait(t_service *tservice) { + string extension = ""; + if (tservice->get_extends()) { + t_service* extends = tservice->get_extends(); + extension = " : " + rust_namespace(extends) + rust_sync_client_trait_name(extends); + } + + render_rustdoc((t_doc*) tservice); + f_gen_ << "pub trait " << rust_sync_client_trait_name(tservice) << extension << " {" << endl; + indent_up(); + + const std::vector functions = tservice->get_functions(); + std::vector::const_iterator func_iter; + for(func_iter = functions.begin(); func_iter != functions.end(); ++func_iter) { + t_function* tfunc = (*func_iter); + string func_name = service_call_client_function_name(tfunc); + string func_args = rust_sync_service_call_declaration(tfunc, true); + string func_return = to_rust_type(tfunc->get_returntype()); + render_rustdoc((t_doc*) tfunc); + f_gen_ << indent() << "fn " << func_name << func_args << " -> thrift::Result<" << func_return << ">;" << endl; + } + + indent_down(); + f_gen_ << indent() << "}" << endl; + f_gen_ << endl; +} + +void t_rs_generator::render_sync_client_marker_trait(t_service *tservice) { + f_gen_ << indent() << "pub trait " << rust_sync_client_marker_trait_name(tservice) << " {}" << endl; + f_gen_ << endl; +} + +void t_rs_generator::render_sync_client_marker_trait_impls(t_service *tservice, const string &impl_struct_name) { + f_gen_ + << indent() + << "impl " + << SYNC_CLIENT_GENERIC_BOUND_VARS + << " " + << rust_namespace(tservice) << rust_sync_client_marker_trait_name(tservice) + << " for " + << impl_struct_name << SYNC_CLIENT_GENERIC_BOUND_VARS + << " " + << SYNC_CLIENT_GENERIC_BOUNDS + << " {}" + << endl; + + t_service* extends = tservice->get_extends(); + if (extends) { + render_sync_client_marker_trait_impls(extends, impl_struct_name); + } +} + +void t_rs_generator::render_sync_client_definition_and_impl(const string& client_impl_name) { + + // render the definition for the client struct + f_gen_ + << "pub struct " + << client_impl_name + << SYNC_CLIENT_GENERIC_BOUND_VARS + << " " + << SYNC_CLIENT_GENERIC_BOUNDS + << " {" + << endl; + indent_up(); + f_gen_ << indent() << "_i_prot: IP," << endl; + f_gen_ << indent() << "_o_prot: OP," << endl; + f_gen_ << indent() << "_sequence_number: i32," << endl; + indent_down(); + f_gen_ << "}" << endl; + f_gen_ << endl; + + // render the struct implementation + // this includes the new() function as well as the helper send/recv methods for each service call + f_gen_ + << "impl " + << SYNC_CLIENT_GENERIC_BOUND_VARS + << " " + << client_impl_name + << SYNC_CLIENT_GENERIC_BOUND_VARS + << " " + << SYNC_CLIENT_GENERIC_BOUNDS + << " {" + << endl; + indent_up(); + render_sync_client_lifecycle_functions(client_impl_name); + indent_down(); + f_gen_ << "}" << endl; + f_gen_ << endl; +} + +void t_rs_generator::render_sync_client_lifecycle_functions(const string& client_struct) { + f_gen_ + << indent() + << "pub fn new(input_protocol: IP, output_protocol: OP) -> " + << client_struct + << SYNC_CLIENT_GENERIC_BOUND_VARS + << " {" + << endl; + indent_up(); + + f_gen_ + << indent() + << client_struct + << " { _i_prot: input_protocol, _o_prot: output_protocol, _sequence_number: 0 }" + << endl; + + indent_down(); + f_gen_ << indent() << "}" << endl; +} + +void t_rs_generator::render_sync_client_tthriftclient_impl(const string &client_impl_name) { + f_gen_ + << indent() + << "impl " + << SYNC_CLIENT_GENERIC_BOUND_VARS + << " TThriftClient for " + << client_impl_name + << SYNC_CLIENT_GENERIC_BOUND_VARS + << " " + << SYNC_CLIENT_GENERIC_BOUNDS + << " {" << endl; + indent_up(); + + f_gen_ << indent() << "fn i_prot_mut(&mut self) -> &mut TInputProtocol { &mut self._i_prot }" << endl; + f_gen_ << indent() << "fn o_prot_mut(&mut self) -> &mut TOutputProtocol { &mut self._o_prot }" << endl; + f_gen_ << indent() << "fn sequence_number(&self) -> i32 { self._sequence_number }" << endl; + f_gen_ + << indent() + << "fn increment_sequence_number(&mut self) -> i32 { self._sequence_number += 1; self._sequence_number }" + << endl; + + indent_down(); + f_gen_ << indent() << "}" << endl; + f_gen_ << endl; +} + +void t_rs_generator::render_sync_client_process_impl(t_service* tservice) { + string marker_extension = "" + sync_client_marker_traits_for_extension(tservice); + + f_gen_ + << "impl " + << rust_sync_client_trait_name(tservice) + << " for C {" << endl; + indent_up(); + + const std::vector functions = tservice->get_functions(); + std::vector::const_iterator func_iter; + for(func_iter = functions.begin(); func_iter != functions.end(); ++func_iter) { + t_function* func = (*func_iter); + render_sync_send_recv_wrapper(func); + } + + indent_down(); + f_gen_ << "}" << endl; + f_gen_ << endl; +} + +string t_rs_generator::sync_client_marker_traits_for_extension(t_service *tservice) { + string marker_extension; + + t_service* extends = tservice->get_extends(); + if (extends) { + marker_extension = " + " + rust_namespace(extends) + rust_sync_client_marker_trait_name(extends); + marker_extension = marker_extension + sync_client_marker_traits_for_extension(extends); + } + + return marker_extension; +} + +void t_rs_generator::render_sync_send_recv_wrapper(t_function* tfunc) { + string func_name = service_call_client_function_name(tfunc); + string func_decl_args = rust_sync_service_call_declaration(tfunc, true); + string func_call_args = rust_sync_service_call_invocation(tfunc); + string func_return = to_rust_type(tfunc->get_returntype()); + + f_gen_ + << indent() + << "fn " << func_name << func_decl_args << " -> thrift::Result<" << func_return + << "> {" + << endl; + indent_up(); + + f_gen_ << indent() << "(" << endl; + indent_up(); + render_sync_send(tfunc); + indent_down(); + f_gen_ << indent() << ")?;" << endl; + if (tfunc->is_oneway()) { + f_gen_ << indent() << "Ok(())" << endl; + } else { + render_sync_recv(tfunc); + } + + indent_down(); + f_gen_ << indent() << "}" << endl; +} + +void t_rs_generator::render_sync_send(t_function* tfunc) { + f_gen_ << indent() << "{" << endl; + indent_up(); + + // increment the sequence number and generate the call header + string message_type = tfunc->is_oneway() ? "TMessageType::OneWay" : "TMessageType::Call"; + f_gen_ << indent() << "self.increment_sequence_number();" << endl; + f_gen_ + << indent() + << "let message_ident = " + << "TMessageIdentifier::new(\"" << tfunc->get_name() << "\", " // note: use *original* name + << message_type << ", " + << "self.sequence_number());" + << endl; + // pack the arguments into the containing struct that we'll write out over the wire + // note that this struct is generated even if we have 0 args + ostringstream struct_definition; + vector members = tfunc->get_arglist()->get_sorted_members(); + vector::iterator members_iter; + for (members_iter = members.begin(); members_iter != members.end(); ++members_iter) { + t_field* member = (*members_iter); + string member_name(rust_field_name(member)); + struct_definition << member_name << ": " << member_name << ", "; + } + string struct_fields = struct_definition.str(); + if (struct_fields.size() > 0) { + struct_fields = struct_fields.substr(0, struct_fields.size() - 2); // strip trailing comma + } + f_gen_ + << indent() + << "let call_args = " + << service_call_args_struct_name(tfunc) + << " { " + << struct_fields + << " };" + << endl; + // write everything over the wire + f_gen_ << indent() << "self.o_prot_mut().write_message_begin(&message_ident)?;" << endl; + f_gen_ << indent() << "call_args.write_to_out_protocol(self.o_prot_mut())?;" << endl; // written even if we have 0 args + f_gen_ << indent() << "self.o_prot_mut().write_message_end()?;" << endl; + f_gen_ << indent() << "self.o_prot_mut().flush()" << endl; + + indent_down(); + f_gen_ << indent() << "}" << endl; +} + +void t_rs_generator::render_sync_recv(t_function* tfunc) { + f_gen_ << indent() << "{" << endl; + indent_up(); + + f_gen_ << indent() << "let message_ident = self.i_prot_mut().read_message_begin()?;" << endl; + f_gen_ << indent() << "verify_expected_sequence_number(self.sequence_number(), message_ident.sequence_number)?;" << endl; + f_gen_ << indent() << "verify_expected_service_call(\"" << tfunc->get_name() <<"\", &message_ident.name)?;" << endl; // note: use *original* name + // FIXME: replace with a "try" block + f_gen_ << indent() << "if message_ident.message_type == TMessageType::Exception {" << endl; + indent_up(); + f_gen_ << indent() << "let remote_error = thrift::Error::read_application_error_from_in_protocol(self.i_prot_mut())?;" << endl; + f_gen_ << indent() << "self.i_prot_mut().read_message_end()?;" << endl; + f_gen_ << indent() << "return Err(thrift::Error::Application(remote_error))" << endl; + indent_down(); + f_gen_ << indent() << "}" << endl; + f_gen_ << indent() << "verify_expected_message_type(TMessageType::Reply, message_ident.message_type)?;" << endl; + f_gen_ << indent() << "let result = " << service_call_result_struct_name(tfunc) << "::read_from_in_protocol(self.i_prot_mut())?;" << endl; + f_gen_ << indent() << "self.i_prot_mut().read_message_end()?;" << endl; + f_gen_ << indent() << "result.ok_or()" << endl; + + indent_down(); + f_gen_ << indent() << "}" << endl; +} + +string t_rs_generator::rust_sync_service_call_declaration(t_function* tfunc, bool self_is_mutable) { + ostringstream func_args; + + if (self_is_mutable) { + func_args << "(&mut self"; + } else { + func_args << "(&self"; + } + + if (has_args(tfunc)) { + func_args << ", "; // put comma after "self" + func_args << struct_to_declaration(tfunc->get_arglist(), T_ARGS); + } + + func_args << ")"; + return func_args.str(); +} + +string t_rs_generator::rust_sync_service_call_invocation(t_function* tfunc, const string& field_prefix) { + ostringstream func_args; + func_args << "("; + + if (has_args(tfunc)) { + func_args << struct_to_invocation(tfunc->get_arglist(), field_prefix); + } + + func_args << ")"; + return func_args.str(); +} + +string t_rs_generator::struct_to_declaration(t_struct* tstruct, t_rs_generator::e_struct_type struct_type) { + ostringstream args; + + bool first_arg = true; + std::vector fields = tstruct->get_sorted_members(); + std::vector::iterator field_iter; + for (field_iter = fields.begin(); field_iter != fields.end(); ++field_iter) { + t_field* tfield = (*field_iter); + t_field::e_req field_req = actual_field_req(tfield, struct_type); + string rust_type = to_rust_type(tfield->get_type()); + rust_type = is_optional(field_req) ? "Option<" + rust_type + ">" : rust_type; + + if (first_arg) { + first_arg = false; + } else { + args << ", "; + } + + args << rust_field_name(tfield) << ": " << rust_type; + } + + return args.str(); +} + +string t_rs_generator::struct_to_invocation(t_struct* tstruct, const string& field_prefix) { + ostringstream args; + + bool first_arg = true; + std::vector fields = tstruct->get_sorted_members(); + std::vector::iterator field_iter; + for (field_iter = fields.begin(); field_iter != fields.end(); ++field_iter) { + t_field* tfield = (*field_iter); + + if (first_arg) { + first_arg = false; + } else { + args << ", "; + } + + args << field_prefix << rust_field_name(tfield); + } + + return args.str(); +} + +void t_rs_generator::render_service_call_args_struct(t_function* tfunc) { + string args_struct_name(service_call_args_struct_name(tfunc)); + render_struct(args_struct_name, tfunc->get_arglist(), t_rs_generator::T_ARGS); +} + +void t_rs_generator::render_service_call_result_value_struct(t_function* tfunc) { + string result_struct_name = service_call_result_struct_name(tfunc); + t_struct result(program_, result_struct_name); + + t_field return_value(tfunc->get_returntype(), SERVICE_RESULT_VARIABLE, 0); + return_value.set_req(t_field::T_OPTIONAL); + if (!tfunc->get_returntype()->is_void()) { + result.append(&return_value); + } + + t_struct* exceptions = tfunc->get_xceptions(); + const vector& exception_types = exceptions->get_members(); + vector::const_iterator exception_iter; + for(exception_iter = exception_types.begin(); exception_iter != exception_types.end(); ++exception_iter) { + t_field* exception_type = *exception_iter; + exception_type->set_req(t_field::T_OPTIONAL); + result.append(exception_type); + } + + render_struct(result_struct_name, &result, t_rs_generator::T_RESULT); +} + +//----------------------------------------------------------------------------- +// +// Sync Processor +// +//----------------------------------------------------------------------------- + +void t_rs_generator::render_sync_processor(t_service *tservice) { + render_type_comment(tservice->get_name() + " service processor"); // note: use *original* name + render_sync_handler_trait(tservice); + render_sync_processor_definition_and_impl(tservice); +} + +void t_rs_generator::render_sync_handler_trait(t_service *tservice) { + string extension = ""; + if (tservice->get_extends() != NULL) { + t_service* extends = tservice->get_extends(); + extension = " : " + rust_namespace(extends) + rust_sync_handler_trait_name(extends); + } + + const std::vector functions = tservice->get_functions(); + std::vector::const_iterator func_iter; + + render_rustdoc((t_doc*) tservice); + f_gen_ << "pub trait " << rust_sync_handler_trait_name(tservice) << extension << " {" << endl; + indent_up(); + for(func_iter = functions.begin(); func_iter != functions.end(); ++func_iter) { + t_function* tfunc = (*func_iter); + string func_name = service_call_handler_function_name(tfunc); + string func_args = rust_sync_service_call_declaration(tfunc, false); + string func_return = to_rust_type(tfunc->get_returntype()); + render_rustdoc((t_doc*) tfunc); + f_gen_ + << indent() + << "fn " + << func_name << func_args + << " -> thrift::Result<" << func_return << ">;" + << endl; + } + indent_down(); + f_gen_ << indent() << "}" << endl; + f_gen_ << endl; +} + +void t_rs_generator::render_sync_processor_definition_and_impl(t_service *tservice) { + string service_processor_name = rust_sync_processor_name(tservice); + string handler_trait_name = rust_sync_handler_trait_name(tservice); + + // struct + f_gen_ + << indent() + << "pub struct " << service_processor_name + << " {" + << endl; + indent_up(); + f_gen_ << indent() << "handler: H," << endl; + indent_down(); + f_gen_ << indent() << "}" << endl; + f_gen_ << endl; + + // delegating impl + f_gen_ + << indent() + << "impl " + << service_processor_name + << " {" + << endl; + indent_up(); + f_gen_ << indent() << "pub fn new(handler: H) -> " << service_processor_name << " {" << endl; + indent_up(); + f_gen_ << indent() << service_processor_name << " {" << endl; + indent_up(); + f_gen_ << indent() << "handler," << endl; + indent_down(); + f_gen_ << indent() << "}" << endl; + indent_down(); + f_gen_ << indent() << "}" << endl; + render_sync_process_delegation_functions(tservice); + indent_down(); + f_gen_ << indent() << "}" << endl; + f_gen_ << endl; + + // actual impl + string service_actual_processor_name = rust_sync_processor_impl_name(tservice); + f_gen_ << indent() << "pub struct " << service_actual_processor_name << ";" << endl; + f_gen_ << endl; + f_gen_ << indent() << "impl " << service_actual_processor_name << " {" << endl; + indent_up(); + + vector functions = tservice->get_functions(); + vector::iterator func_iter; + for(func_iter = functions.begin(); func_iter != functions.end(); ++func_iter) { + t_function* tfunc = (*func_iter); + render_sync_process_function(tfunc, handler_trait_name); + } + + indent_down(); + f_gen_ << indent() << "}" << endl; + f_gen_ << endl; + + // processor impl + f_gen_ + << indent() + << "impl TProcessor for " + << service_processor_name + << " {" + << endl; + indent_up(); + + f_gen_ + << indent() + << "fn process(&self, i_prot: &mut TInputProtocol, o_prot: &mut TOutputProtocol) -> thrift::Result<()> {" + << endl; + indent_up(); + + f_gen_ << indent() << "let message_ident = i_prot.read_message_begin()?;" << endl; + + f_gen_ << indent() << "let res = match &*message_ident.name {" << endl; // [sigh] explicit deref coercion + indent_up(); + render_process_match_statements(tservice); + f_gen_ << indent() << "method => {" << endl; + indent_up(); + render_thrift_error( + "Application", + "ApplicationError", + "ApplicationErrorKind::UnknownMethod", + "format!(\"unknown method {}\", method)" + ); + indent_down(); + f_gen_ << indent() << "}," << endl; + + indent_down(); + f_gen_ << indent() << "};" << endl; + f_gen_ << indent() << "thrift::server::handle_process_result(&message_ident, res, o_prot)" << endl; + + indent_down(); + f_gen_ << indent() << "}" << endl; + + indent_down(); + f_gen_ << indent() << "}" << endl; + f_gen_ << endl; +} + +void t_rs_generator::render_sync_process_delegation_functions(t_service *tservice) { + string actual_processor(rust_namespace(tservice) + rust_sync_processor_impl_name(tservice)); + + vector functions = tservice->get_functions(); + vector::iterator func_iter; + for(func_iter = functions.begin(); func_iter != functions.end(); ++func_iter) { + t_function* tfunc = (*func_iter); + string function_name("process_" + rust_snake_case(tfunc->get_name())); + f_gen_ + << indent() + << "fn " << function_name + << "(&self, " + << "incoming_sequence_number: i32, " + << "i_prot: &mut TInputProtocol, " + << "o_prot: &mut TOutputProtocol) " + << "-> thrift::Result<()> {" + << endl; + indent_up(); + + f_gen_ + << indent() + << actual_processor + << "::" << function_name + << "(" + << "&self.handler, " + << "incoming_sequence_number, " + << "i_prot, " + << "o_prot" + << ")" + << endl; + + indent_down(); + f_gen_ << indent() << "}" << endl; + } + + t_service* extends = tservice->get_extends(); + if (extends) { + render_sync_process_delegation_functions(extends); + } +} + +void t_rs_generator::render_process_match_statements(t_service* tservice) { + vector functions = tservice->get_functions(); + vector::iterator func_iter; + for(func_iter = functions.begin(); func_iter != functions.end(); ++func_iter) { + t_function* tfunc = (*func_iter); + f_gen_ << indent() << "\"" << tfunc->get_name() << "\"" << " => {" << endl; // note: use *original* name + indent_up(); + f_gen_ + << indent() + << "self.process_" << rust_snake_case(tfunc->get_name()) + << "(message_ident.sequence_number, i_prot, o_prot)" + << endl; + indent_down(); + f_gen_ << indent() << "}," << endl; + } + + t_service* extends = tservice->get_extends(); + if (extends) { + render_process_match_statements(extends); + } +} + +void t_rs_generator::render_sync_process_function(t_function *tfunc, const string &handler_type) { + string sequence_number_param("incoming_sequence_number"); + string output_protocol_param("o_prot"); + + if (tfunc->is_oneway()) { + sequence_number_param = "_"; + output_protocol_param = "_"; + } + + f_gen_ + << indent() + << "pub fn process_" << rust_snake_case(tfunc->get_name()) + << "" + << "(handler: &H, " + << sequence_number_param << ": i32, " + << "i_prot: &mut TInputProtocol, " + << output_protocol_param << ": &mut TOutputProtocol) " + << "-> thrift::Result<()> {" + << endl; + + indent_up(); + + // *always* read arguments from the input protocol + f_gen_ + << indent() + << "let " + << (has_non_void_args(tfunc) ? "args" : "_") + << " = " + << service_call_args_struct_name(tfunc) + << "::read_from_in_protocol(i_prot)?;" + << endl; + + f_gen_ + << indent() + << "match handler." + << service_call_handler_function_name(tfunc) + << rust_sync_service_call_invocation(tfunc, "args.") + << " {" + << endl; // start match + indent_up(); + + // handler succeeded + string handler_return_variable = tfunc->is_oneway() || tfunc->get_returntype()->is_void() ? "_" : "handler_return"; + f_gen_ << indent() << "Ok(" << handler_return_variable << ") => {" << endl; + indent_up(); + render_sync_handler_succeeded(tfunc); + indent_down(); + f_gen_ << indent() << "}," << endl; + // handler failed + f_gen_ << indent() << "Err(e) => {" << endl; + indent_up(); + render_sync_handler_failed(tfunc); + indent_down(); + f_gen_ << indent() << "}," << endl; + + indent_down(); + f_gen_ << indent() << "}" << endl; // end match + + indent_down(); + f_gen_ << indent() << "}" << endl; // end function +} + +void t_rs_generator::render_sync_handler_succeeded(t_function *tfunc) { + if (tfunc->is_oneway()) { + f_gen_ << indent() << "Ok(())" << endl; + } else { + f_gen_ + << indent() + << "let message_ident = TMessageIdentifier::new(" + << "\"" << tfunc->get_name() << "\", " // note: use *original* name + << "TMessageType::Reply, " + << "incoming_sequence_number);" + << endl; + f_gen_ << indent() << "o_prot.write_message_begin(&message_ident)?;" << endl; + f_gen_ << indent() << "let ret = " << handler_successful_return_struct(tfunc) <<";" << endl; + f_gen_ << indent() << "ret.write_to_out_protocol(o_prot)?;" << endl; + f_gen_ << indent() << "o_prot.write_message_end()?;" << endl; + f_gen_ << indent() << "o_prot.flush()" << endl; + } +} + +void t_rs_generator::render_sync_handler_failed(t_function *tfunc) { + string err_var("e"); + + f_gen_ << indent() << "match " << err_var << " {" << endl; + indent_up(); + + // if there are any user-defined exceptions for this service call handle them first + if (tfunc->get_xceptions() != NULL && tfunc->get_xceptions()->get_sorted_members().size() > 0) { + string user_err_var("usr_err"); + f_gen_ << indent() << "thrift::Error::User(" << user_err_var << ") => {" << endl; + indent_up(); + render_sync_handler_failed_user_exception_branch(tfunc); + indent_down(); + f_gen_ << indent() << "}," << endl; + } + + // application error + string app_err_var("app_err"); + f_gen_ << indent() << "thrift::Error::Application(" << app_err_var << ") => {" << endl; + indent_up(); + render_sync_handler_failed_application_exception_branch(tfunc, app_err_var); + indent_down(); + f_gen_ << indent() << "}," << endl; + + // default case + f_gen_ << indent() << "_ => {" << endl; + indent_up(); + render_sync_handler_failed_default_exception_branch(tfunc); + indent_down(); + f_gen_ << indent() << "}," << endl; + + indent_down(); + f_gen_ << indent() << "}" << endl; +} + +void t_rs_generator::render_sync_handler_failed_user_exception_branch(t_function *tfunc) { + if (tfunc->get_xceptions() == NULL || tfunc->get_xceptions()->get_sorted_members().empty()) { + throw "cannot render user exception branches if no user exceptions defined"; + } + + const vector txceptions = tfunc->get_xceptions()->get_sorted_members(); + vector::const_iterator xception_iter; + int branches_rendered = 0; + + // run through all user-defined exceptions + for (xception_iter = txceptions.begin(); xception_iter != txceptions.end(); ++xception_iter) { + t_field* xception_field = (*xception_iter); + + string if_statement(branches_rendered == 0 ? "if usr_err" : "} else if usr_err"); + string exception_type(to_rust_type(xception_field->get_type())); + f_gen_ << indent() << if_statement << ".downcast_ref::<" << exception_type << ">().is_some() {" << endl; + indent_up(); + + f_gen_ + << indent() + << "let err = usr_err.downcast::<" << exception_type << ">().expect(\"downcast already checked\");" + << endl; + + // render the members of the return struct + ostringstream members; + + bool has_result_variable = !(tfunc->is_oneway() || tfunc->get_returntype()->is_void()); + if (has_result_variable) { + members << SERVICE_RESULT_VARIABLE << ": None, "; + } + + vector::const_iterator xception_members_iter; + for(xception_members_iter = txceptions.begin(); xception_members_iter != txceptions.end(); ++xception_members_iter) { + t_field* member = (*xception_members_iter); + string member_name(rust_field_name(member)); + if (member == xception_field) { + members << member_name << ": Some(*err), "; + } else { + members << member_name << ": None, "; + } + } + + string member_string = members.str(); + member_string.replace(member_string.size() - 2, 2, " "); // trim trailing comma + + // now write out the return struct + f_gen_ + << indent() + << "let ret_err = " + << service_call_result_struct_name(tfunc) + << "{ " << member_string << "};" + << endl; + + f_gen_ + << indent() + << "let message_ident = " + << "TMessageIdentifier::new(" + << "\"" << tfunc->get_name() << "\", " // note: use *original* name + << "TMessageType::Reply, " + << "incoming_sequence_number);" + << endl; + f_gen_ << indent() << "o_prot.write_message_begin(&message_ident)?;" << endl; + f_gen_ << indent() << "ret_err.write_to_out_protocol(o_prot)?;" << endl; + f_gen_ << indent() << "o_prot.write_message_end()?;" << endl; + f_gen_ << indent() << "o_prot.flush()" << endl; + + indent_down(); + + branches_rendered++; + } + + // the catch all, if somehow it was a user exception that we don't support + f_gen_ << indent() << "} else {" << endl; + indent_up(); + + // FIXME: same as default block below + + f_gen_ << indent() << "let ret_err = {" << endl; + indent_up(); + render_thrift_error_struct("ApplicationError", "ApplicationErrorKind::Unknown", "usr_err.description()"); + indent_down(); + f_gen_ << indent() << "};" << endl; + render_sync_handler_send_exception_response(tfunc, "ret_err"); + + indent_down(); + f_gen_ << indent() << "}" << endl; +} + +void t_rs_generator::render_sync_handler_failed_application_exception_branch( + t_function *tfunc, + const string &app_err_var +) { + if (tfunc->is_oneway()) { + f_gen_ << indent() << "Err(thrift::Error::Application(" << app_err_var << "))" << endl; + } else { + render_sync_handler_send_exception_response(tfunc, app_err_var); + } +} + +void t_rs_generator::render_sync_handler_failed_default_exception_branch(t_function *tfunc) { + f_gen_ << indent() << "let ret_err = {" << endl; + indent_up(); + render_thrift_error_struct("ApplicationError", "ApplicationErrorKind::Unknown", "e.description()"); + indent_down(); + f_gen_ << indent() << "};" << endl; + if (tfunc->is_oneway()) { + f_gen_ << indent() << "Err(thrift::Error::Application(ret_err))" << endl; + } else { + render_sync_handler_send_exception_response(tfunc, "ret_err"); + } +} + +void t_rs_generator::render_sync_handler_send_exception_response(t_function *tfunc, const string &err_var) { + f_gen_ + << indent() + << "let message_ident = TMessageIdentifier::new(" + << "\"" << tfunc->get_name() << "\", " // note: use *original* name + << "TMessageType::Exception, " + << "incoming_sequence_number);" + << endl; + f_gen_ << indent() << "o_prot.write_message_begin(&message_ident)?;" << endl; + f_gen_ << indent() << "thrift::Error::write_application_error_to_out_protocol(&" << err_var << ", o_prot)?;" << endl; + f_gen_ << indent() << "o_prot.write_message_end()?;" << endl; + f_gen_ << indent() << "o_prot.flush()" << endl; +} + +string t_rs_generator::handler_successful_return_struct(t_function* tfunc) { + int member_count = 0; + ostringstream return_struct; + + return_struct << service_call_result_struct_name(tfunc) << " { "; + + // actual return + if (!tfunc->get_returntype()->is_void()) { + return_struct << "result_value: Some(handler_return)"; + member_count++; + } + + // any user-defined exceptions + if (tfunc->get_xceptions() != NULL) { + t_struct* txceptions = tfunc->get_xceptions(); + const vector members = txceptions->get_sorted_members(); + vector::const_iterator members_iter; + for (members_iter = members.begin(); members_iter != members.end(); ++members_iter) { + t_field* xception_field = (*members_iter); + if (member_count > 0) { return_struct << ", "; } + return_struct << rust_field_name(xception_field) << ": None"; + member_count++; + } + } + + return_struct << " }"; + + return return_struct.str(); +} + +//----------------------------------------------------------------------------- +// +// Utility +// +//----------------------------------------------------------------------------- + +void t_rs_generator::render_type_comment(const string& type_name) { + f_gen_ << "//" << endl; + f_gen_ << "// " << type_name << endl; + f_gen_ << "//" << endl; + f_gen_ << endl; +} + +// NOTE: do *not* put in an extra newline after doc is generated. +// This is because rust docs have to abut the line they're documenting. +void t_rs_generator::render_rustdoc(t_doc* tdoc) { + if (!tdoc->has_doc()) { + return; + } + + generate_docstring_comment(f_gen_, "", "/// ", tdoc->get_doc(), ""); +} + +void t_rs_generator::render_thrift_error( + const string& error_kind, + const string& error_struct, + const string& sub_error_kind, + const string& error_message +) { + f_gen_ << indent() << "Err(" << endl; + indent_up(); + f_gen_ << indent() << "thrift::Error::" << error_kind << "(" << endl; + indent_up(); + render_thrift_error_struct(error_struct, sub_error_kind, error_message); + indent_down(); + f_gen_ << indent() << ")" << endl; + indent_down(); + f_gen_ << indent() << ")" << endl; +} + +void t_rs_generator::render_thrift_error_struct( + const string& error_struct, + const string& sub_error_kind, + const string& error_message +) { + f_gen_ << indent() << error_struct << "::new(" << endl; + indent_up(); + f_gen_ << indent() << sub_error_kind << "," << endl; + f_gen_ << indent() << error_message << endl; + indent_down(); + f_gen_ << indent() << ")" << endl; +} + +bool t_rs_generator::is_double(t_type* ttype) { + ttype = get_true_type(ttype); + if (ttype->is_base_type()) { + t_base_type::t_base tbase = ((t_base_type*)ttype)->get_base(); + if (tbase == t_base_type::TYPE_DOUBLE) { + return true; + } + } + + return false; +} + +string t_rs_generator::to_rust_type(t_type* ttype, bool ordered_float) { + // ttype = get_true_type(ttype); <-- recurses through as many typedef layers as necessary + if (ttype->is_base_type()) { + t_base_type* tbase_type = ((t_base_type*)ttype); + switch (tbase_type->get_base()) { + case t_base_type::TYPE_VOID: + return "()"; + case t_base_type::TYPE_STRING: + if (tbase_type->is_binary()) { + return "Vec"; + } else { + return "String"; + } + case t_base_type::TYPE_BOOL: + return "bool"; + case t_base_type::TYPE_I8: + return "i8"; + case t_base_type::TYPE_I16: + return "i16"; + case t_base_type::TYPE_I32: + return "i32"; + case t_base_type::TYPE_I64: + return "i64"; + case t_base_type::TYPE_DOUBLE: + if (ordered_float) { + return "OrderedFloat"; + } else { + return "f64"; + } + } + } else if (ttype->is_typedef()) { + t_typedef* ttypedef = (t_typedef*)ttype; + string rust_type = rust_namespace(ttype) + ttypedef->get_symbolic(); + rust_type = ttypedef->is_forward_typedef() ? "Box<" + rust_type + ">" : rust_type; + return rust_type; + } else if (ttype->is_enum()) { + return rust_namespace(ttype) + rust_camel_case(ttype->get_name()); + } else if (ttype->is_struct() || ttype->is_xception()) { + return rust_namespace(ttype) + rust_camel_case(ttype->get_name()); + } else if (ttype->is_map()) { + t_map* tmap = (t_map*)ttype; + return "BTreeMap<" + to_rust_type(tmap->get_key_type()) + ", " + to_rust_type(tmap->get_val_type()) + ">"; + } else if (ttype->is_set()) { + t_set* tset = (t_set*)ttype; + return "BTreeSet<" + to_rust_type(tset->get_elem_type()) + ">"; + } else if (ttype->is_list()) { + t_list* tlist = (t_list*)ttype; + return "Vec<" + to_rust_type(tlist->get_elem_type()) + ">"; + } + + throw "cannot find rust type for " + ttype->get_name(); +} + +string t_rs_generator::to_rust_const_type(t_type* ttype, bool ordered_float) { + if (ttype->is_base_type()) { + t_base_type* tbase_type = ((t_base_type*)ttype); + if (tbase_type->get_base() == t_base_type::TYPE_STRING) { + if (tbase_type->is_binary()) { + return "&[u8]"; + } else { + return "&str"; + } + } + } + + return to_rust_type(ttype, ordered_float); +} + +string t_rs_generator::to_rust_field_type_enum(t_type* ttype) { + ttype = get_true_type(ttype); + if (ttype->is_base_type()) { + t_base_type::t_base tbase = ((t_base_type*)ttype)->get_base(); + switch (tbase) { + case t_base_type::TYPE_VOID: + throw "will not generate protocol::TType for TYPE_VOID"; + case t_base_type::TYPE_STRING: // both strings and binary are actually encoded as TType::String + return "TType::String"; + case t_base_type::TYPE_BOOL: + return "TType::Bool"; + case t_base_type::TYPE_I8: + return "TType::I08"; + case t_base_type::TYPE_I16: + return "TType::I16"; + case t_base_type::TYPE_I32: + return "TType::I32"; + case t_base_type::TYPE_I64: + return "TType::I64"; + case t_base_type::TYPE_DOUBLE: + return "TType::Double"; + } + } else if (ttype->is_enum()) { + return "TType::I32"; + } else if (ttype->is_struct() || ttype->is_xception()) { + return "TType::Struct"; + } else if (ttype->is_map()) { + return "TType::Map"; + } else if (ttype->is_set()) { + return "TType::Set"; + } else if (ttype->is_list()) { + return "TType::List"; + } + + throw "cannot find TType for " + ttype->get_name(); +} + +string t_rs_generator::opt_in_req_out_value(t_type* ttype) { + ttype = get_true_type(ttype); + if (ttype->is_base_type()) { + t_base_type* tbase_type = ((t_base_type*)ttype); + switch (tbase_type->get_base()) { + case t_base_type::TYPE_VOID: + throw "cannot generate OPT_IN_REQ_OUT value for void"; + case t_base_type::TYPE_STRING: + if (tbase_type->is_binary()) { + return "Some(Vec::new())"; + } else { + return "Some(\"\".to_owned())"; + } + case t_base_type::TYPE_BOOL: + return "Some(false)"; + case t_base_type::TYPE_I8: + case t_base_type::TYPE_I16: + case t_base_type::TYPE_I32: + case t_base_type::TYPE_I64: + return "Some(0)"; + case t_base_type::TYPE_DOUBLE: + return "Some(OrderedFloat::from(0.0))"; + } + + } else if (ttype->is_enum() || ttype->is_struct() || ttype->is_xception()) { + return "None"; + } else if (ttype->is_list()) { + return "Some(Vec::new())"; + } else if (ttype->is_set()) { + return "Some(BTreeSet::new())"; + } else if (ttype->is_map()) { + return "Some(BTreeMap::new())"; + } + + throw "cannot generate opt-in-req-out value for type " + ttype->get_name(); +} + +bool t_rs_generator::can_generate_simple_const(t_type* ttype) { + t_type* actual_type = get_true_type(ttype); + if (actual_type->is_base_type()) { + t_base_type* tbase_type = (t_base_type*)actual_type; + return !(tbase_type->get_base() == t_base_type::TYPE_DOUBLE); + } else { + return false; + } +} + +bool t_rs_generator::can_generate_const_holder(t_type* ttype) { + t_type* actual_type = get_true_type(ttype); + return !can_generate_simple_const(actual_type) && !actual_type->is_service(); +} + +bool t_rs_generator::is_void(t_type* ttype) { + return ttype->is_base_type() && ((t_base_type*)ttype)->get_base() == t_base_type::TYPE_VOID; +} + +bool t_rs_generator::is_optional(t_field::e_req req) { + return req == t_field::T_OPTIONAL || req == t_field::T_OPT_IN_REQ_OUT; +} + +t_field::e_req t_rs_generator::actual_field_req(t_field* tfield, t_rs_generator::e_struct_type struct_type) { + return struct_type == t_rs_generator::T_ARGS ? t_field::T_REQUIRED : tfield->get_req(); +} + +bool t_rs_generator::has_args(t_function* tfunc) { + return tfunc->get_arglist() != NULL && !tfunc->get_arglist()->get_sorted_members().empty(); +} + +bool t_rs_generator::has_non_void_args(t_function* tfunc) { + bool has_non_void_args = false; + + const vector args = tfunc->get_arglist()->get_sorted_members(); + vector::const_iterator args_iter; + for (args_iter = args.begin(); args_iter != args.end(); ++args_iter) { + t_field* tfield = (*args_iter); + if (!tfield->get_type()->is_void()) { + has_non_void_args = true; + break; + } + } + + return has_non_void_args; +} + +string t_rs_generator::visibility_qualifier(t_rs_generator::e_struct_type struct_type) { + switch(struct_type) { + case t_rs_generator::T_ARGS: + case t_rs_generator::T_RESULT: + return ""; + default: + return "pub "; + } +} + +string t_rs_generator::rust_namespace(t_service* tservice) { + if (tservice->get_program()->get_name() != get_program()->get_name()) { + return rust_snake_case(tservice->get_program()->get_name()) + "::"; + } else { + return ""; + } +} + +string t_rs_generator::rust_namespace(t_type* ttype) { + if (ttype->get_program()->get_name() != get_program()->get_name()) { + return rust_snake_case(ttype->get_program()->get_name()) + "::"; + } else { + return ""; + } +} + +bool t_rs_generator::is_reserved(const string& name) { + return RUST_RESERVED_WORDS_SET.find(name) != RUST_RESERVED_WORDS_SET.end(); +} + +string t_rs_generator::rust_struct_name(t_struct* tstruct) { + string base_struct_name(rust_camel_case(tstruct->get_name())); + return rust_safe_name(base_struct_name); +} + +string t_rs_generator::rust_field_name(t_field* tfield) { + string base_field_name(rust_snake_case(tfield->get_name())); + return rust_safe_name(base_field_name); +} + +string t_rs_generator::rust_union_field_name(t_field* tfield) { + string base_field_name(rust_camel_case(tfield->get_name())); + return rust_safe_name(base_field_name); +} + +string t_rs_generator::rust_safe_name(const string& name) { + if (is_reserved(name)) { + return name + "_"; + } else { + return name; + } +} + +string t_rs_generator::service_call_client_function_name(t_function* tfunc) { + return rust_snake_case(tfunc->get_name()); +} + +string t_rs_generator::service_call_handler_function_name(t_function* tfunc) { + return "handle_" + rust_snake_case(tfunc->get_name()); +} + +string t_rs_generator::service_call_args_struct_name(t_function* tfunc) { + // Thrift automatically appends `Args` to the arglist name. No need to do it here. + return rust_camel_case(service_name_) + rust_camel_case(tfunc->get_arglist()->get_name()); +} + +string t_rs_generator::service_call_result_struct_name(t_function* tfunc) { + return rust_camel_case(service_name_) + rust_camel_case(tfunc->get_name()) + RESULT_STRUCT_SUFFIX; +} + +string t_rs_generator::rust_sync_client_marker_trait_name(t_service* tservice) { + return "T" + rust_camel_case(tservice->get_name()) + "SyncClientMarker"; +} + +string t_rs_generator::rust_sync_client_trait_name(t_service* tservice) { + return "T" + rust_camel_case(tservice->get_name()) + "SyncClient"; +} + +string t_rs_generator::rust_sync_client_impl_name(t_service* tservice) { + return rust_camel_case(tservice->get_name()) + "SyncClient"; +} + +string t_rs_generator::rust_sync_handler_trait_name(t_service* tservice) { + return rust_camel_case(tservice->get_name()) + "SyncHandler"; +} + +string t_rs_generator::rust_sync_processor_name(t_service* tservice) { + return rust_camel_case(tservice->get_name()) + "SyncProcessor"; +} + +string t_rs_generator::rust_sync_processor_impl_name(t_service *tservice) { + return "T" + rust_camel_case(tservice->get_name()) + "ProcessFunctions"; +} + +string t_rs_generator::rust_enum_variant_name(const string &name) { + bool all_uppercase = true; + + for (size_t i = 0; i < name.size(); i++) { + if (isalnum(name[i]) && islower(name[i])) { + all_uppercase = false; + break; + } + } + + if (all_uppercase) { + return capitalize(camelcase(lowercase(name))); + } else { + return capitalize(camelcase(name)); + } +} + +string t_rs_generator::rust_upper_case(const string& name) { + string str(uppercase(underscore(name))); + string_replace(str, "__", "_"); + return str; +} + +string t_rs_generator::rust_snake_case(const string& name) { + string str(decapitalize(underscore(name))); + string_replace(str, "__", "_"); + return str; +} + +string t_rs_generator::rust_camel_case(const string& name) { + string str(capitalize(camelcase(name))); + string_replace(str, "_", ""); + return str; +} + +void t_rs_generator::string_replace(string& target, const string& search_string, const string& replace_string) { + if (target.empty()) { + return; + } + + size_t match_len = search_string.length(); + size_t replace_len = replace_string.length(); + + size_t search_idx = 0; + size_t match_idx; + while ((match_idx = target.find(search_string, search_idx)) != string::npos) { + target.replace(match_idx, match_len, replace_string); + search_idx = match_idx + replace_len; + } +} + +THRIFT_REGISTER_GENERATOR( + rs, + "Rust", + "\n") // no Rust-generator-specific options diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_st_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_st_generator.cc index ffd7318..595a949 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_st_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_st_generator.cc @@ -56,6 +56,7 @@ public: const std::string& option_string) : t_oop_generator(program) { (void)option_string; + temporary_var = 0; std::map::const_iterator iter; /* no options yet */ @@ -92,8 +93,8 @@ public: * Struct generation code */ - void generate_st_struct(std::ofstream& out, t_struct* tstruct, bool is_exception); - void generate_accessors(std::ofstream& out, t_struct* tstruct); + void generate_st_struct(std::ostream& out, t_struct* tstruct, bool is_exception); + void generate_accessors(std::ostream& out, t_struct* tstruct); /** * Service-level generation functions @@ -123,15 +124,15 @@ public: std::string st_autogen_comment(); - void st_class_def(std::ofstream& out, std::string name); - void st_method(std::ofstream& out, std::string cls, std::string name); - void st_method(std::ofstream& out, std::string cls, std::string name, std::string category); - void st_close_method(std::ofstream& out); - void st_class_method(std::ofstream& out, std::string cls, std::string name); - void st_class_method(std::ofstream& out, std::string cls, std::string name, std::string category); - void st_setter(std::ofstream& out, std::string cls, std::string name, std::string type); - void st_getter(std::ofstream& out, std::string cls, std::string name); - void st_accessors(std::ofstream& out, std::string cls, std::string name, std::string type); + void st_class_def(std::ostream& out, std::string name); + void st_method(std::ostream& out, std::string cls, std::string name); + void st_method(std::ostream& out, std::string cls, std::string name, std::string category); + void st_close_method(std::ostream& out); + void st_class_method(std::ostream& out, std::string cls, std::string name); + void st_class_method(std::ostream& out, std::string cls, std::string name, std::string category); + void st_setter(std::ostream& out, std::string cls, std::string name, std::string type); + void st_getter(std::ostream& out, std::string cls, std::string name); + void st_accessors(std::ostream& out, std::string cls, std::string name, std::string type); std::string class_name(); static bool is_valid_namespace(const std::string& sub_namespace); @@ -155,7 +156,7 @@ private: * File streams */ int temporary_var; - std::ofstream f_; + ofstream_with_content_based_conditional_update f_; }; /** @@ -249,7 +250,7 @@ void t_st_generator::generate_typedef(t_typedef* ttypedef) { (void)ttypedef; } -void t_st_generator::st_class_def(std::ofstream& out, string name) { +void t_st_generator::st_class_def(std::ostream& out, string name) { out << "Object subclass: #" << prefix(name) << endl; indent_up(); out << indent() << "instanceVariableNames: ''" << endl << indent() << "classVariableNames: ''" @@ -257,19 +258,19 @@ void t_st_generator::st_class_def(std::ofstream& out, string name) { << generated_category() << "'!" << endl << endl; } -void t_st_generator::st_method(std::ofstream& out, string cls, string name) { +void t_st_generator::st_method(std::ostream& out, string cls, string name) { st_method(out, cls, name, "as yet uncategorized"); } -void t_st_generator::st_class_method(std::ofstream& out, string cls, string name) { +void t_st_generator::st_class_method(std::ostream& out, string cls, string name) { st_method(out, cls + " class", name); } -void t_st_generator::st_class_method(std::ofstream& out, string cls, string name, string category) { +void t_st_generator::st_class_method(std::ostream& out, string cls, string name, string category) { st_method(out, cls, name, category); } -void t_st_generator::st_method(std::ofstream& out, string cls, string name, string category) { +void t_st_generator::st_method(std::ostream& out, string cls, string name, string category) { char timestr[50]; time_t rawtime; struct tm* tinfo; @@ -285,12 +286,12 @@ void t_st_generator::st_method(std::ofstream& out, string cls, string name, stri out << indent(); } -void t_st_generator::st_close_method(std::ofstream& out) { +void t_st_generator::st_close_method(std::ostream& out) { out << "! !" << endl << endl; indent_down(); } -void t_st_generator::st_setter(std::ofstream& out, +void t_st_generator::st_setter(std::ostream& out, string cls, string name, string type = "anObject") { @@ -299,13 +300,13 @@ void t_st_generator::st_setter(std::ofstream& out, st_close_method(out); } -void t_st_generator::st_getter(std::ofstream& out, string cls, string name) { +void t_st_generator::st_getter(std::ostream& out, string cls, string name) { st_method(out, cls, name + ""); out << "^ " << name; st_close_method(out); } -void t_st_generator::st_accessors(std::ofstream& out, +void t_st_generator::st_accessors(std::ostream& out, string cls, string name, string type = "anObject") { @@ -401,8 +402,8 @@ string t_st_generator::render_const_value(t_type* type, t_const_value* value) { const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { t_type* field_type = NULL; @@ -427,8 +428,8 @@ string t_st_generator::render_const_value(t_type* type, t_const_value* value) { out << "(Dictionary new" << endl; indent_up(); indent_up(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { out << indent() << indent(); out << "at: " << render_const_value(ktype, v_iter->first); @@ -489,7 +490,7 @@ void t_st_generator::generate_xception(t_struct* txception) { /** * Generates a smalltalk class to represent a struct */ -void t_st_generator::generate_st_struct(std::ofstream& out, +void t_st_generator::generate_st_struct(std::ostream& out, t_struct* tstruct, bool is_exception = false) { const vector& members = tstruct->get_members(); @@ -541,7 +542,7 @@ string t_st_generator::a_type(t_type* type) { return prefix + capitalize(type_name(type)); } -void t_st_generator::generate_accessors(std::ofstream& out, t_struct* tstruct) { +void t_st_generator::generate_accessors(std::ostream& out, t_struct* tstruct) { const vector& members = tstruct->get_members(); vector::const_iterator m_iter; string type; diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_swift_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_swift_generator.cc index 87dd2f0..31db04d 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_swift_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_swift_generator.cc @@ -31,7 +31,6 @@ using std::map; using std::ostream; -using std::ofstream; using std::ostringstream; using std::set; using std::string; @@ -41,9 +40,9 @@ using std::vector; static const string endl = "\n"; // avoid ostream << std::endl flushes /** - * Swift code generator. + * Swift 3 code generator. * - * Designed from the Objective-C (aka Cocoa) generator. + * Designed from the Swift/Cocoa code generator(s) */ class t_swift_generator : public t_oop_generator { public: @@ -56,18 +55,33 @@ public: log_unexpected_ = false; async_clients_ = false; - promise_kit_ = false; debug_descriptions_ = false; + no_strict_ = false; + namespaced_ = false; + gen_cocoa_ = false; + promise_kit_ = false; + safe_enums_ = false; for( iter = parsed_options.begin(); iter != parsed_options.end(); ++iter) { if( iter->first.compare("log_unexpected") == 0) { log_unexpected_ = true; } else if( iter->first.compare("async_clients") == 0) { async_clients_ = true; - } else if( iter->first.compare("promise_kit") == 0) { - promise_kit_ = true; + } else if( iter->first.compare("no_strict") == 0) { + no_strict_ = true; } else if( iter->first.compare("debug_descriptions") == 0) { debug_descriptions_ = true; + } else if( iter->first.compare("namespaced") == 0) { + namespaced_ = true; + } else if( iter->first.compare("cocoa") == 0) { + gen_cocoa_ = true; + } else if( iter->first.compare("safe_enums") == 0) { + safe_enums_ = true; + } else if( iter->first.compare("promise_kit") == 0) { + if (gen_cocoa_ == false) { + throw "PromiseKit only available with Swift 2.x, use `cocoa` option" + iter->first; + } + promise_kit_ = true; } else { throw "unknown option swift:" + iter->first; } @@ -95,42 +109,39 @@ public: void generate_xception(t_struct* txception); void generate_service(t_service* tservice); - void print_const_value(ostream& out, - string name, - t_type* type, - t_const_value* value, - bool defval = false, - bool is_property = false); + void render_const_value(ostream& out, t_type* type, t_const_value* value); - void generate_swift_struct(ofstream& out, + void generate_swift_struct(ostream& out, t_struct* tstruct, bool is_private); - void generate_swift_struct_init(ofstream& out, + + void generate_swift_struct_init(ostream& out, t_struct* tstruct, bool all, bool is_private); - void generate_swift_struct_implementation(ofstream& out, + void generate_swift_struct_implementation(ostream& out, t_struct* tstruct, bool is_result, bool is_private); - void generate_swift_struct_hashable_extension(ofstream& out, + void generate_swift_struct_hashable_extension(ostream& out, t_struct* tstruct, bool is_private); - void generate_swift_struct_equatable_extension(ofstream& out, + void generate_swift_struct_equatable_extension(ostream& out, t_struct* tstruct, bool is_private); - void generate_swift_struct_thrift_extension(ofstream& out, + void generate_swift_struct_thrift_extension(ostream& out, t_struct* tstruct, bool is_result, bool is_private); - void generate_swift_struct_reader(ofstream& out, t_struct* tstruct, bool is_private); - void generate_swift_struct_writer(ofstream& out,t_struct* tstruct, bool is_private); - void generate_swift_struct_result_writer(ofstream& out, t_struct* tstruct); - void generate_swift_struct_printable_extension(ofstream& out, t_struct* tstruct); + void generate_swift_struct_reader(ostream& out, t_struct* tstruct, bool is_private); + + + void generate_swift_struct_printable_extension(ostream& out, t_struct* tstruct); + void generate_swift_union_reader(ostream& out, t_struct* tstruct); string function_result_helper_struct_type(t_service *tservice, t_function* tfunction); string function_args_helper_struct_type(t_service* tservice, t_function* tfunction); @@ -140,28 +151,28 @@ public: * Service-level generation functions */ - void generate_swift_service_protocol(ofstream& out, t_service* tservice); - void generate_swift_service_protocol_async(ofstream& out, t_service* tservice); + void generate_swift_service_protocol(ostream& out, t_service* tservice); + void generate_swift_service_protocol_async(ostream& out, t_service* tservice); - void generate_swift_service_client(ofstream& out, t_service* tservice); - void generate_swift_service_client_async(ofstream& out, t_service* tservice); + void generate_swift_service_client(ostream& out, t_service* tservice); + void generate_swift_service_client_async(ostream& out, t_service* tservice); - void generate_swift_service_client_send_function_implementation(ofstream& out, + void generate_swift_service_client_send_function_implementation(ostream& out, t_service* tservice, t_function* tfunction, bool needs_protocol); - void generate_swift_service_client_send_function_invocation(ofstream& out, t_function* tfunction); - void generate_swift_service_client_send_async_function_invocation(ofstream& out, + void generate_swift_service_client_send_function_invocation(ostream& out, t_function* tfunction); + void generate_swift_service_client_send_async_function_invocation(ostream& out, t_function* tfunction); - void generate_swift_service_client_recv_function_implementation(ofstream& out, + void generate_swift_service_client_recv_function_implementation(ostream& out, t_service* tservice, t_function* tfunction, bool needs_protocol); - void generate_swift_service_client_implementation(ofstream& out, t_service* tservice); - void generate_swift_service_client_async_implementation(ofstream& out, t_service* tservice); + void generate_swift_service_client_implementation(ostream& out, t_service* tservice); + void generate_swift_service_client_async_implementation(ostream& out, t_service* tservice); - void generate_swift_service_server(ofstream& out, t_service* tservice); - void generate_swift_service_server_implementation(ofstream& out, t_service* tservice); + void generate_swift_service_server(ostream& out, t_service* tservice); + void generate_swift_service_server_implementation(ostream& out, t_service* tservice); void generate_swift_service_helpers(t_service* tservice); /** @@ -175,13 +186,40 @@ public: string declare_property(t_field* tfield, bool is_private); string function_signature(t_function* tfunction); string async_function_signature(t_function* tfunction); - string promise_function_signature(t_function* tfunction); - string function_name(t_function* tfunction); + + string argument_list(t_struct* tstruct, string protocol_name, bool is_internal); string type_to_enum(t_type* ttype, bool qualified=false); string maybe_escape_identifier(const string& identifier); void populate_reserved_words(); + /** Swift 3 specific */ + string enum_case_name(t_enum_value* tenum_case, bool declaration); + string enum_const_name(string enum_identifier); + void function_docstring(ostream& out, t_function* tfunction); + void async_function_docstring(ostream& out, t_function* tfunction); + void generate_docstring(ostream& out, string& doc); + /** Swift 2/Cocoa carryover */ + string promise_function_signature(t_function* tfunction); + string function_name(t_function* tfunction); + void generate_old_swift_struct_writer(ostream& out,t_struct* tstruct, bool is_private); + void generate_old_swift_struct_result_writer(ostream& out, t_struct* tstruct); + + /** Swift 2/Cocoa backwards compatibility*/ + void generate_old_enum(t_enum* tenum); + void generate_old_swift_struct(ostream& out, + t_struct* tstruct, + bool is_private); + void generate_old_swift_service_client_async_implementation(ostream& out, + t_service* tservice); + + static std::string get_real_swift_module(const t_program* program) { + std::string real_module = program->get_namespace("swift"); + if (real_module.empty()) { + return program->get_name(); + } + return real_module; + } private: void block_open(ostream& out) { @@ -195,9 +233,15 @@ private: if (end_line) out << endl; } - bool field_is_optional(t_field* tfield) { - return tfield->get_req() == t_field::T_OPTIONAL; + bool opt = tfield->get_req() == t_field::T_OPTIONAL; + if (tfield->annotations_.find("swift.nullable") != tfield->annotations_.end() && tfield->get_req() != t_field::T_REQUIRED) { + opt = true; + } + if (gen_cocoa_) { // Backwards compatibility, only if its actually "optional" + opt = tfield->get_req() == t_field::T_OPTIONAL; + } + return opt; } bool struct_has_required_fields(t_struct* tstruct) { @@ -228,15 +272,22 @@ private: * File streams */ - ofstream f_decl_; - ofstream f_impl_; + ofstream_with_content_based_conditional_update f_decl_; + ofstream_with_content_based_conditional_update f_impl_; bool log_unexpected_; bool async_clients_; - bool promise_kit_; - bool debug_descriptions_; + bool debug_descriptions_; + bool no_strict_; + bool namespaced_; + bool safe_enums_; set swift_reserved_words_; + + /** Swift 2/Cocoa compatibility */ + bool gen_cocoa_; + bool promise_kit_; + }; /** @@ -245,13 +296,21 @@ private: */ void t_swift_generator::init_generator() { // Make output directory - MKDIR(get_out_dir().c_str()); + string module = get_real_swift_module(program_); + string out_dir = get_out_dir(); + string module_path = out_dir; + string name = program_name_; + if (namespaced_ && !module.empty()) { + module_path = module_path + "/" + module; + name = module; + } + MKDIR(module_path.c_str()); populate_reserved_words(); // we have a .swift declarations file... - string f_decl_name = capitalize(program_name_) + ".swift"; - string f_decl_fullname = get_out_dir() + f_decl_name; + string f_decl_name = name + ".swift"; + string f_decl_fullname = module_path + "/" + f_decl_name; f_decl_.open(f_decl_fullname.c_str()); f_decl_ << autogen_comment() << endl; @@ -259,8 +318,8 @@ void t_swift_generator::init_generator() { f_decl_ << swift_imports() << swift_thrift_imports() << endl; // ...and a .swift implementation extensions file - string f_impl_name = capitalize(program_name_) + "+Exts.swift"; - string f_impl_fullname = get_out_dir() + f_impl_name; + string f_impl_name = name + "+Exts.swift"; + string f_impl_fullname = module_path + "/" + f_impl_name; f_impl_.open(f_impl_fullname.c_str()); f_impl_ << autogen_comment() << endl; @@ -286,6 +345,12 @@ string t_swift_generator::swift_imports() { includes << "import " << *i_iter << endl; } + if (namespaced_) { + const vector& program_includes = program_->get_includes(); + for (size_t i = 0; i < program_includes.size(); ++i) { + includes << ("import " + get_real_swift_module(program_includes[i])) << endl; + } + } includes << endl; return includes.str(); @@ -301,7 +366,7 @@ string t_swift_generator::swift_thrift_imports() { vector includes_list; includes_list.push_back("Thrift"); - if (promise_kit_) { + if (gen_cocoa_ && promise_kit_) { includes_list.push_back("PromiseKit"); } @@ -337,14 +402,110 @@ void t_swift_generator::generate_typedef(t_typedef* ttypedef) { f_decl_ << endl; } + /** * Generates code for an enumerated type. In Swift, this is * essentially the same as the thrift definition itself, using - * Swift syntax. + * Swift syntax. Conforms to TEnum which + * implementes read/write. * * @param tenum The enumeration */ void t_swift_generator::generate_enum(t_enum* tenum) { + if (gen_cocoa_) { + generate_old_enum(tenum); + return; + } + f_decl_ << indent() << "public enum " << tenum->get_name() << " : TEnum"; + block_open(f_decl_); + + vector constants = tenum->get_constants(); + vector::iterator c_iter; + + for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) { + f_decl_ << indent() << "case " << enum_case_name((*c_iter), true) << endl; + } + + // unknown associated value case for safety and similar behavior to other languages + if (safe_enums_) { + f_decl_ << indent() << "case unknown(Int32)" << endl; + } + f_decl_ << endl; + + // TSerializable read(from:) + f_decl_ << indent() << "public static func read(from proto: TProtocol) throws -> " + << tenum->get_name(); + block_open(f_decl_); + f_decl_ << indent() << "let raw: Int32 = try proto.read()" << endl; + f_decl_ << indent() << "let new = " << tenum->get_name() << "(rawValue: raw)" << endl; + + f_decl_ << indent() << "if let unwrapped = new {" << endl; + indent_up(); + f_decl_ << indent() << "return unwrapped" << endl; + indent_down(); + f_decl_ << indent() << "} else {" << endl; + indent_up(); + f_decl_ << indent() << "throw TProtocolError(error: .invalidData," << endl; + f_decl_ << indent() << " message: \"Invalid enum value (\\(raw)) for \\(" + << tenum->get_name() << ".self)\")" << endl; + indent_down(); + f_decl_ << indent() << "}" << endl; + block_close(f_decl_); + + // empty init for TSerializable + f_decl_ << endl; + f_decl_ << indent() << "public init()"; + block_open(f_decl_); + + f_decl_ << indent() << "self = ." << enum_case_name(constants.front(), false) << endl; + block_close(f_decl_); + f_decl_ << endl; + + // rawValue getter + f_decl_ << indent() << "public var rawValue: Int32"; + block_open(f_decl_); + f_decl_ << indent() << "switch self {" << endl; + for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) { + f_decl_ << indent() << "case ." << enum_case_name((*c_iter), true) + << ": return " << (*c_iter)->get_value() << endl; + } + if (safe_enums_) { + f_decl_ << indent() << "case .unknown(let value): return value" << endl; + } + f_decl_ << indent() << "}" << endl; + block_close(f_decl_); + f_decl_ << endl; + + // convenience rawValue initalizer + f_decl_ << indent() << "public init?(rawValue: Int32)"; + block_open(f_decl_); + f_decl_ << indent() << "switch rawValue {" << endl;; + for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) { + f_decl_ << indent() << "case " << (*c_iter)->get_value() + << ": self = ." << enum_case_name((*c_iter), true) << endl; + } + if (!safe_enums_) { + f_decl_ << indent() << "default: return nil" << endl; + } else { + f_decl_ << indent() << "default: self = .unknown(rawValue)" << endl; + } + f_decl_ << indent() << "}" << endl; + block_close(f_decl_); + + + + + block_close(f_decl_); + f_decl_ << endl; +} + +/** + * Generates code for an enumerated type. This is for Swift 2.x/Cocoa + * backwards compatibility + * + * @param tenum The enumeration + */ +void t_swift_generator::generate_old_enum(t_enum* tenum) { f_decl_ << indent() << "public enum " << tenum->get_name() << " : Int32"; block_open(f_decl_); @@ -385,6 +546,31 @@ void t_swift_generator::generate_enum(t_enum* tenum) { f_impl_ << endl; } +string t_swift_generator::enum_case_name(t_enum_value* tenum_case, bool declaration) { + string name = tenum_case->get_name(); + // force to lowercase for Swift style, maybe escape if its a keyword + std::transform(name.begin(), name.end(), name.begin(), ::tolower); + if (declaration) { + name = maybe_escape_identifier(name); + } + return name; +} + +/** + * Renders a constant enum value by transforming the value portion to lowercase + * for Swift style. + */ +string t_swift_generator::enum_const_name(string enum_identifier) { + string::iterator it; + for (it = enum_identifier.begin(); it < enum_identifier.end(); ++it) { + if ((*it) == '.') { + break; + } + } + std::transform(it, enum_identifier.end(), it, ::tolower); + return enum_identifier; +} + /** * Generates public constants for all Thrift constants. * @@ -425,7 +611,7 @@ void t_swift_generator::generate_struct(t_struct* tstruct) { } /** - * Exceptions are structs, but they conform to ErrorType + * Exceptions are structs, but they conform to Error * * @param tstruct The struct definition */ @@ -434,6 +620,34 @@ void t_swift_generator::generate_xception(t_struct* txception) { generate_swift_struct_implementation(f_impl_, txception, false, false); } +void t_swift_generator::generate_docstring(ostream& out, string& doc) { + if (doc != "") { + std::vector strings; + + std::string::size_type pos = 0; + std::string::size_type prev = 0; + while (((pos = doc.find("\n", prev)) != std::string::npos) + || ((pos = doc.find("\r", prev)) != std::string::npos) + || ((pos = doc.find("\r\n", prev)) != std::string::npos)) + { + strings.push_back(doc.substr(prev, pos - prev)); + prev = pos + 1; + } + + // To get the last substring (or only, if delimiter is not found) + strings.push_back(doc.substr(prev)); + + vector::const_iterator d_iter; + for (d_iter = strings.begin(); d_iter != strings.end(); ++d_iter) { + if ((*d_iter) != "") { + out << indent() << "/// " << (*d_iter) << endl; + } + } + } +} + + + /** * Generate the interface for a struct. Only properties and * init methods are included. @@ -442,10 +656,87 @@ void t_swift_generator::generate_xception(t_struct* txception) { * @param is_private * Is the struct public or private */ -void t_swift_generator::generate_swift_struct(ofstream& out, +void t_swift_generator::generate_swift_struct(ostream& out, t_struct* tstruct, bool is_private) { + if (gen_cocoa_) { + generate_old_swift_struct(out, tstruct, is_private); + return; + } + string doc = tstruct->get_doc(); + generate_docstring(out, doc); + + + // properties + const vector& members = tstruct->get_members(); + vector::const_iterator m_iter; + + + if (tstruct->is_union()) { + // special, unions + out << indent() << "public enum " << tstruct->get_name(); + block_open(out); + for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { + out << endl; + string doc = (*m_iter)->get_doc(); + generate_docstring(out, doc); + out << indent() << "case " + << maybe_escape_identifier((*m_iter)->get_name()) << "(val: " + << type_name((*m_iter)->get_type(), false) << ")" << endl; + } + } else { + // Normal structs + + string visibility = is_private ? (gen_cocoa_ ? "private" : "fileprivate") : "public"; + + out << indent() << visibility << " final class " << tstruct->get_name(); + + if (tstruct->is_xception()) { + out << " : Swift.Error"; // Error seems to be a common exception name in thrift + } + + block_open(out); + for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { + out << endl; + // TODO: Defaults + + string doc = (*m_iter)->get_doc(); + generate_docstring(out, doc); + + out << indent() << declare_property(*m_iter, is_private) << endl; + } + + out << endl; + out << endl; + + if (!struct_has_required_fields(tstruct)) { + indent(out) << visibility << " init() { }" << endl; + } + if (struct_has_required_fields(tstruct)) { + generate_swift_struct_init(out, tstruct, false, is_private); + } + if (struct_has_optional_fields(tstruct)) { + generate_swift_struct_init(out, tstruct, true, is_private); + } + } + + block_close(out); + + out << endl; +} + +/** + * Legacy Swift2/Cocoa generator + * + * @param tstruct + * @param is_private + */ + + +void t_swift_generator::generate_old_swift_struct(ostream& out, + t_struct* tstruct, + bool is_private) { string visibility = is_private ? "private" : "public"; out << indent() << visibility << " final class " << tstruct->get_name(); @@ -495,12 +786,12 @@ void t_swift_generator::generate_swift_struct(ofstream& out, * @param is_private * Is the initializer public or private */ -void t_swift_generator::generate_swift_struct_init(ofstream& out, +void t_swift_generator::generate_swift_struct_init(ostream& out, t_struct* tstruct, bool all, bool is_private) { - string visibility = is_private ? "private" : "public"; + string visibility = is_private ? (gen_cocoa_ ? "private" : "fileprivate") : "public"; indent(out) << visibility << " init("; @@ -526,9 +817,19 @@ void t_swift_generator::generate_swift_struct_init(ofstream& out, block_open(out); for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { - if (all || (*m_iter)->get_req() == t_field::T_REQUIRED || (*m_iter)->get_req() == t_field::T_OPT_IN_REQ_OUT) { - out << indent() << "self." << maybe_escape_identifier((*m_iter)->get_name()) << " = " - << maybe_escape_identifier((*m_iter)->get_name()) << endl; + if (!gen_cocoa_) { + bool should_set = all; + should_set = should_set || !field_is_optional((*m_iter)); + if (should_set) { + out << indent() << "self." << maybe_escape_identifier((*m_iter)->get_name()) << " = " + << maybe_escape_identifier((*m_iter)->get_name()) << endl; + } + } else { + /** legacy Swift2/Cocoa */ + if (all || (*m_iter)->get_req() == t_field::T_REQUIRED || (*m_iter)->get_req() == t_field::T_OPT_IN_REQ_OUT) { + out << indent() << "self." << maybe_escape_identifier((*m_iter)->get_name()) << " = " + << maybe_escape_identifier((*m_iter)->get_name()) << endl; + } } } @@ -544,38 +845,39 @@ void t_swift_generator::generate_swift_struct_init(ofstream& out, * @param is_private * Is the struct public or private */ -void t_swift_generator::generate_swift_struct_hashable_extension(ofstream& out, +void t_swift_generator::generate_swift_struct_hashable_extension(ostream& out, t_struct* tstruct, bool is_private) { - string visibility = is_private ? "private" : "public"; - + string visibility = is_private ? (gen_cocoa_ ? "private" : "fileprivate") : "public"; indent(out) << "extension " << tstruct->get_name() << " : Hashable"; - block_open(out); - out << endl; - indent(out) << visibility << " var hashValue : Int"; - block_open(out); - const vector& members = tstruct->get_members(); vector::const_iterator m_iter; if (!members.empty()) { indent(out) << "let prime = 31" << endl; indent(out) << "var result = 1" << endl; - - for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { - t_field* tfield = *m_iter; - string accessor = field_is_optional(tfield) ? "?." : "."; - string defaultor = field_is_optional(tfield) ? " ?? 0" : ""; - indent(out) << "result = prime &* result &+ (" << maybe_escape_identifier(tfield->get_name()) << accessor - << "hashValue" << defaultor << ")" << endl; + if (!tstruct->is_union()) { + for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { + t_field* tfield = *m_iter; + string accessor = field_is_optional(tfield) ? "?." : "."; + string defaultor = field_is_optional(tfield) ? " ?? 0" : ""; + indent(out) << "result = prime &* result &+ (" << maybe_escape_identifier(tfield->get_name()) << accessor + << "hashValue" << defaultor << ")" << endl; + } + } else { + indent(out) << "switch self {" << endl; + for (m_iter = members.begin(); m_iter != members.end(); m_iter++) { + t_field *tfield = *m_iter; + indent(out) << "case ." << tfield->get_name() << "(let val): result = prime &* val.hashValue" << endl; + } + indent(out) << "}" << endl << endl; } - indent(out) << "return result" << endl; } else { @@ -583,11 +885,8 @@ void t_swift_generator::generate_swift_struct_hashable_extension(ofstream& out, } block_close(out); - out << endl; - block_close(out); - out << endl; } @@ -598,46 +897,55 @@ void t_swift_generator::generate_swift_struct_hashable_extension(ofstream& out, * @param is_private * Is the struct public or private */ -void t_swift_generator::generate_swift_struct_equatable_extension(ofstream& out, +void t_swift_generator::generate_swift_struct_equatable_extension(ostream& out, t_struct* tstruct, bool is_private) { - string visibility = is_private ? "private" : "public"; - - indent(out) << visibility << " func ==(lhs: " << type_name(tstruct) << ", rhs: " << type_name(tstruct) << ") -> Bool"; + string visibility = is_private ? (gen_cocoa_ ? "private" : "fileprivate") : "public"; + indent(out) << visibility << " func ==(lhs: " << type_name(tstruct) << ", rhs: " + << type_name(tstruct) << ") -> Bool"; block_open(out); - indent(out) << "return"; const vector& members = tstruct->get_members(); vector::const_iterator m_iter; if (members.size()) { - - out << endl; - - indent_up(); - - for (m_iter = members.begin(); m_iter != members.end();) { - t_field* tfield = *m_iter; - indent(out) << "(lhs." << maybe_escape_identifier(tfield->get_name()) - << " ?== rhs." << maybe_escape_identifier(tfield->get_name()) << ")"; - if (++m_iter != members.end()) { - out << " &&"; - } + if (!tstruct->is_union()) { out << endl; + indent_up(); + + for (m_iter = members.begin(); m_iter != members.end();) { + t_field* tfield = *m_iter; + indent(out) << "(lhs." << maybe_escape_identifier(tfield->get_name()) + << (gen_cocoa_ ? " ?" : " ") << "== rhs." << maybe_escape_identifier(tfield->get_name()) << ")"; // swift 2 ?== operator not in 3? + if (++m_iter != members.end()) { + out << " &&"; + } + out << endl; + } + indent_down(); + } else { + block_open(out); + indent(out) << "switch (lhs, rhs) {" << endl; + for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { + t_field* tfield = *m_iter; + indent(out) << "case (." << tfield->get_name() << "(let lval), ." + << tfield->get_name() << "(let rval)): return lval == rval" + << endl; + } + indent(out) << "default: return false" << endl; + indent(out) << "}" << endl; + indent_down(); + indent(out) << "}()" << endl; } - - indent_down(); - } else { out << " true" << endl; } block_close(out); - out << endl; } @@ -651,14 +959,14 @@ void t_swift_generator::generate_swift_struct_equatable_extension(ofstream& out, * @param is_private * Is the struct public or private */ -void t_swift_generator::generate_swift_struct_implementation(ofstream& out, +void t_swift_generator::generate_swift_struct_implementation(ostream& out, t_struct* tstruct, bool is_result, bool is_private) { generate_swift_struct_equatable_extension(out, tstruct, is_private); - if (!is_private && !is_result) { + if (!is_private && !is_result && !gen_cocoa_) { // old compiler didn't use debug_descriptions, OR it with gen_cocoa_ so the flag doesn't matter w/ cocoa generate_swift_struct_printable_extension(out, tstruct); } @@ -677,7 +985,7 @@ void t_swift_generator::generate_swift_struct_implementation(ofstream& out, * @param is_private * Is the struct public or private */ -void t_swift_generator::generate_swift_struct_thrift_extension(ofstream& out, +void t_swift_generator::generate_swift_struct_thrift_extension(ostream& out, t_struct* tstruct, bool is_result, bool is_private) { @@ -687,21 +995,130 @@ void t_swift_generator::generate_swift_struct_thrift_extension(ofstream& out, block_open(out); out << endl; + if (!gen_cocoa_) { + /** Swift 3, no writer we just write field ID's */ + string access = (is_private) ? (gen_cocoa_ ? "private" : "fileprivate") : "public"; + // generate fieldID's dictionary + out << indent() << access << " static var fieldIds: [String: Int32]"; + block_open(out); + out << indent() << "return ["; + const vector& fields = tstruct->get_members(); + vector::const_iterator f_iter; + bool wrote = false; + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { + wrote = true; + out << "\"" << (*f_iter)->get_name() << "\": " << (*f_iter)->get_key() << ", "; + } + if (!wrote) { + // pad a colon + out << ":"; + } + out << "]" << endl; + block_close(out); + out << endl; + out << indent() << access << " static var structName: String { return \"" + << tstruct->get_name() << "\" }" << endl << endl; - generate_swift_struct_reader(out, tstruct, is_private); + if (tstruct->is_union()) { + generate_swift_union_reader(out, tstruct); + } else { + generate_swift_struct_reader(out, tstruct, is_private); + } + } else { + /** Legacy Swift2/Cocoa */ - if (is_result) { - generate_swift_struct_result_writer(out, tstruct); - } - else { - generate_swift_struct_writer(out, tstruct, is_private); + generate_swift_struct_reader(out, tstruct, is_private); + + if (is_result) { + generate_old_swift_struct_result_writer(out, tstruct); + } + else { + generate_old_swift_struct_writer(out, tstruct, is_private); + } } block_close(out); - out << endl; } +void t_swift_generator::generate_swift_union_reader(ostream& out, t_struct* tstruct) { + indent(out) << "public static func read(from proto: TProtocol) throws -> " + << tstruct->get_name(); + block_open(out); + indent(out) << "_ = try proto.readStructBegin()" << endl; + + indent(out) << "var ret: " << tstruct->get_name() << "?"; + out << endl; + indent(out) << "fields: while true"; + block_open(out); + out << endl; + indent(out) << "let (_, fieldType, fieldID) = try proto.readFieldBegin()" << endl << endl; + indent(out) << "switch (fieldID, fieldType)"; + block_open(out); + indent(out) << "case (_, .stop): break fields" << endl; + + const vector& fields = tstruct->get_members(); + vector::const_iterator f_iter; + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { + indent(out) << "case (" << (*f_iter)->get_key() << ", " << type_to_enum((*f_iter)->get_type()) << "):"; + string padding = ""; + + t_type* type = get_true_type((*f_iter)->get_type()); + if (type->is_base_type()) { + t_base_type::t_base tbase = ((t_base_type*)type)->get_base(); + switch (tbase) { + case t_base_type::TYPE_STRING: + case t_base_type::TYPE_DOUBLE: + padding = " "; + break; + + case t_base_type::TYPE_BOOL: + case t_base_type::TYPE_I8: + padding = " "; + break; + case t_base_type::TYPE_I16: + case t_base_type::TYPE_I32: + case t_base_type::TYPE_I64: + padding = " "; + break; + default: break; + } + } else if (type->is_enum() || type->is_set() || type->is_map()) { + padding = " "; + } else if (type->is_struct() || type->is_xception()) { + padding = " "; + } else if (type->is_list()) { + padding = " "; + } + + indent(out) << padding << "ret = " << tstruct->get_name() << "." + << (*f_iter)->get_name() << "(val: " << "try " + << type_name((*f_iter)->get_type(), false, false) + << ".read(from: proto))" << endl; + } + + indent(out) << "case let (_, unknownType): try proto.skip(type: unknownType)" << endl; + + block_close(out); + indent(out) << "try proto.readFieldEnd()" << endl; + + block_close(out); + out << endl; + + indent(out) << "try proto.readStructEnd()" << endl; + + indent(out) << "if let ret = ret"; + block_open(out); + indent(out) << "return ret" << endl; + block_close(out); + out << endl; + indent(out) << "throw TProtocolError(error: .unknown, message: \"Missing required value for type: " + << tstruct->get_name() << "\")"; + block_close(out); + out << endl; + +} + /** * Generates a function to read a struct from * from a protocol. (TStruct compliance) @@ -710,100 +1127,196 @@ void t_swift_generator::generate_swift_struct_thrift_extension(ofstream& out, * @param is_private * Is the struct public or private */ -void t_swift_generator::generate_swift_struct_reader(ofstream& out, +void t_swift_generator::generate_swift_struct_reader(ostream& out, t_struct* tstruct, bool is_private) { - string visibility = is_private ? "private" : "public"; + if (!gen_cocoa_) { + /** Swift 3 case */ + string visibility = is_private ? "fileprivate" : "public"; - indent(out) << visibility << " static func readValueFromProtocol(__proto: TProtocol) throws -> " - << tstruct->get_name(); + indent(out) << visibility << " static func read(from proto: TProtocol) throws -> " + << tstruct->get_name(); - block_open(out); + block_open(out); + indent(out) << "_ = try proto.readStructBegin()" << endl; - out << endl; - - indent(out) << "try __proto.readStructBegin()" << endl << endl; - - const vector& fields = tstruct->get_members(); - vector::const_iterator f_iter; - - for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { - bool optional = field_is_optional(*f_iter); - indent(out) << "var " << maybe_escape_identifier((*f_iter)->get_name()) << " : " - << type_name((*f_iter)->get_type(), optional, !optional) << endl; - } - - out << endl; - - // Loop over reading in fields - indent(out) << "fields: while true"; - - block_open(out); - - out << endl; - - indent(out) << "let (_, fieldType, fieldID) = try __proto.readFieldBegin()" << endl << endl; - indent(out) << "switch (fieldID, fieldType)"; - - block_open(out); - - indent(out) << "case (_, .STOP):" << endl; - indent_up(); - indent(out) << "break fields" << endl << endl; - indent_down(); - - // Generate deserialization code for known cases - for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { - - indent(out) << "case (" << (*f_iter)->get_key() << ", " << type_to_enum((*f_iter)->get_type()) << "):" << endl; - indent_up(); - indent(out) << maybe_escape_identifier((*f_iter)->get_name()) << " = try __proto.readValue() as " - << type_name((*f_iter)->get_type()) << endl << endl; - indent_down(); - - } - - indent(out) << "case let (_, unknownType):" << endl; - indent_up(); - indent(out) << "try __proto.skipType(unknownType)" << endl; - indent_down(); - - block_close(out); - - out << endl; - - // Read field end marker - indent(out) << "try __proto.readFieldEnd()" << endl; - - block_close(out); - - out << endl; - - indent(out) << "try __proto.readStructEnd()" << endl; - - out << endl; - - if (struct_has_required_fields(tstruct)) { - // performs various checks (e.g. check that all required fields are set) - indent(out) << "// Required fields" << endl; + const vector& fields = tstruct->get_members(); + vector::const_iterator f_iter; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { - if (field_is_optional(*f_iter)) { - continue; - } - indent(out) << "try __proto.validateValue(" << (*f_iter)->get_name() << ", " - << "named: \"" << (*f_iter)->get_name() << "\")" << endl; + bool optional = field_is_optional(*f_iter); + indent(out) << "var " << maybe_escape_identifier((*f_iter)->get_name()) << ": " + << type_name((*f_iter)->get_type(), optional, !optional) << endl; } - } - out << endl; + out << endl; - indent(out) << "return " << tstruct->get_name() << "("; - for (f_iter = fields.begin(); f_iter != fields.end();) { - out << (*f_iter)->get_name() << ": " << maybe_escape_identifier((*f_iter)->get_name()); - if (++f_iter != fields.end()) { - out << ", "; + // Loop over reading in fields + indent(out) << "fields: while true"; + block_open(out); + out << endl; + + indent(out) << "let (_, fieldType, fieldID) = try proto.readFieldBegin()" << endl << endl; + indent(out) << "switch (fieldID, fieldType)"; + block_open(out); + indent(out) << "case (_, .stop): break fields" << endl; + + + // Generate deserialization code for known cases + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { + indent(out) << "case (" << (*f_iter)->get_key() << ", " << type_to_enum((*f_iter)->get_type()) << "):"; + string padding = ""; + + t_type* type = get_true_type((*f_iter)->get_type()); + if (type->is_base_type()) { + t_base_type::t_base tbase = ((t_base_type*)type)->get_base(); + switch (tbase) { + case t_base_type::TYPE_STRING: + case t_base_type::TYPE_DOUBLE: + padding = " "; + break; + + case t_base_type::TYPE_BOOL: + case t_base_type::TYPE_I8: + padding = " "; + break; + case t_base_type::TYPE_I16: + case t_base_type::TYPE_I32: + case t_base_type::TYPE_I64: + padding = " "; + break; + default: break; + } + } else if (type->is_enum() || type->is_set() || type->is_map()) { + padding = " "; + } else if (type->is_struct() || type->is_xception()) { + padding = " "; + } else if (type->is_list()) { + padding = " "; + } + + out << padding << maybe_escape_identifier((*f_iter)->get_name()) << " = try " + << type_name((*f_iter)->get_type(), false, false) << ".read(from: proto)" << endl; + } + + indent(out) << "case let (_, unknownType): try proto.skip(type: unknownType)" << endl; + block_close(out); + out << endl; + + // Read field end marker + indent(out) << "try proto.readFieldEnd()" << endl; + block_close(out); + out << endl; + indent(out) << "try proto.readStructEnd()" << endl; + + if (struct_has_required_fields(tstruct)) { + // performs various checks (e.g. check that all required fields are set) + indent(out) << "// Required fields" << endl; + + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { + if (field_is_optional(*f_iter)) { + continue; + } + indent(out) << "try proto.validateValue(" << (*f_iter)->get_name() << ", " + << "named: \"" << (*f_iter)->get_name() << "\")" << endl; + } + } + + out << endl; + + indent(out) << "return " << tstruct->get_name() << "("; + for (f_iter = fields.begin(); f_iter != fields.end();) { + out << (*f_iter)->get_name() << ": " << maybe_escape_identifier((*f_iter)->get_name()); + if (++f_iter != fields.end()) { + out << ", "; + } + } + + } else { + /** Legacy Swif2/Cocoa case */ + string visibility = is_private ? "private" : "public"; + + indent(out) << visibility << " static func readValueFromProtocol(__proto: TProtocol) throws -> " + << tstruct->get_name(); + + block_open(out); + out << endl; + indent(out) << "try __proto.readStructBegin()" << endl << endl; + + const vector& fields = tstruct->get_members(); + vector::const_iterator f_iter; + + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { + bool optional = field_is_optional(*f_iter); + indent(out) << "var " << maybe_escape_identifier((*f_iter)->get_name()) << " : " + << type_name((*f_iter)->get_type(), optional, !optional) << endl; + } + + out << endl; + + // Loop over reading in fields + indent(out) << "fields: while true"; + block_open(out); + out << endl; + + indent(out) << "let (_, fieldType, fieldID) = try __proto.readFieldBegin()" << endl << endl; + indent(out) << "switch (fieldID, fieldType)"; + + block_open(out); + + indent(out) << "case (_, .STOP):" << endl; + indent_up(); + indent(out) << "break fields" << endl << endl; + indent_down(); + + // Generate deserialization code for known cases + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { + + indent(out) << "case (" << (*f_iter)->get_key() << ", " << type_to_enum((*f_iter)->get_type()) << "):" << endl; + indent_up(); + indent(out) << maybe_escape_identifier((*f_iter)->get_name()) << " = try __proto.readValue() as " + << type_name((*f_iter)->get_type()) << endl << endl; + indent_down(); + + } + + indent(out) << "case let (_, unknownType):" << endl; + indent_up(); + indent(out) << "try __proto.skipType(unknownType)" << endl; + indent_down(); + block_close(out); + out << endl; + + // Read field end marker + indent(out) << "try __proto.readFieldEnd()" << endl; + + block_close(out); + out << endl; + indent(out) << "try __proto.readStructEnd()" << endl; + out << endl; + + if (struct_has_required_fields(tstruct)) { + // performs various checks (e.g. check that all required fields are set) + indent(out) << "// Required fields" << endl; + + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { + if (field_is_optional(*f_iter)) { + continue; + } + indent(out) << "try __proto.validateValue(" << (*f_iter)->get_name() << ", " + << "named: \"" << (*f_iter)->get_name() << "\")" << endl; + } + } + + out << endl; + + indent(out) << "return " << tstruct->get_name() << "("; + for (f_iter = fields.begin(); f_iter != fields.end();) { + out << (*f_iter)->get_name() << ": " << maybe_escape_identifier((*f_iter)->get_name()); + if (++f_iter != fields.end()) { + out << ", "; + } } } out << ")" << endl; @@ -815,22 +1328,21 @@ void t_swift_generator::generate_swift_struct_reader(ofstream& out, /** * Generates a function to write a struct to - * a protocol. (TStruct compliance) + * a protocol. (TStruct compliance) ONLY FOR SWIFT2/COCOA * * @param tstruct The structure definition * @param is_private * Is the struct public or private */ -void t_swift_generator::generate_swift_struct_writer(ofstream& out, - t_struct* tstruct, - bool is_private) { +void t_swift_generator::generate_old_swift_struct_writer(ostream& out, + t_struct* tstruct, + bool is_private) { string visibility = is_private ? "private" : "public"; - indent(out) << visibility << " static func writeValue(__value: " << tstruct->get_name() << ", toProtocol __proto: TProtocol) throws"; - + indent(out) << visibility << " static func writeValue(__value: " << tstruct->get_name() + << ", toProtocol __proto: TProtocol) throws"; block_open(out); - out << endl; string name = tstruct->get_name(); @@ -838,7 +1350,6 @@ void t_swift_generator::generate_swift_struct_writer(ofstream& out, vector::const_iterator f_iter; indent(out) << "try __proto.writeStructBeginWithName(\"" << name << "\")" << endl; - out << endl; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { @@ -865,37 +1376,30 @@ void t_swift_generator::generate_swift_struct_writer(ofstream& out, } indent(out) << "try __proto.writeFieldStop()" << endl << endl; - indent(out) << "try __proto.writeStructEnd()" << endl; - block_close(out); - out << endl; } /** * Generates a function to read a struct from - * from a protocol. (TStruct compliance) + * from a protocol. (TStruct compliance) ONLY FOR SWIFT 2/COCOA * * This is specifically a function result. Only * the first available field is written. * * @param tstruct The structure definition */ -void t_swift_generator::generate_swift_struct_result_writer(ofstream& out, t_struct* tstruct) { - - indent(out) << "private static func writeValue(__value: " << tstruct->get_name() << ", toProtocol __proto: TProtocol) throws"; +void t_swift_generator::generate_old_swift_struct_result_writer(ostream& out, t_struct* tstruct) { + indent(out) << "private static func writeValue(__value: " << tstruct->get_name() + << ", toProtocol __proto: TProtocol) throws"; block_open(out); - out << endl; - string name = tstruct->get_name(); const vector& fields = tstruct->get_members(); vector::const_iterator f_iter; - indent(out) << "try __proto.writeStructBeginWithName(\"" << name << "\")" << endl; - out << endl; for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { @@ -914,11 +1418,8 @@ void t_swift_generator::generate_swift_struct_result_writer(ofstream& out, t_str } // Write the struct map indent(out) << "try __proto.writeFieldStop()" << endl << endl; - indent(out) << "try __proto.writeStructEnd()" << endl; - block_close(out); - out << endl; } @@ -927,43 +1428,60 @@ void t_swift_generator::generate_swift_struct_result_writer(ofstream& out, t_str * * @param tstruct The struct definition */ -void t_swift_generator::generate_swift_struct_printable_extension(ofstream& out, t_struct* tstruct) { +void t_swift_generator::generate_swift_struct_printable_extension(ostream& out, t_struct* tstruct) { // Allow use of debugDescription so the app can add description via a cateogory/extension + const vector& fields = tstruct->get_members(); + vector::const_iterator f_iter; + indent(out) << "extension " << tstruct->get_name() << " : " << (debug_descriptions_ ? "CustomDebugStringConvertible" : "CustomStringConvertible"); block_open(out); - out << endl; - indent(out) << "public var description : String"; - block_open(out); + indent(out) << "var desc = \"" << tstruct->get_name(); - indent(out) << "var desc = \"" << tstruct->get_name() << "(\"" << endl; - - const vector& fields = tstruct->get_members(); - vector::const_iterator f_iter; - - for (f_iter = fields.begin(); f_iter != fields.end();) { - indent(out) << "desc += \"" << (*f_iter)->get_name() - << "=\\(self." << maybe_escape_identifier((*f_iter)->get_name()) << ")"; - if (++f_iter != fields.end()) { - out << ", "; + if (!gen_cocoa_) { + if (!tstruct->is_union()) { + out << "(\"" << endl; + for (f_iter = fields.begin(); f_iter != fields.end();) { + indent(out) << "desc += \"" << (*f_iter)->get_name() + << "=\\(String(describing: self." << maybe_escape_identifier((*f_iter)->get_name()) << "))"; + if (++f_iter != fields.end()) { + out << ", "; + } + out << "\"" << endl; + } + } else { + out << ".\"" << endl; + indent(out) << "switch self {" << endl; + for (f_iter = fields.begin(); f_iter != fields.end();f_iter++) { + indent(out) << "case ." << (*f_iter)->get_name() << "(let val): " + << "desc += \"" << (*f_iter)->get_name() << "(val: \\(val))\"" + << endl; + } + indent(out) << "}" << endl; } - out << "\"" << endl; + } else { + out << "(\"" << endl; + for (f_iter = fields.begin(); f_iter != fields.end();) { + indent(out) << "desc += \"" << (*f_iter)->get_name() + << "=\\(self." << maybe_escape_identifier((*f_iter)->get_name()) << ")"; + if (++f_iter != fields.end()) { + out << ", "; + } + out << "\"" << endl; + } + indent(out) << "desc += \")\"" << endl; } - indent(out) << "desc += \")\"" << endl; + indent(out) << "return desc" << endl; - block_close(out); - out << endl; - block_close(out); - out << endl; } @@ -1076,29 +1594,47 @@ void t_swift_generator::generate_function_helpers(t_service *tservice, t_functio * * @param tservice The service to generate a protocol definition for */ -void t_swift_generator::generate_swift_service_protocol(ofstream& out, t_service* tservice) { +void t_swift_generator::generate_swift_service_protocol(ostream& out, t_service* tservice) { + if (!gen_cocoa_) { + string doc = tservice->get_doc(); + generate_docstring(out, doc); - indent(out) << "public protocol " << tservice->get_name(); - - block_open(out); - - vector functions = tservice->get_functions(); - vector::iterator f_iter; - - for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { - out << endl; - indent(out) << function_signature(*f_iter) << " // exceptions: "; - t_struct* xs = (*f_iter)->get_xceptions(); - const vector& xceptions = xs->get_members(); - vector::const_iterator x_iter; - for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) { - out << type_name((*x_iter)->get_type()) + ", "; + indent(out) << "public protocol " << tservice->get_name(); + t_service* parent = tservice->get_extends(); + if (parent != NULL) { + out << " : " << parent->get_name(); } + block_open(out); out << endl; + + vector functions = tservice->get_functions(); + vector::iterator f_iter; + + for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { + function_docstring(out, *f_iter); + indent(out) << function_signature(*f_iter) << endl << endl; + } + + } else { + indent(out) << "public protocol " << tservice->get_name(); + block_open(out); + + vector functions = tservice->get_functions(); + vector::iterator f_iter; + + for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { + out << endl; + indent(out) << function_signature(*f_iter) << " // exceptions: "; + t_struct* xs = (*f_iter)->get_xceptions(); + const vector& xceptions = xs->get_members(); + vector::const_iterator x_iter; + for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) { + out << type_name((*x_iter)->get_type()) + ", "; + } + out << endl; + } } - block_close(out); - out << endl; } @@ -1107,26 +1643,78 @@ void t_swift_generator::generate_swift_service_protocol(ofstream& out, t_service * * @param tservice The service to generate a protocol definition for */ -void t_swift_generator::generate_swift_service_protocol_async(ofstream& out, t_service* tservice) { - +void t_swift_generator::generate_swift_service_protocol_async(ostream& out, t_service* tservice) { + if (!gen_cocoa_) { + string doc = tservice->get_doc(); + generate_docstring(out, doc); + } indent(out) << "public protocol " << tservice->get_name() << "Async"; block_open(out); + if (!gen_cocoa_) { out << endl; } vector functions = tservice->get_functions(); vector::iterator f_iter; - for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { - out << endl; - indent(out) << async_function_signature(*f_iter) << endl; - if (promise_kit_) { - indent(out) << promise_function_signature(*f_iter) << endl; + if (!gen_cocoa_) { + for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { + async_function_docstring(out, *f_iter); + indent(out) << async_function_signature(*f_iter) << endl << endl; } + } else { + for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { + out << endl; + indent(out) << async_function_signature(*f_iter) << endl; + if (promise_kit_) { + indent(out) << promise_function_signature(*f_iter) << endl; + } // + out << endl; + } + } + block_close(out); + out << endl; +} + +/** + * Generates a service client interface definition. + * + * @param tservice The service to generate a client interface definition for + */ +void t_swift_generator::generate_swift_service_client(ostream& out, t_service* tservice) { + if (!gen_cocoa_) { + indent(out) << "open class " << tservice->get_name() << "Client";// : " + + // Inherit from ParentClient + t_service* parent = tservice->get_extends(); + out << " : " << ((parent == NULL) ? "TClient" : parent->get_name() + "Client"); + out << " /* , " << tservice->get_name() << " */"; + block_open(out); + out << endl; + } else { + // a + indent(out) << "public class " << tservice->get_name() << "Client /* : " << tservice->get_name() << " */"; + block_open(out); + out << endl; + + indent(out) << "let __inProtocol : TProtocol" << endl << endl; + indent(out) << "let __outProtocol : TProtocol" << endl << endl; + indent(out) << "public init(inoutProtocol: TProtocol)"; + block_open(out); + + indent(out) << "__inProtocol = inoutProtocol" << endl; + indent(out) << "__outProtocol = inoutProtocol" << endl; + block_close(out); + out << endl; + + indent(out) << "public init(inProtocol: TProtocol, outProtocol: TProtocol)"; + block_open(out); + indent(out) << "__inProtocol = inProtocol" << endl; + indent(out) << "__outProtocol = outProtocol" << endl; + block_close(out); out << endl; } block_close(out); - out << endl; } @@ -1135,80 +1723,35 @@ void t_swift_generator::generate_swift_service_protocol_async(ofstream& out, t_s * * @param tservice The service to generate a client interface definition for */ -void t_swift_generator::generate_swift_service_client(ofstream& out, - t_service* tservice) { +void t_swift_generator::generate_swift_service_client_async(ostream& out, t_service* tservice) { + if (!gen_cocoa_) { + indent(out) << "open class " << tservice->get_name() + << "AsyncClient";// : " - indent(out) << "public class " << tservice->get_name() << "Client /* : " << tservice->get_name() << " */"; + // Inherit from ParentClient + t_service* parent = tservice->get_extends(); - block_open(out); + out << " : " << ((parent == NULL) ? "T" : parent->get_name()) + "AsyncClient"; + out << " /* , " << tservice->get_name() << " */"; - out << endl; + block_open(out); + out << endl; + } else { + indent(out) << "public class " << tservice->get_name() << "AsyncClient /* : " << tservice->get_name() << " */"; + block_open(out); + out << endl; - indent(out) << "let __inProtocol : TProtocol" << endl << endl; - - indent(out) << "let __outProtocol : TProtocol" << endl << endl; - - indent(out) << "public init(inoutProtocol: TProtocol)"; - - block_open(out); - - indent(out) << "__inProtocol = inoutProtocol" << endl; - - indent(out) << "__outProtocol = inoutProtocol" << endl; + indent(out) << "let __protocolFactory : TProtocolFactory" << endl << endl; + indent(out) << "let __transportFactory : TAsyncTransportFactory" << endl << endl; + indent(out) << "public init(protocolFactory: TProtocolFactory, transportFactory: TAsyncTransportFactory)"; + block_open(out); + indent(out) << "__protocolFactory = protocolFactory" << endl; + indent(out) << "__transportFactory = transportFactory" << endl; + block_close(out); + out << endl; + } block_close(out); - - out << endl; - - indent(out) << "public init(inProtocol: TProtocol, outProtocol: TProtocol)"; - - block_open(out); - - indent(out) << "__inProtocol = inProtocol" << endl; - - indent(out) << "__outProtocol = outProtocol" << endl; - - block_close(out); - - out << endl; - - block_close(out); - - out << endl; -} - -/** - * Generates a service client interface definition. - * - * @param tservice The service to generate a client interface definition for - */ -void t_swift_generator::generate_swift_service_client_async(ofstream& out, - t_service* tservice) { - - indent(out) << "public class " << tservice->get_name() << "AsyncClient /* : " << tservice->get_name() << " */"; - - block_open(out); - - out << endl; - - indent(out) << "let __protocolFactory : TProtocolFactory" << endl << endl; - - indent(out) << "let __transportFactory : TAsyncTransportFactory" << endl << endl; - - indent(out) << "public init(protocolFactory: TProtocolFactory, transportFactory: TAsyncTransportFactory)"; - - block_open(out); - - indent(out) << "__protocolFactory = protocolFactory" << endl; - - indent(out) << "__transportFactory = transportFactory" << endl; - - block_close(out); - - out << endl; - - block_close(out); - out << endl; } @@ -1218,29 +1761,38 @@ void t_swift_generator::generate_swift_service_client_async(ofstream& out, * * @param tservice The service to generate a client interface definition for */ -void t_swift_generator::generate_swift_service_server(ofstream& out, - t_service* tservice) { +void t_swift_generator::generate_swift_service_server(ostream& out, t_service* tservice) { + if (!gen_cocoa_) { + indent(out) << "open class " << tservice->get_name() << "Processor /* " << tservice->get_name() << " */"; - indent(out) << "public class " << tservice->get_name() << "Processor : NSObject /* " << tservice->get_name() << " */"; + block_open(out); + out << endl; + out << indent() << "typealias ProcessorHandlerDictionary = " + << "[String: (Int32, TProtocol, TProtocol, " << tservice->get_name() << ") throws -> Void]" << endl + << endl + << indent() << "public var service: " << tservice->get_name() << endl + << endl + << indent() << "public required init(service: " << tservice->get_name() << ")"; + } else { + indent(out) << "public class " << tservice->get_name() << "Processor : NSObject /* " + << tservice->get_name() << " */"; + block_open(out); + out << endl; - block_open(out); + out << indent() << "typealias ProcessorHandlerDictionary = " + << "[String: (Int, TProtocol, TProtocol, " << tservice->get_name() << ") throws -> Void]" << endl + << endl + << indent() << "let service : " << tservice->get_name() << endl + << endl + << indent() << "public init(service: " << tservice->get_name() << ")"; + } - out << endl; - - out << indent() << "typealias ProcessorHandlerDictionary = " - << "[String: (Int, TProtocol, TProtocol, " << tservice->get_name() << ") throws -> Void]" << endl - << endl - << indent() << "let service : " << tservice->get_name() << endl - << endl - << indent() << "public init(service: " << tservice->get_name() << ")"; block_open(out); indent(out) << "self.service = service" << endl; block_close(out); - out << endl; block_close(out); - out << endl; } @@ -1254,7 +1806,7 @@ void t_swift_generator::generate_swift_service_server(ofstream& out, * Wether the first parameter must be a protocol or if * the protocol is to be assumed */ -void t_swift_generator::generate_swift_service_client_send_function_implementation(ofstream& out, +void t_swift_generator::generate_swift_service_client_send_function_implementation(ostream& out, t_service *tservice, t_function* tfunction, bool needs_protocol) { @@ -1268,40 +1820,65 @@ void t_swift_generator::generate_swift_service_client_send_function_implementati string argsname = function_args_helper_struct_type(tservice, tfunction); t_struct* arg_struct = tfunction->get_arglist(); + string proto = needs_protocol ? (gen_cocoa_ ? "__outProtocol" : "on outProtocol") : ""; // Open function - indent(out) << "private func " << send_function.get_name() << "(" << argument_list(tfunction->get_arglist(), needs_protocol ? "__outProtocol" : "", true) << ") throws"; + indent(out) << "private func " << send_function.get_name() << "(" + << argument_list(tfunction->get_arglist(), proto, true) + << ") throws"; block_open(out); + if (!gen_cocoa_) { + // Serialize the request + indent(out) << "try outProtocol.writeMessageBegin(name: \"" << funname << "\", " + << "type: " << (tfunction->is_oneway() ? ".oneway" : ".call") << ", " + << "sequenceID: 0)" << endl; - out << endl; + indent(out) << "let args = " << argsname << "("; - // Serialize the request - indent(out) << "try __outProtocol.writeMessageBeginWithName(\"" << funname << "\", " - << "type: " << (tfunction->is_oneway() ? ".ONEWAY" : ".CALL") << ", " - << "sequenceID: 0)" << endl; + // write out function parameters - out << endl; + const vector& fields = arg_struct->get_members(); + vector::const_iterator f_iter; - indent(out) << "let __args = " << argsname << "("; - - // write out function parameters - - const vector& fields = arg_struct->get_members(); - vector::const_iterator f_iter; - - for (f_iter = fields.begin(); f_iter != fields.end();) { - t_field *tfield = (*f_iter); - out << tfield->get_name() << ": " << tfield->get_name(); - if (++f_iter != fields.end()) { - out << ", "; + for (f_iter = fields.begin(); f_iter != fields.end();) { + t_field *tfield = (*f_iter); + out << tfield->get_name() << ": " << tfield->get_name(); + if (++f_iter != fields.end()) { + out << ", "; + } } - } - out << ")" << endl; - indent(out) << "try " << argsname << ".writeValue(__args, toProtocol: __outProtocol)" << endl << endl; + out << ")" << endl; + indent(out) << "try args.write(to: outProtocol)" << endl; + indent(out) << "try outProtocol.writeMessageEnd()" << endl; + } else { + out << endl; - indent(out) << "try __outProtocol.writeMessageEnd()" << endl; + // Serialize the request + indent(out) << "try __outProtocol.writeMessageBeginWithName(\"" << funname << "\", " + << "type: " << (tfunction->is_oneway() ? ".ONEWAY" : ".CALL") << ", " + << "sequenceID: 0)" << endl; + + out << endl; + + indent(out) << "let __args = " << argsname << "("; + + // write out function parameters + + const vector& fields = arg_struct->get_members(); + vector::const_iterator f_iter; + + for (f_iter = fields.begin(); f_iter != fields.end();) { + t_field *tfield = (*f_iter); + out << tfield->get_name() << ": " << tfield->get_name(); + if (++f_iter != fields.end()) { + out << ", "; + } + } + out << ")" << endl; + indent(out) << "try " << argsname << ".writeValue(__args, toProtocol: __outProtocol)" << endl << endl; + indent(out) << "try __outProtocol.writeMessageEnd()" << endl; + } block_close(out); - out << endl; } @@ -1315,73 +1892,122 @@ void t_swift_generator::generate_swift_service_client_send_function_implementati * Wether the first parameter must be a protocol or if * the protocol is to be assumed */ -void t_swift_generator::generate_swift_service_client_recv_function_implementation(ofstream& out, +void t_swift_generator::generate_swift_service_client_recv_function_implementation(ostream& out, t_service* tservice, t_function* tfunction, bool needs_protocol) { // Open function indent(out) << "private func recv_" << tfunction->get_name() << "("; + if (!gen_cocoa_) { + if (needs_protocol) { + out << "on inProtocol: TProtocol"; + } + out << ") throws"; + if (!tfunction->get_returntype()->is_void()) { + out << " -> " << type_name(tfunction->get_returntype()); + } - if (needs_protocol) { - out << "__inProtocol: TProtocol"; - } - - out << ") throws"; - - if (!tfunction->get_returntype()->is_void()) { - out << " -> " << type_name(tfunction->get_returntype()); - } - - block_open(out); - - // check for an exception - - out << endl; - - indent(out) << "try __inProtocol.readResultMessageBegin() " << endl << endl; - - string resultname = function_result_helper_struct_type(tservice, tfunction); - indent(out); - if (!tfunction->get_returntype()->is_void() || !tfunction->get_xceptions()->get_members().empty()) { - out << "let __result = "; - } - out << "try " << resultname << ".readValueFromProtocol(__inProtocol)" << endl << endl; - - indent(out) << "try __inProtocol.readMessageEnd()" << endl << endl; - - // Careful, only return _result if not a void function - if (!tfunction->get_returntype()->is_void()) { - indent(out) << "if let __success = __result.success"; block_open(out); - indent(out) << "return __success" << endl; - block_close(out); - } - t_struct* xs = tfunction->get_xceptions(); - const vector& xceptions = xs->get_members(); - vector::const_iterator x_iter; + // check for an exception + + indent(out) << "try inProtocol.readResultMessageBegin() " << endl; + + string resultname = function_result_helper_struct_type(tservice, tfunction); + indent(out); + if (!tfunction->get_returntype()->is_void() || !tfunction->get_xceptions()->get_members().empty()) { + out << "let result = "; + } else { + out << "_ = "; + } + + string return_type_name = type_name(tfunction->get_returntype()); + out << "try " << resultname << ".read(from: inProtocol)" << endl; + + indent(out) << "try inProtocol.readMessageEnd()" << endl << endl; + + // Careful, only return _result if not a void function + if (!tfunction->get_returntype()->is_void()) { + indent(out) << "if let success = result.success"; + block_open(out); + indent(out) << "return success" << endl; + block_close(out); + } + + t_struct* xs = tfunction->get_xceptions(); + const vector& xceptions = xs->get_members(); + vector::const_iterator x_iter; + + for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) { + indent(out) << "if let " << (*x_iter)->get_name() << " = result." << (*x_iter)->get_name(); + block_open(out); + indent(out) << "throw " << (*x_iter)->get_name() << endl; + block_close(out); + } + + // If you get here it's an exception, unless a void function + if (!tfunction->get_returntype()->is_void()) { + indent(out) << "throw TApplicationError(error: .missingResult(methodName: \"" + << tfunction->get_name() << "\"))" << endl; + } + } else { + if (needs_protocol) { + out << "__inProtocol: TProtocol"; + } + + out << ") throws"; + + if (!tfunction->get_returntype()->is_void()) { + out << " -> " << type_name(tfunction->get_returntype()); + } - for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) { - indent(out) << "if let " << (*x_iter)->get_name() << " = __result." << (*x_iter)->get_name(); block_open(out); - indent(out) << "throw " << (*x_iter)->get_name() << endl; - block_close(out); - } - // If you get here it's an exception, unless a void function - if (!tfunction->get_returntype()->is_void()) { - indent(out) << "throw NSError(" << endl; - indent_up(); - indent(out) << "domain: TApplicationErrorDomain, " << endl; - indent(out) << "code: Int(TApplicationError.MissingResult.rawValue)," << endl; - indent(out) << "userInfo: [TApplicationErrorMethodKey: \"" << tfunction->get_name() << "\"])" << endl; - indent_down(); + // check for an exception + out << endl; + indent(out) << "try __inProtocol.readResultMessageBegin() " << endl << endl; + string resultname = function_result_helper_struct_type(tservice, tfunction); + indent(out); + if (!tfunction->get_returntype()->is_void() || !tfunction->get_xceptions()->get_members().empty()) { + out << "let __result = "; + } + out << "try " << resultname << ".readValueFromProtocol(__inProtocol)" << endl << endl; + + indent(out) << "try __inProtocol.readMessageEnd()" << endl << endl; + + // Careful, only return _result if not a void function + if (!tfunction->get_returntype()->is_void()) { + indent(out) << "if let __success = __result.success"; + block_open(out); + indent(out) << "return __success" << endl; + block_close(out); + } + + t_struct* xs = tfunction->get_xceptions(); + const vector& xceptions = xs->get_members(); + vector::const_iterator x_iter; + + for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) { + indent(out) << "if let " << (*x_iter)->get_name() << " = __result." << (*x_iter)->get_name(); + block_open(out); + indent(out) << "throw " << (*x_iter)->get_name() << endl; + block_close(out); + } + + // If you get here it's an exception, unless a void function + if (!tfunction->get_returntype()->is_void()) { + indent(out) << "throw NSError(" << endl; + indent_up(); + indent(out) << "domain: TApplicationErrorDomain, " << endl; + indent(out) << "code: Int(TApplicationError.MissingResult.rawValue)," << endl; + indent(out) << "userInfo: [TApplicationErrorMethodKey: \"" << tfunction->get_name() << "\"])" << endl; + indent_down(); + } } // Close function block_close(out); - out << endl; } @@ -1391,7 +2017,7 @@ void t_swift_generator::generate_swift_service_client_recv_function_implementati * * @param tfunction The service to generate an implementation for */ -void t_swift_generator::generate_swift_service_client_send_function_invocation(ofstream& out, +void t_swift_generator::generate_swift_service_client_send_function_invocation(ostream& out, t_function* tfunction) { indent(out) << "try send_" << tfunction->get_name() << "("; @@ -1417,14 +2043,18 @@ void t_swift_generator::generate_swift_service_client_send_function_invocation(o * * @param tfunction The service to generate an implementation for */ -void t_swift_generator::generate_swift_service_client_send_async_function_invocation(ofstream& out, +void t_swift_generator::generate_swift_service_client_send_async_function_invocation(ostream& out, t_function* tfunction) { t_struct* arg_struct = tfunction->get_arglist(); const vector& fields = arg_struct->get_members(); vector::const_iterator f_iter; - indent(out) << "try send_" << tfunction->get_name() << "(__protocol"; + if (!gen_cocoa_) { + indent(out) << "try send_" << tfunction->get_name() << "(on: proto"; + } else { + indent(out) << "try send_" << tfunction->get_name() << "(__protocol"; // + } for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { out << ", " << (*f_iter)->get_name() << ": " << (*f_iter)->get_name(); @@ -1438,15 +2068,12 @@ void t_swift_generator::generate_swift_service_client_send_async_function_invoca * * @param tservice The service to generate an implementation for */ -void t_swift_generator::generate_swift_service_client_implementation(ofstream& out, +void t_swift_generator::generate_swift_service_client_implementation(ostream& out, t_service* tservice) { string name = tservice->get_name() + "Client"; - indent(out) << "extension " << name << " : " << tservice->get_name(); - block_open(out); - out << endl; // generate client method implementations @@ -1462,16 +2089,17 @@ void t_swift_generator::generate_swift_service_client_implementation(ofstream& o // Open function indent(out) << "public " << function_signature(*f_iter); - block_open(out); - out << endl; + if (gen_cocoa_) { out << endl; } generate_swift_service_client_send_function_invocation(out, *f_iter); - - out << endl; - - indent(out) << "try __outProtocol.transport().flush()" << endl << endl; + if (!gen_cocoa_) { + indent(out) << "try outProtocol.transport.flush()" << endl; + } else { + out << endl; + indent(out) << "try __outProtocol.transport().flush()" << endl << endl; + } if (!(*f_iter)->is_oneway()) { if ((*f_iter)->get_returntype()->is_void()) { @@ -1480,14 +2108,10 @@ void t_swift_generator::generate_swift_service_client_implementation(ofstream& o indent(out) << "return try recv_" << (*f_iter)->get_name() << "()" << endl; } } - block_close(out); - out << endl; } - block_close(out); - out << endl; } @@ -1496,16 +2120,16 @@ void t_swift_generator::generate_swift_service_client_implementation(ofstream& o * * @param tservice The service to generate an implementation for */ -void t_swift_generator::generate_swift_service_client_async_implementation(ofstream& out, - t_service* tservice) { - +void t_swift_generator::generate_swift_service_client_async_implementation(ostream& out, t_service* tservice) { + if (gen_cocoa_) { + generate_old_swift_service_client_async_implementation(out, tservice); + return; + } string name = tservice->get_name() + "AsyncClient"; string protocol_name = tservice->get_name() + "Async"; indent(out) << "extension " << name << " : " << protocol_name; - block_open(out); - out << endl; // generate client method implementations @@ -1521,7 +2145,86 @@ void t_swift_generator::generate_swift_service_client_async_implementation(ofstr indent(out) << "public " << async_function_signature(*f_iter); block_open(out); + out << endl; + out << indent() << "let transport = factory.newTransport()" << endl + << indent() << "let proto = Protocol(on: transport)" << endl + << endl; + out << indent() << "do"; + block_open(out); + + generate_swift_service_client_send_async_function_invocation(out, *f_iter); + + indent_down(); + out << indent() << "} catch let error {" << endl; + indent_up(); + out << indent() << "completion(.error(error))" << endl; + block_close(out); + + out << endl; + + bool ret_is_void = (*f_iter)->get_returntype()->is_void(); + bool is_oneway = (*f_iter)->is_oneway(); + + string error_completion_call = "completion(.error(error))"; + indent(out) << "transport.flush"; + block_open(out); + out << indent() << "(trans, error) in" << endl << endl; + out << indent() << "if let error = error"; + block_open(out); + out << indent() << error_completion_call << endl; + block_close(out); + + if (!is_oneway) { + out << indent() << "do"; + block_open(out); + indent(out); + if (!ret_is_void) { + out << "let result = "; + } + out << "try self.recv_" << (*f_iter)->get_name() << "(on: proto)" << endl; + + out << indent() << (ret_is_void ? "completion(.success(Void()))" : "completion(.success(result))") << endl; + indent_down(); + out << indent() << "} catch let error {" << endl; + indent_up(); + out << indent() << error_completion_call << endl; + + block_close(out); + } else { + out << indent() << "completion(.success(Void()))" << endl; + } + block_close(out); + block_close(out); + + } + block_close(out); + out << endl; +} + +void t_swift_generator::generate_old_swift_service_client_async_implementation(ostream& out, + t_service* tservice) { + + string name = tservice->get_name() + "AsyncClient"; + string protocol_name = tservice->get_name() + "Async"; + + indent(out) << "extension " << name << " : " << protocol_name; + block_open(out); + out << endl; + + // generate client method implementations + vector functions = tservice->get_functions(); + vector::const_iterator f_iter; + for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) { + + generate_swift_service_client_send_function_implementation(out, tservice, *f_iter, true); + + if (!(*f_iter)->is_oneway()) { + generate_swift_service_client_recv_function_implementation(out, tservice, *f_iter, true); + } + + indent(out) << "public " << async_function_signature(*f_iter); + block_open(out); out << endl; out << indent() << "let __transport = __transportFactory.newTransport()" << endl @@ -1529,7 +2232,6 @@ void t_swift_generator::generate_swift_service_client_async_implementation(ofstr << endl; generate_swift_service_client_send_async_function_invocation(out, *f_iter); - out << endl; indent(out) << "__transport.flushWithCompletion("; @@ -1563,9 +2265,7 @@ void t_swift_generator::generate_swift_service_client_async_implementation(ofstr indent(out) << ", failure: failure)" << endl; } - block_close(out); - out << endl; // Promise function @@ -1580,9 +2280,7 @@ void t_swift_generator::generate_swift_service_client_async_implementation(ofstr << endl; generate_swift_service_client_send_async_function_invocation(out, *f_iter); - out << endl; - indent(out) << "__transport.flushWithCompletion("; if ((*f_iter)->is_oneway()) { @@ -1620,17 +2318,13 @@ void t_swift_generator::generate_swift_service_client_async_implementation(ofstr } indent(out) << "return __promise" << endl; - block_close(out); - out << endl; } } - block_close(out); - out << endl; } @@ -1643,21 +2337,18 @@ void t_swift_generator::generate_swift_service_client_async_implementation(ofstr * * @param tservice The service to generate an implementation for */ -void t_swift_generator::generate_swift_service_server_implementation(ofstream& out, +void t_swift_generator::generate_swift_service_server_implementation(ostream& out, t_service* tservice) { string name = tservice->get_name() + "Processor"; indent(out) << "extension " << name << " : TProcessor"; block_open(out); - out << endl; - - indent(out) << "static let processorHandlers : ProcessorHandlerDictionary ="; + indent(out) << "static let processorHandlers" << (gen_cocoa_ ? " " : "") << ": ProcessorHandlerDictionary ="; block_open(out); out << endl; - out << indent() << "var processorHandlers = ProcessorHandlerDictionary()" << endl << endl; // generate method map for routing incoming calls @@ -1673,10 +2364,17 @@ void t_swift_generator::generate_swift_service_server_implementation(ofstream& o << endl; indent_up(); - out << indent() << "let args = try " << args_type << ".readValueFromProtocol(inProtocol)" << endl - << endl - << indent() << "try inProtocol.readMessageEnd()" << endl - << endl; + if (!gen_cocoa_) { + out << indent() << "let args = try " << args_type << ".read(from: inProtocol)" << endl + << endl + << indent() << "try inProtocol.readMessageEnd()" << endl + << endl; + } else { + out << indent() << "let args = try " << args_type << ".readValueFromProtocol(inProtocol)" << endl + << endl + << indent() << "try inProtocol.readMessageEnd()" << endl + << endl; + } if (!tfunction->is_oneway() ) { string result_type = function_result_helper_struct_type(tservice, tfunction); @@ -1689,7 +2387,7 @@ void t_swift_generator::generate_swift_service_server_implementation(ofstream& o if (!tfunction->get_returntype()->is_void()) { out << "result.success = "; } - out << "try handler." << function_name(tfunction) << "("; + out << "try handler." << (gen_cocoa_ ? function_name(tfunction) : tfunction->get_name()) << "("; t_struct* arg_struct = tfunction->get_arglist(); const vector& fields = arg_struct->get_members(); @@ -1697,9 +2395,10 @@ void t_swift_generator::generate_swift_service_server_implementation(ofstream& o for (f_iter = fields.begin(); f_iter != fields.end();) { string fieldName = (*f_iter)->get_name(); - if (f_iter != fields.begin()) { + if (!gen_cocoa_ || f_iter != fields.begin()) { out << fieldName << ": "; } + out << "args." << fieldName; if (++f_iter != fields.end()) { out << ", "; @@ -1707,31 +2406,53 @@ void t_swift_generator::generate_swift_service_server_implementation(ofstream& o } out << ")" << endl; - block_close(out); t_struct* xs = tfunction->get_xceptions(); const vector& xfields = xs->get_members(); vector::const_iterator x_iter; - for (x_iter = xfields.begin(); x_iter != xfields.end(); ++x_iter) { - indent(out) << "catch let error as " << (*x_iter)->get_type()->get_name(); + if (!gen_cocoa_) { + for (x_iter = xfields.begin(); x_iter != xfields.end(); ++x_iter) { + indent(out) << "catch let error as "; + + t_program* program = (*x_iter)->get_type()->get_program(); + if ((*x_iter)->get_type()->get_name() == "Error" && namespaced_ && program != program_) { + out << get_real_swift_module(program) << "."; + } + out << (*x_iter)->get_type()->get_name(); + + out << " { result." << (*x_iter)->get_name() << " = error }" << endl; + } + + indent(out) << "catch let error { throw error }" << endl; + out << endl; + + if (!tfunction->is_oneway()) { + out << indent() << "try outProtocol.writeMessageBegin(name: \"" << tfunction->get_name() << "\", type: .reply, sequenceID: sequenceID)" << endl + << indent() << "try result.write(to: outProtocol)" << endl + << indent() << "try outProtocol.writeMessageEnd()" << endl; + } + } else { + for (x_iter = xfields.begin(); x_iter != xfields.end(); ++x_iter) { + indent(out) << "catch let error as " << (*x_iter)->get_type()->get_name(); + block_open(out); + indent(out) << "result." << (*x_iter)->get_name() << " = error" << endl; + block_close(out); + } + + indent(out) << "catch let error"; block_open(out); - indent(out) << "result." << (*x_iter)->get_name() << " = error" << endl; + out << indent() << "throw error" << endl; block_close(out); - } - indent(out) << "catch let error"; - block_open(out); - out << indent() << "throw error" << endl; - block_close(out); + out << endl; - out << endl; - - if (!tfunction->is_oneway()) { - out << indent() << "try outProtocol.writeMessageBeginWithName(\"" << tfunction->get_name() << "\", type: .REPLY, sequenceID: sequenceID)" << endl - << indent() << "try " << result_type << ".writeValue(result, toProtocol: outProtocol)" << endl - << indent() << "try outProtocol.writeMessageEnd()" << endl; + if (!tfunction->is_oneway()) { + out << indent() << "try outProtocol.writeMessageBeginWithName(\"" << tfunction->get_name() << "\", type: .REPLY, sequenceID: sequenceID)" << endl + << indent() << "try " << result_type << ".writeValue(result, toProtocol: outProtocol)" << endl + << indent() << "try outProtocol.writeMessageEnd()" << endl; + } } } block_close(out); @@ -1742,14 +2463,16 @@ void t_swift_generator::generate_swift_service_server_implementation(ofstream& o block_close(out,false); out << "()" << endl; - out << endl; - indent(out) << "public func processOnInputProtocol(inProtocol: TProtocol, outputProtocol outProtocol: TProtocol) throws"; + if (!gen_cocoa_) { + indent(out) << "public func process(on inProtocol: TProtocol, outProtocol: TProtocol) throws"; + } else { + indent(out) << "public func processOnInputProtocol(inProtocol: TProtocol, outputProtocol outProtocol: TProtocol) throws"; + } block_open(out); out << endl; - out << indent() << "let (messageName, _, sequenceID) = try inProtocol.readMessageBegin()" << endl << endl << indent() << "if let processorHandler = " << name << ".processorHandlers[messageName]"; @@ -1758,29 +2481,43 @@ void t_swift_generator::generate_swift_service_server_implementation(ofstream& o block_open(out); out << indent() << "try processorHandler(sequenceID, inProtocol, outProtocol, service)" << endl; block_close(out); - out << indent() << "catch let error as NSError"; - block_open(out); - out << indent() << "try outProtocol.writeExceptionForMessageName(messageName, sequenceID: sequenceID, ex: error)" << endl; - block_close(out); - block_close(out); - out << indent() << "else"; - block_open(out); - out << indent() << "try inProtocol.skipType(.STRUCT)" << endl - << indent() << "try inProtocol.readMessageEnd()" << endl - << indent() << "try outProtocol.writeExceptionForMessageName(messageName," << endl; - indent_up(); - out << indent() << "sequenceID: sequenceID," << endl - << indent() << "ex: NSError(" << endl; - indent_up(); - out << indent() << "domain: TApplicationErrorDomain, " << endl - << indent() << "code: Int(TApplicationError.UnknownMethod.rawValue), " << endl - << indent() << "userInfo: [TApplicationErrorMethodKey: messageName]))" << endl; - indent_down(); - indent_down(); - block_close(out); + if (!gen_cocoa_) { + out << indent() << "catch let error as TApplicationError"; + block_open(out); + out << indent() << "try outProtocol.writeException(messageName: messageName, sequenceID: sequenceID, ex: error)" << endl; + block_close(out); + block_close(out); + out << indent() << "else"; + block_open(out); + out << indent() << "try inProtocol.skip(type: .struct)" << endl + << indent() << "try inProtocol.readMessageEnd()" << endl + << indent() << "let ex = TApplicationError(error: .unknownMethod(methodName: messageName))" << endl + << indent() << "try outProtocol.writeException(messageName: messageName, " + << "sequenceID: sequenceID, ex: ex)" << endl; + } else { + out << indent() << "catch let error as NSError"; + block_open(out); + out << indent() << "try outProtocol.writeExceptionForMessageName(messageName, sequenceID: sequenceID, ex: error)" << endl; + block_close(out); + block_close(out); + out << indent() << "else"; + block_open(out); + out << indent() << "try inProtocol.skipType(.STRUCT)" << endl + << indent() << "try inProtocol.readMessageEnd()" << endl + << indent() << "try outProtocol.writeExceptionForMessageName(messageName," << endl; + indent_up(); + out << indent() << "sequenceID: sequenceID," << endl + << indent() << "ex: NSError(" << endl; + indent_up(); + out << indent() << "domain: TApplicationErrorDomain, " << endl + << indent() << "code: Int(TApplicationError.UnknownMethod.rawValue), " << endl + << indent() << "userInfo: [TApplicationErrorMethodKey: messageName]))" << endl; + indent_down(); + indent_down(); + } block_close(out); - + block_close(out); block_close(out); out << endl; } @@ -1793,27 +2530,31 @@ void t_swift_generator::generate_swift_service_server_implementation(ofstream& o * @return Swift type name, i.e. Dictionary */ string t_swift_generator::type_name(t_type* ttype, bool is_optional, bool is_forced) { - string result; + string result = ""; + if (ttype->is_base_type()) { - result = base_type_name((t_base_type*)ttype); + result += base_type_name((t_base_type*)ttype); } else if (ttype->is_map()) { t_map *map = (t_map *)ttype; - result = "TMap<" + type_name(map->get_key_type()) + ", " + type_name(map->get_val_type()) + ">"; + result += "TMap<" + type_name(map->get_key_type()) + ", " + type_name(map->get_val_type()) + ">"; } else if (ttype->is_set()) { t_set *set = (t_set *)ttype; - result = "TSet<" + type_name(set->get_elem_type()) + ">"; + result += "TSet<" + type_name(set->get_elem_type()) + ">"; } else if (ttype->is_list()) { t_list *list = (t_list *)ttype; - result = "TList<" + type_name(list->get_elem_type()) + ">"; + result += "TList<" + type_name(list->get_elem_type()) + ">"; } else { - result = ttype->get_name(); + t_program* program = ttype->get_program(); + if (namespaced_ && program != program_) { + result += get_real_swift_module(program) + "."; + } + result += ttype->get_name(); } if (is_optional) { result += "?"; } - if (is_forced) { result += "!"; } @@ -1834,7 +2575,7 @@ string t_swift_generator::base_type_name(t_base_type* type) { return "Void"; case t_base_type::TYPE_STRING: if (type->is_binary()) { - return "TBinary"; + return gen_cocoa_ ? "TBinary" : "Data"; } else { return "String"; } @@ -1860,8 +2601,8 @@ string t_swift_generator::base_type_name(t_base_type* type) { * */ void t_swift_generator::render_const_value(ostream& out, - t_type* type, - t_const_value* value) { + t_type* type, + t_const_value* value) { type = get_true_type(type); if (type->is_base_type()) { @@ -1892,7 +2633,7 @@ void t_swift_generator::render_const_value(ostream& out, throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase); } } else if (type->is_enum()) { - out << value->get_identifier(); + out << (gen_cocoa_ ? value->get_identifier() : enum_const_name(value->get_identifier())); // Swift2/Cocoa compatibility } else if (type->is_struct() || type->is_xception()) { out << type_name(type) << "("; @@ -1900,8 +2641,8 @@ void t_swift_generator::render_const_value(ostream& out, const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (f_iter = fields.begin(); f_iter != fields.end();) { t_field* tfield = *f_iter; @@ -1934,8 +2675,8 @@ void t_swift_generator::render_const_value(ostream& out, t_type* ktype = ((t_map*)type)->get_key_type(); t_type* vtype = ((t_map*)type)->get_val_type(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end();) { @@ -1956,8 +2697,8 @@ void t_swift_generator::render_const_value(ostream& out, t_type* etype = ((t_list*)type)->get_elem_type(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end();) { @@ -1976,8 +2717,8 @@ void t_swift_generator::render_const_value(ostream& out, t_type* etype = ((t_set*)type)->get_elem_type(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end();) { @@ -2003,17 +2744,22 @@ void t_swift_generator::render_const_value(ostream& out, */ string t_swift_generator::declare_property(t_field* tfield, bool is_private) { - string visibility = is_private ? "private" : "public"; + string visibility = is_private ? (gen_cocoa_ ? "private" : "fileprivate") : "public"; ostringstream render; render << visibility << " var " << maybe_escape_identifier(tfield->get_name()); if (field_is_optional(tfield)) { - render << " : " << type_name(tfield->get_type(), true); + render << (gen_cocoa_ ? " " : "") << ": " << type_name(tfield->get_type(), true); } else { - render << " = " << type_name(tfield->get_type(), false) << "()"; + if (!gen_cocoa_) { + render << ": " << type_name(tfield->get_type(), false); + } else { + // Swift2/Cocoa backward compat, Bad, default init + render << " = " << type_name(tfield->get_type(), false) << "()"; + } } return render.str(); @@ -2027,9 +2773,9 @@ string t_swift_generator::declare_property(t_field* tfield, bool is_private) { */ string t_swift_generator::function_signature(t_function* tfunction) { - string result = "func " + function_name(tfunction); + string result = "func " + (gen_cocoa_ ? function_name(tfunction) : tfunction->get_name()); - result += "(" + argument_list(tfunction->get_arglist(), "", false) + ") throws"; + result += "(" + argument_list(tfunction->get_arglist(), "", false) + ") throws"; /// argsreview t_type* ttype = tfunction->get_returntype(); if (!ttype->is_void()) { @@ -2039,6 +2785,110 @@ string t_swift_generator::function_signature(t_function* tfunction) { return result; } +/** + * Renders a function docstring + * + * @param tfunction Function definition + * @return String of rendered function definition + */ +void t_swift_generator::function_docstring(ostream& out, t_function* tfunction) { + + // Generate docstring with following format: + // /// + // /// + // /// - Parameters: + // /// - : + // /// - Returns: (Thrift has no docstring on return val) + // /// - Throws: + + // Description + string doc = tfunction->get_doc(); + generate_docstring(out, doc); + indent(out) << "///" << endl; + + // Parameters + const vector& fields = tfunction->get_arglist()->get_members(); + vector::const_iterator f_iter; + if (!fields.empty()) { + indent(out) << "/// - Parameters:" << endl; + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { + indent(out) << "/// - " << (*f_iter)->get_name() << ": "; + string doc = (*f_iter)->get_doc(); + if (!doc.empty() && doc[doc.length()-1] == '\n') { + doc.erase(doc.length()-1); + } + out << doc << endl; + } + } + + // Returns + t_type* ttype = tfunction->get_returntype(); + if (!ttype->is_void()) { + indent(out) << "/// - Returns: " << type_name(ttype) << endl; + } + + // Throws + indent(out) << "/// - Throws: "; + t_struct* xs = tfunction->get_xceptions(); + const vector& xceptions = xs->get_members(); + vector::const_iterator x_iter; + for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) { + out << type_name((*x_iter)->get_type()); + if (*x_iter != xceptions.back()) { + out << ", "; + } } + out << endl; +} + +/** + * Renders a function docstring + * + * @param tfunction Function definition + * @return String of rendered function definition + */ +void t_swift_generator::async_function_docstring(ostream& out, t_function* tfunction) { + // Generate docstring with following format: + // /// + // /// + // /// - Parameters: + // /// - : + // /// - callback: + + // Description + string doc = tfunction->get_doc(); + generate_docstring(out, doc); + indent(out) << "///" << endl; + + // Parameters + const vector& fields = tfunction->get_arglist()->get_members(); + vector::const_iterator f_iter; + if (!fields.empty()) { + indent(out) << "/// - Parameters:" << endl; + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { + indent(out) << "/// - " << (*f_iter)->get_name() << ": "; + string doc = (*f_iter)->get_doc(); + if (!doc.empty() && doc[doc.length()-1] == '\n') { + doc.erase(doc.length()-1); + } + out << doc << endl; + } + } + + // completion + indent(out) << "/// - completion: TAsyncResult<" << type_name(tfunction->get_returntype()) + << "> wrapping return and following Exceptions: "; + t_struct* xs = tfunction->get_xceptions(); + const vector& xceptions = xs->get_members(); + vector::const_iterator x_iter; + for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) { + out << type_name((*x_iter)->get_type()); + if (*x_iter != xceptions.back()) { + out << ", "; + } + } + out << endl; +} + /** * Renders a function signature that returns asynchronously via blocks. * @@ -2048,28 +2898,39 @@ string t_swift_generator::function_signature(t_function* tfunction) { string t_swift_generator::async_function_signature(t_function* tfunction) { t_type* ttype = tfunction->get_returntype(); t_struct* targlist = tfunction->get_arglist(); - string response_param = "(" + ((ttype->is_void()) ? "" : type_name(ttype)) + ") -> Void"; - string result = "func " + function_name(tfunction); - result += "(" + argument_list(tfunction->get_arglist(), "", false) - + (targlist->get_members().size() ? ", " : "") - + "success: " + response_param + ", " - + "failure: (NSError) -> Void) throws"; + string result = "func " + (gen_cocoa_ ? function_name(tfunction) : tfunction->get_name()); + + if (!gen_cocoa_) { + string response_string = "(TAsyncResult<"; + response_string += (ttype->is_void()) ? "Void" : type_name(ttype); + response_string += ">) -> Void"; + result += "(" + argument_list(tfunction->get_arglist(), "", false) + + (targlist->get_members().size() ? ", " : "") + + "completion: @escaping " + response_string + ")"; + } else { + string response_param = "(" + ((ttype->is_void()) ? "" : type_name(ttype)) + ") -> Void"; + result += "(" + argument_list(tfunction->get_arglist(), "", false) + + (targlist->get_members().size() ? ", " : "") + + "success: " + response_param + ", " + + "failure: (NSError) -> Void) throws"; + } return result; } /** * Renders a function signature that returns asynchronously via promises. + * ONLY FOR Swift2/Cocoa BACKWARDS COMPATIBILITY * * @param tfunction Function definition * @return String of rendered function definition */ string t_swift_generator::promise_function_signature(t_function* tfunction) { return "func " + function_name(tfunction) + "(" + argument_list(tfunction->get_arglist(), "", false) + ") throws " - + "-> Promise<" + type_name(tfunction->get_returntype()) + ">"; + + "-> Promise<" + type_name(tfunction->get_returntype()) + ">"; } /** - * Renders a verbose function name suitable for a Swift method + * Renders a verbose function name suitable for a Swift method. ONLY FOR Swift2/Cocoa BACKWARDS COMPATIBILITY */ string t_swift_generator::function_name(t_function* tfunction) { string name = tfunction->get_name(); @@ -2098,15 +2959,21 @@ string t_swift_generator::argument_list(t_struct* tstruct, string protocol_name, if (!fields.empty()) { result += ", "; } - } - else if (!fields.empty() && is_internal) { - // Force first argument to be named + } else if (!fields.empty() && is_internal && gen_cocoa_) { + // Force first argument to be named, Swift2/Cocoa backwards compat result += fields.front()->get_name() + " "; } for (f_iter = fields.begin(); f_iter != fields.end();) { t_field* arg = *f_iter; - result += arg->get_name() + ": " + type_name(arg->get_type()); + + if (!gen_cocoa_) { + // optional args not usually permitted for some reason, even though dynamic langs handle it + // use annotation "swift.nullable" to achieve + result += arg->get_name() + ": " + type_name(arg->get_type(), field_is_optional(arg)); + } else { + result += arg->get_name() + ": " + type_name(arg->get_type()); + } if (++f_iter != fields.end()) { result += ", "; @@ -2121,31 +2988,118 @@ string t_swift_generator::argument_list(t_struct* tstruct, string protocol_name, */ void t_swift_generator::populate_reserved_words() { - swift_reserved_words_.insert("Self"); - swift_reserved_words_.insert("associatedtype"); - swift_reserved_words_.insert("defer"); - swift_reserved_words_.insert("deinit"); - swift_reserved_words_.insert("dynamicType"); - swift_reserved_words_.insert("enum"); - swift_reserved_words_.insert("extension"); - swift_reserved_words_.insert("fallthrough"); - swift_reserved_words_.insert("false"); - swift_reserved_words_.insert("func"); - swift_reserved_words_.insert("guard"); - swift_reserved_words_.insert("init"); - swift_reserved_words_.insert("inout"); - swift_reserved_words_.insert("internal"); - swift_reserved_words_.insert("let"); - swift_reserved_words_.insert("operator"); - swift_reserved_words_.insert("protocol"); - swift_reserved_words_.insert("repeat"); - swift_reserved_words_.insert("rethrows"); - swift_reserved_words_.insert("struct"); - swift_reserved_words_.insert("subscript"); - swift_reserved_words_.insert("throws"); - swift_reserved_words_.insert("true"); - swift_reserved_words_.insert("typealias"); - swift_reserved_words_.insert("where"); + if (!gen_cocoa_) { + swift_reserved_words_.insert("__COLUMN__"); + swift_reserved_words_.insert("__FILE__"); + swift_reserved_words_.insert("__FUNCTION__"); + swift_reserved_words_.insert("__LINE__"); + swift_reserved_words_.insert("Any"); + swift_reserved_words_.insert("as"); + swift_reserved_words_.insert("associatedtype"); + swift_reserved_words_.insert("associativity"); + swift_reserved_words_.insert("break"); + swift_reserved_words_.insert("case"); + swift_reserved_words_.insert("catch"); + swift_reserved_words_.insert("class"); + swift_reserved_words_.insert("continue"); + swift_reserved_words_.insert("convenience"); + swift_reserved_words_.insert("default"); + swift_reserved_words_.insert("defer"); + swift_reserved_words_.insert("deinit"); + swift_reserved_words_.insert("didSet"); + swift_reserved_words_.insert("do"); + swift_reserved_words_.insert("dynamic"); + swift_reserved_words_.insert("dynamicType"); + swift_reserved_words_.insert("else"); + swift_reserved_words_.insert("enum"); + swift_reserved_words_.insert("extension"); + swift_reserved_words_.insert("fallthrough"); + swift_reserved_words_.insert("false"); + swift_reserved_words_.insert("fileprivate"); + swift_reserved_words_.insert("final"); + swift_reserved_words_.insert("for"); + swift_reserved_words_.insert("func"); + swift_reserved_words_.insert("get"); + swift_reserved_words_.insert("guard"); + swift_reserved_words_.insert("if"); + swift_reserved_words_.insert("import"); + swift_reserved_words_.insert("in"); + swift_reserved_words_.insert("indirect"); + swift_reserved_words_.insert("infix"); + swift_reserved_words_.insert("init"); + swift_reserved_words_.insert("inout"); + swift_reserved_words_.insert("internal"); + swift_reserved_words_.insert("is"); + swift_reserved_words_.insert("lazy"); + swift_reserved_words_.insert("left"); + swift_reserved_words_.insert("let"); + swift_reserved_words_.insert("mutating"); + swift_reserved_words_.insert("nil"); + swift_reserved_words_.insert("none"); + swift_reserved_words_.insert("nonmutating"); + swift_reserved_words_.insert("open"); + swift_reserved_words_.insert("operator"); + swift_reserved_words_.insert("optional"); + swift_reserved_words_.insert("override"); + swift_reserved_words_.insert("postfix"); + swift_reserved_words_.insert("precedence"); + swift_reserved_words_.insert("prefix"); + swift_reserved_words_.insert("private"); + swift_reserved_words_.insert("protocol"); + swift_reserved_words_.insert("Protocol"); + swift_reserved_words_.insert("public"); + swift_reserved_words_.insert("repeat"); + swift_reserved_words_.insert("required"); + swift_reserved_words_.insert("rethrows"); + swift_reserved_words_.insert("return"); + swift_reserved_words_.insert("right"); + swift_reserved_words_.insert("self"); + swift_reserved_words_.insert("Self"); + swift_reserved_words_.insert("set"); + swift_reserved_words_.insert("static"); + swift_reserved_words_.insert("struct"); + swift_reserved_words_.insert("subscript"); + swift_reserved_words_.insert("super"); + swift_reserved_words_.insert("switch"); + swift_reserved_words_.insert("throw"); + swift_reserved_words_.insert("throws"); + swift_reserved_words_.insert("true"); + swift_reserved_words_.insert("try"); + swift_reserved_words_.insert("Type"); + swift_reserved_words_.insert("typealias"); + swift_reserved_words_.insert("unowned"); + swift_reserved_words_.insert("var"); + swift_reserved_words_.insert("weak"); + swift_reserved_words_.insert("where"); + swift_reserved_words_.insert("while"); + swift_reserved_words_.insert("willSet"); + } else { + swift_reserved_words_.insert("Self"); + swift_reserved_words_.insert("associatedtype"); + swift_reserved_words_.insert("defer"); + swift_reserved_words_.insert("deinit"); + swift_reserved_words_.insert("dynamicType"); + swift_reserved_words_.insert("enum"); + swift_reserved_words_.insert("extension"); + swift_reserved_words_.insert("fallthrough"); + swift_reserved_words_.insert("false"); + swift_reserved_words_.insert("func"); + swift_reserved_words_.insert("guard"); + swift_reserved_words_.insert("init"); + swift_reserved_words_.insert("inout"); + swift_reserved_words_.insert("internal"); + swift_reserved_words_.insert("let"); + swift_reserved_words_.insert("operator"); + swift_reserved_words_.insert("protocol"); + swift_reserved_words_.insert("repeat"); + swift_reserved_words_.insert("rethrows"); + swift_reserved_words_.insert("struct"); + swift_reserved_words_.insert("subscript"); + swift_reserved_words_.insert("throws"); + swift_reserved_words_.insert("true"); + swift_reserved_words_.insert("typealias"); + swift_reserved_words_.insert("where"); + } } string t_swift_generator::maybe_escape_identifier(const string& identifier) { @@ -2162,37 +3116,70 @@ string t_swift_generator::type_to_enum(t_type* type, bool qualified) { type = get_true_type(type); string result = qualified ? "TType." : "."; - - if (type->is_base_type()) { - t_base_type::t_base tbase = ((t_base_type*)type)->get_base(); - switch (tbase) { - case t_base_type::TYPE_VOID: - throw "NO T_VOID CONSTRUCT"; - case t_base_type::TYPE_STRING: - return result + "STRING"; - case t_base_type::TYPE_BOOL: - return result + "BOOL"; - case t_base_type::TYPE_I8: - return result + "BYTE"; - case t_base_type::TYPE_I16: - return result + "I16"; - case t_base_type::TYPE_I32: - return result + "I32"; - case t_base_type::TYPE_I64: - return result + "I64"; - case t_base_type::TYPE_DOUBLE: - return result + "DOUBLE"; + if (!gen_cocoa_) { + if (type->is_base_type()) { + t_base_type::t_base tbase = ((t_base_type*)type)->get_base(); + switch (tbase) { + case t_base_type::TYPE_VOID: + throw "NO T_VOID CONSTRUCT"; + case t_base_type::TYPE_STRING: + return result + "string"; + case t_base_type::TYPE_BOOL: + return result + "bool"; + case t_base_type::TYPE_I8: + return result + "i8"; + case t_base_type::TYPE_I16: + return result + "i16"; + case t_base_type::TYPE_I32: + return result + "i32"; + case t_base_type::TYPE_I64: + return result + "i64"; + case t_base_type::TYPE_DOUBLE: + return result + "double"; + } + } else if (type->is_enum()) { + return result + "i32"; + } else if (type->is_struct() || type->is_xception()) { + return result + "struct"; + } else if (type->is_map()) { + return result + "map"; + } else if (type->is_set()) { + return result + "set"; + } else if (type->is_list()) { + return result + "list"; + } + } else { + if (type->is_base_type()) { + t_base_type::t_base tbase = ((t_base_type*)type)->get_base(); + switch (tbase) { + case t_base_type::TYPE_VOID: + throw "NO T_VOID CONSTRUCT"; + case t_base_type::TYPE_STRING: + return result + "STRING"; + case t_base_type::TYPE_BOOL: + return result + "BOOL"; + case t_base_type::TYPE_I8: + return result + "BYTE"; + case t_base_type::TYPE_I16: + return result + "I16"; + case t_base_type::TYPE_I32: + return result + "I32"; + case t_base_type::TYPE_I64: + return result + "I64"; + case t_base_type::TYPE_DOUBLE: + return result + "DOUBLE"; + } + } else if (type->is_enum()) { + return result + "I32"; + } else if (type->is_struct() || type->is_xception()) { + return result + "STRUCT"; + } else if (type->is_map()) { + return result + "MAP"; + } else if (type->is_set()) { + return result + "SET"; + } else if (type->is_list()) { + return result + "LIST"; } - } else if (type->is_enum()) { - return result + "I32"; - } else if (type->is_struct() || type->is_xception()) { - return result + "STRUCT"; - } else if (type->is_map()) { - return result + "MAP"; - } else if (type->is_set()) { - return result + "SET"; - } else if (type->is_list()) { - return result + "LIST"; } throw "INVALID TYPE IN type_to_enum: " + type->get_name(); @@ -2201,9 +3188,12 @@ string t_swift_generator::type_to_enum(t_type* type, bool qualified) { THRIFT_REGISTER_GENERATOR( swift, - "Swift", + "Swift 3.0", " log_unexpected: Log every time an unexpected field ID or type is encountered.\n" " debug_descriptions:\n" " Allow use of debugDescription so the app can add description via a cateogory/extension\n" " async_clients: Generate clients which invoke asynchronously via block syntax.\n" - " promise_kit: Generate clients which invoke asynchronously via promises.\n") + " namespaced: Generate source in Module scoped output directories for Swift Namespacing.\n" + " cocoa: Generate Swift 2.x code compatible with the Thrift/Cocoa library\n" + " promise_kit: Generate clients which invoke asynchronously via promises (only use with cocoa flag)\n" + " safe_enums: Generate enum types with an unknown case to handle unspecified values rather than throw a serialization error\n") diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_xml_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_xml_generator.cc index b35f351..35fed14 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_xml_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_xml_generator.cc @@ -101,7 +101,7 @@ private: bool should_use_default_ns_; bool should_use_namespaces_; - std::ofstream f_xml_; + ofstream_with_content_based_conditional_update f_xml_; std::set programs_; std::stack elements_; @@ -391,11 +391,16 @@ void t_xml_generator::write_type(t_type* ttype) { if (type == "id") { write_attribute("type-module", ttype->get_program()->get_name()); write_attribute("type-id", ttype->get_name()); - } else if (type == "list" || type == "set") { + } else if (type == "list") { t_type* etype = ((t_list*)ttype)->get_elem_type(); write_element_start("elemType"); write_type(etype); write_element_end(); + } else if (type == "set") { + t_type* etype = ((t_set*)ttype)->get_elem_type(); + write_element_start("elemType"); + write_type(etype); + write_element_end(); } else if (type == "map") { t_type* ktype = ((t_map*)ttype)->get_key_type(); write_element_start("keyType"); @@ -478,8 +483,8 @@ void t_xml_generator::write_const_value(t_const_value* value) { case t_const_value::CV_MAP: { write_element_start("map"); - std::map map = value->get_map(); - std::map::iterator mit; + std::map map = value->get_map(); + std::map::iterator mit; for (mit = map.begin(); mit != map.end(); ++mit) { write_element_start("entry"); write_element_start("key"); diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_xsd_generator.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_xsd_generator.cc index fa51ba0..e487ffc 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_xsd_generator.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/t_xsd_generator.cc @@ -103,8 +103,8 @@ private: /** * Output xsd/php file */ - std::ofstream f_xsd_; - std::ofstream f_php_; + ofstream_with_content_based_conditional_update f_xsd_; + ofstream_with_content_based_conditional_update f_php_; /** * Output string stream diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/thrift-t_php_generator.o-a60a38e9 b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/generate/thrift-t_php_generator.o-a60a38e9 new file mode 100644 index 0000000..e69de29 diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/main.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/main.cc index 8421840..cdc171c 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/main.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/main.cc @@ -805,8 +805,8 @@ void validate_const_rec(std::string name, t_type* type, t_const_value* value) { const vector& fields = ((t_struct*)type)->get_members(); vector::const_iterator f_iter; - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { if (v_iter->first->get_type() != t_const_value::CV_STRING) { throw "type error: " + name + " struct key must be string"; @@ -826,8 +826,8 @@ void validate_const_rec(std::string name, t_type* type, t_const_value* value) { } else if (type->is_map()) { t_type* k_type = ((t_map*)type)->get_key_type(); t_type* v_type = ((t_map*)type)->get_val_type(); - const map& val = value->get_map(); - map::const_iterator v_iter; + const map& val = value->get_map(); + map::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { validate_const_rec(name + "", k_type, v_iter->first); validate_const_rec(name + "", v_type, v_iter->second); @@ -1028,6 +1028,7 @@ void generate(t_program* program, const vector& generator_strings) { g_generator_failure = true; #endif } else if (generator) { + generator->validate_input(); pverbose("Generating \"%s\"\n", iter->c_str()); generator->generate_program(); delete generator; diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_base_type.h b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_base_type.h index 32523cb..71398ba 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_base_type.h +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_base_type.h @@ -57,15 +57,15 @@ public: void set_string_list(bool val) { string_list_ = val; } - bool is_string_list() const { return (base_ == TYPE_STRING) && string_list_; } + bool is_string_list() const { return string_list_ && (base_ == TYPE_STRING); } void set_binary(bool val) { binary_ = val; } - bool is_binary() const { return (base_ == TYPE_STRING) && binary_; } + bool is_binary() const { return binary_ && (base_ == TYPE_STRING); } void set_string_enum(bool val) { string_enum_ = val; } - bool is_string_enum() const { return base_ == TYPE_STRING && string_enum_; } + bool is_string_enum() const { return string_enum_ && base_ == TYPE_STRING; } void add_string_enum_val(std::string val) { string_enum_vals_.push_back(val); } diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_const_value.h b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_const_value.h index 5507803..6a114cf 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_const_value.h +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_const_value.h @@ -38,13 +38,24 @@ void convert(From*, To&); */ class t_const_value { public: - enum t_const_value_type { CV_INTEGER, CV_DOUBLE, CV_STRING, CV_MAP, CV_LIST, CV_IDENTIFIER }; + /** + * Comparator to sort fields in ascending order by key. + * Make this a functor instead of a function to help GCC inline it. + */ + struct value_compare { + public: + bool operator()(t_const_value const* const& left, t_const_value const* const& right) const { + return *left < *right; + } + }; - t_const_value() {} + enum t_const_value_type { CV_INTEGER, CV_DOUBLE, CV_STRING, CV_MAP, CV_LIST, CV_IDENTIFIER, CV_UNKNOWN }; - t_const_value(int64_t val) { set_integer(val); } + t_const_value() : intVal_(0), doubleVal_(0.0f), enum_((t_enum*)0), valType_(CV_UNKNOWN) {} - t_const_value(std::string val) { set_string(val); } + t_const_value(int64_t val) : doubleVal_(0.0f), enum_((t_enum*)0), valType_(CV_UNKNOWN) { set_integer(val); } + + t_const_value(std::string val) : intVal_(0), doubleVal_(0.0f), enum_((t_enum*)0), valType_(CV_UNKNOWN) { set_string(val); } void set_string(std::string val) { valType_ = CV_STRING; @@ -90,7 +101,7 @@ public: void add_map(t_const_value* key, t_const_value* val) { mapVal_[key] = val; } - const std::map& get_map() const { return mapVal_; } + const std::map& get_map() const { return mapVal_; } void set_list() { valType_ = CV_LIST; } @@ -134,10 +145,57 @@ public: void set_enum(t_enum* tenum) { enum_ = tenum; } - t_const_value_type get_type() const { return valType_; } + t_const_value_type get_type() const { if (valType_ == CV_UNKNOWN) { throw std::string("unknown t_const_value"); } return valType_; } + + /** + * Comparator to sort map fields in ascending order by key and then value. + * This is used for map comparison in lexicographic order. + */ + struct map_entry_compare { + private: + typedef std::pair ConstPair; + public: + bool operator()(ConstPair left, ConstPair right) const { + if (*(left.first) < *(right.first)) { + return true; + } else { + if (*(right.first) < *(left.first)) { + return false; + } else { + return *(left.second) < *(right.second); + } + } + } + }; + + bool operator < (const t_const_value& that) const { + ::t_const_value::t_const_value_type t1 = get_type(); + ::t_const_value::t_const_value_type t2 = that.get_type(); + if (t1 != t2) + return t1 < t2; + switch (t1) { + case ::t_const_value::CV_INTEGER: + return intVal_ < that.intVal_; + case ::t_const_value::CV_DOUBLE: + return doubleVal_ < that.doubleVal_; + case ::t_const_value::CV_STRING: + return stringVal_ < that.stringVal_; + case ::t_const_value::CV_IDENTIFIER: + return identifierVal_ < that.identifierVal_; + case ::t_const_value::CV_MAP: + return std::lexicographical_compare( + mapVal_.begin(), mapVal_.end(), that.mapVal_.begin(), that.mapVal_.end(), map_entry_compare()); + case ::t_const_value::CV_LIST: + return std::lexicographical_compare( + listVal_.begin(), listVal_.end(), that.listVal_.begin(), that.listVal_.end(), value_compare()); + case ::t_const_value::CV_UNKNOWN: + default: + throw "unknown value type"; + } + } private: - std::map mapVal_; + std::map mapVal_; std::vector listVal_; std::string stringVal_; int64_t intVal_; diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_function.h b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_function.h index 05dc930..22d2609 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_function.h +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_function.h @@ -34,8 +34,12 @@ class t_function : public t_doc { public: t_function(t_type* returntype, std::string name, t_struct* arglist, bool oneway = false) - : returntype_(returntype), name_(name), arglist_(arglist), oneway_(oneway) { - xceptions_ = new t_struct(NULL); + : returntype_(returntype), + name_(name), + arglist_(arglist), + xceptions_(new t_struct(NULL)), + own_xceptions_(true), + oneway_(oneway) { if (oneway_ && (!returntype_->is_void())) { pwarning(1, "Oneway methods should return void.\n"); } @@ -50,6 +54,7 @@ public: name_(name), arglist_(arglist), xceptions_(xceptions), + own_xceptions_(false), oneway_(oneway) { if (oneway_ && !xceptions_->get_members().empty()) { throw std::string("Oneway methods can't throw exceptions."); @@ -59,7 +64,10 @@ public: } } - ~t_function() {} + ~t_function() { + if (own_xceptions_) + delete xceptions_; + } t_type* get_returntype() const { return returntype_; } @@ -78,6 +86,7 @@ private: std::string name_; t_struct* arglist_; t_struct* xceptions_; + bool own_xceptions_; bool oneway_; }; diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_scope.h b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_scope.h index e196200..6f160a5 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_scope.h +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_scope.h @@ -31,6 +31,7 @@ #include "thrift/parse/t_base_type.h" #include "thrift/parse/t_map.h" #include "thrift/parse/t_list.h" +#include "thrift/parse/t_set.h" namespace plugin_output { template @@ -75,22 +76,28 @@ public: void resolve_const_value(t_const_value* const_val, t_type* ttype) { if (ttype->is_map()) { - const std::map& map = const_val->get_map(); - std::map::const_iterator v_iter; + const std::map& map = const_val->get_map(); + std::map::const_iterator v_iter; for (v_iter = map.begin(); v_iter != map.end(); ++v_iter) { resolve_const_value(v_iter->first, ((t_map*)ttype)->get_key_type()); resolve_const_value(v_iter->second, ((t_map*)ttype)->get_val_type()); } - } else if (ttype->is_list() || ttype->is_set()) { + } else if (ttype->is_list()) { const std::vector& val = const_val->get_list(); std::vector::const_iterator v_iter; for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { resolve_const_value((*v_iter), ((t_list*)ttype)->get_elem_type()); } + } else if (ttype->is_set()) { + const std::vector& val = const_val->get_list(); + std::vector::const_iterator v_iter; + for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) { + resolve_const_value((*v_iter), ((t_set*)ttype)->get_elem_type()); + } } else if (ttype->is_struct()) { t_struct* tstruct = (t_struct*)ttype; - const std::map& map = const_val->get_map(); - std::map::const_iterator v_iter; + const std::map& map = const_val->get_map(); + std::map::const_iterator v_iter; for (v_iter = map.begin(); v_iter != map.end(); ++v_iter) { t_field* field = tstruct->get_field_by_name(v_iter->first->get_string()); if (field == NULL) { @@ -130,8 +137,8 @@ public: throw "Constants cannot be of type VOID"; } } else if (const_type->is_map()) { - const std::map& map = constant->get_value()->get_map(); - std::map::const_iterator v_iter; + const std::map& map = constant->get_value()->get_map(); + std::map::const_iterator v_iter; const_val->set_map(); for (v_iter = map.begin(); v_iter != map.end(); ++v_iter) { diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_type.h b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_type.h index 30f8c1f..3a6d1e0 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_type.h +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_type.h @@ -47,6 +47,7 @@ public: virtual bool is_void() const { return false; } virtual bool is_base_type() const { return false; } virtual bool is_string() const { return false; } + virtual bool is_binary() const { return false; } virtual bool is_bool() const { return false; } virtual bool is_typedef() const { return false; } virtual bool is_enum() const { return false; } diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_typedef.h b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_typedef.h index 0cccc26..aad3a50 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_typedef.h +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/parse/t_typedef.h @@ -33,7 +33,7 @@ class t_typedef : public t_type { public: t_typedef(t_program* program, t_type* type, const std::string& symbolic) - : t_type(program, symbolic), type_(type), symbolic_(symbolic), forward_(false), seen_(false) {} + : t_type(program, symbolic), type_(type), symbolic_(symbolic), forward_(false) {} /** * This constructor is used to refer to a type that is lazily @@ -44,8 +44,8 @@ public: : t_type(program, symbolic), type_(NULL), symbolic_(symbolic), - forward_(forward), - seen_(false) {} + forward_(forward) + {} ~t_typedef() {} @@ -61,7 +61,6 @@ private: t_type* type_; std::string symbolic_; bool forward_; - mutable bool seen_; }; #endif diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/platform.h b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/platform.h index 7a8edae..f49adb9 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/platform.h +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/platform.h @@ -34,10 +34,13 @@ #include #endif +#include + +// ignore EEXIST, throw on any other error #ifdef _WIN32 -#define MKDIR(x) mkdir(x) +#define MKDIR(x) { int r = _mkdir(x); if (r == -1 && errno != EEXIST) { throw (std::string(x) + ": ") + strerror(errno); } } #else -#define MKDIR(x) mkdir(x, S_IRWXU | S_IRWXG | S_IRWXO) +#define MKDIR(x) { int r = mkdir(x, S_IRWXU | S_IRWXG | S_IRWXO); if (r == -1 && errno != EEXIST) { throw (std::string(x) + ": ") + strerror(errno); } } #endif #ifdef PATH_MAX diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/plugin/plugin.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/plugin/plugin.cc index 1d45d89..ca5d287 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/plugin/plugin.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/plugin/plugin.cc @@ -27,17 +27,15 @@ #include #include -#include #include #include -#include #include "thrift/generate/t_generator.h" #include "thrift/plugin/type_util.h" #include "thrift/protocol/TBinaryProtocol.h" #include "thrift/transport/TBufferTransports.h" #include "thrift/transport/TFDTransport.h" - +#include "thrift/stdcxx.h" #include "thrift/plugin/plugin_types.h" namespace apache { @@ -121,11 +119,16 @@ struct TypeCache { void compileAll() { boost::for_each(*source | boost::adaptors::map_keys, - boost::bind(&TypeCache::compile, this, _1)); + stdcxx::bind(&TypeCache::compile, this, stdcxx::placeholders::_1)); } std::map const* source; + void clear() { + source = nullptr ; + cache.clear() ; + } + protected: std::map cache; @@ -143,6 +146,12 @@ TypeCache< ::t_type, t_type> g_type_cache; TypeCache< ::t_const, t_const> g_const_cache; TypeCache< ::t_service, t_service> g_service_cache; +void clear_global_cache() { + g_type_cache.clear(); + g_const_cache.clear(); + g_service_cache.clear(); +} + void set_global_cache(const TypeRegistry& from) { g_type_cache.source = &from.types; g_const_cache.source = &from.constants; @@ -218,7 +227,7 @@ THRIFT_CONVERSION(t_enum, g_program_cache[from.metadata.program_id]) { assert(to); THRIFT_ASSIGN_METADATA(); boost::for_each(from.constants | boost::adaptors::transformed(convert), - boost::bind(&::t_enum::append, to, _1)); + stdcxx::bind(&::t_enum::append, to, stdcxx::placeholders::_1)); } THRIFT_CONVERSION(t_list, resolve_type< ::t_type>(from.elem_type)) { assert(to); @@ -255,16 +264,16 @@ THRIFT_CONVERSION(t_const_value, ) { } else if (from.__isset.list_val) { to->set_list(); boost::for_each(from.list_val | boost::adaptors::transformed(&convert), - boost::bind(&::t_const_value::add_list, to, _1)); + stdcxx::bind(&::t_const_value::add_list, to, stdcxx::placeholders::_1)); } else T_CONST_VALUE_CASE(string); else T_CONST_VALUE_CASE(integer); else T_CONST_VALUE_CASE(double); - else { - T_CONST_VALUE_CASE(identifier); - if (from.__isset.enum_val) - to->set_enum(resolve_type< ::t_enum>(from.enum_val)); + else if (from.__isset.const_identifier_val) { + to->set_identifier(from.const_identifier_val.identifier_val) ; + to->set_enum(resolve_type< ::t_enum>(from.const_identifier_val.enum_val)) ; } + #undef T_CONST_VALUE_CASE } THRIFT_CONVERSION(t_field, resolve_type< ::t_type>(from.type), from.name, from.key) { @@ -282,7 +291,7 @@ THRIFT_CONVERSION(t_struct, g_program_cache[from.metadata.program_id]) { to->set_union(from.is_union); to->set_xception(from.is_xception); boost::for_each(from.members | boost::adaptors::transformed(convert), - boost::bind(&::t_struct::append, to, _1)); + stdcxx::bind(&::t_struct::append, to, stdcxx::placeholders::_1)); } THRIFT_CONVERSION(t_const, resolve_type< ::t_type>(from.type), @@ -309,7 +318,7 @@ THRIFT_CONVERSION(t_service, g_program_cache[from.metadata.program_id]) { THRIFT_ASSIGN_METADATA(); boost::for_each(from.functions | boost::adaptors::transformed(convert), - boost::bind(&::t_service::add_function, to, _1)); + stdcxx::bind(&::t_service::add_function, to, stdcxx::placeholders::_1)); if (from.__isset.extends_) to->set_extends(resolve_service(from.extends_)); @@ -390,9 +399,9 @@ THRIFT_CONVERT_COMPLETE(t_program) { to->set_out_path(from.out_path, from.out_path_is_absolute); boost::for_each(from.typedefs | boost::adaptors::transformed(&resolve_type< ::t_typedef>), - boost::bind(&::t_program::add_typedef, to, _1)); + stdcxx::bind(&::t_program::add_typedef, to, stdcxx::placeholders::_1)); boost::for_each(from.enums | boost::adaptors::transformed(&resolve_type< ::t_enum>), - boost::bind(&::t_program::add_enum, to, _1)); + stdcxx::bind(&::t_program::add_enum, to, stdcxx::placeholders::_1)); for (std::vector::const_iterator it = from.objects.begin(); it != from.objects.end(); it++) { ::t_struct* t2 = resolve_type< ::t_struct>(*it); @@ -403,18 +412,18 @@ THRIFT_CONVERT_COMPLETE(t_program) { } } boost::for_each(from.consts | boost::adaptors::transformed(&resolve_const), - boost::bind(&::t_program::add_const, to, _1)); + stdcxx::bind(&::t_program::add_const, to, stdcxx::placeholders::_1)); boost::for_each(from.services | boost::adaptors::transformed(&resolve_service), - boost::bind(&::t_program::add_service, to, _1)); + stdcxx::bind(&::t_program::add_service, to, stdcxx::placeholders::_1)); for (std::vector::const_iterator it = from.includes.begin(); it != from.includes.end(); it++) { convert(*it, g_program_cache[it->program_id]); } std::for_each(from.c_includes.begin(), from.c_includes.end(), - boost::bind(&::t_program::add_c_include, to, _1)); + stdcxx::bind(&::t_program::add_c_include, to, stdcxx::placeholders::_1)); std::for_each(from.cpp_includes.begin(), from.cpp_includes.end(), - boost::bind(&::t_program::add_cpp_include, to, _1)); + stdcxx::bind(&::t_program::add_cpp_include, to, stdcxx::placeholders::_1)); for (std::map::const_iterator it = from.namespaces.begin(); it != from.namespaces.end(); it++) { to->set_namespace(it->first, it->second); @@ -428,8 +437,8 @@ int GeneratorPlugin::exec(int, char* []) { #ifdef _WIN32 _setmode(fileno(stdin), _O_BINARY); #endif - boost::shared_ptr transport( - new TFramedTransport(boost::make_shared(fileno(stdin)))); + stdcxx::shared_ptr transport( + new TFramedTransport(stdcxx::make_shared(fileno(stdin)))); TBinaryProtocol proto(transport); GeneratorInput input; try { @@ -460,9 +469,7 @@ int GeneratorPlugin::exec(int, char* []) { return ::t_const_value::CV_INTEGER; if (v.__isset.double_val) return ::t_const_value::CV_DOUBLE; - if (v.__isset.identifier_val) - return ::t_const_value::CV_IDENTIFIER; - if (v.__isset.enum_val) + if (v.__isset.const_identifier_val) return ::t_const_value::CV_IDENTIFIER; throw ThriftPluginError("Unknown const value type"); } diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/plugin/plugin.thrift b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/plugin/plugin.thrift index a93873d..6d98f99 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/plugin/plugin.thrift +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/plugin/plugin.thrift @@ -105,27 +105,26 @@ enum Requiredness { T_OPT_IN_REQ_OUT = 2 } +struct t_const_identifier_value { + 1: required string identifier_val + 2: required t_type_id enum_val +} + union t_const_value { 1: optional map map_val 2: optional list list_val 3: optional string string_val 4: optional i64 integer_val 5: optional double double_val - 6: optional string identifier_val - 7: optional t_type_id enum_val + 8: optional t_const_identifier_value const_identifier_val } + struct t_const { 1: required string name 2: required t_type_id type 3: required t_const_value value 100: optional string doc } -struct t_struct { - 1: required TypeMetadata metadata - 2: required list members - 3: required bool is_union - 4: required bool is_xception -} struct t_field { 1: required string name 2: required t_type_id type @@ -136,6 +135,12 @@ struct t_field { 99: optional map annotations 100: optional string doc } +struct t_struct { + 1: required TypeMetadata metadata + 2: required list members + 3: required bool is_union + 4: required bool is_xception +} struct t_function { 1: required string name 2: required t_type_id returntype diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/plugin/plugin_output.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/plugin/plugin_output.cc index 168a4a6..81b9a2a 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/plugin/plugin_output.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/plugin/plugin_output.cc @@ -34,12 +34,12 @@ #include #include #include -#include #include "thrift/generate/t_generator.h" #include "thrift/plugin/plugin.h" #include "thrift/plugin/type_util.h" #include "thrift/protocol/TBinaryProtocol.h" +#include "thrift/stdcxx.h" #include "thrift/transport/TBufferTransports.h" #include "thrift/transport/TFDTransport.h" @@ -55,6 +55,8 @@ typename apache::thrift::plugin::ToType::type convert(From* from) { } using apache::thrift::protocol::TBinaryProtocol; +using apache::thrift::stdcxx::make_shared; +using apache::thrift::stdcxx::shared_ptr; using apache::thrift::transport::TFDTransport; using apache::thrift::transport::TFramedTransport; @@ -97,29 +99,62 @@ using namespace apache::thrift; #define THRIFT_ASSIGN_METADATA() convert(reinterpret_cast(from), to.metadata) +// a generator of sequential unique identifiers for addresses -- so +// that the TypeCache below can use those IDs instead of +// addresses. This allows GeneratorInput's various +// t_{program,type,etc}_id types to be dense consecutively-numbered +// integers, instead of large random-seeming integers. +// +// Furthermore, this allows GeneratorInput to be deterministic (no +// addresses, so no pseudo-randomness) and that means reproducibility +// of output. +const int64_t ONE_MILLION = 1000 * 1000; +class id_generator { +public: + id_generator() : addr2id_(), next_id_(ONE_MILLION) {} + + void clear() { + addr2id_.clear() ; + next_id_ = ONE_MILLION ; + } + + int64_t gensym(const int64_t addr) { + if (!addr) return 0L ; + std::map::iterator it = addr2id_.find(addr); + if (it != addr2id_.end()) return it->second ; + int64_t id = next_id_++ ; + addr2id_.insert(std::make_pair(addr, id)) ; + return id ; + } + + std::map addr2id_ ; + int64_t next_id_ ; +} ; + // To avoid multiple instances of same type, t_type, t_const and t_service are stored in one place // and referenced by ID. template struct TypeCache { typedef typename plugin::ToType::type to_type; + id_generator idgen ; std::map cache; template int64_t store(T2* t) { - intptr_t id = reinterpret_cast(t); - if (id) { - typename std::map::iterator it = cache.find(id); - if (it == cache.end()) { - // HACK: fake resolve for recursive type - cache.insert(std::make_pair(id, to_type())); - // overwrite with true value - cache[id] = convert(t); - } - } - return static_cast(id); + intptr_t addr = reinterpret_cast(t); + if (!addr) return 0L ; + + int64_t id = idgen.gensym(addr) ; + if (cache.end() != cache.find(id)) return id ; + + // HACK: fake resolve for recursive type + cache.insert(std::make_pair(id, to_type())); + // overwrite with true value + cache[id] = convert(t); + return id ; } - void clear() { cache.clear(); } + void clear() { cache.clear() ; idgen.clear(); } }; template @@ -135,6 +170,8 @@ T_STORE(type) T_STORE(const) T_STORE(service) #undef T_STORE +// this id_generator is for gensymm-ing t_program_id +id_generator program_cache ; #define THRIFT_ASSIGN_ID_N(t, from_name, to_name) \ do { \ @@ -155,7 +192,7 @@ T_STORE(service) } while (0) THRIFT_CONVERSION_N(::t_type, plugin::TypeMetadata) { - to.program_id = reinterpret_cast(from->get_program()); + to.program_id = program_cache.gensym(reinterpret_cast(from->get_program())); THRIFT_ASSIGN_N(annotations_, annotations, ); if (from->has_doc()) { to.__set_doc(from->get_doc()); @@ -193,8 +230,13 @@ THRIFT_CONVERSION(t_const_value) { THRIFT_ASSIGN_N(get_string(), string_val, ); break; case t_const_value::CV_IDENTIFIER: - THRIFT_ASSIGN_ID_N(t_type, enum_, enum_val); - THRIFT_ASSIGN_N(get_identifier(), identifier_val, ); + if (from) { + apache::thrift::plugin::t_const_identifier_value cidval ; + if (from->enum_) + cidval.__set_enum_val(store_type(from->enum_)); + cidval.__set_identifier_val(from->get_identifier()); + to.__set_const_identifier_val(cidval) ; + } break; case t_const_value::CV_MAP: to.__isset.map_val = true; @@ -339,6 +381,7 @@ void clear_global_cache() { type_cache.clear(); const_cache.clear(); service_cache.clear(); + program_cache.clear() ; } THRIFT_CONVERSION(t_program) { @@ -358,7 +401,7 @@ THRIFT_CONVERSION(t_program) { THRIFT_ASSIGN_LIST_ID(t_const, const); THRIFT_ASSIGN_LIST_ID(t_service, service); THRIFT_ASSIGN_LIST_N(t_program, get_includes(), includes); - to.program_id = reinterpret_cast(from); + to.program_id = program_cache.gensym(reinterpret_cast(from)); } PluginDelegateResult delegateToPlugin(t_program* program, const std::string& options) { @@ -377,8 +420,8 @@ PluginDelegateResult delegateToPlugin(t_program* program, const std::string& opt #ifdef _WIN32 _setmode(fileno(fd), _O_BINARY); #endif - boost::shared_ptr transport( - new TFramedTransport(boost::make_shared(fileno(fd)))); + shared_ptr transport( + new TFramedTransport(make_shared(fileno(fd)))); TBinaryProtocol proto(transport); plugin::GeneratorInput input; @@ -408,3 +451,4 @@ PluginDelegateResult delegateToPlugin(t_program* program, const std::string& opt return PLUGIN_NOT_FOUND; } } + diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/plugin/type_util.h b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/plugin/type_util.h index 508b741..996b5c6 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/plugin/type_util.h +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/plugin/type_util.h @@ -38,6 +38,7 @@ typename ToType::type* convert(const From& from); class TypeRegistry; void set_global_cache(const TypeRegistry&); +void clear_global_cache(); } } } diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/thriftl.ll b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/thriftl.ll index bf7e8a5..4f783be 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/thriftl.ll +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/thriftl.ll @@ -39,9 +39,15 @@ #endif #ifdef _MSC_VER -//warning C4102: 'find_rule' : unreferenced label -#pragma warning(disable:4102) -//avoid isatty redefinition +#pragma warning( push ) + +// warning C4102: 'find_rule' : unreferenced label +#pragma warning( disable : 4102 ) + +// warning C4267: 'argument' : conversion from 'size_t' to 'int', possible loss of data +#pragma warning( disable : 4267 ) + +// avoid isatty redefinition #define YY_NEVER_INTERACTIVE 1 #define YY_NO_UNISTD_H 1 @@ -70,11 +76,6 @@ #include "thrift/thrifty.hh" #endif -void thrift_reserved_keyword(char* keyword) { - yyerror("Cannot use reserved language keyword: \"%s\"\n", keyword); - exit(1); -} - void integer_overflow(char* text) { yyerror("This integer is too big: \"%s\"\n", text); exit(1); @@ -263,111 +264,6 @@ literal_begin (['\"]) } "&" { return tok_reference; } - -"BEGIN" { thrift_reserved_keyword(yytext); } -"END" { thrift_reserved_keyword(yytext); } -"__CLASS__" { thrift_reserved_keyword(yytext); } -"__DIR__" { thrift_reserved_keyword(yytext); } -"__FILE__" { thrift_reserved_keyword(yytext); } -"__FUNCTION__" { thrift_reserved_keyword(yytext); } -"__LINE__" { thrift_reserved_keyword(yytext); } -"__METHOD__" { thrift_reserved_keyword(yytext); } -"__NAMESPACE__" { thrift_reserved_keyword(yytext); } -"abstract" { thrift_reserved_keyword(yytext); } -"alias" { thrift_reserved_keyword(yytext); } -"and" { thrift_reserved_keyword(yytext); } -"args" { thrift_reserved_keyword(yytext); } -"as" { thrift_reserved_keyword(yytext); } -"assert" { thrift_reserved_keyword(yytext); } -"begin" { thrift_reserved_keyword(yytext); } -"break" { thrift_reserved_keyword(yytext); } -"case" { thrift_reserved_keyword(yytext); } -"catch" { thrift_reserved_keyword(yytext); } -"class" { thrift_reserved_keyword(yytext); } -"clone" { thrift_reserved_keyword(yytext); } -"continue" { thrift_reserved_keyword(yytext); } -"declare" { thrift_reserved_keyword(yytext); } -"def" { thrift_reserved_keyword(yytext); } -"default" { thrift_reserved_keyword(yytext); } -"del" { thrift_reserved_keyword(yytext); } -"delete" { thrift_reserved_keyword(yytext); } -"do" { thrift_reserved_keyword(yytext); } -"dynamic" { thrift_reserved_keyword(yytext); } -"elif" { thrift_reserved_keyword(yytext); } -"else" { thrift_reserved_keyword(yytext); } -"elseif" { thrift_reserved_keyword(yytext); } -"elsif" { thrift_reserved_keyword(yytext); } -"end" { thrift_reserved_keyword(yytext); } -"enddeclare" { thrift_reserved_keyword(yytext); } -"endfor" { thrift_reserved_keyword(yytext); } -"endforeach" { thrift_reserved_keyword(yytext); } -"endif" { thrift_reserved_keyword(yytext); } -"endswitch" { thrift_reserved_keyword(yytext); } -"endwhile" { thrift_reserved_keyword(yytext); } -"ensure" { thrift_reserved_keyword(yytext); } -"except" { thrift_reserved_keyword(yytext); } -"exec" { thrift_reserved_keyword(yytext); } -"finally" { thrift_reserved_keyword(yytext); } -"float" { thrift_reserved_keyword(yytext); } -"for" { thrift_reserved_keyword(yytext); } -"foreach" { thrift_reserved_keyword(yytext); } -"from" { thrift_reserved_keyword(yytext); } -"function" { thrift_reserved_keyword(yytext); } -"global" { thrift_reserved_keyword(yytext); } -"goto" { thrift_reserved_keyword(yytext); } -"if" { thrift_reserved_keyword(yytext); } -"implements" { thrift_reserved_keyword(yytext); } -"import" { thrift_reserved_keyword(yytext); } -"in" { thrift_reserved_keyword(yytext); } -"inline" { thrift_reserved_keyword(yytext); } -"instanceof" { thrift_reserved_keyword(yytext); } -"interface" { thrift_reserved_keyword(yytext); } -"is" { thrift_reserved_keyword(yytext); } -"lambda" { thrift_reserved_keyword(yytext); } -"module" { thrift_reserved_keyword(yytext); } -"native" { thrift_reserved_keyword(yytext); } -"new" { thrift_reserved_keyword(yytext); } -"next" { thrift_reserved_keyword(yytext); } -"nil" { thrift_reserved_keyword(yytext); } -"not" { thrift_reserved_keyword(yytext); } -"or" { thrift_reserved_keyword(yytext); } -"package" { thrift_reserved_keyword(yytext); } -"pass" { thrift_reserved_keyword(yytext); } -"public" { thrift_reserved_keyword(yytext); } -"print" { thrift_reserved_keyword(yytext); } -"private" { thrift_reserved_keyword(yytext); } -"protected" { thrift_reserved_keyword(yytext); } -"raise" { thrift_reserved_keyword(yytext); } -"redo" { thrift_reserved_keyword(yytext); } -"rescue" { thrift_reserved_keyword(yytext); } -"retry" { thrift_reserved_keyword(yytext); } -"register" { thrift_reserved_keyword(yytext); } -"return" { thrift_reserved_keyword(yytext); } -"self" { thrift_reserved_keyword(yytext); } -"sizeof" { thrift_reserved_keyword(yytext); } -"static" { thrift_reserved_keyword(yytext); } -"super" { thrift_reserved_keyword(yytext); } -"switch" { thrift_reserved_keyword(yytext); } -"synchronized" { thrift_reserved_keyword(yytext); } -"then" { thrift_reserved_keyword(yytext); } -"this" { thrift_reserved_keyword(yytext); } -"throw" { thrift_reserved_keyword(yytext); } -"transient" { thrift_reserved_keyword(yytext); } -"try" { thrift_reserved_keyword(yytext); } -"undef" { thrift_reserved_keyword(yytext); } -"unless" { thrift_reserved_keyword(yytext); } -"unsigned" { thrift_reserved_keyword(yytext); } -"until" { thrift_reserved_keyword(yytext); } -"use" { thrift_reserved_keyword(yytext); } -"var" { thrift_reserved_keyword(yytext); } -"virtual" { thrift_reserved_keyword(yytext); } -"volatile" { thrift_reserved_keyword(yytext); } -"when" { thrift_reserved_keyword(yytext); } -"while" { thrift_reserved_keyword(yytext); } -"with" { thrift_reserved_keyword(yytext); } -"xor" { thrift_reserved_keyword(yytext); } -"yield" { thrift_reserved_keyword(yytext); } - {intconstant} { errno = 0; yylval.iconst = strtoll(yytext, NULL, 10); @@ -459,5 +355,9 @@ literal_begin (['\"]) %% +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + /* vim: filetype=lex */ diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/thrifty.yy b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/thrifty.yy index b7a7f72..df34adf 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/thrifty.yy +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/thrifty.yy @@ -1,3 +1,6 @@ +%code requires { +#include "thrift/parse/t_program.h" +} %{ /* * Licensed to the Apache Software Foundation (ASF) under one @@ -25,9 +28,14 @@ * */ +#ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS +#endif +#ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS +#endif #include +#include #ifndef _MSC_VER #include #else diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/windows/config.h b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/windows/config.h index 5f057ca..d2269cf 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/windows/config.h +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/src/thrift/windows/config.h @@ -34,9 +34,13 @@ #define strtoll(begin_ptr, end_ptr, length) _strtoi64(begin_ptr, end_ptr, length) -#define PRIu64 "I64d" -#define PRIi64 "I64d" +#ifndef PRIu64 +#define PRIu64 "I64u" +#endif +#ifndef PRIi64 +#define PRIi64 "I64i" +#endif // squelch deprecation warnings #pragma warning(disable : 4996) // squelch bool conversion performance warning diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/CMakeLists.txt b/vendor/git.apache.org/thrift.git/compiler/cpp/test/CMakeLists.txt index c1fe914..a09f23d 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/test/CMakeLists.txt +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/CMakeLists.txt @@ -75,3 +75,18 @@ if(${WITH_PLUGIN}) -DSRCDIR=${CMAKE_CURRENT_SOURCE_DIR} -P ${CMAKE_CURRENT_SOURCE_DIR}/cpp_plugin_test.cmake) endif() + +file(GLOB KEYWORD_SAMPLES "${CMAKE_CURRENT_SOURCE_DIR}/keyword-samples/*.thrift") +foreach(LANG ${thrift_compiler_LANGS}) + foreach(SAMPLE ${KEYWORD_SAMPLES}) + get_filename_component(FILENAME ${SAMPLE} NAME_WE) + add_test(NAME "${LANG}_${FILENAME}" + COMMAND thrift-compiler --gen ${LANG} ${SAMPLE}) + set_tests_properties("${LANG}_${FILENAME}" PROPERTIES + PASS_REGULAR_EXPRESSION "Cannot use reserved language keyword") + endforeach() +endforeach() + + +find_package(PythonInterp REQUIRED) +add_test(NAME StalenessCheckTest COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/compiler/staleness_check.py ${THRIFT_COMPILER}) diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/Makefile.am b/vendor/git.apache.org/thrift.git/compiler/cpp/test/Makefile.am index 5a23202..b7fc91d 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/test/Makefile.am +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/Makefile.am @@ -32,6 +32,8 @@ check_PROGRAMS = plugintest noinst_PROGRAMS = thrift-gen-mycpp +all-local: thrift-gen-bincat + AM_CPPFLAGS += -I$(top_srcdir)/lib/cpp/src -I$(top_builddir)/lib/cpp/src plugintest_SOURCES = plugin/conversion_test.cc @@ -43,9 +45,16 @@ thrift_gen_mycpp_CPPFLAGS = $(AM_CPPFLAGS) -I$(top_srcdir)/compiler/cpp -I$(top_ thrift_gen_mycpp_LDADD = $(top_builddir)/compiler/cpp/libthriftc.la cpp_plugin_test.sh: thrift-gen-mycpp -TESTS = $(check_PROGRAMS) cpp_plugin_test.sh + +thrift-gen-bincat: + cp bincat.sh $@ + chmod 755 $@ + +plugin_stability_test.sh: thrift-gen-bincat + +TESTS = $(check_PROGRAMS) cpp_plugin_test.sh plugin_stability_test.sh clean-local: - $(RM) -rf gen-cpp gen-mycpp + $(RM) -rf gen-cpp gen-mycpp gen-bincat thrift-gen-bincat endif diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/bincat.sh b/vendor/git.apache.org/thrift.git/compiler/cpp/test/bincat.sh new file mode 100755 index 0000000..c7f9078 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/bincat.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +exec /bin/cat diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/compiler/Included.thrift b/vendor/git.apache.org/thrift.git/compiler/cpp/test/compiler/Included.thrift new file mode 100644 index 0000000..ce84ab6 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/compiler/Included.thrift @@ -0,0 +1,18 @@ +const string foo = "bar" + +struct a_struct { + 1: bool im_true, + 2: bool im_false, + 3: i8 a_bite, + 4: i16 integer16, + 5: i32 integer32, + 6: i64 integer64, + 7: double double_precision, + 8: string some_characters, + 9: string zomg_unicode, + 10: bool what_who, +} + +service AService { + i32 a_procedure(1: i32 arg) +} diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/compiler/Including.thrift b/vendor/git.apache.org/thrift.git/compiler/cpp/test/compiler/Including.thrift new file mode 100644 index 0000000..677af7b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/compiler/Including.thrift @@ -0,0 +1,7 @@ +include "Included.thrift" + +const string s = "string" + +struct BStruct { + 1: Included.a_struct one_of_each +} diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/compiler/Single.thrift b/vendor/git.apache.org/thrift.git/compiler/cpp/test/compiler/Single.thrift new file mode 100644 index 0000000..2ec301f --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/compiler/Single.thrift @@ -0,0 +1 @@ +const string foo = "bar" diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/compiler/staleness_check.py b/vendor/git.apache.org/thrift.git/compiler/cpp/test/compiler/staleness_check.py new file mode 100755 index 0000000..5b11dff --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/compiler/staleness_check.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# +from __future__ import print_function +import os +import shutil +import subprocess +import sys +import tempfile +import time +import unittest + + +class TestStalenessCheck(unittest.TestCase): + + CURRENT_DIR_PATH = os.path.dirname(os.path.realpath(__file__)) + THRIFT_EXECUTABLE_PATH = None + SINGLE_THRIFT_FILE_PATH = os.path.join(CURRENT_DIR_PATH, "Single.thrift") + INCLUDING_THRIFT_FILE_PATH = os.path.join(CURRENT_DIR_PATH, "Including.thrift") + INCLUDED_THRIFT_FILE_PATH = os.path.join(CURRENT_DIR_PATH, "Included.thrift") + + def test_staleness_check_of_single_thrift_file_without_changed_output(self): + temp_dir = tempfile.mkdtemp(dir=TestStalenessCheck.CURRENT_DIR_PATH) + + command = [TestStalenessCheck.THRIFT_EXECUTABLE_PATH, "-gen", "cpp", "-o", temp_dir] + command += [TestStalenessCheck.SINGLE_THRIFT_FILE_PATH] + subprocess.call(command) + + used_file_path = os.path.join(temp_dir, "gen-cpp", "Single_constants.cpp") + + first_modification_time = os.path.getmtime(os.path.join(used_file_path)) + + time.sleep(0.1) + + subprocess.call(command) + + second_modification_time = os.path.getmtime(used_file_path) + + self.assertEqual(second_modification_time, first_modification_time) + + shutil.rmtree(temp_dir, ignore_errors=True) + + def test_staleness_check_of_single_thrift_file_with_changed_output(self): + temp_dir = tempfile.mkdtemp(dir=TestStalenessCheck.CURRENT_DIR_PATH) + + command = [TestStalenessCheck.THRIFT_EXECUTABLE_PATH, "-gen", "cpp", "-o", temp_dir] + command += [TestStalenessCheck.SINGLE_THRIFT_FILE_PATH] + subprocess.call(command) + + used_file_path = os.path.join(temp_dir, "gen-cpp", "Single_constants.cpp") + + first_modification_time = os.path.getmtime(os.path.join(used_file_path)) + used_file = open(used_file_path, "r") + first_contents = used_file.read() + used_file.close() + + used_file = open(used_file_path, "a") + used_file.write("\n/* This is a comment */\n") + used_file.close() + + time.sleep(0.1) + + subprocess.call(command) + + second_modification_time = os.path.getmtime(used_file_path) + used_file = open(used_file_path, "r") + second_contents = used_file.read() + used_file.close() + + self.assertGreater(second_modification_time, first_modification_time) + self.assertEqual(first_contents, second_contents) + + shutil.rmtree(temp_dir, ignore_errors=True) + + def test_staleness_check_of_included_file(self): + temp_dir = tempfile.mkdtemp(dir=TestStalenessCheck.CURRENT_DIR_PATH) + + temp_included_file_path = os.path.join(temp_dir, "Included.thrift") + temp_including_file_path = os.path.join(temp_dir, "Including.thrift") + + shutil.copy2(TestStalenessCheck.INCLUDED_THRIFT_FILE_PATH, temp_included_file_path) + shutil.copy2(TestStalenessCheck.INCLUDING_THRIFT_FILE_PATH, temp_including_file_path) + + command = [TestStalenessCheck.THRIFT_EXECUTABLE_PATH, "-gen", "cpp", "-recurse", "-o", temp_dir] + command += [temp_including_file_path] + + subprocess.call(command) + + included_constants_cpp_file_path = os.path.join(temp_dir, "gen-cpp", "Included_constants.cpp") + including_constants_cpp_file_path = os.path.join(temp_dir, "gen-cpp", "Including_constants.cpp") + + included_constants_cpp_first_modification_time = os.path.getmtime(included_constants_cpp_file_path) + including_constants_cpp_first_modification_time = os.path.getmtime(including_constants_cpp_file_path) + + temp_included_file = open(temp_included_file_path, "a") + temp_included_file.write("\nconst i32 an_integer = 42\n") + temp_included_file.close() + + time.sleep(0.1) + + subprocess.call(command) + + included_constants_cpp_second_modification_time = os.path.getmtime(included_constants_cpp_file_path) + including_constants_cpp_second_modification_time = os.path.getmtime(including_constants_cpp_file_path) + + self.assertGreater( + included_constants_cpp_second_modification_time, included_constants_cpp_first_modification_time) + self.assertEqual( + including_constants_cpp_first_modification_time, including_constants_cpp_second_modification_time) + + shutil.rmtree(temp_dir, ignore_errors=True) + + +def suite(): + suite = unittest.TestSuite() + loader = unittest.TestLoader() + suite.addTest(loader.loadTestsFromTestCase(TestStalenessCheck)) + return suite + + +if __name__ == "__main__": + # The path of Thrift compiler is passed as an argument to the test script. + # Remove it to not confuse the unit testing framework + TestStalenessCheck.THRIFT_EXECUTABLE_PATH = sys.argv[-1] + del sys.argv[-1] + unittest.main(defaultTest="suite", testRunner=unittest.TextTestRunner(verbosity=2)) diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/const1_return.thrift b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/const1_return.thrift new file mode 100644 index 0000000..735e4ac --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/const1_return.thrift @@ -0,0 +1 @@ +const bool return = 0 diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/enum1_return.thrift b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/enum1_return.thrift new file mode 100644 index 0000000..6d834e1 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/enum1_return.thrift @@ -0,0 +1,2 @@ +enum return { +} diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/enum2_return.thrift b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/enum2_return.thrift new file mode 100644 index 0000000..a2caa8e --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/enum2_return.thrift @@ -0,0 +1,3 @@ +enum enum_name { + return +} diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/exception1_return.thrift b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/exception1_return.thrift new file mode 100644 index 0000000..eadb338 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/exception1_return.thrift @@ -0,0 +1 @@ +exception return {} diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/exception2_return.thrift b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/exception2_return.thrift new file mode 100644 index 0000000..493c352 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/exception2_return.thrift @@ -0,0 +1,3 @@ +exception exception_name { + 1: required i8 return +} diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/service1_return.thrift b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/service1_return.thrift new file mode 100644 index 0000000..5286a36 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/service1_return.thrift @@ -0,0 +1 @@ +service return {} diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/service2_return.thrift b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/service2_return.thrift new file mode 100644 index 0000000..6f7331d --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/service2_return.thrift @@ -0,0 +1,3 @@ +service service_name { + bool function_name(1: i32 return) +} diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/service3_return.thrift b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/service3_return.thrift new file mode 100644 index 0000000..c6dd946 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/service3_return.thrift @@ -0,0 +1,3 @@ +service service_name { + void return() +} diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/service4_return.thrift b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/service4_return.thrift new file mode 100644 index 0000000..d0787df --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/service4_return.thrift @@ -0,0 +1,5 @@ +exception exception_name {} + +service service_name { + void function_name() throws ( 1: exception_name return) +} diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/struct1_return.thrift b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/struct1_return.thrift new file mode 100644 index 0000000..c82b8b9 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/struct1_return.thrift @@ -0,0 +1 @@ +struct return {} diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/struct2_return.thrift b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/struct2_return.thrift new file mode 100644 index 0000000..a0700d1 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/struct2_return.thrift @@ -0,0 +1,3 @@ +struct struct_name { + 1: required bool return = 1 +} diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/typedef1_return.thrift b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/typedef1_return.thrift new file mode 100644 index 0000000..f159bb8 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/typedef1_return.thrift @@ -0,0 +1 @@ +typedef bool return diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/union1_return.thrift b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/union1_return.thrift new file mode 100644 index 0000000..368df13 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/union1_return.thrift @@ -0,0 +1 @@ +union return {} diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/union2_return.thrift b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/union2_return.thrift new file mode 100644 index 0000000..9719d1e --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/keyword-samples/union2_return.thrift @@ -0,0 +1,3 @@ +union union_name { + 1: optional bool return=1 +} diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/plugin/conversion_test.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/test/plugin/conversion_test.cc index 5159ba4..3c8d812 100644 --- a/vendor/git.apache.org/thrift.git/compiler/cpp/test/plugin/conversion_test.cc +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/plugin/conversion_test.cc @@ -234,6 +234,8 @@ void migrate_global_cache() { template T* round_trip(T* t) { typename plugin::ToType::type p; + plugin::clear_global_cache(); + plugin_output::clear_global_cache(); plugin_output::convert(t, p); migrate_global_cache(); return plugin::convert(p); @@ -275,12 +277,12 @@ void test_const_value(t_const_value* sut) { BOOST_CHECK_EQUAL(sut->get_map().size(), sut2->get_map().size()); { std::map sut_values; - for (std::map::const_iterator it = sut->get_map().begin(); + for (std::map::const_iterator it = sut->get_map().begin(); it != sut->get_map().end(); it++) { sut_values[it->first->get_type()] = it->second->get_type(); } std::map sut2_values; - for (std::map::const_iterator it = sut2->get_map().begin(); + for (std::map::const_iterator it = sut2->get_map().begin(); it != sut2->get_map().end(); it++) { sut2_values[it->first->get_type()] = it->second->get_type(); } diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/test/plugin_stability_test.sh b/vendor/git.apache.org/thrift.git/compiler/cpp/test/plugin_stability_test.sh new file mode 100755 index 0000000..eb7c93d --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/test/plugin_stability_test.sh @@ -0,0 +1,32 @@ +#!/bin/sh + +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +# this file is intended to be invoked by make. +# +# This file runs the compiler twice, using a plugin that just invokes +# /bin/cat, and compares the output. If GeneratorInput is +# nondeterminsitic, you'd expect the output to differ from run-to-run. +# So this tests that in fact, the output is stable from run-to-run. +set -e +mkdir -p gen-bincat +PATH=.:"$PATH" ../thrift -r -gen bincat ../../../test/Include.thrift > gen-bincat/1.ser +PATH=.:"$PATH" ../thrift -r -gen bincat ../../../test/Include.thrift > gen-bincat/2.ser +diff --binary gen-bincat/1.ser gen-bincat/2.ser diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/tests/CMakeLists.txt b/vendor/git.apache.org/thrift.git/compiler/cpp/tests/CMakeLists.txt new file mode 100644 index 0000000..e2b100c --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/tests/CMakeLists.txt @@ -0,0 +1,153 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# +cmake_minimum_required(VERSION 2.8.12) + +project(thrift_compiler_tests) + +set(THRIFT_COMPILER_SOURCE_DIR + ${CMAKE_CURRENT_SOURCE_DIR}/.. +) + +# don't generate ZERO_CHECK +set(CMAKE_SUPPRESS_REGENERATION true) + +configure_file(${THRIFT_COMPILER_SOURCE_DIR}/src/thrift/version.h.in ${CMAKE_CURRENT_BINARY_DIR}/thrift/version.h) +if(MSVC) + # The winflexbison generator outputs some macros that conflict with the Visual Studio 2010 copy of stdint.h + # This might be fixed in later versions of Visual Studio, but an easy solution is to include stdint.h first + if(HAVE_STDINT_H) + add_definitions(-D__STDC_LIMIT_MACROS) + add_definitions(/FI"stdint.h") + endif(HAVE_STDINT_H) +endif() + +find_package(FLEX REQUIRED) +find_package(BISON REQUIRED) + +# create directory for thrifty and thriftl +file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/thrift/) + +# Create flex and bison files and build the lib parse static library +BISON_TARGET(thrifty ${THRIFT_COMPILER_SOURCE_DIR}/src/thrift/thrifty.yy ${CMAKE_CURRENT_BINARY_DIR}/thrift/thrifty.cc) +FLEX_TARGET(thriftl ${THRIFT_COMPILER_SOURCE_DIR}/src/thrift/thriftl.ll ${CMAKE_CURRENT_BINARY_DIR}/thrift/thriftl.cc) +ADD_FLEX_BISON_DEPENDENCY(thriftl thrifty) + +set(parse_SOURCES + ${CMAKE_CURRENT_BINARY_DIR}/thrift/thrifty.cc + ${CMAKE_CURRENT_BINARY_DIR}/thrift/thriftl.cc + ${CMAKE_CURRENT_BINARY_DIR}/thrift/thrifty.hh +) + +add_library(parse STATIC ${parse_SOURCES}) + +# Thrift compiler tests +set(thrift_compiler_tests +) + +# you can add some files manually there +set(thrift_compiler_tests_manual_SOURCES + # tests file to avoid main in every test file + ${CMAKE_CURRENT_SOURCE_DIR}/tests_main.cc +) + +# set variable for tests sources - will be filled later +set(thrift_compiler_tests_SOURCES +) + +set(thrift_compiler_SOURCES + ${THRIFT_COMPILER_SOURCE_DIR}/src/thrift/logging.cc # we use logging instead of main to avoid breaking compillation (2 main v) + ${THRIFT_COMPILER_SOURCE_DIR}/src/thrift/audit/t_audit.cpp + ${THRIFT_COMPILER_SOURCE_DIR}/src/thrift/common.cc + ${THRIFT_COMPILER_SOURCE_DIR}/src/thrift/generate/t_generator.cc + ${THRIFT_COMPILER_SOURCE_DIR}/src/thrift/parse/t_typedef.cc + ${THRIFT_COMPILER_SOURCE_DIR}/src/thrift/parse/parse.cc + ${CMAKE_CURRENT_BINARY_DIR}/thrift/version.h +) + +# This macro adds an option THRIFT_COMPILER_${NAME} +# that allows enabling or disabling certain languages +macro(THRIFT_ADD_COMPILER name description initial) + string(TOUPPER "THRIFT_COMPILER_${name}" enabler) + set(src "${THRIFT_COMPILER_SOURCE_DIR}/src/thrift/generate/t_${name}_generator.cc") + option(${enabler} ${description} ${initial}) + if(${enabler}) + list(APPEND thrift_compiler_SOURCES ${src}) + file(GLOB thrift_compiler_tests_SOURCES + "${CMAKE_CURRENT_SOURCE_DIR}/${name}/*.c*" + "${CMAKE_CURRENT_SOURCE_DIR}/${name}/*.thrift" + ) + endif() +endmacro() + +# The following compiler with unit tests can be enabled or disabled +THRIFT_ADD_COMPILER(c_glib "Enable compiler for C with Glib" OFF) +THRIFT_ADD_COMPILER(cpp "Enable compiler for C++" OFF) +THRIFT_ADD_COMPILER(java "Enable compiler for Java" OFF) +THRIFT_ADD_COMPILER(as3 "Enable compiler for ActionScript 3" OFF) +THRIFT_ADD_COMPILER(dart "Enable compiler for Dart" OFF) +THRIFT_ADD_COMPILER(haxe "Enable compiler for Haxe" OFF) +THRIFT_ADD_COMPILER(csharp "Enable compiler for C#" OFF) +THRIFT_ADD_COMPILER(netcore "Enable compiler for .NET Core" ON) +THRIFT_ADD_COMPILER(py "Enable compiler for Python 2.0" OFF) +THRIFT_ADD_COMPILER(rb "Enable compiler for Ruby" OFF) +THRIFT_ADD_COMPILER(perl "Enable compiler for Perl" OFF) +THRIFT_ADD_COMPILER(php "Enable compiler for PHP" OFF) +THRIFT_ADD_COMPILER(erl "Enable compiler for Erlang" OFF) +THRIFT_ADD_COMPILER(cocoa "Enable compiler for Cocoa Objective-C" OFF) +THRIFT_ADD_COMPILER(swift "Enable compiler for Cocoa Swift" OFF) +THRIFT_ADD_COMPILER(st "Enable compiler for Smalltalk" OFF) +THRIFT_ADD_COMPILER(ocaml "Enable compiler for OCaml" OFF) +THRIFT_ADD_COMPILER(hs "Enable compiler for Haskell" OFF) +THRIFT_ADD_COMPILER(xsd "Enable compiler for XSD" OFF) +THRIFT_ADD_COMPILER(html "Enable compiler for HTML Documentation" OFF) +THRIFT_ADD_COMPILER(js "Enable compiler for JavaScript" OFF) +THRIFT_ADD_COMPILER(json "Enable compiler for JSON" OFF) +THRIFT_ADD_COMPILER(javame "Enable compiler for Java ME" OFF) +THRIFT_ADD_COMPILER(delphi "Enable compiler for Delphi" OFF) +THRIFT_ADD_COMPILER(go "Enable compiler for Go" OFF) +THRIFT_ADD_COMPILER(d "Enable compiler for D" OFF) +THRIFT_ADD_COMPILER(lua "Enable compiler for Lua" OFF) +THRIFT_ADD_COMPILER(gv "Enable compiler for GraphViz" OFF) +THRIFT_ADD_COMPILER(rs "Enable compiler for Rust" OFF) +THRIFT_ADD_COMPILER(xml "Enable compiler for XML" OFF) + +# Thrift is looking for include files in the src directory +# we also add the current binary directory for generated files +include_directories(${CMAKE_CURRENT_BINARY_DIR} ${THRIFT_COMPILER_SOURCE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/catch) + +add_library(thrift_compiler ${thrift_compiler_SOURCES}) + +#link parse lib to thrift_compiler lib +target_link_libraries(thrift_compiler parse) + +# add tests executable +add_executable(thrift_compiler_tests ${thrift_compiler_tests_manual_SOURCES} ${thrift_compiler_tests_SOURCES}) + +# if generates for Visual Studio set thrift_compiler_tests as default project +if(MSVC) + set_property(TARGET thrift_compiler_tests PROPERTY VS_STARTUP_PROJECT thrift_compiler_tests) +endif() + +set_target_properties(thrift_compiler_tests PROPERTIES RUNTIME_OUTPUT_DIRECTORY bin/) +set_target_properties(thrift_compiler_tests PROPERTIES OUTPUT_NAME thrift_compiler_tests) + +target_link_libraries(thrift_compiler_tests thrift_compiler) + +enable_testing() +add_test(NAME ThriftTests COMMAND thrift_compiler_tests) \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/tests/README.md b/vendor/git.apache.org/thrift.git/compiler/cpp/tests/README.md new file mode 100644 index 0000000..27be491 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/tests/README.md @@ -0,0 +1,88 @@ +# Build and run compiler tests using CMake + + + +- [Build and run compiler tests using CMake](#build-and-run-compiler-tests-using-cmake) + - [General information](#general-information) + - [How to add your tests](#how-to-add-your-tests) + - [Build and run tests on Unix-like systems](#build-and-run-tests-on-unix-like-systems) + - [Prerequisites:](#prerequisites) + - [Build and run test with CMake](#build-and-run-test-with-cmake) + - [Build and run tests on Windows](#build-and-run-tests-on-windows) + - [Prerequisites:](#prerequisites-1) + - [Generation of VS project with CMake, build and run on Windows](#generation-of-vs-project-with-cmake-build-and-run-on-windows) + + + +## General information + +Added generic way to cover code by tests for many languages (you just need to make a correct header file for generator for your language - example in **netcore** implementation) + +At current moment these tests use free Catch library (https://github.com/catchorg/Catch2/tree/Catch1.x) for easy test creation and usage. +Decision to use it was because of simplicity, easy usage, one header file to use, stable community and growing interest (https://cpp.libhunt.com/project/googletest-google/vs/catch?rel=cmp-cmp) + +Also, maybe, later it will be migrated to Catch2 (https://github.com/philsquared/Catch) - depends on need to support legacy compilers (c++98) + +## How to add your tests + +- Open **CMakeLists.txt** +- Set **On** to call of **THRIFT_ADD_COMPILER** for your language + +``` cmake +THRIFT_ADD_COMPILER(netcore "Enable compiler for .NET Core" ON) +``` + +- Create folder with name specified in list of languages in **CMakeLists.txt** +- Create tests in folder for your language (with extensions like *.c* - cc, cpp, etc) + - Don't forget to add include of catch.hpp in your test file + ``` C + #include "../catch/catch.hpp" + ``` + +- If you need - add files manually to **thrift_compiler_tests_manual_SOURCES** in **CMakeLists.txt** similar to + +``` cmake +# you can add some files manually there +set(thrift_compiler_tests_manual_SOURCES + # tests file to avoid main in every test file + ${CMAKE_CURRENT_SOURCE_DIR}/tests_main.cc +) +``` + +- Run **cmake** with arguments for your environment and compiler +- Enjoy + +## Build and run tests on Unix-like systems + +### Prerequisites: +- Install CMake - +- Install winflexbison - + +### Build and run test with CMake + +- Run commands in command line in current directory: + +``` +mkdir cmake-vs && cd cmake-vs +cmake .. +cmake --build . +ctest -C Debug -V +``` + +## Build and run tests on Windows + +### Prerequisites: +- Install CMake - +- Install winflexbison - +- Install VS2017 Community Edition - (ensure that you installed workload "Desktop Development with C++" for VS2017) + +### Generation of VS project with CMake, build and run on Windows +- Run commands in command line in current directory (ensure that VS installed): + +``` +mkdir cmake-vs +cd cmake-vs +cmake .. +cmake --build . +ctest -C Debug -V +``` \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/tests/catch/catch.hpp b/vendor/git.apache.org/thrift.git/compiler/cpp/tests/catch/catch.hpp new file mode 100644 index 0000000..33d037e --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/tests/catch/catch.hpp @@ -0,0 +1,11508 @@ +/* + * Catch v1.9.4 + * Generated: 2017-05-16 13:51:55.506519 + * ---------------------------------------------------------- + * This file has been merged from multiple headers. Please don't edit it directly + * Copyright (c) 2012 Two Blue Cubes Ltd. All rights reserved. + * + * Distributed under the Boost Software License, Version 1.0. (See accompanying + * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + */ +#ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED +#define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED + +#define TWOBLUECUBES_CATCH_HPP_INCLUDED + +#ifdef __clang__ +# pragma clang system_header +#elif defined __GNUC__ +# pragma GCC system_header +#endif + +// #included from: internal/catch_suppress_warnings.h + +#ifdef __clang__ +# ifdef __ICC // icpc defines the __clang__ macro +# pragma warning(push) +# pragma warning(disable: 161 1682) +# else // __ICC +# pragma clang diagnostic ignored "-Wglobal-constructors" +# pragma clang diagnostic ignored "-Wvariadic-macros" +# pragma clang diagnostic ignored "-Wc99-extensions" +# pragma clang diagnostic ignored "-Wunused-variable" +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wpadded" +# pragma clang diagnostic ignored "-Wc++98-compat" +# pragma clang diagnostic ignored "-Wc++98-compat-pedantic" +# pragma clang diagnostic ignored "-Wswitch-enum" +# pragma clang diagnostic ignored "-Wcovered-switch-default" +# endif +#elif defined __GNUC__ +# pragma GCC diagnostic ignored "-Wvariadic-macros" +# pragma GCC diagnostic ignored "-Wunused-variable" +# pragma GCC diagnostic ignored "-Wparentheses" + +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wpadded" +#endif +#if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER) +# define CATCH_IMPL +#endif + +#ifdef CATCH_IMPL +# ifndef CLARA_CONFIG_MAIN +# define CLARA_CONFIG_MAIN_NOT_DEFINED +# define CLARA_CONFIG_MAIN +# endif +#endif + +// #included from: internal/catch_notimplemented_exception.h +#define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_H_INCLUDED + +// #included from: catch_common.h +#define TWOBLUECUBES_CATCH_COMMON_H_INCLUDED + +// #included from: catch_compiler_capabilities.h +#define TWOBLUECUBES_CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED + +// Detect a number of compiler features - mostly C++11/14 conformance - by compiler +// The following features are defined: +// +// CATCH_CONFIG_CPP11_NULLPTR : is nullptr supported? +// CATCH_CONFIG_CPP11_NOEXCEPT : is noexcept supported? +// CATCH_CONFIG_CPP11_GENERATED_METHODS : The delete and default keywords for compiler generated methods +// CATCH_CONFIG_CPP11_IS_ENUM : std::is_enum is supported? +// CATCH_CONFIG_CPP11_TUPLE : std::tuple is supported +// CATCH_CONFIG_CPP11_LONG_LONG : is long long supported? +// CATCH_CONFIG_CPP11_OVERRIDE : is override supported? +// CATCH_CONFIG_CPP11_UNIQUE_PTR : is unique_ptr supported (otherwise use auto_ptr) +// CATCH_CONFIG_CPP11_SHUFFLE : is std::shuffle supported? +// CATCH_CONFIG_CPP11_TYPE_TRAITS : are type_traits and enable_if supported? + +// CATCH_CONFIG_CPP11_OR_GREATER : Is C++11 supported? + +// CATCH_CONFIG_VARIADIC_MACROS : are variadic macros supported? +// CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported? +// CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported? +// CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported? +// **************** +// Note to maintainers: if new toggles are added please document them +// in configuration.md, too +// **************** + +// In general each macro has a _NO_ form +// (e.g. CATCH_CONFIG_CPP11_NO_NULLPTR) which disables the feature. +// Many features, at point of detection, define an _INTERNAL_ macro, so they +// can be combined, en-mass, with the _NO_ forms later. + +// All the C++11 features can be disabled with CATCH_CONFIG_NO_CPP11 + +#ifdef __cplusplus + +# if __cplusplus >= 201103L +# define CATCH_CPP11_OR_GREATER +# endif + +# if __cplusplus >= 201402L +# define CATCH_CPP14_OR_GREATER +# endif + +#endif + +#ifdef __clang__ + +# if __has_feature(cxx_nullptr) +# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR +# endif + +# if __has_feature(cxx_noexcept) +# define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT +# endif + +# if defined(CATCH_CPP11_OR_GREATER) +# define CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ + _Pragma( "clang diagnostic push" ) \ + _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) +# define CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \ + _Pragma( "clang diagnostic pop" ) + +# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ + _Pragma( "clang diagnostic push" ) \ + _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) +# define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \ + _Pragma( "clang diagnostic pop" ) +# endif + +#endif // __clang__ + +//////////////////////////////////////////////////////////////////////////////// +// We know some environments not to support full POSIX signals +#if defined(__CYGWIN__) || defined(__QNX__) + +# if !defined(CATCH_CONFIG_POSIX_SIGNALS) +# define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS +# endif + +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Cygwin +#ifdef __CYGWIN__ + +// Required for some versions of Cygwin to declare gettimeofday +// see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin +# define _BSD_SOURCE + +#endif // __CYGWIN__ + +//////////////////////////////////////////////////////////////////////////////// +// Borland +#ifdef __BORLANDC__ + +#endif // __BORLANDC__ + +//////////////////////////////////////////////////////////////////////////////// +// EDG +#ifdef __EDG_VERSION__ + +#endif // __EDG_VERSION__ + +//////////////////////////////////////////////////////////////////////////////// +// Digital Mars +#ifdef __DMC__ + +#endif // __DMC__ + +//////////////////////////////////////////////////////////////////////////////// +// GCC +#ifdef __GNUC__ + +# if __GNUC__ == 4 && __GNUC_MINOR__ >= 6 && defined(__GXX_EXPERIMENTAL_CXX0X__) +# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR +# endif + +// - otherwise more recent versions define __cplusplus >= 201103L +// and will get picked up below + +#endif // __GNUC__ + +//////////////////////////////////////////////////////////////////////////////// +// Visual C++ +#ifdef _MSC_VER + +#define CATCH_INTERNAL_CONFIG_WINDOWS_SEH + +#if (_MSC_VER >= 1600) +# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR +# define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR +#endif + +#if (_MSC_VER >= 1900 ) // (VC++ 13 (VS2015)) +#define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT +#define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS +#define CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE +#define CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS +#endif + +#endif // _MSC_VER + +//////////////////////////////////////////////////////////////////////////////// + +// Use variadic macros if the compiler supports them +#if ( defined _MSC_VER && _MSC_VER > 1400 && !defined __EDGE__) || \ + ( defined __WAVE__ && __WAVE_HAS_VARIADICS ) || \ + ( defined __GNUC__ && __GNUC__ >= 3 ) || \ + ( !defined __cplusplus && __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L ) + +#define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS + +#endif + +// Use __COUNTER__ if the compiler supports it +#if ( defined _MSC_VER && _MSC_VER >= 1300 ) || \ + ( defined __GNUC__ && __GNUC__ >= 4 && __GNUC_MINOR__ >= 3 ) || \ + ( defined __clang__ && __clang_major__ >= 3 ) + +#define CATCH_INTERNAL_CONFIG_COUNTER + +#endif + +//////////////////////////////////////////////////////////////////////////////// +// C++ language feature support + +// catch all support for C++11 +#if defined(CATCH_CPP11_OR_GREATER) + +# if !defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR) +# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR +# endif + +# ifndef CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT +# define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT +# endif + +# ifndef CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS +# define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS +# endif + +# ifndef CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM +# define CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM +# endif + +# ifndef CATCH_INTERNAL_CONFIG_CPP11_TUPLE +# define CATCH_INTERNAL_CONFIG_CPP11_TUPLE +# endif + +# ifndef CATCH_INTERNAL_CONFIG_VARIADIC_MACROS +# define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS +# endif + +# if !defined(CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG) +# define CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG +# endif + +# if !defined(CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE) +# define CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE +# endif +# if !defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) +# define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR +# endif +# if !defined(CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE) +# define CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE +# endif +# if !defined(CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS) +# define CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS +# endif + +#endif // __cplusplus >= 201103L + +// Now set the actual defines based on the above + anything the user has configured +#if defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NO_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_NO_CPP11) +# define CATCH_CONFIG_CPP11_NULLPTR +#endif +#if defined(CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NO_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_NO_CPP11) +# define CATCH_CONFIG_CPP11_NOEXCEPT +#endif +#if defined(CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_NO_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_NO_CPP11) +# define CATCH_CONFIG_CPP11_GENERATED_METHODS +#endif +#if defined(CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_NO_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_NO_CPP11) +# define CATCH_CONFIG_CPP11_IS_ENUM +#endif +#if defined(CATCH_INTERNAL_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_CPP11_NO_TUPLE) && !defined(CATCH_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_NO_CPP11) +# define CATCH_CONFIG_CPP11_TUPLE +#endif +#if defined(CATCH_INTERNAL_CONFIG_VARIADIC_MACROS) && !defined(CATCH_CONFIG_NO_VARIADIC_MACROS) && !defined(CATCH_CONFIG_VARIADIC_MACROS) +# define CATCH_CONFIG_VARIADIC_MACROS +#endif +#if defined(CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_CPP11_NO_LONG_LONG) && !defined(CATCH_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_NO_CPP11) +# define CATCH_CONFIG_CPP11_LONG_LONG +#endif +#if defined(CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_CPP11_NO_OVERRIDE) && !defined(CATCH_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_NO_CPP11) +# define CATCH_CONFIG_CPP11_OVERRIDE +#endif +#if defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_NO_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_NO_CPP11) +# define CATCH_CONFIG_CPP11_UNIQUE_PTR +#endif +// Use of __COUNTER__ is suppressed if __JETBRAINS_IDE__ is #defined (meaning we're being parsed by a JetBrains IDE for +// analytics) because, at time of writing, __COUNTER__ is not properly handled by it. +// This does not affect compilation +#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) && !defined(__JETBRAINS_IDE__) +# define CATCH_CONFIG_COUNTER +#endif +#if defined(CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE) && !defined(CATCH_CONFIG_CPP11_NO_SHUFFLE) && !defined(CATCH_CONFIG_CPP11_SHUFFLE) && !defined(CATCH_CONFIG_NO_CPP11) +# define CATCH_CONFIG_CPP11_SHUFFLE +#endif +# if defined(CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS) && !defined(CATCH_CONFIG_CPP11_NO_TYPE_TRAITS) && !defined(CATCH_CONFIG_CPP11_TYPE_TRAITS) && !defined(CATCH_CONFIG_NO_CPP11) +# define CATCH_CONFIG_CPP11_TYPE_TRAITS +# endif +#if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) +# define CATCH_CONFIG_WINDOWS_SEH +#endif +// This is set by default, because we assume that unix compilers are posix-signal-compatible by default. +#if !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS) +# define CATCH_CONFIG_POSIX_SIGNALS +#endif + +#if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS +# define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS +#endif +#if !defined(CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS +# define CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS +#endif + +// noexcept support: +#if defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_NOEXCEPT) +# define CATCH_NOEXCEPT noexcept +# define CATCH_NOEXCEPT_IS(x) noexcept(x) +#else +# define CATCH_NOEXCEPT throw() +# define CATCH_NOEXCEPT_IS(x) +#endif + +// nullptr support +#ifdef CATCH_CONFIG_CPP11_NULLPTR +# define CATCH_NULL nullptr +#else +# define CATCH_NULL NULL +#endif + +// override support +#ifdef CATCH_CONFIG_CPP11_OVERRIDE +# define CATCH_OVERRIDE override +#else +# define CATCH_OVERRIDE +#endif + +// unique_ptr support +#ifdef CATCH_CONFIG_CPP11_UNIQUE_PTR +# define CATCH_AUTO_PTR( T ) std::unique_ptr +#else +# define CATCH_AUTO_PTR( T ) std::auto_ptr +#endif + +#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line +#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) +#ifdef CATCH_CONFIG_COUNTER +# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ ) +#else +# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) +#endif + +#define INTERNAL_CATCH_STRINGIFY2( expr ) #expr +#define INTERNAL_CATCH_STRINGIFY( expr ) INTERNAL_CATCH_STRINGIFY2( expr ) + +#include +#include + +namespace Catch { + + struct IConfig; + + struct CaseSensitive { enum Choice { + Yes, + No + }; }; + + class NonCopyable { +#ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS + NonCopyable( NonCopyable const& ) = delete; + NonCopyable( NonCopyable && ) = delete; + NonCopyable& operator = ( NonCopyable const& ) = delete; + NonCopyable& operator = ( NonCopyable && ) = delete; +#else + NonCopyable( NonCopyable const& info ); + NonCopyable& operator = ( NonCopyable const& ); +#endif + + protected: + NonCopyable() {} + virtual ~NonCopyable(); + }; + + class SafeBool { + public: + typedef void (SafeBool::*type)() const; + + static type makeSafe( bool value ) { + return value ? &SafeBool::trueValue : 0; + } + private: + void trueValue() const {} + }; + + template + inline void deleteAll( ContainerT& container ) { + typename ContainerT::const_iterator it = container.begin(); + typename ContainerT::const_iterator itEnd = container.end(); + for(; it != itEnd; ++it ) + delete *it; + } + template + inline void deleteAllValues( AssociativeContainerT& container ) { + typename AssociativeContainerT::const_iterator it = container.begin(); + typename AssociativeContainerT::const_iterator itEnd = container.end(); + for(; it != itEnd; ++it ) + delete it->second; + } + + bool startsWith( std::string const& s, std::string const& prefix ); + bool startsWith( std::string const& s, char prefix ); + bool endsWith( std::string const& s, std::string const& suffix ); + bool endsWith( std::string const& s, char suffix ); + bool contains( std::string const& s, std::string const& infix ); + void toLowerInPlace( std::string& s ); + std::string toLower( std::string const& s ); + std::string trim( std::string const& str ); + bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ); + + struct pluralise { + pluralise( std::size_t count, std::string const& label ); + + friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ); + + std::size_t m_count; + std::string m_label; + }; + + struct SourceLineInfo { + + SourceLineInfo(); + SourceLineInfo( char const* _file, std::size_t _line ); +# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS + SourceLineInfo(SourceLineInfo const& other) = default; + SourceLineInfo( SourceLineInfo && ) = default; + SourceLineInfo& operator = ( SourceLineInfo const& ) = default; + SourceLineInfo& operator = ( SourceLineInfo && ) = default; +# endif + bool empty() const; + bool operator == ( SourceLineInfo const& other ) const; + bool operator < ( SourceLineInfo const& other ) const; + + char const* file; + std::size_t line; + }; + + std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ); + + // This is just here to avoid compiler warnings with macro constants and boolean literals + inline bool isTrue( bool value ){ return value; } + inline bool alwaysTrue() { return true; } + inline bool alwaysFalse() { return false; } + + void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo ); + + void seedRng( IConfig const& config ); + unsigned int rngSeed(); + + // Use this in variadic streaming macros to allow + // >> +StreamEndStop + // as well as + // >> stuff +StreamEndStop + struct StreamEndStop { + std::string operator+() { + return std::string(); + } + }; + template + T const& operator + ( T const& value, StreamEndStop ) { + return value; + } +} + +#define CATCH_INTERNAL_LINEINFO ::Catch::SourceLineInfo( __FILE__, static_cast( __LINE__ ) ) +#define CATCH_INTERNAL_ERROR( msg ) ::Catch::throwLogicError( msg, CATCH_INTERNAL_LINEINFO ); + +namespace Catch { + + class NotImplementedException : public std::exception + { + public: + NotImplementedException( SourceLineInfo const& lineInfo ); + NotImplementedException( NotImplementedException const& ) {} + + virtual ~NotImplementedException() CATCH_NOEXCEPT {} + + virtual const char* what() const CATCH_NOEXCEPT; + + private: + std::string m_what; + SourceLineInfo m_lineInfo; + }; + +} // end namespace Catch + +/////////////////////////////////////////////////////////////////////////////// +#define CATCH_NOT_IMPLEMENTED throw Catch::NotImplementedException( CATCH_INTERNAL_LINEINFO ) + +// #included from: internal/catch_context.h +#define TWOBLUECUBES_CATCH_CONTEXT_H_INCLUDED + +// #included from: catch_interfaces_generators.h +#define TWOBLUECUBES_CATCH_INTERFACES_GENERATORS_H_INCLUDED + +#include + +namespace Catch { + + struct IGeneratorInfo { + virtual ~IGeneratorInfo(); + virtual bool moveNext() = 0; + virtual std::size_t getCurrentIndex() const = 0; + }; + + struct IGeneratorsForTest { + virtual ~IGeneratorsForTest(); + + virtual IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) = 0; + virtual bool moveNext() = 0; + }; + + IGeneratorsForTest* createGeneratorsForTest(); + +} // end namespace Catch + +// #included from: catch_ptr.hpp +#define TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpadded" +#endif + +namespace Catch { + + // An intrusive reference counting smart pointer. + // T must implement addRef() and release() methods + // typically implementing the IShared interface + template + class Ptr { + public: + Ptr() : m_p( CATCH_NULL ){} + Ptr( T* p ) : m_p( p ){ + if( m_p ) + m_p->addRef(); + } + Ptr( Ptr const& other ) : m_p( other.m_p ){ + if( m_p ) + m_p->addRef(); + } + ~Ptr(){ + if( m_p ) + m_p->release(); + } + void reset() { + if( m_p ) + m_p->release(); + m_p = CATCH_NULL; + } + Ptr& operator = ( T* p ){ + Ptr temp( p ); + swap( temp ); + return *this; + } + Ptr& operator = ( Ptr const& other ){ + Ptr temp( other ); + swap( temp ); + return *this; + } + void swap( Ptr& other ) { std::swap( m_p, other.m_p ); } + T* get() const{ return m_p; } + T& operator*() const { return *m_p; } + T* operator->() const { return m_p; } + bool operator !() const { return m_p == CATCH_NULL; } + operator SafeBool::type() const { return SafeBool::makeSafe( m_p != CATCH_NULL ); } + + private: + T* m_p; + }; + + struct IShared : NonCopyable { + virtual ~IShared(); + virtual void addRef() const = 0; + virtual void release() const = 0; + }; + + template + struct SharedImpl : T { + + SharedImpl() : m_rc( 0 ){} + + virtual void addRef() const { + ++m_rc; + } + virtual void release() const { + if( --m_rc == 0 ) + delete this; + } + + mutable unsigned int m_rc; + }; + +} // end namespace Catch + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +namespace Catch { + + class TestCase; + class Stream; + struct IResultCapture; + struct IRunner; + struct IGeneratorsForTest; + struct IConfig; + + struct IContext + { + virtual ~IContext(); + + virtual IResultCapture* getResultCapture() = 0; + virtual IRunner* getRunner() = 0; + virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) = 0; + virtual bool advanceGeneratorsForCurrentTest() = 0; + virtual Ptr getConfig() const = 0; + }; + + struct IMutableContext : IContext + { + virtual ~IMutableContext(); + virtual void setResultCapture( IResultCapture* resultCapture ) = 0; + virtual void setRunner( IRunner* runner ) = 0; + virtual void setConfig( Ptr const& config ) = 0; + }; + + IContext& getCurrentContext(); + IMutableContext& getCurrentMutableContext(); + void cleanUpContext(); + Stream createStream( std::string const& streamName ); + +} + +// #included from: internal/catch_test_registry.hpp +#define TWOBLUECUBES_CATCH_TEST_REGISTRY_HPP_INCLUDED + +// #included from: catch_interfaces_testcase.h +#define TWOBLUECUBES_CATCH_INTERFACES_TESTCASE_H_INCLUDED + +#include + +namespace Catch { + + class TestSpec; + + struct ITestCase : IShared { + virtual void invoke () const = 0; + protected: + virtual ~ITestCase(); + }; + + class TestCase; + struct IConfig; + + struct ITestCaseRegistry { + virtual ~ITestCaseRegistry(); + virtual std::vector const& getAllTests() const = 0; + virtual std::vector const& getAllTestsSorted( IConfig const& config ) const = 0; + }; + + bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ); + std::vector filterTests( std::vector const& testCases, TestSpec const& testSpec, IConfig const& config ); + std::vector const& getAllTestCasesSorted( IConfig const& config ); + +} + +namespace Catch { + +template +class MethodTestCase : public SharedImpl { + +public: + MethodTestCase( void (C::*method)() ) : m_method( method ) {} + + virtual void invoke() const { + C obj; + (obj.*m_method)(); + } + +private: + virtual ~MethodTestCase() {} + + void (C::*m_method)(); +}; + +typedef void(*TestFunction)(); + +struct NameAndDesc { + NameAndDesc( const char* _name = "", const char* _description= "" ) + : name( _name ), description( _description ) + {} + + const char* name; + const char* description; +}; + +void registerTestCase + ( ITestCase* testCase, + char const* className, + NameAndDesc const& nameAndDesc, + SourceLineInfo const& lineInfo ); + +struct AutoReg { + + AutoReg + ( TestFunction function, + SourceLineInfo const& lineInfo, + NameAndDesc const& nameAndDesc ); + + template + AutoReg + ( void (C::*method)(), + char const* className, + NameAndDesc const& nameAndDesc, + SourceLineInfo const& lineInfo ) { + + registerTestCase + ( new MethodTestCase( method ), + className, + nameAndDesc, + lineInfo ); + } + + ~AutoReg(); + +private: + AutoReg( AutoReg const& ); + void operator= ( AutoReg const& ); +}; + +void registerTestCaseFunction + ( TestFunction function, + SourceLineInfo const& lineInfo, + NameAndDesc const& nameAndDesc ); + +} // end namespace Catch + +#ifdef CATCH_CONFIG_VARIADIC_MACROS + /////////////////////////////////////////////////////////////////////////////// + #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \ + static void TestName(); \ + CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ + namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &TestName, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); } \ + CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \ + static void TestName() + #define INTERNAL_CATCH_TESTCASE( ... ) \ + INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ ) + + /////////////////////////////////////////////////////////////////////////////// + #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \ + CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ + namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); } \ + CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS + + /////////////////////////////////////////////////////////////////////////////// + #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\ + CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ + namespace{ \ + struct TestName : ClassName{ \ + void test(); \ + }; \ + Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &TestName::test, #ClassName, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); \ + } \ + CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \ + void TestName::test() + #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \ + INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ ) + + /////////////////////////////////////////////////////////////////////////////// + #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \ + CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ + Catch::AutoReg( Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); \ + CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS + +#else + /////////////////////////////////////////////////////////////////////////////// + #define INTERNAL_CATCH_TESTCASE2( TestName, Name, Desc ) \ + static void TestName(); \ + CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ + namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &TestName, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); }\ + CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \ + static void TestName() + #define INTERNAL_CATCH_TESTCASE( Name, Desc ) \ + INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), Name, Desc ) + + /////////////////////////////////////////////////////////////////////////////// + #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, Name, Desc ) \ + CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ + namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( Name, Desc ), CATCH_INTERNAL_LINEINFO ); } \ + CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS + + /////////////////////////////////////////////////////////////////////////////// + #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestCaseName, ClassName, TestName, Desc )\ + CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ + namespace{ \ + struct TestCaseName : ClassName{ \ + void test(); \ + }; \ + Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &TestCaseName::test, #ClassName, Catch::NameAndDesc( TestName, Desc ), CATCH_INTERNAL_LINEINFO ); \ + } \ + CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \ + void TestCaseName::test() + #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, TestName, Desc )\ + INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, TestName, Desc ) + + /////////////////////////////////////////////////////////////////////////////// + #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, Name, Desc ) \ + CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ + Catch::AutoReg( Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); \ + CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS + +#endif + +// #included from: internal/catch_capture.hpp +#define TWOBLUECUBES_CATCH_CAPTURE_HPP_INCLUDED + +// #included from: catch_result_builder.h +#define TWOBLUECUBES_CATCH_RESULT_BUILDER_H_INCLUDED + +// #included from: catch_result_type.h +#define TWOBLUECUBES_CATCH_RESULT_TYPE_H_INCLUDED + +namespace Catch { + + // ResultWas::OfType enum + struct ResultWas { enum OfType { + Unknown = -1, + Ok = 0, + Info = 1, + Warning = 2, + + FailureBit = 0x10, + + ExpressionFailed = FailureBit | 1, + ExplicitFailure = FailureBit | 2, + + Exception = 0x100 | FailureBit, + + ThrewException = Exception | 1, + DidntThrowException = Exception | 2, + + FatalErrorCondition = 0x200 | FailureBit + + }; }; + + inline bool isOk( ResultWas::OfType resultType ) { + return ( resultType & ResultWas::FailureBit ) == 0; + } + inline bool isJustInfo( int flags ) { + return flags == ResultWas::Info; + } + + // ResultDisposition::Flags enum + struct ResultDisposition { enum Flags { + Normal = 0x01, + + ContinueOnFailure = 0x02, // Failures fail test, but execution continues + FalseTest = 0x04, // Prefix expression with ! + SuppressFail = 0x08 // Failures are reported but do not fail the test + }; }; + + inline ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) { + return static_cast( static_cast( lhs ) | static_cast( rhs ) ); + } + + inline bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; } + inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; } + inline bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; } + +} // end namespace Catch + +// #included from: catch_assertionresult.h +#define TWOBLUECUBES_CATCH_ASSERTIONRESULT_H_INCLUDED + +#include + +namespace Catch { + + struct STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison; + + struct DecomposedExpression + { + virtual ~DecomposedExpression() {} + virtual bool isBinaryExpression() const { + return false; + } + virtual void reconstructExpression( std::string& dest ) const = 0; + + // Only simple binary comparisons can be decomposed. + // If more complex check is required then wrap sub-expressions in parentheses. + template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator + ( T const& ); + template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator - ( T const& ); + template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator * ( T const& ); + template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator / ( T const& ); + template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator % ( T const& ); + template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( T const& ); + template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( T const& ); + + private: + DecomposedExpression& operator = (DecomposedExpression const&); + }; + + struct AssertionInfo + { + AssertionInfo() {} + AssertionInfo( std::string const& _macroName, + SourceLineInfo const& _lineInfo, + std::string const& _capturedExpression, + ResultDisposition::Flags _resultDisposition ); + + std::string macroName; + SourceLineInfo lineInfo; + std::string capturedExpression; + ResultDisposition::Flags resultDisposition; + }; + + struct AssertionResultData + { + AssertionResultData() : decomposedExpression( CATCH_NULL ) + , resultType( ResultWas::Unknown ) + , negated( false ) + , parenthesized( false ) {} + + void negate( bool parenthesize ) { + negated = !negated; + parenthesized = parenthesize; + if( resultType == ResultWas::Ok ) + resultType = ResultWas::ExpressionFailed; + else if( resultType == ResultWas::ExpressionFailed ) + resultType = ResultWas::Ok; + } + + std::string const& reconstructExpression() const { + if( decomposedExpression != CATCH_NULL ) { + decomposedExpression->reconstructExpression( reconstructedExpression ); + if( parenthesized ) { + reconstructedExpression.insert( 0, 1, '(' ); + reconstructedExpression.append( 1, ')' ); + } + if( negated ) { + reconstructedExpression.insert( 0, 1, '!' ); + } + decomposedExpression = CATCH_NULL; + } + return reconstructedExpression; + } + + mutable DecomposedExpression const* decomposedExpression; + mutable std::string reconstructedExpression; + std::string message; + ResultWas::OfType resultType; + bool negated; + bool parenthesized; + }; + + class AssertionResult { + public: + AssertionResult(); + AssertionResult( AssertionInfo const& info, AssertionResultData const& data ); + ~AssertionResult(); +# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS + AssertionResult( AssertionResult const& ) = default; + AssertionResult( AssertionResult && ) = default; + AssertionResult& operator = ( AssertionResult const& ) = default; + AssertionResult& operator = ( AssertionResult && ) = default; +# endif + + bool isOk() const; + bool succeeded() const; + ResultWas::OfType getResultType() const; + bool hasExpression() const; + bool hasMessage() const; + std::string getExpression() const; + std::string getExpressionInMacro() const; + bool hasExpandedExpression() const; + std::string getExpandedExpression() const; + std::string getMessage() const; + SourceLineInfo getSourceInfo() const; + std::string getTestMacroName() const; + void discardDecomposedExpression() const; + void expandDecomposedExpression() const; + + protected: + AssertionInfo m_info; + AssertionResultData m_resultData; + }; + +} // end namespace Catch + +// #included from: catch_matchers.hpp +#define TWOBLUECUBES_CATCH_MATCHERS_HPP_INCLUDED + +namespace Catch { +namespace Matchers { + namespace Impl { + + template struct MatchAllOf; + template struct MatchAnyOf; + template struct MatchNotOf; + + class MatcherUntypedBase { + public: + std::string toString() const { + if( m_cachedToString.empty() ) + m_cachedToString = describe(); + return m_cachedToString; + } + + protected: + virtual ~MatcherUntypedBase(); + virtual std::string describe() const = 0; + mutable std::string m_cachedToString; + private: + MatcherUntypedBase& operator = ( MatcherUntypedBase const& ); + }; + + template + struct MatcherMethod { + virtual bool match( ObjectT const& arg ) const = 0; + }; + template + struct MatcherMethod { + virtual bool match( PtrT* arg ) const = 0; + }; + + template + struct MatcherBase : MatcherUntypedBase, MatcherMethod { + + MatchAllOf operator && ( MatcherBase const& other ) const; + MatchAnyOf operator || ( MatcherBase const& other ) const; + MatchNotOf operator ! () const; + }; + + template + struct MatchAllOf : MatcherBase { + virtual bool match( ArgT const& arg ) const CATCH_OVERRIDE { + for( std::size_t i = 0; i < m_matchers.size(); ++i ) { + if (!m_matchers[i]->match(arg)) + return false; + } + return true; + } + virtual std::string describe() const CATCH_OVERRIDE { + std::string description; + description.reserve( 4 + m_matchers.size()*32 ); + description += "( "; + for( std::size_t i = 0; i < m_matchers.size(); ++i ) { + if( i != 0 ) + description += " and "; + description += m_matchers[i]->toString(); + } + description += " )"; + return description; + } + + MatchAllOf& operator && ( MatcherBase const& other ) { + m_matchers.push_back( &other ); + return *this; + } + + std::vector const*> m_matchers; + }; + template + struct MatchAnyOf : MatcherBase { + + virtual bool match( ArgT const& arg ) const CATCH_OVERRIDE { + for( std::size_t i = 0; i < m_matchers.size(); ++i ) { + if (m_matchers[i]->match(arg)) + return true; + } + return false; + } + virtual std::string describe() const CATCH_OVERRIDE { + std::string description; + description.reserve( 4 + m_matchers.size()*32 ); + description += "( "; + for( std::size_t i = 0; i < m_matchers.size(); ++i ) { + if( i != 0 ) + description += " or "; + description += m_matchers[i]->toString(); + } + description += " )"; + return description; + } + + MatchAnyOf& operator || ( MatcherBase const& other ) { + m_matchers.push_back( &other ); + return *this; + } + + std::vector const*> m_matchers; + }; + + template + struct MatchNotOf : MatcherBase { + + MatchNotOf( MatcherBase const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {} + + virtual bool match( ArgT const& arg ) const CATCH_OVERRIDE { + return !m_underlyingMatcher.match( arg ); + } + + virtual std::string describe() const CATCH_OVERRIDE { + return "not " + m_underlyingMatcher.toString(); + } + MatcherBase const& m_underlyingMatcher; + }; + + template + MatchAllOf MatcherBase::operator && ( MatcherBase const& other ) const { + return MatchAllOf() && *this && other; + } + template + MatchAnyOf MatcherBase::operator || ( MatcherBase const& other ) const { + return MatchAnyOf() || *this || other; + } + template + MatchNotOf MatcherBase::operator ! () const { + return MatchNotOf( *this ); + } + + } // namespace Impl + + // The following functions create the actual matcher objects. + // This allows the types to be inferred + // - deprecated: prefer ||, && and ! + template + inline Impl::MatchNotOf Not( Impl::MatcherBase const& underlyingMatcher ) { + return Impl::MatchNotOf( underlyingMatcher ); + } + template + inline Impl::MatchAllOf AllOf( Impl::MatcherBase const& m1, Impl::MatcherBase const& m2 ) { + return Impl::MatchAllOf() && m1 && m2; + } + template + inline Impl::MatchAllOf AllOf( Impl::MatcherBase const& m1, Impl::MatcherBase const& m2, Impl::MatcherBase const& m3 ) { + return Impl::MatchAllOf() && m1 && m2 && m3; + } + template + inline Impl::MatchAnyOf AnyOf( Impl::MatcherBase const& m1, Impl::MatcherBase const& m2 ) { + return Impl::MatchAnyOf() || m1 || m2; + } + template + inline Impl::MatchAnyOf AnyOf( Impl::MatcherBase const& m1, Impl::MatcherBase const& m2, Impl::MatcherBase const& m3 ) { + return Impl::MatchAnyOf() || m1 || m2 || m3; + } + +} // namespace Matchers + +using namespace Matchers; +using Matchers::Impl::MatcherBase; + +} // namespace Catch + +namespace Catch { + + struct TestFailureException{}; + + template class ExpressionLhs; + + struct CopyableStream { + CopyableStream() {} + CopyableStream( CopyableStream const& other ) { + oss << other.oss.str(); + } + CopyableStream& operator=( CopyableStream const& other ) { + oss.str(std::string()); + oss << other.oss.str(); + return *this; + } + std::ostringstream oss; + }; + + class ResultBuilder : public DecomposedExpression { + public: + ResultBuilder( char const* macroName, + SourceLineInfo const& lineInfo, + char const* capturedExpression, + ResultDisposition::Flags resultDisposition, + char const* secondArg = "" ); + ~ResultBuilder(); + + template + ExpressionLhs operator <= ( T const& operand ); + ExpressionLhs operator <= ( bool value ); + + template + ResultBuilder& operator << ( T const& value ) { + m_stream.oss << value; + return *this; + } + + ResultBuilder& setResultType( ResultWas::OfType result ); + ResultBuilder& setResultType( bool result ); + + void endExpression( DecomposedExpression const& expr ); + + virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE; + + AssertionResult build() const; + AssertionResult build( DecomposedExpression const& expr ) const; + + void useActiveException( ResultDisposition::Flags resultDisposition = ResultDisposition::Normal ); + void captureResult( ResultWas::OfType resultType ); + void captureExpression(); + void captureExpectedException( std::string const& expectedMessage ); + void captureExpectedException( Matchers::Impl::MatcherBase const& matcher ); + void handleResult( AssertionResult const& result ); + void react(); + bool shouldDebugBreak() const; + bool allowThrows() const; + + template + void captureMatch( ArgT const& arg, MatcherT const& matcher, char const* matcherString ); + + void setExceptionGuard(); + void unsetExceptionGuard(); + + private: + AssertionInfo m_assertionInfo; + AssertionResultData m_data; + CopyableStream m_stream; + + bool m_shouldDebugBreak; + bool m_shouldThrow; + bool m_guardException; + }; + +} // namespace Catch + +// Include after due to circular dependency: +// #included from: catch_expression_lhs.hpp +#define TWOBLUECUBES_CATCH_EXPRESSION_LHS_HPP_INCLUDED + +// #included from: catch_evaluate.hpp +#define TWOBLUECUBES_CATCH_EVALUATE_HPP_INCLUDED + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable:4389) // '==' : signed/unsigned mismatch +#pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform) +#endif + +#include + +namespace Catch { +namespace Internal { + + enum Operator { + IsEqualTo, + IsNotEqualTo, + IsLessThan, + IsGreaterThan, + IsLessThanOrEqualTo, + IsGreaterThanOrEqualTo + }; + + template struct OperatorTraits { static const char* getName(){ return "*error*"; } }; + template<> struct OperatorTraits { static const char* getName(){ return "=="; } }; + template<> struct OperatorTraits { static const char* getName(){ return "!="; } }; + template<> struct OperatorTraits { static const char* getName(){ return "<"; } }; + template<> struct OperatorTraits { static const char* getName(){ return ">"; } }; + template<> struct OperatorTraits { static const char* getName(){ return "<="; } }; + template<> struct OperatorTraits{ static const char* getName(){ return ">="; } }; + + template + inline T& opCast(T const& t) { return const_cast(t); } + +// nullptr_t support based on pull request #154 from Konstantin Baumann +#ifdef CATCH_CONFIG_CPP11_NULLPTR + inline std::nullptr_t opCast(std::nullptr_t) { return nullptr; } +#endif // CATCH_CONFIG_CPP11_NULLPTR + + // So the compare overloads can be operator agnostic we convey the operator as a template + // enum, which is used to specialise an Evaluator for doing the comparison. + template + class Evaluator{}; + + template + struct Evaluator { + static bool evaluate( T1 const& lhs, T2 const& rhs) { + return bool( opCast( lhs ) == opCast( rhs ) ); + } + }; + template + struct Evaluator { + static bool evaluate( T1 const& lhs, T2 const& rhs ) { + return bool( opCast( lhs ) != opCast( rhs ) ); + } + }; + template + struct Evaluator { + static bool evaluate( T1 const& lhs, T2 const& rhs ) { + return bool( opCast( lhs ) < opCast( rhs ) ); + } + }; + template + struct Evaluator { + static bool evaluate( T1 const& lhs, T2 const& rhs ) { + return bool( opCast( lhs ) > opCast( rhs ) ); + } + }; + template + struct Evaluator { + static bool evaluate( T1 const& lhs, T2 const& rhs ) { + return bool( opCast( lhs ) >= opCast( rhs ) ); + } + }; + template + struct Evaluator { + static bool evaluate( T1 const& lhs, T2 const& rhs ) { + return bool( opCast( lhs ) <= opCast( rhs ) ); + } + }; + + template + bool applyEvaluator( T1 const& lhs, T2 const& rhs ) { + return Evaluator::evaluate( lhs, rhs ); + } + + // This level of indirection allows us to specialise for integer types + // to avoid signed/ unsigned warnings + + // "base" overload + template + bool compare( T1 const& lhs, T2 const& rhs ) { + return Evaluator::evaluate( lhs, rhs ); + } + + // unsigned X to int + template bool compare( unsigned int lhs, int rhs ) { + return applyEvaluator( lhs, static_cast( rhs ) ); + } + template bool compare( unsigned long lhs, int rhs ) { + return applyEvaluator( lhs, static_cast( rhs ) ); + } + template bool compare( unsigned char lhs, int rhs ) { + return applyEvaluator( lhs, static_cast( rhs ) ); + } + + // unsigned X to long + template bool compare( unsigned int lhs, long rhs ) { + return applyEvaluator( lhs, static_cast( rhs ) ); + } + template bool compare( unsigned long lhs, long rhs ) { + return applyEvaluator( lhs, static_cast( rhs ) ); + } + template bool compare( unsigned char lhs, long rhs ) { + return applyEvaluator( lhs, static_cast( rhs ) ); + } + + // int to unsigned X + template bool compare( int lhs, unsigned int rhs ) { + return applyEvaluator( static_cast( lhs ), rhs ); + } + template bool compare( int lhs, unsigned long rhs ) { + return applyEvaluator( static_cast( lhs ), rhs ); + } + template bool compare( int lhs, unsigned char rhs ) { + return applyEvaluator( static_cast( lhs ), rhs ); + } + + // long to unsigned X + template bool compare( long lhs, unsigned int rhs ) { + return applyEvaluator( static_cast( lhs ), rhs ); + } + template bool compare( long lhs, unsigned long rhs ) { + return applyEvaluator( static_cast( lhs ), rhs ); + } + template bool compare( long lhs, unsigned char rhs ) { + return applyEvaluator( static_cast( lhs ), rhs ); + } + + // pointer to long (when comparing against NULL) + template bool compare( long lhs, T* rhs ) { + return Evaluator::evaluate( reinterpret_cast( lhs ), rhs ); + } + template bool compare( T* lhs, long rhs ) { + return Evaluator::evaluate( lhs, reinterpret_cast( rhs ) ); + } + + // pointer to int (when comparing against NULL) + template bool compare( int lhs, T* rhs ) { + return Evaluator::evaluate( reinterpret_cast( lhs ), rhs ); + } + template bool compare( T* lhs, int rhs ) { + return Evaluator::evaluate( lhs, reinterpret_cast( rhs ) ); + } + +#ifdef CATCH_CONFIG_CPP11_LONG_LONG + // long long to unsigned X + template bool compare( long long lhs, unsigned int rhs ) { + return applyEvaluator( static_cast( lhs ), rhs ); + } + template bool compare( long long lhs, unsigned long rhs ) { + return applyEvaluator( static_cast( lhs ), rhs ); + } + template bool compare( long long lhs, unsigned long long rhs ) { + return applyEvaluator( static_cast( lhs ), rhs ); + } + template bool compare( long long lhs, unsigned char rhs ) { + return applyEvaluator( static_cast( lhs ), rhs ); + } + + // unsigned long long to X + template bool compare( unsigned long long lhs, int rhs ) { + return applyEvaluator( static_cast( lhs ), rhs ); + } + template bool compare( unsigned long long lhs, long rhs ) { + return applyEvaluator( static_cast( lhs ), rhs ); + } + template bool compare( unsigned long long lhs, long long rhs ) { + return applyEvaluator( static_cast( lhs ), rhs ); + } + template bool compare( unsigned long long lhs, char rhs ) { + return applyEvaluator( static_cast( lhs ), rhs ); + } + + // pointer to long long (when comparing against NULL) + template bool compare( long long lhs, T* rhs ) { + return Evaluator::evaluate( reinterpret_cast( lhs ), rhs ); + } + template bool compare( T* lhs, long long rhs ) { + return Evaluator::evaluate( lhs, reinterpret_cast( rhs ) ); + } +#endif // CATCH_CONFIG_CPP11_LONG_LONG + +#ifdef CATCH_CONFIG_CPP11_NULLPTR + // pointer to nullptr_t (when comparing against nullptr) + template bool compare( std::nullptr_t, T* rhs ) { + return Evaluator::evaluate( nullptr, rhs ); + } + template bool compare( T* lhs, std::nullptr_t ) { + return Evaluator::evaluate( lhs, nullptr ); + } +#endif // CATCH_CONFIG_CPP11_NULLPTR + +} // end of namespace Internal +} // end of namespace Catch + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +// #included from: catch_tostring.h +#define TWOBLUECUBES_CATCH_TOSTRING_H_INCLUDED + +#include +#include +#include +#include +#include + +#ifdef __OBJC__ +// #included from: catch_objc_arc.hpp +#define TWOBLUECUBES_CATCH_OBJC_ARC_HPP_INCLUDED + +#import + +#ifdef __has_feature +#define CATCH_ARC_ENABLED __has_feature(objc_arc) +#else +#define CATCH_ARC_ENABLED 0 +#endif + +void arcSafeRelease( NSObject* obj ); +id performOptionalSelector( id obj, SEL sel ); + +#if !CATCH_ARC_ENABLED +inline void arcSafeRelease( NSObject* obj ) { + [obj release]; +} +inline id performOptionalSelector( id obj, SEL sel ) { + if( [obj respondsToSelector: sel] ) + return [obj performSelector: sel]; + return nil; +} +#define CATCH_UNSAFE_UNRETAINED +#define CATCH_ARC_STRONG +#else +inline void arcSafeRelease( NSObject* ){} +inline id performOptionalSelector( id obj, SEL sel ) { +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" +#endif + if( [obj respondsToSelector: sel] ) + return [obj performSelector: sel]; +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + return nil; +} +#define CATCH_UNSAFE_UNRETAINED __unsafe_unretained +#define CATCH_ARC_STRONG __strong +#endif + +#endif + +#ifdef CATCH_CONFIG_CPP11_TUPLE +#include +#endif + +#ifdef CATCH_CONFIG_CPP11_IS_ENUM +#include +#endif + +namespace Catch { + +// Why we're here. +template +std::string toString( T const& value ); + +// Built in overloads + +std::string toString( std::string const& value ); +std::string toString( std::wstring const& value ); +std::string toString( const char* const value ); +std::string toString( char* const value ); +std::string toString( const wchar_t* const value ); +std::string toString( wchar_t* const value ); +std::string toString( int value ); +std::string toString( unsigned long value ); +std::string toString( unsigned int value ); +std::string toString( const double value ); +std::string toString( const float value ); +std::string toString( bool value ); +std::string toString( char value ); +std::string toString( signed char value ); +std::string toString( unsigned char value ); + +#ifdef CATCH_CONFIG_CPP11_LONG_LONG +std::string toString( long long value ); +std::string toString( unsigned long long value ); +#endif + +#ifdef CATCH_CONFIG_CPP11_NULLPTR +std::string toString( std::nullptr_t ); +#endif + +#ifdef __OBJC__ + std::string toString( NSString const * const& nsstring ); + std::string toString( NSString * CATCH_ARC_STRONG const& nsstring ); + std::string toString( NSObject* const& nsObject ); +#endif + +namespace Detail { + + extern const std::string unprintableString; + + #if !defined(CATCH_CONFIG_CPP11_STREAM_INSERTABLE_CHECK) + struct BorgType { + template BorgType( T const& ); + }; + + struct TrueType { char sizer[1]; }; + struct FalseType { char sizer[2]; }; + + TrueType& testStreamable( std::ostream& ); + FalseType testStreamable( FalseType ); + + FalseType operator<<( std::ostream const&, BorgType const& ); + + template + struct IsStreamInsertable { + static std::ostream &s; + static T const&t; + enum { value = sizeof( testStreamable(s << t) ) == sizeof( TrueType ) }; + }; +#else + template + class IsStreamInsertable { + template + static auto test(int) + -> decltype( std::declval() << std::declval(), std::true_type() ); + + template + static auto test(...) -> std::false_type; + + public: + static const bool value = decltype(test(0))::value; + }; +#endif + +#if defined(CATCH_CONFIG_CPP11_IS_ENUM) + template::value + > + struct EnumStringMaker + { + static std::string convert( T const& ) { return unprintableString; } + }; + + template + struct EnumStringMaker + { + static std::string convert( T const& v ) + { + return ::Catch::toString( + static_cast::type>(v) + ); + } + }; +#endif + template + struct StringMakerBase { +#if defined(CATCH_CONFIG_CPP11_IS_ENUM) + template + static std::string convert( T const& v ) + { + return EnumStringMaker::convert( v ); + } +#else + template + static std::string convert( T const& ) { return unprintableString; } +#endif + }; + + template<> + struct StringMakerBase { + template + static std::string convert( T const& _value ) { + std::ostringstream oss; + oss << _value; + return oss.str(); + } + }; + + std::string rawMemoryToString( const void *object, std::size_t size ); + + template + inline std::string rawMemoryToString( const T& object ) { + return rawMemoryToString( &object, sizeof(object) ); + } + +} // end namespace Detail + +template +struct StringMaker : + Detail::StringMakerBase::value> {}; + +template +struct StringMaker { + template + static std::string convert( U* p ) { + if( !p ) + return "NULL"; + else + return Detail::rawMemoryToString( p ); + } +}; + +template +struct StringMaker { + static std::string convert( R C::* p ) { + if( !p ) + return "NULL"; + else + return Detail::rawMemoryToString( p ); + } +}; + +namespace Detail { + template + std::string rangeToString( InputIterator first, InputIterator last ); +} + +//template +//struct StringMaker > { +// static std::string convert( std::vector const& v ) { +// return Detail::rangeToString( v.begin(), v.end() ); +// } +//}; + +template +std::string toString( std::vector const& v ) { + return Detail::rangeToString( v.begin(), v.end() ); +} + +#ifdef CATCH_CONFIG_CPP11_TUPLE + +// toString for tuples +namespace TupleDetail { + template< + typename Tuple, + std::size_t N = 0, + bool = (N < std::tuple_size::value) + > + struct ElementPrinter { + static void print( const Tuple& tuple, std::ostream& os ) + { + os << ( N ? ", " : " " ) + << Catch::toString(std::get(tuple)); + ElementPrinter::print(tuple,os); + } + }; + + template< + typename Tuple, + std::size_t N + > + struct ElementPrinter { + static void print( const Tuple&, std::ostream& ) {} + }; + +} + +template +struct StringMaker> { + + static std::string convert( const std::tuple& tuple ) + { + std::ostringstream os; + os << '{'; + TupleDetail::ElementPrinter>::print( tuple, os ); + os << " }"; + return os.str(); + } +}; +#endif // CATCH_CONFIG_CPP11_TUPLE + +namespace Detail { + template + std::string makeString( T const& value ) { + return StringMaker::convert( value ); + } +} // end namespace Detail + +/// \brief converts any type to a string +/// +/// The default template forwards on to ostringstream - except when an +/// ostringstream overload does not exist - in which case it attempts to detect +/// that and writes {?}. +/// Overload (not specialise) this template for custom typs that you don't want +/// to provide an ostream overload for. +template +std::string toString( T const& value ) { + return StringMaker::convert( value ); +} + + namespace Detail { + template + std::string rangeToString( InputIterator first, InputIterator last ) { + std::ostringstream oss; + oss << "{ "; + if( first != last ) { + oss << Catch::toString( *first ); + for( ++first ; first != last ; ++first ) + oss << ", " << Catch::toString( *first ); + } + oss << " }"; + return oss.str(); + } +} + +} // end namespace Catch + +namespace Catch { + +template +class BinaryExpression; + +template +class MatchExpression; + +// Wraps the LHS of an expression and overloads comparison operators +// for also capturing those and RHS (if any) +template +class ExpressionLhs : public DecomposedExpression { +public: + ExpressionLhs( ResultBuilder& rb, T lhs ) : m_rb( rb ), m_lhs( lhs ), m_truthy(false) {} + + ExpressionLhs& operator = ( const ExpressionLhs& ); + + template + BinaryExpression + operator == ( RhsT const& rhs ) { + return captureExpression( rhs ); + } + + template + BinaryExpression + operator != ( RhsT const& rhs ) { + return captureExpression( rhs ); + } + + template + BinaryExpression + operator < ( RhsT const& rhs ) { + return captureExpression( rhs ); + } + + template + BinaryExpression + operator > ( RhsT const& rhs ) { + return captureExpression( rhs ); + } + + template + BinaryExpression + operator <= ( RhsT const& rhs ) { + return captureExpression( rhs ); + } + + template + BinaryExpression + operator >= ( RhsT const& rhs ) { + return captureExpression( rhs ); + } + + BinaryExpression operator == ( bool rhs ) { + return captureExpression( rhs ); + } + + BinaryExpression operator != ( bool rhs ) { + return captureExpression( rhs ); + } + + void endExpression() { + m_truthy = m_lhs ? true : false; + m_rb + .setResultType( m_truthy ) + .endExpression( *this ); + } + + virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE { + dest = Catch::toString( m_truthy ); + } + +private: + template + BinaryExpression captureExpression( RhsT& rhs ) const { + return BinaryExpression( m_rb, m_lhs, rhs ); + } + + template + BinaryExpression captureExpression( bool rhs ) const { + return BinaryExpression( m_rb, m_lhs, rhs ); + } + +private: + ResultBuilder& m_rb; + T m_lhs; + bool m_truthy; +}; + +template +class BinaryExpression : public DecomposedExpression { +public: + BinaryExpression( ResultBuilder& rb, LhsT lhs, RhsT rhs ) + : m_rb( rb ), m_lhs( lhs ), m_rhs( rhs ) {} + + BinaryExpression& operator = ( BinaryExpression& ); + + void endExpression() const { + m_rb + .setResultType( Internal::compare( m_lhs, m_rhs ) ) + .endExpression( *this ); + } + + virtual bool isBinaryExpression() const CATCH_OVERRIDE { + return true; + } + + virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE { + std::string lhs = Catch::toString( m_lhs ); + std::string rhs = Catch::toString( m_rhs ); + char delim = lhs.size() + rhs.size() < 40 && + lhs.find('\n') == std::string::npos && + rhs.find('\n') == std::string::npos ? ' ' : '\n'; + dest.reserve( 7 + lhs.size() + rhs.size() ); + // 2 for spaces around operator + // 2 for operator + // 2 for parentheses (conditionally added later) + // 1 for negation (conditionally added later) + dest = lhs; + dest += delim; + dest += Internal::OperatorTraits::getName(); + dest += delim; + dest += rhs; + } + +private: + ResultBuilder& m_rb; + LhsT m_lhs; + RhsT m_rhs; +}; + +template +class MatchExpression : public DecomposedExpression { +public: + MatchExpression( ArgT arg, MatcherT matcher, char const* matcherString ) + : m_arg( arg ), m_matcher( matcher ), m_matcherString( matcherString ) {} + + virtual bool isBinaryExpression() const CATCH_OVERRIDE { + return true; + } + + virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE { + std::string matcherAsString = m_matcher.toString(); + dest = Catch::toString( m_arg ); + dest += ' '; + if( matcherAsString == Detail::unprintableString ) + dest += m_matcherString; + else + dest += matcherAsString; + } + +private: + ArgT m_arg; + MatcherT m_matcher; + char const* m_matcherString; +}; + +} // end namespace Catch + + +namespace Catch { + + template + inline ExpressionLhs ResultBuilder::operator <= ( T const& operand ) { + return ExpressionLhs( *this, operand ); + } + + inline ExpressionLhs ResultBuilder::operator <= ( bool value ) { + return ExpressionLhs( *this, value ); + } + + template + inline void ResultBuilder::captureMatch( ArgT const& arg, MatcherT const& matcher, + char const* matcherString ) { + MatchExpression expr( arg, matcher, matcherString ); + setResultType( matcher.match( arg ) ); + endExpression( expr ); + } + +} // namespace Catch + +// #included from: catch_message.h +#define TWOBLUECUBES_CATCH_MESSAGE_H_INCLUDED + +#include + +namespace Catch { + + struct MessageInfo { + MessageInfo( std::string const& _macroName, + SourceLineInfo const& _lineInfo, + ResultWas::OfType _type ); + + std::string macroName; + SourceLineInfo lineInfo; + ResultWas::OfType type; + std::string message; + unsigned int sequence; + + bool operator == ( MessageInfo const& other ) const { + return sequence == other.sequence; + } + bool operator < ( MessageInfo const& other ) const { + return sequence < other.sequence; + } + private: + static unsigned int globalCount; + }; + + struct MessageBuilder { + MessageBuilder( std::string const& macroName, + SourceLineInfo const& lineInfo, + ResultWas::OfType type ) + : m_info( macroName, lineInfo, type ) + {} + + template + MessageBuilder& operator << ( T const& value ) { + m_stream << value; + return *this; + } + + MessageInfo m_info; + std::ostringstream m_stream; + }; + + class ScopedMessage { + public: + ScopedMessage( MessageBuilder const& builder ); + ScopedMessage( ScopedMessage const& other ); + ~ScopedMessage(); + + MessageInfo m_info; + }; + +} // end namespace Catch + +// #included from: catch_interfaces_capture.h +#define TWOBLUECUBES_CATCH_INTERFACES_CAPTURE_H_INCLUDED + +#include + +namespace Catch { + + class TestCase; + class AssertionResult; + struct AssertionInfo; + struct SectionInfo; + struct SectionEndInfo; + struct MessageInfo; + class ScopedMessageBuilder; + struct Counts; + + struct IResultCapture { + + virtual ~IResultCapture(); + + virtual void assertionEnded( AssertionResult const& result ) = 0; + virtual bool sectionStarted( SectionInfo const& sectionInfo, + Counts& assertions ) = 0; + virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0; + virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0; + virtual void pushScopedMessage( MessageInfo const& message ) = 0; + virtual void popScopedMessage( MessageInfo const& message ) = 0; + + virtual std::string getCurrentTestName() const = 0; + virtual const AssertionResult* getLastResult() const = 0; + + virtual void exceptionEarlyReported() = 0; + + virtual void handleFatalErrorCondition( std::string const& message ) = 0; + }; + + IResultCapture& getResultCapture(); +} + +// #included from: catch_debugger.h +#define TWOBLUECUBES_CATCH_DEBUGGER_H_INCLUDED + +// #included from: catch_platform.h +#define TWOBLUECUBES_CATCH_PLATFORM_H_INCLUDED + +#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) +# define CATCH_PLATFORM_MAC +#elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +# define CATCH_PLATFORM_IPHONE +#elif defined(linux) || defined(__linux) || defined(__linux__) +# define CATCH_PLATFORM_LINUX +#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) +# define CATCH_PLATFORM_WINDOWS +# if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX) +# define CATCH_DEFINES_NOMINMAX +# endif +# if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN) +# define CATCH_DEFINES_WIN32_LEAN_AND_MEAN +# endif +#endif + +#include + +namespace Catch{ + + bool isDebuggerActive(); + void writeToDebugConsole( std::string const& text ); +} + +#ifdef CATCH_PLATFORM_MAC + + // The following code snippet based on: + // http://cocoawithlove.com/2008/03/break-into-debugger.html + #if defined(__ppc64__) || defined(__ppc__) + #define CATCH_TRAP() \ + __asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n" \ + : : : "memory","r0","r3","r4" ) + #else + #define CATCH_TRAP() __asm__("int $3\n" : : ) + #endif + +#elif defined(CATCH_PLATFORM_LINUX) + // If we can use inline assembler, do it because this allows us to break + // directly at the location of the failing check instead of breaking inside + // raise() called from it, i.e. one stack frame below. + #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64)) + #define CATCH_TRAP() asm volatile ("int $3") + #else // Fall back to the generic way. + #include + + #define CATCH_TRAP() raise(SIGTRAP) + #endif +#elif defined(_MSC_VER) + #define CATCH_TRAP() __debugbreak() +#elif defined(__MINGW32__) + extern "C" __declspec(dllimport) void __stdcall DebugBreak(); + #define CATCH_TRAP() DebugBreak() +#endif + +#ifdef CATCH_TRAP + #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } +#else + #define CATCH_BREAK_INTO_DEBUGGER() Catch::alwaysTrue(); +#endif + +// #included from: catch_interfaces_runner.h +#define TWOBLUECUBES_CATCH_INTERFACES_RUNNER_H_INCLUDED + +namespace Catch { + class TestCase; + + struct IRunner { + virtual ~IRunner(); + virtual bool aborting() const = 0; + }; +} + +#if defined(CATCH_CONFIG_FAST_COMPILE) +/////////////////////////////////////////////////////////////////////////////// +// We can speedup compilation significantly by breaking into debugger lower in +// the callstack, because then we don't have to expand CATCH_BREAK_INTO_DEBUGGER +// macro in each assertion +#define INTERNAL_CATCH_REACT( resultBuilder ) \ + resultBuilder.react(); + +/////////////////////////////////////////////////////////////////////////////// +// Another way to speed-up compilation is to omit local try-catch for REQUIRE* +// macros. +// This can potentially cause false negative, if the test code catches +// the exception before it propagates back up to the runner. +#define INTERNAL_CATCH_TEST_NO_TRY( macroName, resultDisposition, expr ) \ + do { \ + Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ + __catchResult.setExceptionGuard(); \ + CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ + ( __catchResult <= expr ).endExpression(); \ + CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \ + __catchResult.unsetExceptionGuard(); \ + INTERNAL_CATCH_REACT( __catchResult ) \ + } while( Catch::isTrue( false && static_cast( !!(expr) ) ) ) // expr here is never evaluated at runtime but it forces the compiler to give it a look +// The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&. + +#define INTERNAL_CHECK_THAT_NO_TRY( macroName, matcher, resultDisposition, arg ) \ + do { \ + Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #arg ", " #matcher, resultDisposition ); \ + __catchResult.setExceptionGuard(); \ + __catchResult.captureMatch( arg, matcher, #matcher ); \ + __catchResult.unsetExceptionGuard(); \ + INTERNAL_CATCH_REACT( __catchResult ) \ + } while( Catch::alwaysFalse() ) + +#else +/////////////////////////////////////////////////////////////////////////////// +// In the event of a failure works out if the debugger needs to be invoked +// and/or an exception thrown and takes appropriate action. +// This needs to be done as a macro so the debugger will stop in the user +// source code rather than in Catch library code +#define INTERNAL_CATCH_REACT( resultBuilder ) \ + if( resultBuilder.shouldDebugBreak() ) CATCH_BREAK_INTO_DEBUGGER(); \ + resultBuilder.react(); +#endif + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_TEST( macroName, resultDisposition, expr ) \ + do { \ + Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ + try { \ + CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ + ( __catchResult <= expr ).endExpression(); \ + CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \ + } \ + catch( ... ) { \ + __catchResult.useActiveException( resultDisposition ); \ + } \ + INTERNAL_CATCH_REACT( __catchResult ) \ + } while( Catch::isTrue( false && static_cast( !!(expr) ) ) ) // expr here is never evaluated at runtime but it forces the compiler to give it a look + // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&. + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_IF( macroName, resultDisposition, expr ) \ + INTERNAL_CATCH_TEST( macroName, resultDisposition, expr ); \ + if( Catch::getResultCapture().getLastResult()->succeeded() ) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_ELSE( macroName, resultDisposition, expr ) \ + INTERNAL_CATCH_TEST( macroName, resultDisposition, expr ); \ + if( !Catch::getResultCapture().getLastResult()->succeeded() ) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, expr ) \ + do { \ + Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ + try { \ + static_cast(expr); \ + __catchResult.captureResult( Catch::ResultWas::Ok ); \ + } \ + catch( ... ) { \ + __catchResult.useActiveException( resultDisposition ); \ + } \ + INTERNAL_CATCH_REACT( __catchResult ) \ + } while( Catch::alwaysFalse() ) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_THROWS( macroName, resultDisposition, matcher, expr ) \ + do { \ + Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition, #matcher ); \ + if( __catchResult.allowThrows() ) \ + try { \ + static_cast(expr); \ + __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \ + } \ + catch( ... ) { \ + __catchResult.captureExpectedException( matcher ); \ + } \ + else \ + __catchResult.captureResult( Catch::ResultWas::Ok ); \ + INTERNAL_CATCH_REACT( __catchResult ) \ + } while( Catch::alwaysFalse() ) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \ + do { \ + Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr ", " #exceptionType, resultDisposition ); \ + if( __catchResult.allowThrows() ) \ + try { \ + static_cast(expr); \ + __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \ + } \ + catch( exceptionType ) { \ + __catchResult.captureResult( Catch::ResultWas::Ok ); \ + } \ + catch( ... ) { \ + __catchResult.useActiveException( resultDisposition ); \ + } \ + else \ + __catchResult.captureResult( Catch::ResultWas::Ok ); \ + INTERNAL_CATCH_REACT( __catchResult ) \ + } while( Catch::alwaysFalse() ) + +/////////////////////////////////////////////////////////////////////////////// +#ifdef CATCH_CONFIG_VARIADIC_MACROS + #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \ + do { \ + Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \ + __catchResult << __VA_ARGS__ + ::Catch::StreamEndStop(); \ + __catchResult.captureResult( messageType ); \ + INTERNAL_CATCH_REACT( __catchResult ) \ + } while( Catch::alwaysFalse() ) +#else + #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, log ) \ + do { \ + Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \ + __catchResult << log + ::Catch::StreamEndStop(); \ + __catchResult.captureResult( messageType ); \ + INTERNAL_CATCH_REACT( __catchResult ) \ + } while( Catch::alwaysFalse() ) +#endif + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_INFO( macroName, log ) \ + Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage ) = Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log; + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \ + do { \ + Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #arg ", " #matcher, resultDisposition ); \ + try { \ + __catchResult.captureMatch( arg, matcher, #matcher ); \ + } catch( ... ) { \ + __catchResult.useActiveException( resultDisposition | Catch::ResultDisposition::ContinueOnFailure ); \ + } \ + INTERNAL_CATCH_REACT( __catchResult ) \ + } while( Catch::alwaysFalse() ) + +// #included from: internal/catch_section.h +#define TWOBLUECUBES_CATCH_SECTION_H_INCLUDED + +// #included from: catch_section_info.h +#define TWOBLUECUBES_CATCH_SECTION_INFO_H_INCLUDED + +// #included from: catch_totals.hpp +#define TWOBLUECUBES_CATCH_TOTALS_HPP_INCLUDED + +#include + +namespace Catch { + + struct Counts { + Counts() : passed( 0 ), failed( 0 ), failedButOk( 0 ) {} + + Counts operator - ( Counts const& other ) const { + Counts diff; + diff.passed = passed - other.passed; + diff.failed = failed - other.failed; + diff.failedButOk = failedButOk - other.failedButOk; + return diff; + } + Counts& operator += ( Counts const& other ) { + passed += other.passed; + failed += other.failed; + failedButOk += other.failedButOk; + return *this; + } + + std::size_t total() const { + return passed + failed + failedButOk; + } + bool allPassed() const { + return failed == 0 && failedButOk == 0; + } + bool allOk() const { + return failed == 0; + } + + std::size_t passed; + std::size_t failed; + std::size_t failedButOk; + }; + + struct Totals { + + Totals operator - ( Totals const& other ) const { + Totals diff; + diff.assertions = assertions - other.assertions; + diff.testCases = testCases - other.testCases; + return diff; + } + + Totals delta( Totals const& prevTotals ) const { + Totals diff = *this - prevTotals; + if( diff.assertions.failed > 0 ) + ++diff.testCases.failed; + else if( diff.assertions.failedButOk > 0 ) + ++diff.testCases.failedButOk; + else + ++diff.testCases.passed; + return diff; + } + + Totals& operator += ( Totals const& other ) { + assertions += other.assertions; + testCases += other.testCases; + return *this; + } + + Counts assertions; + Counts testCases; + }; +} + +#include + +namespace Catch { + + struct SectionInfo { + SectionInfo + ( SourceLineInfo const& _lineInfo, + std::string const& _name, + std::string const& _description = std::string() ); + + std::string name; + std::string description; + SourceLineInfo lineInfo; + }; + + struct SectionEndInfo { + SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds ) + : sectionInfo( _sectionInfo ), prevAssertions( _prevAssertions ), durationInSeconds( _durationInSeconds ) + {} + + SectionInfo sectionInfo; + Counts prevAssertions; + double durationInSeconds; + }; + +} // end namespace Catch + +// #included from: catch_timer.h +#define TWOBLUECUBES_CATCH_TIMER_H_INCLUDED + +#ifdef _MSC_VER + +namespace Catch { + typedef unsigned long long UInt64; +} +#else +#include +namespace Catch { + typedef uint64_t UInt64; +} +#endif + +namespace Catch { + class Timer { + public: + Timer() : m_ticks( 0 ) {} + void start(); + unsigned int getElapsedMicroseconds() const; + unsigned int getElapsedMilliseconds() const; + double getElapsedSeconds() const; + + private: + UInt64 m_ticks; + }; + +} // namespace Catch + +#include + +namespace Catch { + + class Section : NonCopyable { + public: + Section( SectionInfo const& info ); + ~Section(); + + // This indicates whether the section should be executed or not + operator bool() const; + + private: + SectionInfo m_info; + + std::string m_name; + Counts m_assertions; + bool m_sectionIncluded; + Timer m_timer; + }; + +} // end namespace Catch + +#ifdef CATCH_CONFIG_VARIADIC_MACROS + #define INTERNAL_CATCH_SECTION( ... ) \ + if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) +#else + #define INTERNAL_CATCH_SECTION( name, desc ) \ + if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, name, desc ) ) +#endif + +// #included from: internal/catch_generators.hpp +#define TWOBLUECUBES_CATCH_GENERATORS_HPP_INCLUDED + +#include +#include +#include + +namespace Catch { + +template +struct IGenerator { + virtual ~IGenerator() {} + virtual T getValue( std::size_t index ) const = 0; + virtual std::size_t size () const = 0; +}; + +template +class BetweenGenerator : public IGenerator { +public: + BetweenGenerator( T from, T to ) : m_from( from ), m_to( to ){} + + virtual T getValue( std::size_t index ) const { + return m_from+static_cast( index ); + } + + virtual std::size_t size() const { + return static_cast( 1+m_to-m_from ); + } + +private: + + T m_from; + T m_to; +}; + +template +class ValuesGenerator : public IGenerator { +public: + ValuesGenerator(){} + + void add( T value ) { + m_values.push_back( value ); + } + + virtual T getValue( std::size_t index ) const { + return m_values[index]; + } + + virtual std::size_t size() const { + return m_values.size(); + } + +private: + std::vector m_values; +}; + +template +class CompositeGenerator { +public: + CompositeGenerator() : m_totalSize( 0 ) {} + + // *** Move semantics, similar to auto_ptr *** + CompositeGenerator( CompositeGenerator& other ) + : m_fileInfo( other.m_fileInfo ), + m_totalSize( 0 ) + { + move( other ); + } + + CompositeGenerator& setFileInfo( const char* fileInfo ) { + m_fileInfo = fileInfo; + return *this; + } + + ~CompositeGenerator() { + deleteAll( m_composed ); + } + + operator T () const { + size_t overallIndex = getCurrentContext().getGeneratorIndex( m_fileInfo, m_totalSize ); + + typename std::vector*>::const_iterator it = m_composed.begin(); + typename std::vector*>::const_iterator itEnd = m_composed.end(); + for( size_t index = 0; it != itEnd; ++it ) + { + const IGenerator* generator = *it; + if( overallIndex >= index && overallIndex < index + generator->size() ) + { + return generator->getValue( overallIndex-index ); + } + index += generator->size(); + } + CATCH_INTERNAL_ERROR( "Indexed past end of generated range" ); + return T(); // Suppress spurious "not all control paths return a value" warning in Visual Studio - if you know how to fix this please do so + } + + void add( const IGenerator* generator ) { + m_totalSize += generator->size(); + m_composed.push_back( generator ); + } + + CompositeGenerator& then( CompositeGenerator& other ) { + move( other ); + return *this; + } + + CompositeGenerator& then( T value ) { + ValuesGenerator* valuesGen = new ValuesGenerator(); + valuesGen->add( value ); + add( valuesGen ); + return *this; + } + +private: + + void move( CompositeGenerator& other ) { + m_composed.insert( m_composed.end(), other.m_composed.begin(), other.m_composed.end() ); + m_totalSize += other.m_totalSize; + other.m_composed.clear(); + } + + std::vector*> m_composed; + std::string m_fileInfo; + size_t m_totalSize; +}; + +namespace Generators +{ + template + CompositeGenerator between( T from, T to ) { + CompositeGenerator generators; + generators.add( new BetweenGenerator( from, to ) ); + return generators; + } + + template + CompositeGenerator values( T val1, T val2 ) { + CompositeGenerator generators; + ValuesGenerator* valuesGen = new ValuesGenerator(); + valuesGen->add( val1 ); + valuesGen->add( val2 ); + generators.add( valuesGen ); + return generators; + } + + template + CompositeGenerator values( T val1, T val2, T val3 ){ + CompositeGenerator generators; + ValuesGenerator* valuesGen = new ValuesGenerator(); + valuesGen->add( val1 ); + valuesGen->add( val2 ); + valuesGen->add( val3 ); + generators.add( valuesGen ); + return generators; + } + + template + CompositeGenerator values( T val1, T val2, T val3, T val4 ) { + CompositeGenerator generators; + ValuesGenerator* valuesGen = new ValuesGenerator(); + valuesGen->add( val1 ); + valuesGen->add( val2 ); + valuesGen->add( val3 ); + valuesGen->add( val4 ); + generators.add( valuesGen ); + return generators; + } + +} // end namespace Generators + +using namespace Generators; + +} // end namespace Catch + +#define INTERNAL_CATCH_LINESTR2( line ) #line +#define INTERNAL_CATCH_LINESTR( line ) INTERNAL_CATCH_LINESTR2( line ) + +#define INTERNAL_CATCH_GENERATE( expr ) expr.setFileInfo( __FILE__ "(" INTERNAL_CATCH_LINESTR( __LINE__ ) ")" ) + +// #included from: internal/catch_interfaces_exception.h +#define TWOBLUECUBES_CATCH_INTERFACES_EXCEPTION_H_INCLUDED + +#include +#include + +// #included from: catch_interfaces_registry_hub.h +#define TWOBLUECUBES_CATCH_INTERFACES_REGISTRY_HUB_H_INCLUDED + +#include + +namespace Catch { + + class TestCase; + struct ITestCaseRegistry; + struct IExceptionTranslatorRegistry; + struct IExceptionTranslator; + struct IReporterRegistry; + struct IReporterFactory; + struct ITagAliasRegistry; + + struct IRegistryHub { + virtual ~IRegistryHub(); + + virtual IReporterRegistry const& getReporterRegistry() const = 0; + virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0; + virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0; + + virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0; + }; + + struct IMutableRegistryHub { + virtual ~IMutableRegistryHub(); + virtual void registerReporter( std::string const& name, Ptr const& factory ) = 0; + virtual void registerListener( Ptr const& factory ) = 0; + virtual void registerTest( TestCase const& testInfo ) = 0; + virtual void registerTranslator( const IExceptionTranslator* translator ) = 0; + virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0; + }; + + IRegistryHub& getRegistryHub(); + IMutableRegistryHub& getMutableRegistryHub(); + void cleanUp(); + std::string translateActiveException(); + +} + +namespace Catch { + + typedef std::string(*exceptionTranslateFunction)(); + + struct IExceptionTranslator; + typedef std::vector ExceptionTranslators; + + struct IExceptionTranslator { + virtual ~IExceptionTranslator(); + virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0; + }; + + struct IExceptionTranslatorRegistry { + virtual ~IExceptionTranslatorRegistry(); + + virtual std::string translateActiveException() const = 0; + }; + + class ExceptionTranslatorRegistrar { + template + class ExceptionTranslator : public IExceptionTranslator { + public: + + ExceptionTranslator( std::string(*translateFunction)( T& ) ) + : m_translateFunction( translateFunction ) + {} + + virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const CATCH_OVERRIDE { + try { + if( it == itEnd ) + throw; + else + return (*it)->translate( it+1, itEnd ); + } + catch( T& ex ) { + return m_translateFunction( ex ); + } + } + + protected: + std::string(*m_translateFunction)( T& ); + }; + + public: + template + ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) { + getMutableRegistryHub().registerTranslator + ( new ExceptionTranslator( translateFunction ) ); + } + }; +} + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \ + static std::string translatorName( signature ); \ + namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); }\ + static std::string translatorName( signature ) + +#define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) + +// #included from: internal/catch_approx.hpp +#define TWOBLUECUBES_CATCH_APPROX_HPP_INCLUDED + +#include +#include + +#if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS) +#include +#endif + +namespace Catch { +namespace Detail { + + class Approx { + public: + explicit Approx ( double value ) + : m_epsilon( std::numeric_limits::epsilon()*100 ), + m_margin( 0.0 ), + m_scale( 1.0 ), + m_value( value ) + {} + + Approx( Approx const& other ) + : m_epsilon( other.m_epsilon ), + m_margin( other.m_margin ), + m_scale( other.m_scale ), + m_value( other.m_value ) + {} + + static Approx custom() { + return Approx( 0 ); + } + +#if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS) + + template ::value>::type> + Approx operator()( T value ) { + Approx approx( static_cast(value) ); + approx.epsilon( m_epsilon ); + approx.margin( m_margin ); + approx.scale( m_scale ); + return approx; + } + + template ::value>::type> + explicit Approx( T value ): Approx(static_cast(value)) + {} + + template ::value>::type> + friend bool operator == ( const T& lhs, Approx const& rhs ) { + // Thanks to Richard Harris for his help refining this formula + auto lhs_v = double(lhs); + bool relativeOK = std::fabs(lhs_v - rhs.m_value) < rhs.m_epsilon * (rhs.m_scale + (std::max)(std::fabs(lhs_v), std::fabs(rhs.m_value))); + if (relativeOK) { + return true; + } + return std::fabs(lhs_v - rhs.m_value) < rhs.m_margin; + } + + template ::value>::type> + friend bool operator == ( Approx const& lhs, const T& rhs ) { + return operator==( rhs, lhs ); + } + + template ::value>::type> + friend bool operator != ( T lhs, Approx const& rhs ) { + return !operator==( lhs, rhs ); + } + + template ::value>::type> + friend bool operator != ( Approx const& lhs, T rhs ) { + return !operator==( rhs, lhs ); + } + + template ::value>::type> + friend bool operator <= ( T lhs, Approx const& rhs ) { + return double(lhs) < rhs.m_value || lhs == rhs; + } + + template ::value>::type> + friend bool operator <= ( Approx const& lhs, T rhs ) { + return lhs.m_value < double(rhs) || lhs == rhs; + } + + template ::value>::type> + friend bool operator >= ( T lhs, Approx const& rhs ) { + return double(lhs) > rhs.m_value || lhs == rhs; + } + + template ::value>::type> + friend bool operator >= ( Approx const& lhs, T rhs ) { + return lhs.m_value > double(rhs) || lhs == rhs; + } + + template ::value>::type> + Approx& epsilon( T newEpsilon ) { + m_epsilon = double(newEpsilon); + return *this; + } + + template ::value>::type> + Approx& margin( T newMargin ) { + m_margin = double(newMargin); + return *this; + } + + template ::value>::type> + Approx& scale( T newScale ) { + m_scale = double(newScale); + return *this; + } + +#else + + Approx operator()( double value ) { + Approx approx( value ); + approx.epsilon( m_epsilon ); + approx.margin( m_margin ); + approx.scale( m_scale ); + return approx; + } + + friend bool operator == ( double lhs, Approx const& rhs ) { + // Thanks to Richard Harris for his help refining this formula + bool relativeOK = std::fabs( lhs - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( std::fabs(lhs), std::fabs(rhs.m_value) ) ); + if (relativeOK) { + return true; + } + return std::fabs(lhs - rhs.m_value) < rhs.m_margin; + } + + friend bool operator == ( Approx const& lhs, double rhs ) { + return operator==( rhs, lhs ); + } + + friend bool operator != ( double lhs, Approx const& rhs ) { + return !operator==( lhs, rhs ); + } + + friend bool operator != ( Approx const& lhs, double rhs ) { + return !operator==( rhs, lhs ); + } + + friend bool operator <= ( double lhs, Approx const& rhs ) { + return lhs < rhs.m_value || lhs == rhs; + } + + friend bool operator <= ( Approx const& lhs, double rhs ) { + return lhs.m_value < rhs || lhs == rhs; + } + + friend bool operator >= ( double lhs, Approx const& rhs ) { + return lhs > rhs.m_value || lhs == rhs; + } + + friend bool operator >= ( Approx const& lhs, double rhs ) { + return lhs.m_value > rhs || lhs == rhs; + } + + Approx& epsilon( double newEpsilon ) { + m_epsilon = newEpsilon; + return *this; + } + + Approx& margin( double newMargin ) { + m_margin = newMargin; + return *this; + } + + Approx& scale( double newScale ) { + m_scale = newScale; + return *this; + } +#endif + + std::string toString() const { + std::ostringstream oss; + oss << "Approx( " << Catch::toString( m_value ) << " )"; + return oss.str(); + } + + private: + double m_epsilon; + double m_margin; + double m_scale; + double m_value; + }; +} + +template<> +inline std::string toString( Detail::Approx const& value ) { + return value.toString(); +} + +} // end namespace Catch + +// #included from: internal/catch_matchers_string.h +#define TWOBLUECUBES_CATCH_MATCHERS_STRING_H_INCLUDED + +namespace Catch { +namespace Matchers { + + namespace StdString { + + struct CasedString + { + CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity ); + std::string adjustString( std::string const& str ) const; + std::string caseSensitivitySuffix() const; + + CaseSensitive::Choice m_caseSensitivity; + std::string m_str; + }; + + struct StringMatcherBase : MatcherBase { + StringMatcherBase( std::string const& operation, CasedString const& comparator ); + virtual std::string describe() const CATCH_OVERRIDE; + + CasedString m_comparator; + std::string m_operation; + }; + + struct EqualsMatcher : StringMatcherBase { + EqualsMatcher( CasedString const& comparator ); + virtual bool match( std::string const& source ) const CATCH_OVERRIDE; + }; + struct ContainsMatcher : StringMatcherBase { + ContainsMatcher( CasedString const& comparator ); + virtual bool match( std::string const& source ) const CATCH_OVERRIDE; + }; + struct StartsWithMatcher : StringMatcherBase { + StartsWithMatcher( CasedString const& comparator ); + virtual bool match( std::string const& source ) const CATCH_OVERRIDE; + }; + struct EndsWithMatcher : StringMatcherBase { + EndsWithMatcher( CasedString const& comparator ); + virtual bool match( std::string const& source ) const CATCH_OVERRIDE; + }; + + } // namespace StdString + + // The following functions create the actual matcher objects. + // This allows the types to be inferred + + StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); + StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); + StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); + StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); + +} // namespace Matchers +} // namespace Catch + +// #included from: internal/catch_matchers_vector.h +#define TWOBLUECUBES_CATCH_MATCHERS_VECTOR_H_INCLUDED + +namespace Catch { +namespace Matchers { + + namespace Vector { + + template + struct ContainsElementMatcher : MatcherBase, T> { + + ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {} + + bool match(std::vector const &v) const CATCH_OVERRIDE { + return std::find(v.begin(), v.end(), m_comparator) != v.end(); + } + + virtual std::string describe() const CATCH_OVERRIDE { + return "Contains: " + Catch::toString( m_comparator ); + } + + T const& m_comparator; + }; + + template + struct ContainsMatcher : MatcherBase, std::vector > { + + ContainsMatcher(std::vector const &comparator) : m_comparator( comparator ) {} + + bool match(std::vector const &v) const CATCH_OVERRIDE { + // !TBD: see note in EqualsMatcher + if (m_comparator.size() > v.size()) + return false; + for (size_t i = 0; i < m_comparator.size(); ++i) + if (std::find(v.begin(), v.end(), m_comparator[i]) == v.end()) + return false; + return true; + } + virtual std::string describe() const CATCH_OVERRIDE { + return "Contains: " + Catch::toString( m_comparator ); + } + + std::vector const& m_comparator; + }; + + template + struct EqualsMatcher : MatcherBase, std::vector > { + + EqualsMatcher(std::vector const &comparator) : m_comparator( comparator ) {} + + bool match(std::vector const &v) const CATCH_OVERRIDE { + // !TBD: This currently works if all elements can be compared using != + // - a more general approach would be via a compare template that defaults + // to using !=. but could be specialised for, e.g. std::vector etc + // - then just call that directly + if (m_comparator.size() != v.size()) + return false; + for (size_t i = 0; i < v.size(); ++i) + if (m_comparator[i] != v[i]) + return false; + return true; + } + virtual std::string describe() const CATCH_OVERRIDE { + return "Equals: " + Catch::toString( m_comparator ); + } + std::vector const& m_comparator; + }; + + } // namespace Vector + + // The following functions create the actual matcher objects. + // This allows the types to be inferred + + template + Vector::ContainsMatcher Contains( std::vector const& comparator ) { + return Vector::ContainsMatcher( comparator ); + } + + template + Vector::ContainsElementMatcher VectorContains( T const& comparator ) { + return Vector::ContainsElementMatcher( comparator ); + } + + template + Vector::EqualsMatcher Equals( std::vector const& comparator ) { + return Vector::EqualsMatcher( comparator ); + } + +} // namespace Matchers +} // namespace Catch + +// #included from: internal/catch_interfaces_tag_alias_registry.h +#define TWOBLUECUBES_CATCH_INTERFACES_TAG_ALIAS_REGISTRY_H_INCLUDED + +// #included from: catch_tag_alias.h +#define TWOBLUECUBES_CATCH_TAG_ALIAS_H_INCLUDED + +#include + +namespace Catch { + + struct TagAlias { + TagAlias( std::string const& _tag, SourceLineInfo _lineInfo ) : tag( _tag ), lineInfo( _lineInfo ) {} + + std::string tag; + SourceLineInfo lineInfo; + }; + + struct RegistrarForTagAliases { + RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); + }; + +} // end namespace Catch + +#define CATCH_REGISTER_TAG_ALIAS( alias, spec ) namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } +// #included from: catch_option.hpp +#define TWOBLUECUBES_CATCH_OPTION_HPP_INCLUDED + +namespace Catch { + + // An optional type + template + class Option { + public: + Option() : nullableValue( CATCH_NULL ) {} + Option( T const& _value ) + : nullableValue( new( storage ) T( _value ) ) + {} + Option( Option const& _other ) + : nullableValue( _other ? new( storage ) T( *_other ) : CATCH_NULL ) + {} + + ~Option() { + reset(); + } + + Option& operator= ( Option const& _other ) { + if( &_other != this ) { + reset(); + if( _other ) + nullableValue = new( storage ) T( *_other ); + } + return *this; + } + Option& operator = ( T const& _value ) { + reset(); + nullableValue = new( storage ) T( _value ); + return *this; + } + + void reset() { + if( nullableValue ) + nullableValue->~T(); + nullableValue = CATCH_NULL; + } + + T& operator*() { return *nullableValue; } + T const& operator*() const { return *nullableValue; } + T* operator->() { return nullableValue; } + const T* operator->() const { return nullableValue; } + + T valueOr( T const& defaultValue ) const { + return nullableValue ? *nullableValue : defaultValue; + } + + bool some() const { return nullableValue != CATCH_NULL; } + bool none() const { return nullableValue == CATCH_NULL; } + + bool operator !() const { return nullableValue == CATCH_NULL; } + operator SafeBool::type() const { + return SafeBool::makeSafe( some() ); + } + + private: + T *nullableValue; + union { + char storage[sizeof(T)]; + + // These are here to force alignment for the storage + long double dummy1; + void (*dummy2)(); + long double dummy3; +#ifdef CATCH_CONFIG_CPP11_LONG_LONG + long long dummy4; +#endif + }; + }; + +} // end namespace Catch + +namespace Catch { + + struct ITagAliasRegistry { + virtual ~ITagAliasRegistry(); + virtual Option find( std::string const& alias ) const = 0; + virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0; + + static ITagAliasRegistry const& get(); + }; + +} // end namespace Catch + +// These files are included here so the single_include script doesn't put them +// in the conditionally compiled sections +// #included from: internal/catch_test_case_info.h +#define TWOBLUECUBES_CATCH_TEST_CASE_INFO_H_INCLUDED + +#include +#include + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpadded" +#endif + +namespace Catch { + + struct ITestCase; + + struct TestCaseInfo { + enum SpecialProperties{ + None = 0, + IsHidden = 1 << 1, + ShouldFail = 1 << 2, + MayFail = 1 << 3, + Throws = 1 << 4, + NonPortable = 1 << 5 + }; + + TestCaseInfo( std::string const& _name, + std::string const& _className, + std::string const& _description, + std::set const& _tags, + SourceLineInfo const& _lineInfo ); + + TestCaseInfo( TestCaseInfo const& other ); + + friend void setTags( TestCaseInfo& testCaseInfo, std::set const& tags ); + + bool isHidden() const; + bool throws() const; + bool okToFail() const; + bool expectedToFail() const; + + std::string name; + std::string className; + std::string description; + std::set tags; + std::set lcaseTags; + std::string tagsAsString; + SourceLineInfo lineInfo; + SpecialProperties properties; + }; + + class TestCase : public TestCaseInfo { + public: + + TestCase( ITestCase* testCase, TestCaseInfo const& info ); + TestCase( TestCase const& other ); + + TestCase withName( std::string const& _newName ) const; + + void invoke() const; + + TestCaseInfo const& getTestCaseInfo() const; + + void swap( TestCase& other ); + bool operator == ( TestCase const& other ) const; + bool operator < ( TestCase const& other ) const; + TestCase& operator = ( TestCase const& other ); + + private: + Ptr test; + }; + + TestCase makeTestCase( ITestCase* testCase, + std::string const& className, + std::string const& name, + std::string const& description, + SourceLineInfo const& lineInfo ); +} + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + + +#ifdef __OBJC__ +// #included from: internal/catch_objc.hpp +#define TWOBLUECUBES_CATCH_OBJC_HPP_INCLUDED + +#import + +#include + +// NB. Any general catch headers included here must be included +// in catch.hpp first to make sure they are included by the single +// header for non obj-usage + +/////////////////////////////////////////////////////////////////////////////// +// This protocol is really only here for (self) documenting purposes, since +// all its methods are optional. +@protocol OcFixture + +@optional + +-(void) setUp; +-(void) tearDown; + +@end + +namespace Catch { + + class OcMethod : public SharedImpl { + + public: + OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {} + + virtual void invoke() const { + id obj = [[m_cls alloc] init]; + + performOptionalSelector( obj, @selector(setUp) ); + performOptionalSelector( obj, m_sel ); + performOptionalSelector( obj, @selector(tearDown) ); + + arcSafeRelease( obj ); + } + private: + virtual ~OcMethod() {} + + Class m_cls; + SEL m_sel; + }; + + namespace Detail{ + + inline std::string getAnnotation( Class cls, + std::string const& annotationName, + std::string const& testCaseName ) { + NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()]; + SEL sel = NSSelectorFromString( selStr ); + arcSafeRelease( selStr ); + id value = performOptionalSelector( cls, sel ); + if( value ) + return [(NSString*)value UTF8String]; + return ""; + } + } + + inline size_t registerTestMethods() { + size_t noTestMethods = 0; + int noClasses = objc_getClassList( CATCH_NULL, 0 ); + + Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses); + objc_getClassList( classes, noClasses ); + + for( int c = 0; c < noClasses; c++ ) { + Class cls = classes[c]; + { + u_int count; + Method* methods = class_copyMethodList( cls, &count ); + for( u_int m = 0; m < count ; m++ ) { + SEL selector = method_getName(methods[m]); + std::string methodName = sel_getName(selector); + if( startsWith( methodName, "Catch_TestCase_" ) ) { + std::string testCaseName = methodName.substr( 15 ); + std::string name = Detail::getAnnotation( cls, "Name", testCaseName ); + std::string desc = Detail::getAnnotation( cls, "Description", testCaseName ); + const char* className = class_getName( cls ); + + getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, name.c_str(), desc.c_str(), SourceLineInfo() ) ); + noTestMethods++; + } + } + free(methods); + } + } + return noTestMethods; + } + + namespace Matchers { + namespace Impl { + namespace NSStringMatchers { + + struct StringHolder : MatcherBase{ + StringHolder( NSString* substr ) : m_substr( [substr copy] ){} + StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){} + StringHolder() { + arcSafeRelease( m_substr ); + } + + virtual bool match( NSString* arg ) const CATCH_OVERRIDE { + return false; + } + + NSString* m_substr; + }; + + struct Equals : StringHolder { + Equals( NSString* substr ) : StringHolder( substr ){} + + virtual bool match( NSString* str ) const CATCH_OVERRIDE { + return (str != nil || m_substr == nil ) && + [str isEqualToString:m_substr]; + } + + virtual std::string describe() const CATCH_OVERRIDE { + return "equals string: " + Catch::toString( m_substr ); + } + }; + + struct Contains : StringHolder { + Contains( NSString* substr ) : StringHolder( substr ){} + + virtual bool match( NSString* str ) const { + return (str != nil || m_substr == nil ) && + [str rangeOfString:m_substr].location != NSNotFound; + } + + virtual std::string describe() const CATCH_OVERRIDE { + return "contains string: " + Catch::toString( m_substr ); + } + }; + + struct StartsWith : StringHolder { + StartsWith( NSString* substr ) : StringHolder( substr ){} + + virtual bool match( NSString* str ) const { + return (str != nil || m_substr == nil ) && + [str rangeOfString:m_substr].location == 0; + } + + virtual std::string describe() const CATCH_OVERRIDE { + return "starts with: " + Catch::toString( m_substr ); + } + }; + struct EndsWith : StringHolder { + EndsWith( NSString* substr ) : StringHolder( substr ){} + + virtual bool match( NSString* str ) const { + return (str != nil || m_substr == nil ) && + [str rangeOfString:m_substr].location == [str length] - [m_substr length]; + } + + virtual std::string describe() const CATCH_OVERRIDE { + return "ends with: " + Catch::toString( m_substr ); + } + }; + + } // namespace NSStringMatchers + } // namespace Impl + + inline Impl::NSStringMatchers::Equals + Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); } + + inline Impl::NSStringMatchers::Contains + Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); } + + inline Impl::NSStringMatchers::StartsWith + StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); } + + inline Impl::NSStringMatchers::EndsWith + EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); } + + } // namespace Matchers + + using namespace Matchers; + +} // namespace Catch + +/////////////////////////////////////////////////////////////////////////////// +#define OC_TEST_CASE( name, desc )\ ++(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Name_test ) \ +{\ +return @ name; \ +}\ ++(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Description_test ) \ +{ \ +return @ desc; \ +} \ +-(void) INTERNAL_CATCH_UNIQUE_NAME( Catch_TestCase_test ) + +#endif + +#ifdef CATCH_IMPL + +// !TBD: Move the leak detector code into a separate header +#ifdef CATCH_CONFIG_WINDOWS_CRTDBG +#include +class LeakDetector { +public: + LeakDetector() { + int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); + flag |= _CRTDBG_LEAK_CHECK_DF; + flag |= _CRTDBG_ALLOC_MEM_DF; + _CrtSetDbgFlag(flag); + _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); + _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); + // Change this to leaking allocation's number to break there + _CrtSetBreakAlloc(-1); + } +}; +#else +class LeakDetector {}; +#endif + +LeakDetector leakDetector; + +// #included from: internal/catch_impl.hpp +#define TWOBLUECUBES_CATCH_IMPL_HPP_INCLUDED + +// Collect all the implementation files together here +// These are the equivalent of what would usually be cpp files + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wweak-vtables" +#endif + +// #included from: ../catch_session.hpp +#define TWOBLUECUBES_CATCH_RUNNER_HPP_INCLUDED + +// #included from: internal/catch_commandline.hpp +#define TWOBLUECUBES_CATCH_COMMANDLINE_HPP_INCLUDED + +// #included from: catch_config.hpp +#define TWOBLUECUBES_CATCH_CONFIG_HPP_INCLUDED + +// #included from: catch_test_spec_parser.hpp +#define TWOBLUECUBES_CATCH_TEST_SPEC_PARSER_HPP_INCLUDED + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpadded" +#endif + +// #included from: catch_test_spec.hpp +#define TWOBLUECUBES_CATCH_TEST_SPEC_HPP_INCLUDED + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpadded" +#endif + +// #included from: catch_wildcard_pattern.hpp +#define TWOBLUECUBES_CATCH_WILDCARD_PATTERN_HPP_INCLUDED + +#include + +namespace Catch +{ + class WildcardPattern { + enum WildcardPosition { + NoWildcard = 0, + WildcardAtStart = 1, + WildcardAtEnd = 2, + WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd + }; + + public: + + WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity ) + : m_caseSensitivity( caseSensitivity ), + m_wildcard( NoWildcard ), + m_pattern( adjustCase( pattern ) ) + { + if( startsWith( m_pattern, '*' ) ) { + m_pattern = m_pattern.substr( 1 ); + m_wildcard = WildcardAtStart; + } + if( endsWith( m_pattern, '*' ) ) { + m_pattern = m_pattern.substr( 0, m_pattern.size()-1 ); + m_wildcard = static_cast( m_wildcard | WildcardAtEnd ); + } + } + virtual ~WildcardPattern(); + virtual bool matches( std::string const& str ) const { + switch( m_wildcard ) { + case NoWildcard: + return m_pattern == adjustCase( str ); + case WildcardAtStart: + return endsWith( adjustCase( str ), m_pattern ); + case WildcardAtEnd: + return startsWith( adjustCase( str ), m_pattern ); + case WildcardAtBothEnds: + return contains( adjustCase( str ), m_pattern ); + } + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunreachable-code" +#endif + throw std::logic_error( "Unknown enum" ); +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + } + private: + std::string adjustCase( std::string const& str ) const { + return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str; + } + CaseSensitive::Choice m_caseSensitivity; + WildcardPosition m_wildcard; + std::string m_pattern; + }; +} + +#include +#include + +namespace Catch { + + class TestSpec { + struct Pattern : SharedImpl<> { + virtual ~Pattern(); + virtual bool matches( TestCaseInfo const& testCase ) const = 0; + }; + class NamePattern : public Pattern { + public: + NamePattern( std::string const& name ) + : m_wildcardPattern( toLower( name ), CaseSensitive::No ) + {} + virtual ~NamePattern(); + virtual bool matches( TestCaseInfo const& testCase ) const { + return m_wildcardPattern.matches( toLower( testCase.name ) ); + } + private: + WildcardPattern m_wildcardPattern; + }; + + class TagPattern : public Pattern { + public: + TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {} + virtual ~TagPattern(); + virtual bool matches( TestCaseInfo const& testCase ) const { + return testCase.lcaseTags.find( m_tag ) != testCase.lcaseTags.end(); + } + private: + std::string m_tag; + }; + + class ExcludedPattern : public Pattern { + public: + ExcludedPattern( Ptr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {} + virtual ~ExcludedPattern(); + virtual bool matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); } + private: + Ptr m_underlyingPattern; + }; + + struct Filter { + std::vector > m_patterns; + + bool matches( TestCaseInfo const& testCase ) const { + // All patterns in a filter must match for the filter to be a match + for( std::vector >::const_iterator it = m_patterns.begin(), itEnd = m_patterns.end(); it != itEnd; ++it ) { + if( !(*it)->matches( testCase ) ) + return false; + } + return true; + } + }; + + public: + bool hasFilters() const { + return !m_filters.empty(); + } + bool matches( TestCaseInfo const& testCase ) const { + // A TestSpec matches if any filter matches + for( std::vector::const_iterator it = m_filters.begin(), itEnd = m_filters.end(); it != itEnd; ++it ) + if( it->matches( testCase ) ) + return true; + return false; + } + + private: + std::vector m_filters; + + friend class TestSpecParser; + }; +} + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +namespace Catch { + + class TestSpecParser { + enum Mode{ None, Name, QuotedName, Tag, EscapedName }; + Mode m_mode; + bool m_exclusion; + std::size_t m_start, m_pos; + std::string m_arg; + std::vector m_escapeChars; + TestSpec::Filter m_currentFilter; + TestSpec m_testSpec; + ITagAliasRegistry const* m_tagAliases; + + public: + TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {} + + TestSpecParser& parse( std::string const& arg ) { + m_mode = None; + m_exclusion = false; + m_start = std::string::npos; + m_arg = m_tagAliases->expandAliases( arg ); + m_escapeChars.clear(); + for( m_pos = 0; m_pos < m_arg.size(); ++m_pos ) + visitChar( m_arg[m_pos] ); + if( m_mode == Name ) + addPattern(); + return *this; + } + TestSpec testSpec() { + addFilter(); + return m_testSpec; + } + private: + void visitChar( char c ) { + if( m_mode == None ) { + switch( c ) { + case ' ': return; + case '~': m_exclusion = true; return; + case '[': return startNewMode( Tag, ++m_pos ); + case '"': return startNewMode( QuotedName, ++m_pos ); + case '\\': return escape(); + default: startNewMode( Name, m_pos ); break; + } + } + if( m_mode == Name ) { + if( c == ',' ) { + addPattern(); + addFilter(); + } + else if( c == '[' ) { + if( subString() == "exclude:" ) + m_exclusion = true; + else + addPattern(); + startNewMode( Tag, ++m_pos ); + } + else if( c == '\\' ) + escape(); + } + else if( m_mode == EscapedName ) + m_mode = Name; + else if( m_mode == QuotedName && c == '"' ) + addPattern(); + else if( m_mode == Tag && c == ']' ) + addPattern(); + } + void startNewMode( Mode mode, std::size_t start ) { + m_mode = mode; + m_start = start; + } + void escape() { + if( m_mode == None ) + m_start = m_pos; + m_mode = EscapedName; + m_escapeChars.push_back( m_pos ); + } + std::string subString() const { return m_arg.substr( m_start, m_pos - m_start ); } + template + void addPattern() { + std::string token = subString(); + for( size_t i = 0; i < m_escapeChars.size(); ++i ) + token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 ); + m_escapeChars.clear(); + if( startsWith( token, "exclude:" ) ) { + m_exclusion = true; + token = token.substr( 8 ); + } + if( !token.empty() ) { + Ptr pattern = new T( token ); + if( m_exclusion ) + pattern = new TestSpec::ExcludedPattern( pattern ); + m_currentFilter.m_patterns.push_back( pattern ); + } + m_exclusion = false; + m_mode = None; + } + void addFilter() { + if( !m_currentFilter.m_patterns.empty() ) { + m_testSpec.m_filters.push_back( m_currentFilter ); + m_currentFilter = TestSpec::Filter(); + } + } + }; + inline TestSpec parseTestSpec( std::string const& arg ) { + return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec(); + } + +} // namespace Catch + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +// #included from: catch_interfaces_config.h +#define TWOBLUECUBES_CATCH_INTERFACES_CONFIG_H_INCLUDED + +#include +#include +#include + +namespace Catch { + + struct Verbosity { enum Level { + NoOutput = 0, + Quiet, + Normal + }; }; + + struct WarnAbout { enum What { + Nothing = 0x00, + NoAssertions = 0x01 + }; }; + + struct ShowDurations { enum OrNot { + DefaultForReporter, + Always, + Never + }; }; + struct RunTests { enum InWhatOrder { + InDeclarationOrder, + InLexicographicalOrder, + InRandomOrder + }; }; + struct UseColour { enum YesOrNo { + Auto, + Yes, + No + }; }; + + class TestSpec; + + struct IConfig : IShared { + + virtual ~IConfig(); + + virtual bool allowThrows() const = 0; + virtual std::ostream& stream() const = 0; + virtual std::string name() const = 0; + virtual bool includeSuccessfulResults() const = 0; + virtual bool shouldDebugBreak() const = 0; + virtual bool warnAboutMissingAssertions() const = 0; + virtual int abortAfter() const = 0; + virtual bool showInvisibles() const = 0; + virtual ShowDurations::OrNot showDurations() const = 0; + virtual TestSpec const& testSpec() const = 0; + virtual RunTests::InWhatOrder runOrder() const = 0; + virtual unsigned int rngSeed() const = 0; + virtual UseColour::YesOrNo useColour() const = 0; + virtual std::vector const& getSectionsToRun() const = 0; + + }; +} + +// #included from: catch_stream.h +#define TWOBLUECUBES_CATCH_STREAM_H_INCLUDED + +// #included from: catch_streambuf.h +#define TWOBLUECUBES_CATCH_STREAMBUF_H_INCLUDED + +#include + +namespace Catch { + + class StreamBufBase : public std::streambuf { + public: + virtual ~StreamBufBase() CATCH_NOEXCEPT; + }; +} + +#include +#include +#include +#include + +namespace Catch { + + std::ostream& cout(); + std::ostream& cerr(); + + struct IStream { + virtual ~IStream() CATCH_NOEXCEPT; + virtual std::ostream& stream() const = 0; + }; + + class FileStream : public IStream { + mutable std::ofstream m_ofs; + public: + FileStream( std::string const& filename ); + virtual ~FileStream() CATCH_NOEXCEPT; + public: // IStream + virtual std::ostream& stream() const CATCH_OVERRIDE; + }; + + class CoutStream : public IStream { + mutable std::ostream m_os; + public: + CoutStream(); + virtual ~CoutStream() CATCH_NOEXCEPT; + + public: // IStream + virtual std::ostream& stream() const CATCH_OVERRIDE; + }; + + class DebugOutStream : public IStream { + CATCH_AUTO_PTR( StreamBufBase ) m_streamBuf; + mutable std::ostream m_os; + public: + DebugOutStream(); + virtual ~DebugOutStream() CATCH_NOEXCEPT; + + public: // IStream + virtual std::ostream& stream() const CATCH_OVERRIDE; + }; +} + +#include +#include +#include +#include + +#ifndef CATCH_CONFIG_CONSOLE_WIDTH +#define CATCH_CONFIG_CONSOLE_WIDTH 80 +#endif + +namespace Catch { + + struct ConfigData { + + ConfigData() + : listTests( false ), + listTags( false ), + listReporters( false ), + listTestNamesOnly( false ), + showSuccessfulTests( false ), + shouldDebugBreak( false ), + noThrow( false ), + showHelp( false ), + showInvisibles( false ), + filenamesAsTags( false ), + abortAfter( -1 ), + rngSeed( 0 ), + verbosity( Verbosity::Normal ), + warnings( WarnAbout::Nothing ), + showDurations( ShowDurations::DefaultForReporter ), + runOrder( RunTests::InDeclarationOrder ), + useColour( UseColour::Auto ) + {} + + bool listTests; + bool listTags; + bool listReporters; + bool listTestNamesOnly; + + bool showSuccessfulTests; + bool shouldDebugBreak; + bool noThrow; + bool showHelp; + bool showInvisibles; + bool filenamesAsTags; + + int abortAfter; + unsigned int rngSeed; + + Verbosity::Level verbosity; + WarnAbout::What warnings; + ShowDurations::OrNot showDurations; + RunTests::InWhatOrder runOrder; + UseColour::YesOrNo useColour; + + std::string outputFilename; + std::string name; + std::string processName; + + std::vector reporterNames; + std::vector testsOrTags; + std::vector sectionsToRun; + }; + + class Config : public SharedImpl { + private: + Config( Config const& other ); + Config& operator = ( Config const& other ); + virtual void dummy(); + public: + + Config() + {} + + Config( ConfigData const& data ) + : m_data( data ), + m_stream( openStream() ) + { + if( !data.testsOrTags.empty() ) { + TestSpecParser parser( ITagAliasRegistry::get() ); + for( std::size_t i = 0; i < data.testsOrTags.size(); ++i ) + parser.parse( data.testsOrTags[i] ); + m_testSpec = parser.testSpec(); + } + } + + virtual ~Config() {} + + std::string const& getFilename() const { + return m_data.outputFilename ; + } + + bool listTests() const { return m_data.listTests; } + bool listTestNamesOnly() const { return m_data.listTestNamesOnly; } + bool listTags() const { return m_data.listTags; } + bool listReporters() const { return m_data.listReporters; } + + std::string getProcessName() const { return m_data.processName; } + + std::vector const& getReporterNames() const { return m_data.reporterNames; } + std::vector const& getSectionsToRun() const CATCH_OVERRIDE { return m_data.sectionsToRun; } + + virtual TestSpec const& testSpec() const CATCH_OVERRIDE { return m_testSpec; } + + bool showHelp() const { return m_data.showHelp; } + + // IConfig interface + virtual bool allowThrows() const CATCH_OVERRIDE { return !m_data.noThrow; } + virtual std::ostream& stream() const CATCH_OVERRIDE { return m_stream->stream(); } + virtual std::string name() const CATCH_OVERRIDE { return m_data.name.empty() ? m_data.processName : m_data.name; } + virtual bool includeSuccessfulResults() const CATCH_OVERRIDE { return m_data.showSuccessfulTests; } + virtual bool warnAboutMissingAssertions() const CATCH_OVERRIDE { return m_data.warnings & WarnAbout::NoAssertions; } + virtual ShowDurations::OrNot showDurations() const CATCH_OVERRIDE { return m_data.showDurations; } + virtual RunTests::InWhatOrder runOrder() const CATCH_OVERRIDE { return m_data.runOrder; } + virtual unsigned int rngSeed() const CATCH_OVERRIDE { return m_data.rngSeed; } + virtual UseColour::YesOrNo useColour() const CATCH_OVERRIDE { return m_data.useColour; } + virtual bool shouldDebugBreak() const CATCH_OVERRIDE { return m_data.shouldDebugBreak; } + virtual int abortAfter() const CATCH_OVERRIDE { return m_data.abortAfter; } + virtual bool showInvisibles() const CATCH_OVERRIDE { return m_data.showInvisibles; } + + private: + + IStream const* openStream() { + if( m_data.outputFilename.empty() ) + return new CoutStream(); + else if( m_data.outputFilename[0] == '%' ) { + if( m_data.outputFilename == "%debug" ) + return new DebugOutStream(); + else + throw std::domain_error( "Unrecognised stream: " + m_data.outputFilename ); + } + else + return new FileStream( m_data.outputFilename ); + } + ConfigData m_data; + + CATCH_AUTO_PTR( IStream const ) m_stream; + TestSpec m_testSpec; + }; + +} // end namespace Catch + +// #included from: catch_clara.h +#define TWOBLUECUBES_CATCH_CLARA_H_INCLUDED + +// Use Catch's value for console width (store Clara's off to the side, if present) +#ifdef CLARA_CONFIG_CONSOLE_WIDTH +#define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CLARA_CONFIG_CONSOLE_WIDTH +#undef CLARA_CONFIG_CONSOLE_WIDTH +#endif +#define CLARA_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH + +// Declare Clara inside the Catch namespace +#define STITCH_CLARA_OPEN_NAMESPACE namespace Catch { +// #included from: ../external/clara.h + +// Version 0.0.2.4 + +// Only use header guard if we are not using an outer namespace +#if !defined(TWOBLUECUBES_CLARA_H_INCLUDED) || defined(STITCH_CLARA_OPEN_NAMESPACE) + +#ifndef STITCH_CLARA_OPEN_NAMESPACE +#define TWOBLUECUBES_CLARA_H_INCLUDED +#define STITCH_CLARA_OPEN_NAMESPACE +#define STITCH_CLARA_CLOSE_NAMESPACE +#else +#define STITCH_CLARA_CLOSE_NAMESPACE } +#endif + +#define STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE STITCH_CLARA_OPEN_NAMESPACE + +// ----------- #included from tbc_text_format.h ----------- + +// Only use header guard if we are not using an outer namespace +#if !defined(TBC_TEXT_FORMAT_H_INCLUDED) || defined(STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE) +#ifndef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE +#define TBC_TEXT_FORMAT_H_INCLUDED +#endif + +#include +#include +#include +#include +#include + +// Use optional outer namespace +#ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE +namespace STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE { +#endif + +namespace Tbc { + +#ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH + const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH; +#else + const unsigned int consoleWidth = 80; +#endif + + struct TextAttributes { + TextAttributes() + : initialIndent( std::string::npos ), + indent( 0 ), + width( consoleWidth-1 ), + tabChar( '\t' ) + {} + + TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; } + TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; } + TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; } + TextAttributes& setTabChar( char _value ) { tabChar = _value; return *this; } + + std::size_t initialIndent; // indent of first line, or npos + std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos + std::size_t width; // maximum width of text, including indent. Longer text will wrap + char tabChar; // If this char is seen the indent is changed to current pos + }; + + class Text { + public: + Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() ) + : attr( _attr ) + { + std::string wrappableChars = " [({.,/|\\-"; + std::size_t indent = _attr.initialIndent != std::string::npos + ? _attr.initialIndent + : _attr.indent; + std::string remainder = _str; + + while( !remainder.empty() ) { + if( lines.size() >= 1000 ) { + lines.push_back( "... message truncated due to excessive size" ); + return; + } + std::size_t tabPos = std::string::npos; + std::size_t width = (std::min)( remainder.size(), _attr.width - indent ); + std::size_t pos = remainder.find_first_of( '\n' ); + if( pos <= width ) { + width = pos; + } + pos = remainder.find_last_of( _attr.tabChar, width ); + if( pos != std::string::npos ) { + tabPos = pos; + if( remainder[width] == '\n' ) + width--; + remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 ); + } + + if( width == remainder.size() ) { + spliceLine( indent, remainder, width ); + } + else if( remainder[width] == '\n' ) { + spliceLine( indent, remainder, width ); + if( width <= 1 || remainder.size() != 1 ) + remainder = remainder.substr( 1 ); + indent = _attr.indent; + } + else { + pos = remainder.find_last_of( wrappableChars, width ); + if( pos != std::string::npos && pos > 0 ) { + spliceLine( indent, remainder, pos ); + if( remainder[0] == ' ' ) + remainder = remainder.substr( 1 ); + } + else { + spliceLine( indent, remainder, width-1 ); + lines.back() += "-"; + } + if( lines.size() == 1 ) + indent = _attr.indent; + if( tabPos != std::string::npos ) + indent += tabPos; + } + } + } + + void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) { + lines.push_back( std::string( _indent, ' ' ) + _remainder.substr( 0, _pos ) ); + _remainder = _remainder.substr( _pos ); + } + + typedef std::vector::const_iterator const_iterator; + + const_iterator begin() const { return lines.begin(); } + const_iterator end() const { return lines.end(); } + std::string const& last() const { return lines.back(); } + std::size_t size() const { return lines.size(); } + std::string const& operator[]( std::size_t _index ) const { return lines[_index]; } + std::string toString() const { + std::ostringstream oss; + oss << *this; + return oss.str(); + } + + inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) { + for( Text::const_iterator it = _text.begin(), itEnd = _text.end(); + it != itEnd; ++it ) { + if( it != _text.begin() ) + _stream << "\n"; + _stream << *it; + } + return _stream; + } + + private: + std::string str; + TextAttributes attr; + std::vector lines; + }; + +} // end namespace Tbc + +#ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE +} // end outer namespace +#endif + +#endif // TBC_TEXT_FORMAT_H_INCLUDED + +// ----------- end of #include from tbc_text_format.h ----------- +// ........... back in clara.h + +#undef STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE + +// ----------- #included from clara_compilers.h ----------- + +#ifndef TWOBLUECUBES_CLARA_COMPILERS_H_INCLUDED +#define TWOBLUECUBES_CLARA_COMPILERS_H_INCLUDED + +// Detect a number of compiler features - mostly C++11/14 conformance - by compiler +// The following features are defined: +// +// CLARA_CONFIG_CPP11_NULLPTR : is nullptr supported? +// CLARA_CONFIG_CPP11_NOEXCEPT : is noexcept supported? +// CLARA_CONFIG_CPP11_GENERATED_METHODS : The delete and default keywords for compiler generated methods +// CLARA_CONFIG_CPP11_OVERRIDE : is override supported? +// CLARA_CONFIG_CPP11_UNIQUE_PTR : is unique_ptr supported (otherwise use auto_ptr) + +// CLARA_CONFIG_CPP11_OR_GREATER : Is C++11 supported? + +// CLARA_CONFIG_VARIADIC_MACROS : are variadic macros supported? + +// In general each macro has a _NO_ form +// (e.g. CLARA_CONFIG_CPP11_NO_NULLPTR) which disables the feature. +// Many features, at point of detection, define an _INTERNAL_ macro, so they +// can be combined, en-mass, with the _NO_ forms later. + +// All the C++11 features can be disabled with CLARA_CONFIG_NO_CPP11 + +#ifdef __clang__ + +#if __has_feature(cxx_nullptr) +#define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR +#endif + +#if __has_feature(cxx_noexcept) +#define CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT +#endif + +#endif // __clang__ + +//////////////////////////////////////////////////////////////////////////////// +// GCC +#ifdef __GNUC__ + +#if __GNUC__ == 4 && __GNUC_MINOR__ >= 6 && defined(__GXX_EXPERIMENTAL_CXX0X__) +#define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR +#endif + +// - otherwise more recent versions define __cplusplus >= 201103L +// and will get picked up below + +#endif // __GNUC__ + +//////////////////////////////////////////////////////////////////////////////// +// Visual C++ +#ifdef _MSC_VER + +#if (_MSC_VER >= 1600) +#define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR +#define CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR +#endif + +#if (_MSC_VER >= 1900 ) // (VC++ 13 (VS2015)) +#define CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT +#define CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS +#endif + +#endif // _MSC_VER + +//////////////////////////////////////////////////////////////////////////////// +// C++ language feature support + +// catch all support for C++11 +#if defined(__cplusplus) && __cplusplus >= 201103L + +#define CLARA_CPP11_OR_GREATER + +#if !defined(CLARA_INTERNAL_CONFIG_CPP11_NULLPTR) +#define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR +#endif + +#ifndef CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT +#define CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT +#endif + +#ifndef CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS +#define CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS +#endif + +#if !defined(CLARA_INTERNAL_CONFIG_CPP11_OVERRIDE) +#define CLARA_INTERNAL_CONFIG_CPP11_OVERRIDE +#endif +#if !defined(CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) +#define CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR +#endif + +#endif // __cplusplus >= 201103L + +// Now set the actual defines based on the above + anything the user has configured +#if defined(CLARA_INTERNAL_CONFIG_CPP11_NULLPTR) && !defined(CLARA_CONFIG_CPP11_NO_NULLPTR) && !defined(CLARA_CONFIG_CPP11_NULLPTR) && !defined(CLARA_CONFIG_NO_CPP11) +#define CLARA_CONFIG_CPP11_NULLPTR +#endif +#if defined(CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT) && !defined(CLARA_CONFIG_CPP11_NO_NOEXCEPT) && !defined(CLARA_CONFIG_CPP11_NOEXCEPT) && !defined(CLARA_CONFIG_NO_CPP11) +#define CLARA_CONFIG_CPP11_NOEXCEPT +#endif +#if defined(CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS) && !defined(CLARA_CONFIG_CPP11_NO_GENERATED_METHODS) && !defined(CLARA_CONFIG_CPP11_GENERATED_METHODS) && !defined(CLARA_CONFIG_NO_CPP11) +#define CLARA_CONFIG_CPP11_GENERATED_METHODS +#endif +#if defined(CLARA_INTERNAL_CONFIG_CPP11_OVERRIDE) && !defined(CLARA_CONFIG_NO_OVERRIDE) && !defined(CLARA_CONFIG_CPP11_OVERRIDE) && !defined(CLARA_CONFIG_NO_CPP11) +#define CLARA_CONFIG_CPP11_OVERRIDE +#endif +#if defined(CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) && !defined(CLARA_CONFIG_NO_UNIQUE_PTR) && !defined(CLARA_CONFIG_CPP11_UNIQUE_PTR) && !defined(CLARA_CONFIG_NO_CPP11) +#define CLARA_CONFIG_CPP11_UNIQUE_PTR +#endif + +// noexcept support: +#if defined(CLARA_CONFIG_CPP11_NOEXCEPT) && !defined(CLARA_NOEXCEPT) +#define CLARA_NOEXCEPT noexcept +# define CLARA_NOEXCEPT_IS(x) noexcept(x) +#else +#define CLARA_NOEXCEPT throw() +# define CLARA_NOEXCEPT_IS(x) +#endif + +// nullptr support +#ifdef CLARA_CONFIG_CPP11_NULLPTR +#define CLARA_NULL nullptr +#else +#define CLARA_NULL NULL +#endif + +// override support +#ifdef CLARA_CONFIG_CPP11_OVERRIDE +#define CLARA_OVERRIDE override +#else +#define CLARA_OVERRIDE +#endif + +// unique_ptr support +#ifdef CLARA_CONFIG_CPP11_UNIQUE_PTR +# define CLARA_AUTO_PTR( T ) std::unique_ptr +#else +# define CLARA_AUTO_PTR( T ) std::auto_ptr +#endif + +#endif // TWOBLUECUBES_CLARA_COMPILERS_H_INCLUDED + +// ----------- end of #include from clara_compilers.h ----------- +// ........... back in clara.h + +#include +#include +#include + +#if defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) +#define CLARA_PLATFORM_WINDOWS +#endif + +// Use optional outer namespace +#ifdef STITCH_CLARA_OPEN_NAMESPACE +STITCH_CLARA_OPEN_NAMESPACE +#endif + +namespace Clara { + + struct UnpositionalTag {}; + + extern UnpositionalTag _; + +#ifdef CLARA_CONFIG_MAIN + UnpositionalTag _; +#endif + + namespace Detail { + +#ifdef CLARA_CONSOLE_WIDTH + const unsigned int consoleWidth = CLARA_CONFIG_CONSOLE_WIDTH; +#else + const unsigned int consoleWidth = 80; +#endif + + using namespace Tbc; + + inline bool startsWith( std::string const& str, std::string const& prefix ) { + return str.size() >= prefix.size() && str.substr( 0, prefix.size() ) == prefix; + } + + template struct RemoveConstRef{ typedef T type; }; + template struct RemoveConstRef{ typedef T type; }; + template struct RemoveConstRef{ typedef T type; }; + template struct RemoveConstRef{ typedef T type; }; + + template struct IsBool { static const bool value = false; }; + template<> struct IsBool { static const bool value = true; }; + + template + void convertInto( std::string const& _source, T& _dest ) { + std::stringstream ss; + ss << _source; + ss >> _dest; + if( ss.fail() ) + throw std::runtime_error( "Unable to convert " + _source + " to destination type" ); + } + inline void convertInto( std::string const& _source, std::string& _dest ) { + _dest = _source; + } + char toLowerCh(char c) { + return static_cast( std::tolower( c ) ); + } + inline void convertInto( std::string const& _source, bool& _dest ) { + std::string sourceLC = _source; + std::transform( sourceLC.begin(), sourceLC.end(), sourceLC.begin(), toLowerCh ); + if( sourceLC == "y" || sourceLC == "1" || sourceLC == "true" || sourceLC == "yes" || sourceLC == "on" ) + _dest = true; + else if( sourceLC == "n" || sourceLC == "0" || sourceLC == "false" || sourceLC == "no" || sourceLC == "off" ) + _dest = false; + else + throw std::runtime_error( "Expected a boolean value but did not recognise:\n '" + _source + "'" ); + } + + template + struct IArgFunction { + virtual ~IArgFunction() {} +#ifdef CLARA_CONFIG_CPP11_GENERATED_METHODS + IArgFunction() = default; + IArgFunction( IArgFunction const& ) = default; +#endif + virtual void set( ConfigT& config, std::string const& value ) const = 0; + virtual bool takesArg() const = 0; + virtual IArgFunction* clone() const = 0; + }; + + template + class BoundArgFunction { + public: + BoundArgFunction() : functionObj( CLARA_NULL ) {} + BoundArgFunction( IArgFunction* _functionObj ) : functionObj( _functionObj ) {} + BoundArgFunction( BoundArgFunction const& other ) : functionObj( other.functionObj ? other.functionObj->clone() : CLARA_NULL ) {} + BoundArgFunction& operator = ( BoundArgFunction const& other ) { + IArgFunction* newFunctionObj = other.functionObj ? other.functionObj->clone() : CLARA_NULL; + delete functionObj; + functionObj = newFunctionObj; + return *this; + } + ~BoundArgFunction() { delete functionObj; } + + void set( ConfigT& config, std::string const& value ) const { + functionObj->set( config, value ); + } + bool takesArg() const { return functionObj->takesArg(); } + + bool isSet() const { + return functionObj != CLARA_NULL; + } + private: + IArgFunction* functionObj; + }; + + template + struct NullBinder : IArgFunction{ + virtual void set( C&, std::string const& ) const {} + virtual bool takesArg() const { return true; } + virtual IArgFunction* clone() const { return new NullBinder( *this ); } + }; + + template + struct BoundDataMember : IArgFunction{ + BoundDataMember( M C::* _member ) : member( _member ) {} + virtual void set( C& p, std::string const& stringValue ) const { + convertInto( stringValue, p.*member ); + } + virtual bool takesArg() const { return !IsBool::value; } + virtual IArgFunction* clone() const { return new BoundDataMember( *this ); } + M C::* member; + }; + template + struct BoundUnaryMethod : IArgFunction{ + BoundUnaryMethod( void (C::*_member)( M ) ) : member( _member ) {} + virtual void set( C& p, std::string const& stringValue ) const { + typename RemoveConstRef::type value; + convertInto( stringValue, value ); + (p.*member)( value ); + } + virtual bool takesArg() const { return !IsBool::value; } + virtual IArgFunction* clone() const { return new BoundUnaryMethod( *this ); } + void (C::*member)( M ); + }; + template + struct BoundNullaryMethod : IArgFunction{ + BoundNullaryMethod( void (C::*_member)() ) : member( _member ) {} + virtual void set( C& p, std::string const& stringValue ) const { + bool value; + convertInto( stringValue, value ); + if( value ) + (p.*member)(); + } + virtual bool takesArg() const { return false; } + virtual IArgFunction* clone() const { return new BoundNullaryMethod( *this ); } + void (C::*member)(); + }; + + template + struct BoundUnaryFunction : IArgFunction{ + BoundUnaryFunction( void (*_function)( C& ) ) : function( _function ) {} + virtual void set( C& obj, std::string const& stringValue ) const { + bool value; + convertInto( stringValue, value ); + if( value ) + function( obj ); + } + virtual bool takesArg() const { return false; } + virtual IArgFunction* clone() const { return new BoundUnaryFunction( *this ); } + void (*function)( C& ); + }; + + template + struct BoundBinaryFunction : IArgFunction{ + BoundBinaryFunction( void (*_function)( C&, T ) ) : function( _function ) {} + virtual void set( C& obj, std::string const& stringValue ) const { + typename RemoveConstRef::type value; + convertInto( stringValue, value ); + function( obj, value ); + } + virtual bool takesArg() const { return !IsBool::value; } + virtual IArgFunction* clone() const { return new BoundBinaryFunction( *this ); } + void (*function)( C&, T ); + }; + + } // namespace Detail + + inline std::vector argsToVector( int argc, char const* const* const argv ) { + std::vector args( static_cast( argc ) ); + for( std::size_t i = 0; i < static_cast( argc ); ++i ) + args[i] = argv[i]; + + return args; + } + + class Parser { + enum Mode { None, MaybeShortOpt, SlashOpt, ShortOpt, LongOpt, Positional }; + Mode mode; + std::size_t from; + bool inQuotes; + public: + + struct Token { + enum Type { Positional, ShortOpt, LongOpt }; + Token( Type _type, std::string const& _data ) : type( _type ), data( _data ) {} + Type type; + std::string data; + }; + + Parser() : mode( None ), from( 0 ), inQuotes( false ){} + + void parseIntoTokens( std::vector const& args, std::vector& tokens ) { + const std::string doubleDash = "--"; + for( std::size_t i = 1; i < args.size() && args[i] != doubleDash; ++i ) + parseIntoTokens( args[i], tokens); + } + + void parseIntoTokens( std::string const& arg, std::vector& tokens ) { + for( std::size_t i = 0; i < arg.size(); ++i ) { + char c = arg[i]; + if( c == '"' ) + inQuotes = !inQuotes; + mode = handleMode( i, c, arg, tokens ); + } + mode = handleMode( arg.size(), '\0', arg, tokens ); + } + Mode handleMode( std::size_t i, char c, std::string const& arg, std::vector& tokens ) { + switch( mode ) { + case None: return handleNone( i, c ); + case MaybeShortOpt: return handleMaybeShortOpt( i, c ); + case ShortOpt: + case LongOpt: + case SlashOpt: return handleOpt( i, c, arg, tokens ); + case Positional: return handlePositional( i, c, arg, tokens ); + default: throw std::logic_error( "Unknown mode" ); + } + } + + Mode handleNone( std::size_t i, char c ) { + if( inQuotes ) { + from = i; + return Positional; + } + switch( c ) { + case '-': return MaybeShortOpt; +#ifdef CLARA_PLATFORM_WINDOWS + case '/': from = i+1; return SlashOpt; +#endif + default: from = i; return Positional; + } + } + Mode handleMaybeShortOpt( std::size_t i, char c ) { + switch( c ) { + case '-': from = i+1; return LongOpt; + default: from = i; return ShortOpt; + } + } + + Mode handleOpt( std::size_t i, char c, std::string const& arg, std::vector& tokens ) { + if( std::string( ":=\0", 3 ).find( c ) == std::string::npos ) + return mode; + + std::string optName = arg.substr( from, i-from ); + if( mode == ShortOpt ) + for( std::size_t j = 0; j < optName.size(); ++j ) + tokens.push_back( Token( Token::ShortOpt, optName.substr( j, 1 ) ) ); + else if( mode == SlashOpt && optName.size() == 1 ) + tokens.push_back( Token( Token::ShortOpt, optName ) ); + else + tokens.push_back( Token( Token::LongOpt, optName ) ); + return None; + } + Mode handlePositional( std::size_t i, char c, std::string const& arg, std::vector& tokens ) { + if( inQuotes || std::string( "\0", 1 ).find( c ) == std::string::npos ) + return mode; + + std::string data = arg.substr( from, i-from ); + tokens.push_back( Token( Token::Positional, data ) ); + return None; + } + }; + + template + struct CommonArgProperties { + CommonArgProperties() {} + CommonArgProperties( Detail::BoundArgFunction const& _boundField ) : boundField( _boundField ) {} + + Detail::BoundArgFunction boundField; + std::string description; + std::string detail; + std::string placeholder; // Only value if boundField takes an arg + + bool takesArg() const { + return !placeholder.empty(); + } + void validate() const { + if( !boundField.isSet() ) + throw std::logic_error( "option not bound" ); + } + }; + struct OptionArgProperties { + std::vector shortNames; + std::string longName; + + bool hasShortName( std::string const& shortName ) const { + return std::find( shortNames.begin(), shortNames.end(), shortName ) != shortNames.end(); + } + bool hasLongName( std::string const& _longName ) const { + return _longName == longName; + } + }; + struct PositionalArgProperties { + PositionalArgProperties() : position( -1 ) {} + int position; // -1 means non-positional (floating) + + bool isFixedPositional() const { + return position != -1; + } + }; + + template + class CommandLine { + + struct Arg : CommonArgProperties, OptionArgProperties, PositionalArgProperties { + Arg() {} + Arg( Detail::BoundArgFunction const& _boundField ) : CommonArgProperties( _boundField ) {} + + using CommonArgProperties::placeholder; // !TBD + + std::string dbgName() const { + if( !longName.empty() ) + return "--" + longName; + if( !shortNames.empty() ) + return "-" + shortNames[0]; + return "positional args"; + } + std::string commands() const { + std::ostringstream oss; + bool first = true; + std::vector::const_iterator it = shortNames.begin(), itEnd = shortNames.end(); + for(; it != itEnd; ++it ) { + if( first ) + first = false; + else + oss << ", "; + oss << "-" << *it; + } + if( !longName.empty() ) { + if( !first ) + oss << ", "; + oss << "--" << longName; + } + if( !placeholder.empty() ) + oss << " <" << placeholder << ">"; + return oss.str(); + } + }; + + typedef CLARA_AUTO_PTR( Arg ) ArgAutoPtr; + + friend void addOptName( Arg& arg, std::string const& optName ) + { + if( optName.empty() ) + return; + if( Detail::startsWith( optName, "--" ) ) { + if( !arg.longName.empty() ) + throw std::logic_error( "Only one long opt may be specified. '" + + arg.longName + + "' already specified, now attempting to add '" + + optName + "'" ); + arg.longName = optName.substr( 2 ); + } + else if( Detail::startsWith( optName, "-" ) ) + arg.shortNames.push_back( optName.substr( 1 ) ); + else + throw std::logic_error( "option must begin with - or --. Option was: '" + optName + "'" ); + } + friend void setPositionalArg( Arg& arg, int position ) + { + arg.position = position; + } + + class ArgBuilder { + public: + ArgBuilder( Arg* arg ) : m_arg( arg ) {} + + // Bind a non-boolean data member (requires placeholder string) + template + void bind( M C::* field, std::string const& placeholder ) { + m_arg->boundField = new Detail::BoundDataMember( field ); + m_arg->placeholder = placeholder; + } + // Bind a boolean data member (no placeholder required) + template + void bind( bool C::* field ) { + m_arg->boundField = new Detail::BoundDataMember( field ); + } + + // Bind a method taking a single, non-boolean argument (requires a placeholder string) + template + void bind( void (C::* unaryMethod)( M ), std::string const& placeholder ) { + m_arg->boundField = new Detail::BoundUnaryMethod( unaryMethod ); + m_arg->placeholder = placeholder; + } + + // Bind a method taking a single, boolean argument (no placeholder string required) + template + void bind( void (C::* unaryMethod)( bool ) ) { + m_arg->boundField = new Detail::BoundUnaryMethod( unaryMethod ); + } + + // Bind a method that takes no arguments (will be called if opt is present) + template + void bind( void (C::* nullaryMethod)() ) { + m_arg->boundField = new Detail::BoundNullaryMethod( nullaryMethod ); + } + + // Bind a free function taking a single argument - the object to operate on (no placeholder string required) + template + void bind( void (* unaryFunction)( C& ) ) { + m_arg->boundField = new Detail::BoundUnaryFunction( unaryFunction ); + } + + // Bind a free function taking a single argument - the object to operate on (requires a placeholder string) + template + void bind( void (* binaryFunction)( C&, T ), std::string const& placeholder ) { + m_arg->boundField = new Detail::BoundBinaryFunction( binaryFunction ); + m_arg->placeholder = placeholder; + } + + ArgBuilder& describe( std::string const& description ) { + m_arg->description = description; + return *this; + } + ArgBuilder& detail( std::string const& detail ) { + m_arg->detail = detail; + return *this; + } + + protected: + Arg* m_arg; + }; + + class OptBuilder : public ArgBuilder { + public: + OptBuilder( Arg* arg ) : ArgBuilder( arg ) {} + OptBuilder( OptBuilder& other ) : ArgBuilder( other ) {} + + OptBuilder& operator[]( std::string const& optName ) { + addOptName( *ArgBuilder::m_arg, optName ); + return *this; + } + }; + + public: + + CommandLine() + : m_boundProcessName( new Detail::NullBinder() ), + m_highestSpecifiedArgPosition( 0 ), + m_throwOnUnrecognisedTokens( false ) + {} + CommandLine( CommandLine const& other ) + : m_boundProcessName( other.m_boundProcessName ), + m_options ( other.m_options ), + m_positionalArgs( other.m_positionalArgs ), + m_highestSpecifiedArgPosition( other.m_highestSpecifiedArgPosition ), + m_throwOnUnrecognisedTokens( other.m_throwOnUnrecognisedTokens ) + { + if( other.m_floatingArg.get() ) + m_floatingArg.reset( new Arg( *other.m_floatingArg ) ); + } + + CommandLine& setThrowOnUnrecognisedTokens( bool shouldThrow = true ) { + m_throwOnUnrecognisedTokens = shouldThrow; + return *this; + } + + OptBuilder operator[]( std::string const& optName ) { + m_options.push_back( Arg() ); + addOptName( m_options.back(), optName ); + OptBuilder builder( &m_options.back() ); + return builder; + } + + ArgBuilder operator[]( int position ) { + m_positionalArgs.insert( std::make_pair( position, Arg() ) ); + if( position > m_highestSpecifiedArgPosition ) + m_highestSpecifiedArgPosition = position; + setPositionalArg( m_positionalArgs[position], position ); + ArgBuilder builder( &m_positionalArgs[position] ); + return builder; + } + + // Invoke this with the _ instance + ArgBuilder operator[]( UnpositionalTag ) { + if( m_floatingArg.get() ) + throw std::logic_error( "Only one unpositional argument can be added" ); + m_floatingArg.reset( new Arg() ); + ArgBuilder builder( m_floatingArg.get() ); + return builder; + } + + template + void bindProcessName( M C::* field ) { + m_boundProcessName = new Detail::BoundDataMember( field ); + } + template + void bindProcessName( void (C::*_unaryMethod)( M ) ) { + m_boundProcessName = new Detail::BoundUnaryMethod( _unaryMethod ); + } + + void optUsage( std::ostream& os, std::size_t indent = 0, std::size_t width = Detail::consoleWidth ) const { + typename std::vector::const_iterator itBegin = m_options.begin(), itEnd = m_options.end(), it; + std::size_t maxWidth = 0; + for( it = itBegin; it != itEnd; ++it ) + maxWidth = (std::max)( maxWidth, it->commands().size() ); + + for( it = itBegin; it != itEnd; ++it ) { + Detail::Text usage( it->commands(), Detail::TextAttributes() + .setWidth( maxWidth+indent ) + .setIndent( indent ) ); + Detail::Text desc( it->description, Detail::TextAttributes() + .setWidth( width - maxWidth - 3 ) ); + + for( std::size_t i = 0; i < (std::max)( usage.size(), desc.size() ); ++i ) { + std::string usageCol = i < usage.size() ? usage[i] : ""; + os << usageCol; + + if( i < desc.size() && !desc[i].empty() ) + os << std::string( indent + 2 + maxWidth - usageCol.size(), ' ' ) + << desc[i]; + os << "\n"; + } + } + } + std::string optUsage() const { + std::ostringstream oss; + optUsage( oss ); + return oss.str(); + } + + void argSynopsis( std::ostream& os ) const { + for( int i = 1; i <= m_highestSpecifiedArgPosition; ++i ) { + if( i > 1 ) + os << " "; + typename std::map::const_iterator it = m_positionalArgs.find( i ); + if( it != m_positionalArgs.end() ) + os << "<" << it->second.placeholder << ">"; + else if( m_floatingArg.get() ) + os << "<" << m_floatingArg->placeholder << ">"; + else + throw std::logic_error( "non consecutive positional arguments with no floating args" ); + } + // !TBD No indication of mandatory args + if( m_floatingArg.get() ) { + if( m_highestSpecifiedArgPosition > 1 ) + os << " "; + os << "[<" << m_floatingArg->placeholder << "> ...]"; + } + } + std::string argSynopsis() const { + std::ostringstream oss; + argSynopsis( oss ); + return oss.str(); + } + + void usage( std::ostream& os, std::string const& procName ) const { + validate(); + os << "usage:\n " << procName << " "; + argSynopsis( os ); + if( !m_options.empty() ) { + os << " [options]\n\nwhere options are: \n"; + optUsage( os, 2 ); + } + os << "\n"; + } + std::string usage( std::string const& procName ) const { + std::ostringstream oss; + usage( oss, procName ); + return oss.str(); + } + + ConfigT parse( std::vector const& args ) const { + ConfigT config; + parseInto( args, config ); + return config; + } + + std::vector parseInto( std::vector const& args, ConfigT& config ) const { + std::string processName = args.empty() ? std::string() : args[0]; + std::size_t lastSlash = processName.find_last_of( "/\\" ); + if( lastSlash != std::string::npos ) + processName = processName.substr( lastSlash+1 ); + m_boundProcessName.set( config, processName ); + std::vector tokens; + Parser parser; + parser.parseIntoTokens( args, tokens ); + return populate( tokens, config ); + } + + std::vector populate( std::vector const& tokens, ConfigT& config ) const { + validate(); + std::vector unusedTokens = populateOptions( tokens, config ); + unusedTokens = populateFixedArgs( unusedTokens, config ); + unusedTokens = populateFloatingArgs( unusedTokens, config ); + return unusedTokens; + } + + std::vector populateOptions( std::vector const& tokens, ConfigT& config ) const { + std::vector unusedTokens; + std::vector errors; + for( std::size_t i = 0; i < tokens.size(); ++i ) { + Parser::Token const& token = tokens[i]; + typename std::vector::const_iterator it = m_options.begin(), itEnd = m_options.end(); + for(; it != itEnd; ++it ) { + Arg const& arg = *it; + + try { + if( ( token.type == Parser::Token::ShortOpt && arg.hasShortName( token.data ) ) || + ( token.type == Parser::Token::LongOpt && arg.hasLongName( token.data ) ) ) { + if( arg.takesArg() ) { + if( i == tokens.size()-1 || tokens[i+1].type != Parser::Token::Positional ) + errors.push_back( "Expected argument to option: " + token.data ); + else + arg.boundField.set( config, tokens[++i].data ); + } + else { + arg.boundField.set( config, "true" ); + } + break; + } + } + catch( std::exception& ex ) { + errors.push_back( std::string( ex.what() ) + "\n- while parsing: (" + arg.commands() + ")" ); + } + } + if( it == itEnd ) { + if( token.type == Parser::Token::Positional || !m_throwOnUnrecognisedTokens ) + unusedTokens.push_back( token ); + else if( errors.empty() && m_throwOnUnrecognisedTokens ) + errors.push_back( "unrecognised option: " + token.data ); + } + } + if( !errors.empty() ) { + std::ostringstream oss; + for( std::vector::const_iterator it = errors.begin(), itEnd = errors.end(); + it != itEnd; + ++it ) { + if( it != errors.begin() ) + oss << "\n"; + oss << *it; + } + throw std::runtime_error( oss.str() ); + } + return unusedTokens; + } + std::vector populateFixedArgs( std::vector const& tokens, ConfigT& config ) const { + std::vector unusedTokens; + int position = 1; + for( std::size_t i = 0; i < tokens.size(); ++i ) { + Parser::Token const& token = tokens[i]; + typename std::map::const_iterator it = m_positionalArgs.find( position ); + if( it != m_positionalArgs.end() ) + it->second.boundField.set( config, token.data ); + else + unusedTokens.push_back( token ); + if( token.type == Parser::Token::Positional ) + position++; + } + return unusedTokens; + } + std::vector populateFloatingArgs( std::vector const& tokens, ConfigT& config ) const { + if( !m_floatingArg.get() ) + return tokens; + std::vector unusedTokens; + for( std::size_t i = 0; i < tokens.size(); ++i ) { + Parser::Token const& token = tokens[i]; + if( token.type == Parser::Token::Positional ) + m_floatingArg->boundField.set( config, token.data ); + else + unusedTokens.push_back( token ); + } + return unusedTokens; + } + + void validate() const + { + if( m_options.empty() && m_positionalArgs.empty() && !m_floatingArg.get() ) + throw std::logic_error( "No options or arguments specified" ); + + for( typename std::vector::const_iterator it = m_options.begin(), + itEnd = m_options.end(); + it != itEnd; ++it ) + it->validate(); + } + + private: + Detail::BoundArgFunction m_boundProcessName; + std::vector m_options; + std::map m_positionalArgs; + ArgAutoPtr m_floatingArg; + int m_highestSpecifiedArgPosition; + bool m_throwOnUnrecognisedTokens; + }; + +} // end namespace Clara + +STITCH_CLARA_CLOSE_NAMESPACE +#undef STITCH_CLARA_OPEN_NAMESPACE +#undef STITCH_CLARA_CLOSE_NAMESPACE + +#endif // TWOBLUECUBES_CLARA_H_INCLUDED +#undef STITCH_CLARA_OPEN_NAMESPACE + +// Restore Clara's value for console width, if present +#ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH +#define CLARA_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH +#undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH +#endif + +#include +#include + +namespace Catch { + + inline void abortAfterFirst( ConfigData& config ) { config.abortAfter = 1; } + inline void abortAfterX( ConfigData& config, int x ) { + if( x < 1 ) + throw std::runtime_error( "Value after -x or --abortAfter must be greater than zero" ); + config.abortAfter = x; + } + inline void addTestOrTags( ConfigData& config, std::string const& _testSpec ) { config.testsOrTags.push_back( _testSpec ); } + inline void addSectionToRun( ConfigData& config, std::string const& sectionName ) { config.sectionsToRun.push_back( sectionName ); } + inline void addReporterName( ConfigData& config, std::string const& _reporterName ) { config.reporterNames.push_back( _reporterName ); } + + inline void addWarning( ConfigData& config, std::string const& _warning ) { + if( _warning == "NoAssertions" ) + config.warnings = static_cast( config.warnings | WarnAbout::NoAssertions ); + else + throw std::runtime_error( "Unrecognised warning: '" + _warning + '\'' ); + } + inline void setOrder( ConfigData& config, std::string const& order ) { + if( startsWith( "declared", order ) ) + config.runOrder = RunTests::InDeclarationOrder; + else if( startsWith( "lexical", order ) ) + config.runOrder = RunTests::InLexicographicalOrder; + else if( startsWith( "random", order ) ) + config.runOrder = RunTests::InRandomOrder; + else + throw std::runtime_error( "Unrecognised ordering: '" + order + '\'' ); + } + inline void setRngSeed( ConfigData& config, std::string const& seed ) { + if( seed == "time" ) { + config.rngSeed = static_cast( std::time(0) ); + } + else { + std::stringstream ss; + ss << seed; + ss >> config.rngSeed; + if( ss.fail() ) + throw std::runtime_error( "Argument to --rng-seed should be the word 'time' or a number" ); + } + } + inline void setVerbosity( ConfigData& config, int level ) { + // !TBD: accept strings? + config.verbosity = static_cast( level ); + } + inline void setShowDurations( ConfigData& config, bool _showDurations ) { + config.showDurations = _showDurations + ? ShowDurations::Always + : ShowDurations::Never; + } + inline void setUseColour( ConfigData& config, std::string const& value ) { + std::string mode = toLower( value ); + + if( mode == "yes" ) + config.useColour = UseColour::Yes; + else if( mode == "no" ) + config.useColour = UseColour::No; + else if( mode == "auto" ) + config.useColour = UseColour::Auto; + else + throw std::runtime_error( "colour mode must be one of: auto, yes or no" ); + } + inline void forceColour( ConfigData& config ) { + config.useColour = UseColour::Yes; + } + inline void loadTestNamesFromFile( ConfigData& config, std::string const& _filename ) { + std::ifstream f( _filename.c_str() ); + if( !f.is_open() ) + throw std::domain_error( "Unable to load input file: " + _filename ); + + std::string line; + while( std::getline( f, line ) ) { + line = trim(line); + if( !line.empty() && !startsWith( line, '#' ) ) { + if( !startsWith( line, '"' ) ) + line = '"' + line + '"'; + addTestOrTags( config, line + ',' ); + } + } + } + + inline Clara::CommandLine makeCommandLineParser() { + + using namespace Clara; + CommandLine cli; + + cli.bindProcessName( &ConfigData::processName ); + + cli["-?"]["-h"]["--help"] + .describe( "display usage information" ) + .bind( &ConfigData::showHelp ); + + cli["-l"]["--list-tests"] + .describe( "list all/matching test cases" ) + .bind( &ConfigData::listTests ); + + cli["-t"]["--list-tags"] + .describe( "list all/matching tags" ) + .bind( &ConfigData::listTags ); + + cli["-s"]["--success"] + .describe( "include successful tests in output" ) + .bind( &ConfigData::showSuccessfulTests ); + + cli["-b"]["--break"] + .describe( "break into debugger on failure" ) + .bind( &ConfigData::shouldDebugBreak ); + + cli["-e"]["--nothrow"] + .describe( "skip exception tests" ) + .bind( &ConfigData::noThrow ); + + cli["-i"]["--invisibles"] + .describe( "show invisibles (tabs, newlines)" ) + .bind( &ConfigData::showInvisibles ); + + cli["-o"]["--out"] + .describe( "output filename" ) + .bind( &ConfigData::outputFilename, "filename" ); + + cli["-r"]["--reporter"] +// .placeholder( "name[:filename]" ) + .describe( "reporter to use (defaults to console)" ) + .bind( &addReporterName, "name" ); + + cli["-n"]["--name"] + .describe( "suite name" ) + .bind( &ConfigData::name, "name" ); + + cli["-a"]["--abort"] + .describe( "abort at first failure" ) + .bind( &abortAfterFirst ); + + cli["-x"]["--abortx"] + .describe( "abort after x failures" ) + .bind( &abortAfterX, "no. failures" ); + + cli["-w"]["--warn"] + .describe( "enable warnings" ) + .bind( &addWarning, "warning name" ); + +// - needs updating if reinstated +// cli.into( &setVerbosity ) +// .describe( "level of verbosity (0=no output)" ) +// .shortOpt( "v") +// .longOpt( "verbosity" ) +// .placeholder( "level" ); + + cli[_] + .describe( "which test or tests to use" ) + .bind( &addTestOrTags, "test name, pattern or tags" ); + + cli["-d"]["--durations"] + .describe( "show test durations" ) + .bind( &setShowDurations, "yes|no" ); + + cli["-f"]["--input-file"] + .describe( "load test names to run from a file" ) + .bind( &loadTestNamesFromFile, "filename" ); + + cli["-#"]["--filenames-as-tags"] + .describe( "adds a tag for the filename" ) + .bind( &ConfigData::filenamesAsTags ); + + cli["-c"]["--section"] + .describe( "specify section to run" ) + .bind( &addSectionToRun, "section name" ); + + // Less common commands which don't have a short form + cli["--list-test-names-only"] + .describe( "list all/matching test cases names only" ) + .bind( &ConfigData::listTestNamesOnly ); + + cli["--list-reporters"] + .describe( "list all reporters" ) + .bind( &ConfigData::listReporters ); + + cli["--order"] + .describe( "test case order (defaults to decl)" ) + .bind( &setOrder, "decl|lex|rand" ); + + cli["--rng-seed"] + .describe( "set a specific seed for random numbers" ) + .bind( &setRngSeed, "'time'|number" ); + + cli["--force-colour"] + .describe( "force colourised output (deprecated)" ) + .bind( &forceColour ); + + cli["--use-colour"] + .describe( "should output be colourised" ) + .bind( &setUseColour, "yes|no" ); + + return cli; + } + +} // end namespace Catch + +// #included from: internal/catch_list.hpp +#define TWOBLUECUBES_CATCH_LIST_HPP_INCLUDED + +// #included from: catch_text.h +#define TWOBLUECUBES_CATCH_TEXT_H_INCLUDED + +#define TBC_TEXT_FORMAT_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH + +#define CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE Catch +// #included from: ../external/tbc_text_format.h +// Only use header guard if we are not using an outer namespace +#ifndef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE +# ifdef TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED +# ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED +# define TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED +# endif +# else +# define TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED +# endif +#endif +#ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED +#include +#include +#include + +// Use optional outer namespace +#ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE +namespace CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE { +#endif + +namespace Tbc { + +#ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH + const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH; +#else + const unsigned int consoleWidth = 80; +#endif + + struct TextAttributes { + TextAttributes() + : initialIndent( std::string::npos ), + indent( 0 ), + width( consoleWidth-1 ) + {} + + TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; } + TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; } + TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; } + + std::size_t initialIndent; // indent of first line, or npos + std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos + std::size_t width; // maximum width of text, including indent. Longer text will wrap + }; + + class Text { + public: + Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() ) + : attr( _attr ) + { + const std::string wrappableBeforeChars = "[({<\t"; + const std::string wrappableAfterChars = "])}>-,./|\\"; + const std::string wrappableInsteadOfChars = " \n\r"; + std::string indent = _attr.initialIndent != std::string::npos + ? std::string( _attr.initialIndent, ' ' ) + : std::string( _attr.indent, ' ' ); + + typedef std::string::const_iterator iterator; + iterator it = _str.begin(); + const iterator strEnd = _str.end(); + + while( it != strEnd ) { + + if( lines.size() >= 1000 ) { + lines.push_back( "... message truncated due to excessive size" ); + return; + } + + std::string suffix; + std::size_t width = (std::min)( static_cast( strEnd-it ), _attr.width-static_cast( indent.size() ) ); + iterator itEnd = it+width; + iterator itNext = _str.end(); + + iterator itNewLine = std::find( it, itEnd, '\n' ); + if( itNewLine != itEnd ) + itEnd = itNewLine; + + if( itEnd != strEnd ) { + bool foundWrapPoint = false; + iterator findIt = itEnd; + do { + if( wrappableAfterChars.find( *findIt ) != std::string::npos && findIt != itEnd ) { + itEnd = findIt+1; + itNext = findIt+1; + foundWrapPoint = true; + } + else if( findIt > it && wrappableBeforeChars.find( *findIt ) != std::string::npos ) { + itEnd = findIt; + itNext = findIt; + foundWrapPoint = true; + } + else if( wrappableInsteadOfChars.find( *findIt ) != std::string::npos ) { + itNext = findIt+1; + itEnd = findIt; + foundWrapPoint = true; + } + if( findIt == it ) + break; + else + --findIt; + } + while( !foundWrapPoint ); + + if( !foundWrapPoint ) { + // No good wrap char, so we'll break mid word and add a hyphen + --itEnd; + itNext = itEnd; + suffix = "-"; + } + else { + while( itEnd > it && wrappableInsteadOfChars.find( *(itEnd-1) ) != std::string::npos ) + --itEnd; + } + } + lines.push_back( indent + std::string( it, itEnd ) + suffix ); + + if( indent.size() != _attr.indent ) + indent = std::string( _attr.indent, ' ' ); + it = itNext; + } + } + + typedef std::vector::const_iterator const_iterator; + + const_iterator begin() const { return lines.begin(); } + const_iterator end() const { return lines.end(); } + std::string const& last() const { return lines.back(); } + std::size_t size() const { return lines.size(); } + std::string const& operator[]( std::size_t _index ) const { return lines[_index]; } + std::string toString() const { + std::ostringstream oss; + oss << *this; + return oss.str(); + } + + inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) { + for( Text::const_iterator it = _text.begin(), itEnd = _text.end(); + it != itEnd; ++it ) { + if( it != _text.begin() ) + _stream << "\n"; + _stream << *it; + } + return _stream; + } + + private: + std::string str; + TextAttributes attr; + std::vector lines; + }; + +} // end namespace Tbc + +#ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE +} // end outer namespace +#endif + +#endif // TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED +#undef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE + +namespace Catch { + using Tbc::Text; + using Tbc::TextAttributes; +} + +// #included from: catch_console_colour.hpp +#define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_HPP_INCLUDED + +namespace Catch { + + struct Colour { + enum Code { + None = 0, + + White, + Red, + Green, + Blue, + Cyan, + Yellow, + Grey, + + Bright = 0x10, + + BrightRed = Bright | Red, + BrightGreen = Bright | Green, + LightGrey = Bright | Grey, + BrightWhite = Bright | White, + + // By intention + FileName = LightGrey, + Warning = Yellow, + ResultError = BrightRed, + ResultSuccess = BrightGreen, + ResultExpectedFailure = Warning, + + Error = BrightRed, + Success = Green, + + OriginalExpression = Cyan, + ReconstructedExpression = Yellow, + + SecondaryText = LightGrey, + Headers = White + }; + + // Use constructed object for RAII guard + Colour( Code _colourCode ); + Colour( Colour const& other ); + ~Colour(); + + // Use static method for one-shot changes + static void use( Code _colourCode ); + + private: + bool m_moved; + }; + + inline std::ostream& operator << ( std::ostream& os, Colour const& ) { return os; } + +} // end namespace Catch + +// #included from: catch_interfaces_reporter.h +#define TWOBLUECUBES_CATCH_INTERFACES_REPORTER_H_INCLUDED + +#include +#include +#include + +namespace Catch +{ + struct ReporterConfig { + explicit ReporterConfig( Ptr const& _fullConfig ) + : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {} + + ReporterConfig( Ptr const& _fullConfig, std::ostream& _stream ) + : m_stream( &_stream ), m_fullConfig( _fullConfig ) {} + + std::ostream& stream() const { return *m_stream; } + Ptr fullConfig() const { return m_fullConfig; } + + private: + std::ostream* m_stream; + Ptr m_fullConfig; + }; + + struct ReporterPreferences { + ReporterPreferences() + : shouldRedirectStdOut( false ) + {} + + bool shouldRedirectStdOut; + }; + + template + struct LazyStat : Option { + LazyStat() : used( false ) {} + LazyStat& operator=( T const& _value ) { + Option::operator=( _value ); + used = false; + return *this; + } + void reset() { + Option::reset(); + used = false; + } + bool used; + }; + + struct TestRunInfo { + TestRunInfo( std::string const& _name ) : name( _name ) {} + std::string name; + }; + struct GroupInfo { + GroupInfo( std::string const& _name, + std::size_t _groupIndex, + std::size_t _groupsCount ) + : name( _name ), + groupIndex( _groupIndex ), + groupsCounts( _groupsCount ) + {} + + std::string name; + std::size_t groupIndex; + std::size_t groupsCounts; + }; + + struct AssertionStats { + AssertionStats( AssertionResult const& _assertionResult, + std::vector const& _infoMessages, + Totals const& _totals ) + : assertionResult( _assertionResult ), + infoMessages( _infoMessages ), + totals( _totals ) + { + if( assertionResult.hasMessage() ) { + // Copy message into messages list. + // !TBD This should have been done earlier, somewhere + MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() ); + builder << assertionResult.getMessage(); + builder.m_info.message = builder.m_stream.str(); + + infoMessages.push_back( builder.m_info ); + } + } + virtual ~AssertionStats(); + +# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS + AssertionStats( AssertionStats const& ) = default; + AssertionStats( AssertionStats && ) = default; + AssertionStats& operator = ( AssertionStats const& ) = default; + AssertionStats& operator = ( AssertionStats && ) = default; +# endif + + AssertionResult assertionResult; + std::vector infoMessages; + Totals totals; + }; + + struct SectionStats { + SectionStats( SectionInfo const& _sectionInfo, + Counts const& _assertions, + double _durationInSeconds, + bool _missingAssertions ) + : sectionInfo( _sectionInfo ), + assertions( _assertions ), + durationInSeconds( _durationInSeconds ), + missingAssertions( _missingAssertions ) + {} + virtual ~SectionStats(); +# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS + SectionStats( SectionStats const& ) = default; + SectionStats( SectionStats && ) = default; + SectionStats& operator = ( SectionStats const& ) = default; + SectionStats& operator = ( SectionStats && ) = default; +# endif + + SectionInfo sectionInfo; + Counts assertions; + double durationInSeconds; + bool missingAssertions; + }; + + struct TestCaseStats { + TestCaseStats( TestCaseInfo const& _testInfo, + Totals const& _totals, + std::string const& _stdOut, + std::string const& _stdErr, + bool _aborting ) + : testInfo( _testInfo ), + totals( _totals ), + stdOut( _stdOut ), + stdErr( _stdErr ), + aborting( _aborting ) + {} + virtual ~TestCaseStats(); + +# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS + TestCaseStats( TestCaseStats const& ) = default; + TestCaseStats( TestCaseStats && ) = default; + TestCaseStats& operator = ( TestCaseStats const& ) = default; + TestCaseStats& operator = ( TestCaseStats && ) = default; +# endif + + TestCaseInfo testInfo; + Totals totals; + std::string stdOut; + std::string stdErr; + bool aborting; + }; + + struct TestGroupStats { + TestGroupStats( GroupInfo const& _groupInfo, + Totals const& _totals, + bool _aborting ) + : groupInfo( _groupInfo ), + totals( _totals ), + aborting( _aborting ) + {} + TestGroupStats( GroupInfo const& _groupInfo ) + : groupInfo( _groupInfo ), + aborting( false ) + {} + virtual ~TestGroupStats(); + +# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS + TestGroupStats( TestGroupStats const& ) = default; + TestGroupStats( TestGroupStats && ) = default; + TestGroupStats& operator = ( TestGroupStats const& ) = default; + TestGroupStats& operator = ( TestGroupStats && ) = default; +# endif + + GroupInfo groupInfo; + Totals totals; + bool aborting; + }; + + struct TestRunStats { + TestRunStats( TestRunInfo const& _runInfo, + Totals const& _totals, + bool _aborting ) + : runInfo( _runInfo ), + totals( _totals ), + aborting( _aborting ) + {} + virtual ~TestRunStats(); + +# ifndef CATCH_CONFIG_CPP11_GENERATED_METHODS + TestRunStats( TestRunStats const& _other ) + : runInfo( _other.runInfo ), + totals( _other.totals ), + aborting( _other.aborting ) + {} +# else + TestRunStats( TestRunStats const& ) = default; + TestRunStats( TestRunStats && ) = default; + TestRunStats& operator = ( TestRunStats const& ) = default; + TestRunStats& operator = ( TestRunStats && ) = default; +# endif + + TestRunInfo runInfo; + Totals totals; + bool aborting; + }; + + class MultipleReporters; + + struct IStreamingReporter : IShared { + virtual ~IStreamingReporter(); + + // Implementing class must also provide the following static method: + // static std::string getDescription(); + + virtual ReporterPreferences getPreferences() const = 0; + + virtual void noMatchingTestCases( std::string const& spec ) = 0; + + virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0; + virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0; + + virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0; + virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0; + + virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0; + + // The return value indicates if the messages buffer should be cleared: + virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0; + + virtual void sectionEnded( SectionStats const& sectionStats ) = 0; + virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0; + virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0; + virtual void testRunEnded( TestRunStats const& testRunStats ) = 0; + + virtual void skipTest( TestCaseInfo const& testInfo ) = 0; + + virtual MultipleReporters* tryAsMulti() { return CATCH_NULL; } + }; + + struct IReporterFactory : IShared { + virtual ~IReporterFactory(); + virtual IStreamingReporter* create( ReporterConfig const& config ) const = 0; + virtual std::string getDescription() const = 0; + }; + + struct IReporterRegistry { + typedef std::map > FactoryMap; + typedef std::vector > Listeners; + + virtual ~IReporterRegistry(); + virtual IStreamingReporter* create( std::string const& name, Ptr const& config ) const = 0; + virtual FactoryMap const& getFactories() const = 0; + virtual Listeners const& getListeners() const = 0; + }; + + Ptr addReporter( Ptr const& existingReporter, Ptr const& additionalReporter ); + +} + +#include +#include + +namespace Catch { + + inline std::size_t listTests( Config const& config ) { + + TestSpec testSpec = config.testSpec(); + if( config.testSpec().hasFilters() ) + Catch::cout() << "Matching test cases:\n"; + else { + Catch::cout() << "All available test cases:\n"; + testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec(); + } + + std::size_t matchedTests = 0; + TextAttributes nameAttr, tagsAttr; + nameAttr.setInitialIndent( 2 ).setIndent( 4 ); + tagsAttr.setIndent( 6 ); + + std::vector matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); + for( std::vector::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); + it != itEnd; + ++it ) { + matchedTests++; + TestCaseInfo const& testCaseInfo = it->getTestCaseInfo(); + Colour::Code colour = testCaseInfo.isHidden() + ? Colour::SecondaryText + : Colour::None; + Colour colourGuard( colour ); + + Catch::cout() << Text( testCaseInfo.name, nameAttr ) << std::endl; + if( !testCaseInfo.tags.empty() ) + Catch::cout() << Text( testCaseInfo.tagsAsString, tagsAttr ) << std::endl; + } + + if( !config.testSpec().hasFilters() ) + Catch::cout() << pluralise( matchedTests, "test case" ) << '\n' << std::endl; + else + Catch::cout() << pluralise( matchedTests, "matching test case" ) << '\n' << std::endl; + return matchedTests; + } + + inline std::size_t listTestsNamesOnly( Config const& config ) { + TestSpec testSpec = config.testSpec(); + if( !config.testSpec().hasFilters() ) + testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec(); + std::size_t matchedTests = 0; + std::vector matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); + for( std::vector::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); + it != itEnd; + ++it ) { + matchedTests++; + TestCaseInfo const& testCaseInfo = it->getTestCaseInfo(); + if( startsWith( testCaseInfo.name, '#' ) ) + Catch::cout() << '"' << testCaseInfo.name << '"' << std::endl; + else + Catch::cout() << testCaseInfo.name << std::endl; + } + return matchedTests; + } + + struct TagInfo { + TagInfo() : count ( 0 ) {} + void add( std::string const& spelling ) { + ++count; + spellings.insert( spelling ); + } + std::string all() const { + std::string out; + for( std::set::const_iterator it = spellings.begin(), itEnd = spellings.end(); + it != itEnd; + ++it ) + out += "[" + *it + "]"; + return out; + } + std::set spellings; + std::size_t count; + }; + + inline std::size_t listTags( Config const& config ) { + TestSpec testSpec = config.testSpec(); + if( config.testSpec().hasFilters() ) + Catch::cout() << "Tags for matching test cases:\n"; + else { + Catch::cout() << "All available tags:\n"; + testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec(); + } + + std::map tagCounts; + + std::vector matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); + for( std::vector::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); + it != itEnd; + ++it ) { + for( std::set::const_iterator tagIt = it->getTestCaseInfo().tags.begin(), + tagItEnd = it->getTestCaseInfo().tags.end(); + tagIt != tagItEnd; + ++tagIt ) { + std::string tagName = *tagIt; + std::string lcaseTagName = toLower( tagName ); + std::map::iterator countIt = tagCounts.find( lcaseTagName ); + if( countIt == tagCounts.end() ) + countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first; + countIt->second.add( tagName ); + } + } + + for( std::map::const_iterator countIt = tagCounts.begin(), + countItEnd = tagCounts.end(); + countIt != countItEnd; + ++countIt ) { + std::ostringstream oss; + oss << " " << std::setw(2) << countIt->second.count << " "; + Text wrapper( countIt->second.all(), TextAttributes() + .setInitialIndent( 0 ) + .setIndent( oss.str().size() ) + .setWidth( CATCH_CONFIG_CONSOLE_WIDTH-10 ) ); + Catch::cout() << oss.str() << wrapper << '\n'; + } + Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl; + return tagCounts.size(); + } + + inline std::size_t listReporters( Config const& /*config*/ ) { + Catch::cout() << "Available reporters:\n"; + IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories(); + IReporterRegistry::FactoryMap::const_iterator itBegin = factories.begin(), itEnd = factories.end(), it; + std::size_t maxNameLen = 0; + for(it = itBegin; it != itEnd; ++it ) + maxNameLen = (std::max)( maxNameLen, it->first.size() ); + + for(it = itBegin; it != itEnd; ++it ) { + Text wrapper( it->second->getDescription(), TextAttributes() + .setInitialIndent( 0 ) + .setIndent( 7+maxNameLen ) + .setWidth( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 ) ); + Catch::cout() << " " + << it->first + << ':' + << std::string( maxNameLen - it->first.size() + 2, ' ' ) + << wrapper << '\n'; + } + Catch::cout() << std::endl; + return factories.size(); + } + + inline Option list( Config const& config ) { + Option listedCount; + if( config.listTests() ) + listedCount = listedCount.valueOr(0) + listTests( config ); + if( config.listTestNamesOnly() ) + listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config ); + if( config.listTags() ) + listedCount = listedCount.valueOr(0) + listTags( config ); + if( config.listReporters() ) + listedCount = listedCount.valueOr(0) + listReporters( config ); + return listedCount; + } + +} // end namespace Catch + +// #included from: internal/catch_run_context.hpp +#define TWOBLUECUBES_CATCH_RUNNER_IMPL_HPP_INCLUDED + +// #included from: catch_test_case_tracker.hpp +#define TWOBLUECUBES_CATCH_TEST_CASE_TRACKER_HPP_INCLUDED + +#include +#include +#include +#include +#include + +CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS + +namespace Catch { +namespace TestCaseTracking { + + struct NameAndLocation { + std::string name; + SourceLineInfo location; + + NameAndLocation( std::string const& _name, SourceLineInfo const& _location ) + : name( _name ), + location( _location ) + {} + }; + + struct ITracker : SharedImpl<> { + virtual ~ITracker(); + + // static queries + virtual NameAndLocation const& nameAndLocation() const = 0; + + // dynamic queries + virtual bool isComplete() const = 0; // Successfully completed or failed + virtual bool isSuccessfullyCompleted() const = 0; + virtual bool isOpen() const = 0; // Started but not complete + virtual bool hasChildren() const = 0; + + virtual ITracker& parent() = 0; + + // actions + virtual void close() = 0; // Successfully complete + virtual void fail() = 0; + virtual void markAsNeedingAnotherRun() = 0; + + virtual void addChild( Ptr const& child ) = 0; + virtual ITracker* findChild( NameAndLocation const& nameAndLocation ) = 0; + virtual void openChild() = 0; + + // Debug/ checking + virtual bool isSectionTracker() const = 0; + virtual bool isIndexTracker() const = 0; + }; + + class TrackerContext { + + enum RunState { + NotStarted, + Executing, + CompletedCycle + }; + + Ptr m_rootTracker; + ITracker* m_currentTracker; + RunState m_runState; + + public: + + static TrackerContext& instance() { + static TrackerContext s_instance; + return s_instance; + } + + TrackerContext() + : m_currentTracker( CATCH_NULL ), + m_runState( NotStarted ) + {} + + ITracker& startRun(); + + void endRun() { + m_rootTracker.reset(); + m_currentTracker = CATCH_NULL; + m_runState = NotStarted; + } + + void startCycle() { + m_currentTracker = m_rootTracker.get(); + m_runState = Executing; + } + void completeCycle() { + m_runState = CompletedCycle; + } + + bool completedCycle() const { + return m_runState == CompletedCycle; + } + ITracker& currentTracker() { + return *m_currentTracker; + } + void setCurrentTracker( ITracker* tracker ) { + m_currentTracker = tracker; + } + }; + + class TrackerBase : public ITracker { + protected: + enum CycleState { + NotStarted, + Executing, + ExecutingChildren, + NeedsAnotherRun, + CompletedSuccessfully, + Failed + }; + class TrackerHasName { + NameAndLocation m_nameAndLocation; + public: + TrackerHasName( NameAndLocation const& nameAndLocation ) : m_nameAndLocation( nameAndLocation ) {} + bool operator ()( Ptr const& tracker ) { + return + tracker->nameAndLocation().name == m_nameAndLocation.name && + tracker->nameAndLocation().location == m_nameAndLocation.location; + } + }; + typedef std::vector > Children; + NameAndLocation m_nameAndLocation; + TrackerContext& m_ctx; + ITracker* m_parent; + Children m_children; + CycleState m_runState; + public: + TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ) + : m_nameAndLocation( nameAndLocation ), + m_ctx( ctx ), + m_parent( parent ), + m_runState( NotStarted ) + {} + virtual ~TrackerBase(); + + virtual NameAndLocation const& nameAndLocation() const CATCH_OVERRIDE { + return m_nameAndLocation; + } + virtual bool isComplete() const CATCH_OVERRIDE { + return m_runState == CompletedSuccessfully || m_runState == Failed; + } + virtual bool isSuccessfullyCompleted() const CATCH_OVERRIDE { + return m_runState == CompletedSuccessfully; + } + virtual bool isOpen() const CATCH_OVERRIDE { + return m_runState != NotStarted && !isComplete(); + } + virtual bool hasChildren() const CATCH_OVERRIDE { + return !m_children.empty(); + } + + virtual void addChild( Ptr const& child ) CATCH_OVERRIDE { + m_children.push_back( child ); + } + + virtual ITracker* findChild( NameAndLocation const& nameAndLocation ) CATCH_OVERRIDE { + Children::const_iterator it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( nameAndLocation ) ); + return( it != m_children.end() ) + ? it->get() + : CATCH_NULL; + } + virtual ITracker& parent() CATCH_OVERRIDE { + assert( m_parent ); // Should always be non-null except for root + return *m_parent; + } + + virtual void openChild() CATCH_OVERRIDE { + if( m_runState != ExecutingChildren ) { + m_runState = ExecutingChildren; + if( m_parent ) + m_parent->openChild(); + } + } + + virtual bool isSectionTracker() const CATCH_OVERRIDE { return false; } + virtual bool isIndexTracker() const CATCH_OVERRIDE { return false; } + + void open() { + m_runState = Executing; + moveToThis(); + if( m_parent ) + m_parent->openChild(); + } + + virtual void close() CATCH_OVERRIDE { + + // Close any still open children (e.g. generators) + while( &m_ctx.currentTracker() != this ) + m_ctx.currentTracker().close(); + + switch( m_runState ) { + case NotStarted: + case CompletedSuccessfully: + case Failed: + throw std::logic_error( "Illogical state" ); + + case NeedsAnotherRun: + break;; + + case Executing: + m_runState = CompletedSuccessfully; + break; + case ExecutingChildren: + if( m_children.empty() || m_children.back()->isComplete() ) + m_runState = CompletedSuccessfully; + break; + + default: + throw std::logic_error( "Unexpected state" ); + } + moveToParent(); + m_ctx.completeCycle(); + } + virtual void fail() CATCH_OVERRIDE { + m_runState = Failed; + if( m_parent ) + m_parent->markAsNeedingAnotherRun(); + moveToParent(); + m_ctx.completeCycle(); + } + virtual void markAsNeedingAnotherRun() CATCH_OVERRIDE { + m_runState = NeedsAnotherRun; + } + private: + void moveToParent() { + assert( m_parent ); + m_ctx.setCurrentTracker( m_parent ); + } + void moveToThis() { + m_ctx.setCurrentTracker( this ); + } + }; + + class SectionTracker : public TrackerBase { + std::vector m_filters; + public: + SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ) + : TrackerBase( nameAndLocation, ctx, parent ) + { + if( parent ) { + while( !parent->isSectionTracker() ) + parent = &parent->parent(); + + SectionTracker& parentSection = static_cast( *parent ); + addNextFilters( parentSection.m_filters ); + } + } + virtual ~SectionTracker(); + + virtual bool isSectionTracker() const CATCH_OVERRIDE { return true; } + + static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) { + SectionTracker* section = CATCH_NULL; + + ITracker& currentTracker = ctx.currentTracker(); + if( ITracker* childTracker = currentTracker.findChild( nameAndLocation ) ) { + assert( childTracker ); + assert( childTracker->isSectionTracker() ); + section = static_cast( childTracker ); + } + else { + section = new SectionTracker( nameAndLocation, ctx, ¤tTracker ); + currentTracker.addChild( section ); + } + if( !ctx.completedCycle() ) + section->tryOpen(); + return *section; + } + + void tryOpen() { + if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) ) + open(); + } + + void addInitialFilters( std::vector const& filters ) { + if( !filters.empty() ) { + m_filters.push_back(""); // Root - should never be consulted + m_filters.push_back(""); // Test Case - not a section filter + m_filters.insert( m_filters.end(), filters.begin(), filters.end() ); + } + } + void addNextFilters( std::vector const& filters ) { + if( filters.size() > 1 ) + m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() ); + } + }; + + class IndexTracker : public TrackerBase { + int m_size; + int m_index; + public: + IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size ) + : TrackerBase( nameAndLocation, ctx, parent ), + m_size( size ), + m_index( -1 ) + {} + virtual ~IndexTracker(); + + virtual bool isIndexTracker() const CATCH_OVERRIDE { return true; } + + static IndexTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size ) { + IndexTracker* tracker = CATCH_NULL; + + ITracker& currentTracker = ctx.currentTracker(); + if( ITracker* childTracker = currentTracker.findChild( nameAndLocation ) ) { + assert( childTracker ); + assert( childTracker->isIndexTracker() ); + tracker = static_cast( childTracker ); + } + else { + tracker = new IndexTracker( nameAndLocation, ctx, ¤tTracker, size ); + currentTracker.addChild( tracker ); + } + + if( !ctx.completedCycle() && !tracker->isComplete() ) { + if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun ) + tracker->moveNext(); + tracker->open(); + } + + return *tracker; + } + + int index() const { return m_index; } + + void moveNext() { + m_index++; + m_children.clear(); + } + + virtual void close() CATCH_OVERRIDE { + TrackerBase::close(); + if( m_runState == CompletedSuccessfully && m_index < m_size-1 ) + m_runState = Executing; + } + }; + + inline ITracker& TrackerContext::startRun() { + m_rootTracker = new SectionTracker( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, CATCH_NULL ); + m_currentTracker = CATCH_NULL; + m_runState = Executing; + return *m_rootTracker; + } + +} // namespace TestCaseTracking + +using TestCaseTracking::ITracker; +using TestCaseTracking::TrackerContext; +using TestCaseTracking::SectionTracker; +using TestCaseTracking::IndexTracker; + +} // namespace Catch + +CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS + +// #included from: catch_fatal_condition.hpp +#define TWOBLUECUBES_CATCH_FATAL_CONDITION_H_INCLUDED + +namespace Catch { + + // Report the error condition + inline void reportFatal( std::string const& message ) { + IContext& context = Catch::getCurrentContext(); + IResultCapture* resultCapture = context.getResultCapture(); + resultCapture->handleFatalErrorCondition( message ); + } + +} // namespace Catch + +#if defined ( CATCH_PLATFORM_WINDOWS ) ///////////////////////////////////////// +// #included from: catch_windows_h_proxy.h + +#define TWOBLUECUBES_CATCH_WINDOWS_H_PROXY_H_INCLUDED + +#ifdef CATCH_DEFINES_NOMINMAX +# define NOMINMAX +#endif +#ifdef CATCH_DEFINES_WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +#endif + +#ifdef __AFXDLL +#include +#else +#include +#endif + +#ifdef CATCH_DEFINES_NOMINMAX +# undef NOMINMAX +#endif +#ifdef CATCH_DEFINES_WIN32_LEAN_AND_MEAN +# undef WIN32_LEAN_AND_MEAN +#endif + + +# if !defined ( CATCH_CONFIG_WINDOWS_SEH ) + +namespace Catch { + struct FatalConditionHandler { + void reset() {} + }; +} + +# else // CATCH_CONFIG_WINDOWS_SEH is defined + +namespace Catch { + + struct SignalDefs { DWORD id; const char* name; }; + extern SignalDefs signalDefs[]; + // There is no 1-1 mapping between signals and windows exceptions. + // Windows can easily distinguish between SO and SigSegV, + // but SigInt, SigTerm, etc are handled differently. + SignalDefs signalDefs[] = { + { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" }, + { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" }, + { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" }, + { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" }, + }; + + struct FatalConditionHandler { + + static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) { + for (int i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) { + if (ExceptionInfo->ExceptionRecord->ExceptionCode == signalDefs[i].id) { + reportFatal(signalDefs[i].name); + } + } + // If its not an exception we care about, pass it along. + // This stops us from eating debugger breaks etc. + return EXCEPTION_CONTINUE_SEARCH; + } + + FatalConditionHandler() { + isSet = true; + // 32k seems enough for Catch to handle stack overflow, + // but the value was found experimentally, so there is no strong guarantee + guaranteeSize = 32 * 1024; + exceptionHandlerHandle = CATCH_NULL; + // Register as first handler in current chain + exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException); + // Pass in guarantee size to be filled + SetThreadStackGuarantee(&guaranteeSize); + } + + static void reset() { + if (isSet) { + // Unregister handler and restore the old guarantee + RemoveVectoredExceptionHandler(exceptionHandlerHandle); + SetThreadStackGuarantee(&guaranteeSize); + exceptionHandlerHandle = CATCH_NULL; + isSet = false; + } + } + + ~FatalConditionHandler() { + reset(); + } + private: + static bool isSet; + static ULONG guaranteeSize; + static PVOID exceptionHandlerHandle; + }; + + bool FatalConditionHandler::isSet = false; + ULONG FatalConditionHandler::guaranteeSize = 0; + PVOID FatalConditionHandler::exceptionHandlerHandle = CATCH_NULL; + +} // namespace Catch + +# endif // CATCH_CONFIG_WINDOWS_SEH + +#else // Not Windows - assumed to be POSIX compatible ////////////////////////// + +# if !defined(CATCH_CONFIG_POSIX_SIGNALS) + +namespace Catch { + struct FatalConditionHandler { + void reset() {} + }; +} + +# else // CATCH_CONFIG_POSIX_SIGNALS is defined + +#include + +namespace Catch { + + struct SignalDefs { + int id; + const char* name; + }; + extern SignalDefs signalDefs[]; + SignalDefs signalDefs[] = { + { SIGINT, "SIGINT - Terminal interrupt signal" }, + { SIGILL, "SIGILL - Illegal instruction signal" }, + { SIGFPE, "SIGFPE - Floating point error signal" }, + { SIGSEGV, "SIGSEGV - Segmentation violation signal" }, + { SIGTERM, "SIGTERM - Termination request signal" }, + { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" } + }; + + struct FatalConditionHandler { + + static bool isSet; + static struct sigaction oldSigActions [sizeof(signalDefs)/sizeof(SignalDefs)]; + static stack_t oldSigStack; + static char altStackMem[SIGSTKSZ]; + + static void handleSignal( int sig ) { + std::string name = ""; + for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) { + SignalDefs &def = signalDefs[i]; + if (sig == def.id) { + name = def.name; + break; + } + } + reset(); + reportFatal(name); + raise( sig ); + } + + FatalConditionHandler() { + isSet = true; + stack_t sigStack; + sigStack.ss_sp = altStackMem; + sigStack.ss_size = SIGSTKSZ; + sigStack.ss_flags = 0; + sigaltstack(&sigStack, &oldSigStack); + struct sigaction sa = { 0 }; + + sa.sa_handler = handleSignal; + sa.sa_flags = SA_ONSTACK; + for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) { + sigaction(signalDefs[i].id, &sa, &oldSigActions[i]); + } + } + + ~FatalConditionHandler() { + reset(); + } + static void reset() { + if( isSet ) { + // Set signals back to previous values -- hopefully nobody overwrote them in the meantime + for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) { + sigaction(signalDefs[i].id, &oldSigActions[i], CATCH_NULL); + } + // Return the old stack + sigaltstack(&oldSigStack, CATCH_NULL); + isSet = false; + } + } + }; + + bool FatalConditionHandler::isSet = false; + struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {}; + stack_t FatalConditionHandler::oldSigStack = {}; + char FatalConditionHandler::altStackMem[SIGSTKSZ] = {}; + +} // namespace Catch + +# endif // CATCH_CONFIG_POSIX_SIGNALS + +#endif // not Windows + +#include +#include + +namespace Catch { + + class StreamRedirect { + + public: + StreamRedirect( std::ostream& stream, std::string& targetString ) + : m_stream( stream ), + m_prevBuf( stream.rdbuf() ), + m_targetString( targetString ) + { + stream.rdbuf( m_oss.rdbuf() ); + } + + ~StreamRedirect() { + m_targetString += m_oss.str(); + m_stream.rdbuf( m_prevBuf ); + } + + private: + std::ostream& m_stream; + std::streambuf* m_prevBuf; + std::ostringstream m_oss; + std::string& m_targetString; + }; + + /////////////////////////////////////////////////////////////////////////// + + class RunContext : public IResultCapture, public IRunner { + + RunContext( RunContext const& ); + void operator =( RunContext const& ); + + public: + + explicit RunContext( Ptr const& _config, Ptr const& reporter ) + : m_runInfo( _config->name() ), + m_context( getCurrentMutableContext() ), + m_activeTestCase( CATCH_NULL ), + m_config( _config ), + m_reporter( reporter ), + m_shouldReportUnexpected ( true ) + { + m_context.setRunner( this ); + m_context.setConfig( m_config ); + m_context.setResultCapture( this ); + m_reporter->testRunStarting( m_runInfo ); + } + + virtual ~RunContext() { + m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, aborting() ) ); + } + + void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount ) { + m_reporter->testGroupStarting( GroupInfo( testSpec, groupIndex, groupsCount ) ); + } + void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount ) { + m_reporter->testGroupEnded( TestGroupStats( GroupInfo( testSpec, groupIndex, groupsCount ), totals, aborting() ) ); + } + + Totals runTest( TestCase const& testCase ) { + Totals prevTotals = m_totals; + + std::string redirectedCout; + std::string redirectedCerr; + + TestCaseInfo testInfo = testCase.getTestCaseInfo(); + + m_reporter->testCaseStarting( testInfo ); + + m_activeTestCase = &testCase; + + do { + ITracker& rootTracker = m_trackerContext.startRun(); + assert( rootTracker.isSectionTracker() ); + static_cast( rootTracker ).addInitialFilters( m_config->getSectionsToRun() ); + do { + m_trackerContext.startCycle(); + m_testCaseTracker = &SectionTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( testInfo.name, testInfo.lineInfo ) ); + runCurrentTest( redirectedCout, redirectedCerr ); + } + while( !m_testCaseTracker->isSuccessfullyCompleted() && !aborting() ); + } + // !TBD: deprecated - this will be replaced by indexed trackers + while( getCurrentContext().advanceGeneratorsForCurrentTest() && !aborting() ); + + Totals deltaTotals = m_totals.delta( prevTotals ); + if( testInfo.expectedToFail() && deltaTotals.testCases.passed > 0 ) { + deltaTotals.assertions.failed++; + deltaTotals.testCases.passed--; + deltaTotals.testCases.failed++; + } + m_totals.testCases += deltaTotals.testCases; + m_reporter->testCaseEnded( TestCaseStats( testInfo, + deltaTotals, + redirectedCout, + redirectedCerr, + aborting() ) ); + + m_activeTestCase = CATCH_NULL; + m_testCaseTracker = CATCH_NULL; + + return deltaTotals; + } + + Ptr config() const { + return m_config; + } + + private: // IResultCapture + + virtual void assertionEnded( AssertionResult const& result ) { + if( result.getResultType() == ResultWas::Ok ) { + m_totals.assertions.passed++; + } + else if( !result.isOk() ) { + m_totals.assertions.failed++; + } + + // We have no use for the return value (whether messages should be cleared), because messages were made scoped + // and should be let to clear themselves out. + static_cast(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals))); + + // Reset working state + m_lastAssertionInfo = AssertionInfo( std::string(), m_lastAssertionInfo.lineInfo, "{Unknown expression after the reported line}" , m_lastAssertionInfo.resultDisposition ); + m_lastResult = result; + } + + virtual bool sectionStarted ( + SectionInfo const& sectionInfo, + Counts& assertions + ) + { + ITracker& sectionTracker = SectionTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( sectionInfo.name, sectionInfo.lineInfo ) ); + if( !sectionTracker.isOpen() ) + return false; + m_activeSections.push_back( §ionTracker ); + + m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo; + + m_reporter->sectionStarting( sectionInfo ); + + assertions = m_totals.assertions; + + return true; + } + bool testForMissingAssertions( Counts& assertions ) { + if( assertions.total() != 0 ) + return false; + if( !m_config->warnAboutMissingAssertions() ) + return false; + if( m_trackerContext.currentTracker().hasChildren() ) + return false; + m_totals.assertions.failed++; + assertions.failed++; + return true; + } + + virtual void sectionEnded( SectionEndInfo const& endInfo ) { + Counts assertions = m_totals.assertions - endInfo.prevAssertions; + bool missingAssertions = testForMissingAssertions( assertions ); + + if( !m_activeSections.empty() ) { + m_activeSections.back()->close(); + m_activeSections.pop_back(); + } + + m_reporter->sectionEnded( SectionStats( endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions ) ); + m_messages.clear(); + } + + virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) { + if( m_unfinishedSections.empty() ) + m_activeSections.back()->fail(); + else + m_activeSections.back()->close(); + m_activeSections.pop_back(); + + m_unfinishedSections.push_back( endInfo ); + } + + virtual void pushScopedMessage( MessageInfo const& message ) { + m_messages.push_back( message ); + } + + virtual void popScopedMessage( MessageInfo const& message ) { + m_messages.erase( std::remove( m_messages.begin(), m_messages.end(), message ), m_messages.end() ); + } + + virtual std::string getCurrentTestName() const { + return m_activeTestCase + ? m_activeTestCase->getTestCaseInfo().name + : std::string(); + } + + virtual const AssertionResult* getLastResult() const { + return &m_lastResult; + } + + virtual void exceptionEarlyReported() { + m_shouldReportUnexpected = false; + } + + virtual void handleFatalErrorCondition( std::string const& message ) { + // Don't rebuild the result -- the stringification itself can cause more fatal errors + // Instead, fake a result data. + AssertionResultData tempResult; + tempResult.resultType = ResultWas::FatalErrorCondition; + tempResult.message = message; + AssertionResult result(m_lastAssertionInfo, tempResult); + + getResultCapture().assertionEnded(result); + + handleUnfinishedSections(); + + // Recreate section for test case (as we will lose the one that was in scope) + TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); + SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description ); + + Counts assertions; + assertions.failed = 1; + SectionStats testCaseSectionStats( testCaseSection, assertions, 0, false ); + m_reporter->sectionEnded( testCaseSectionStats ); + + TestCaseInfo testInfo = m_activeTestCase->getTestCaseInfo(); + + Totals deltaTotals; + deltaTotals.testCases.failed = 1; + m_reporter->testCaseEnded( TestCaseStats( testInfo, + deltaTotals, + std::string(), + std::string(), + false ) ); + m_totals.testCases.failed++; + testGroupEnded( std::string(), m_totals, 1, 1 ); + m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, false ) ); + } + + public: + // !TBD We need to do this another way! + bool aborting() const { + return m_totals.assertions.failed == static_cast( m_config->abortAfter() ); + } + + private: + + void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr ) { + TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); + SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description ); + m_reporter->sectionStarting( testCaseSection ); + Counts prevAssertions = m_totals.assertions; + double duration = 0; + m_shouldReportUnexpected = true; + try { + m_lastAssertionInfo = AssertionInfo( "TEST_CASE", testCaseInfo.lineInfo, std::string(), ResultDisposition::Normal ); + + seedRng( *m_config ); + + Timer timer; + timer.start(); + if( m_reporter->getPreferences().shouldRedirectStdOut ) { + StreamRedirect coutRedir( Catch::cout(), redirectedCout ); + StreamRedirect cerrRedir( Catch::cerr(), redirectedCerr ); + invokeActiveTestCase(); + } + else { + invokeActiveTestCase(); + } + duration = timer.getElapsedSeconds(); + } + catch( TestFailureException& ) { + // This just means the test was aborted due to failure + } + catch(...) { + // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions + // are reported without translation at the point of origin. + if (m_shouldReportUnexpected) { + makeUnexpectedResultBuilder().useActiveException(); + } + } + m_testCaseTracker->close(); + handleUnfinishedSections(); + m_messages.clear(); + + Counts assertions = m_totals.assertions - prevAssertions; + bool missingAssertions = testForMissingAssertions( assertions ); + + if( testCaseInfo.okToFail() ) { + std::swap( assertions.failedButOk, assertions.failed ); + m_totals.assertions.failed -= assertions.failedButOk; + m_totals.assertions.failedButOk += assertions.failedButOk; + } + + SectionStats testCaseSectionStats( testCaseSection, assertions, duration, missingAssertions ); + m_reporter->sectionEnded( testCaseSectionStats ); + } + + void invokeActiveTestCase() { + FatalConditionHandler fatalConditionHandler; // Handle signals + m_activeTestCase->invoke(); + fatalConditionHandler.reset(); + } + + private: + + ResultBuilder makeUnexpectedResultBuilder() const { + return ResultBuilder( m_lastAssertionInfo.macroName.c_str(), + m_lastAssertionInfo.lineInfo, + m_lastAssertionInfo.capturedExpression.c_str(), + m_lastAssertionInfo.resultDisposition ); + } + + void handleUnfinishedSections() { + // If sections ended prematurely due to an exception we stored their + // infos here so we can tear them down outside the unwind process. + for( std::vector::const_reverse_iterator it = m_unfinishedSections.rbegin(), + itEnd = m_unfinishedSections.rend(); + it != itEnd; + ++it ) + sectionEnded( *it ); + m_unfinishedSections.clear(); + } + + TestRunInfo m_runInfo; + IMutableContext& m_context; + TestCase const* m_activeTestCase; + ITracker* m_testCaseTracker; + ITracker* m_currentSectionTracker; + AssertionResult m_lastResult; + + Ptr m_config; + Totals m_totals; + Ptr m_reporter; + std::vector m_messages; + AssertionInfo m_lastAssertionInfo; + std::vector m_unfinishedSections; + std::vector m_activeSections; + TrackerContext m_trackerContext; + bool m_shouldReportUnexpected; + }; + + IResultCapture& getResultCapture() { + if( IResultCapture* capture = getCurrentContext().getResultCapture() ) + return *capture; + else + throw std::logic_error( "No result capture instance" ); + } + +} // end namespace Catch + +// #included from: internal/catch_version.h +#define TWOBLUECUBES_CATCH_VERSION_H_INCLUDED + +namespace Catch { + + // Versioning information + struct Version { + Version( unsigned int _majorVersion, + unsigned int _minorVersion, + unsigned int _patchNumber, + char const * const _branchName, + unsigned int _buildNumber ); + + unsigned int const majorVersion; + unsigned int const minorVersion; + unsigned int const patchNumber; + + // buildNumber is only used if branchName is not null + char const * const branchName; + unsigned int const buildNumber; + + friend std::ostream& operator << ( std::ostream& os, Version const& version ); + + private: + void operator=( Version const& ); + }; + + inline Version libraryVersion(); +} + +#include +#include +#include + +namespace Catch { + + Ptr createReporter( std::string const& reporterName, Ptr const& config ) { + Ptr reporter = getRegistryHub().getReporterRegistry().create( reporterName, config.get() ); + if( !reporter ) { + std::ostringstream oss; + oss << "No reporter registered with name: '" << reporterName << "'"; + throw std::domain_error( oss.str() ); + } + return reporter; + } + + Ptr makeReporter( Ptr const& config ) { + std::vector reporters = config->getReporterNames(); + if( reporters.empty() ) + reporters.push_back( "console" ); + + Ptr reporter; + for( std::vector::const_iterator it = reporters.begin(), itEnd = reporters.end(); + it != itEnd; + ++it ) + reporter = addReporter( reporter, createReporter( *it, config ) ); + return reporter; + } + Ptr addListeners( Ptr const& config, Ptr reporters ) { + IReporterRegistry::Listeners listeners = getRegistryHub().getReporterRegistry().getListeners(); + for( IReporterRegistry::Listeners::const_iterator it = listeners.begin(), itEnd = listeners.end(); + it != itEnd; + ++it ) + reporters = addReporter(reporters, (*it)->create( ReporterConfig( config ) ) ); + return reporters; + } + + Totals runTests( Ptr const& config ) { + + Ptr iconfig = config.get(); + + Ptr reporter = makeReporter( config ); + reporter = addListeners( iconfig, reporter ); + + RunContext context( iconfig, reporter ); + + Totals totals; + + context.testGroupStarting( config->name(), 1, 1 ); + + TestSpec testSpec = config->testSpec(); + if( !testSpec.hasFilters() ) + testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "~[.]" ).testSpec(); // All not hidden tests + + std::vector const& allTestCases = getAllTestCasesSorted( *iconfig ); + for( std::vector::const_iterator it = allTestCases.begin(), itEnd = allTestCases.end(); + it != itEnd; + ++it ) { + if( !context.aborting() && matchTest( *it, testSpec, *iconfig ) ) + totals += context.runTest( *it ); + else + reporter->skipTest( *it ); + } + + context.testGroupEnded( iconfig->name(), totals, 1, 1 ); + return totals; + } + + void applyFilenamesAsTags( IConfig const& config ) { + std::vector const& tests = getAllTestCasesSorted( config ); + for(std::size_t i = 0; i < tests.size(); ++i ) { + TestCase& test = const_cast( tests[i] ); + std::set tags = test.tags; + + std::string filename = test.lineInfo.file; + std::string::size_type lastSlash = filename.find_last_of( "\\/" ); + if( lastSlash != std::string::npos ) + filename = filename.substr( lastSlash+1 ); + + std::string::size_type lastDot = filename.find_last_of( "." ); + if( lastDot != std::string::npos ) + filename = filename.substr( 0, lastDot ); + + tags.insert( "#" + filename ); + setTags( test, tags ); + } + } + + class Session : NonCopyable { + static bool alreadyInstantiated; + + public: + + struct OnUnusedOptions { enum DoWhat { Ignore, Fail }; }; + + Session() + : m_cli( makeCommandLineParser() ) { + if( alreadyInstantiated ) { + std::string msg = "Only one instance of Catch::Session can ever be used"; + Catch::cerr() << msg << std::endl; + throw std::logic_error( msg ); + } + alreadyInstantiated = true; + } + ~Session() { + Catch::cleanUp(); + } + + void showHelp( std::string const& processName ) { + Catch::cout() << "\nCatch v" << libraryVersion() << "\n"; + + m_cli.usage( Catch::cout(), processName ); + Catch::cout() << "For more detail usage please see the project docs\n" << std::endl; + } + + int applyCommandLine( int argc, char const* const* const argv, OnUnusedOptions::DoWhat unusedOptionBehaviour = OnUnusedOptions::Fail ) { + try { + m_cli.setThrowOnUnrecognisedTokens( unusedOptionBehaviour == OnUnusedOptions::Fail ); + m_unusedTokens = m_cli.parseInto( Clara::argsToVector( argc, argv ), m_configData ); + if( m_configData.showHelp ) + showHelp( m_configData.processName ); + m_config.reset(); + } + catch( std::exception& ex ) { + { + Colour colourGuard( Colour::Red ); + Catch::cerr() + << "\nError(s) in input:\n" + << Text( ex.what(), TextAttributes().setIndent(2) ) + << "\n\n"; + } + m_cli.usage( Catch::cout(), m_configData.processName ); + return (std::numeric_limits::max)(); + } + return 0; + } + + void useConfigData( ConfigData const& _configData ) { + m_configData = _configData; + m_config.reset(); + } + + int run( int argc, char const* const* const argv ) { + + int returnCode = applyCommandLine( argc, argv ); + if( returnCode == 0 ) + returnCode = run(); + return returnCode; + } + + #if defined(WIN32) && defined(UNICODE) + int run( int argc, wchar_t const* const* const argv ) { + + char **utf8Argv = new char *[ argc ]; + + for ( int i = 0; i < argc; ++i ) { + int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL ); + + utf8Argv[ i ] = new char[ bufSize ]; + + WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL ); + } + + int returnCode = applyCommandLine( argc, utf8Argv ); + if( returnCode == 0 ) + returnCode = run(); + + for ( int i = 0; i < argc; ++i ) + delete [] utf8Argv[ i ]; + + delete [] utf8Argv; + + return returnCode; + } + #endif + + int run() { + if( m_configData.showHelp ) + return 0; + + try + { + config(); // Force config to be constructed + + seedRng( *m_config ); + + if( m_configData.filenamesAsTags ) + applyFilenamesAsTags( *m_config ); + + // Handle list request + if( Option listed = list( config() ) ) + return static_cast( *listed ); + + return static_cast( runTests( m_config ).assertions.failed ); + } + catch( std::exception& ex ) { + Catch::cerr() << ex.what() << std::endl; + return (std::numeric_limits::max)(); + } + } + + Clara::CommandLine const& cli() const { + return m_cli; + } + std::vector const& unusedTokens() const { + return m_unusedTokens; + } + ConfigData& configData() { + return m_configData; + } + Config& config() { + if( !m_config ) + m_config = new Config( m_configData ); + return *m_config; + } + private: + Clara::CommandLine m_cli; + std::vector m_unusedTokens; + ConfigData m_configData; + Ptr m_config; + }; + + bool Session::alreadyInstantiated = false; + +} // end namespace Catch + +// #included from: catch_registry_hub.hpp +#define TWOBLUECUBES_CATCH_REGISTRY_HUB_HPP_INCLUDED + +// #included from: catch_test_case_registry_impl.hpp +#define TWOBLUECUBES_CATCH_TEST_CASE_REGISTRY_IMPL_HPP_INCLUDED + +#include +#include +#include +#include + +namespace Catch { + + struct RandomNumberGenerator { + typedef std::ptrdiff_t result_type; + + result_type operator()( result_type n ) const { return std::rand() % n; } + +#ifdef CATCH_CONFIG_CPP11_SHUFFLE + static constexpr result_type min() { return 0; } + static constexpr result_type max() { return 1000000; } + result_type operator()() const { return std::rand() % max(); } +#endif + template + static void shuffle( V& vector ) { + RandomNumberGenerator rng; +#ifdef CATCH_CONFIG_CPP11_SHUFFLE + std::shuffle( vector.begin(), vector.end(), rng ); +#else + std::random_shuffle( vector.begin(), vector.end(), rng ); +#endif + } + }; + + inline std::vector sortTests( IConfig const& config, std::vector const& unsortedTestCases ) { + + std::vector sorted = unsortedTestCases; + + switch( config.runOrder() ) { + case RunTests::InLexicographicalOrder: + std::sort( sorted.begin(), sorted.end() ); + break; + case RunTests::InRandomOrder: + { + seedRng( config ); + RandomNumberGenerator::shuffle( sorted ); + } + break; + case RunTests::InDeclarationOrder: + // already in declaration order + break; + } + return sorted; + } + bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) { + return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() ); + } + + void enforceNoDuplicateTestCases( std::vector const& functions ) { + std::set seenFunctions; + for( std::vector::const_iterator it = functions.begin(), itEnd = functions.end(); + it != itEnd; + ++it ) { + std::pair::const_iterator, bool> prev = seenFunctions.insert( *it ); + if( !prev.second ) { + std::ostringstream ss; + + ss << Colour( Colour::Red ) + << "error: TEST_CASE( \"" << it->name << "\" ) already defined.\n" + << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << '\n' + << "\tRedefined at " << it->getTestCaseInfo().lineInfo << std::endl; + + throw std::runtime_error(ss.str()); + } + } + } + + std::vector filterTests( std::vector const& testCases, TestSpec const& testSpec, IConfig const& config ) { + std::vector filtered; + filtered.reserve( testCases.size() ); + for( std::vector::const_iterator it = testCases.begin(), itEnd = testCases.end(); + it != itEnd; + ++it ) + if( matchTest( *it, testSpec, config ) ) + filtered.push_back( *it ); + return filtered; + } + std::vector const& getAllTestCasesSorted( IConfig const& config ) { + return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config ); + } + + class TestRegistry : public ITestCaseRegistry { + public: + TestRegistry() + : m_currentSortOrder( RunTests::InDeclarationOrder ), + m_unnamedCount( 0 ) + {} + virtual ~TestRegistry(); + + virtual void registerTest( TestCase const& testCase ) { + std::string name = testCase.getTestCaseInfo().name; + if( name.empty() ) { + std::ostringstream oss; + oss << "Anonymous test case " << ++m_unnamedCount; + return registerTest( testCase.withName( oss.str() ) ); + } + m_functions.push_back( testCase ); + } + + virtual std::vector const& getAllTests() const { + return m_functions; + } + virtual std::vector const& getAllTestsSorted( IConfig const& config ) const { + if( m_sortedFunctions.empty() ) + enforceNoDuplicateTestCases( m_functions ); + + if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) { + m_sortedFunctions = sortTests( config, m_functions ); + m_currentSortOrder = config.runOrder(); + } + return m_sortedFunctions; + } + + private: + std::vector m_functions; + mutable RunTests::InWhatOrder m_currentSortOrder; + mutable std::vector m_sortedFunctions; + size_t m_unnamedCount; + std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised + }; + + /////////////////////////////////////////////////////////////////////////// + + class FreeFunctionTestCase : public SharedImpl { + public: + + FreeFunctionTestCase( TestFunction fun ) : m_fun( fun ) {} + + virtual void invoke() const { + m_fun(); + } + + private: + virtual ~FreeFunctionTestCase(); + + TestFunction m_fun; + }; + + inline std::string extractClassName( std::string const& classOrQualifiedMethodName ) { + std::string className = classOrQualifiedMethodName; + if( startsWith( className, '&' ) ) + { + std::size_t lastColons = className.rfind( "::" ); + std::size_t penultimateColons = className.rfind( "::", lastColons-1 ); + if( penultimateColons == std::string::npos ) + penultimateColons = 1; + className = className.substr( penultimateColons, lastColons-penultimateColons ); + } + return className; + } + + void registerTestCase + ( ITestCase* testCase, + char const* classOrQualifiedMethodName, + NameAndDesc const& nameAndDesc, + SourceLineInfo const& lineInfo ) { + + getMutableRegistryHub().registerTest + ( makeTestCase + ( testCase, + extractClassName( classOrQualifiedMethodName ), + nameAndDesc.name, + nameAndDesc.description, + lineInfo ) ); + } + void registerTestCaseFunction + ( TestFunction function, + SourceLineInfo const& lineInfo, + NameAndDesc const& nameAndDesc ) { + registerTestCase( new FreeFunctionTestCase( function ), "", nameAndDesc, lineInfo ); + } + + /////////////////////////////////////////////////////////////////////////// + + AutoReg::AutoReg + ( TestFunction function, + SourceLineInfo const& lineInfo, + NameAndDesc const& nameAndDesc ) { + registerTestCaseFunction( function, lineInfo, nameAndDesc ); + } + + AutoReg::~AutoReg() {} + +} // end namespace Catch + +// #included from: catch_reporter_registry.hpp +#define TWOBLUECUBES_CATCH_REPORTER_REGISTRY_HPP_INCLUDED + +#include + +namespace Catch { + + class ReporterRegistry : public IReporterRegistry { + + public: + + virtual ~ReporterRegistry() CATCH_OVERRIDE {} + + virtual IStreamingReporter* create( std::string const& name, Ptr const& config ) const CATCH_OVERRIDE { + FactoryMap::const_iterator it = m_factories.find( name ); + if( it == m_factories.end() ) + return CATCH_NULL; + return it->second->create( ReporterConfig( config ) ); + } + + void registerReporter( std::string const& name, Ptr const& factory ) { + m_factories.insert( std::make_pair( name, factory ) ); + } + void registerListener( Ptr const& factory ) { + m_listeners.push_back( factory ); + } + + virtual FactoryMap const& getFactories() const CATCH_OVERRIDE { + return m_factories; + } + virtual Listeners const& getListeners() const CATCH_OVERRIDE { + return m_listeners; + } + + private: + FactoryMap m_factories; + Listeners m_listeners; + }; +} + +// #included from: catch_exception_translator_registry.hpp +#define TWOBLUECUBES_CATCH_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED + +#ifdef __OBJC__ +#import "Foundation/Foundation.h" +#endif + +namespace Catch { + + class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry { + public: + ~ExceptionTranslatorRegistry() { + deleteAll( m_translators ); + } + + virtual void registerTranslator( const IExceptionTranslator* translator ) { + m_translators.push_back( translator ); + } + + virtual std::string translateActiveException() const { + try { +#ifdef __OBJC__ + // In Objective-C try objective-c exceptions first + @try { + return tryTranslators(); + } + @catch (NSException *exception) { + return Catch::toString( [exception description] ); + } +#else + return tryTranslators(); +#endif + } + catch( TestFailureException& ) { + throw; + } + catch( std::exception& ex ) { + return ex.what(); + } + catch( std::string& msg ) { + return msg; + } + catch( const char* msg ) { + return msg; + } + catch(...) { + return "Unknown exception"; + } + } + + std::string tryTranslators() const { + if( m_translators.empty() ) + throw; + else + return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() ); + } + + private: + std::vector m_translators; + }; +} + +// #included from: catch_tag_alias_registry.h +#define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_H_INCLUDED + +#include + +namespace Catch { + + class TagAliasRegistry : public ITagAliasRegistry { + public: + virtual ~TagAliasRegistry(); + virtual Option find( std::string const& alias ) const; + virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const; + void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ); + + private: + std::map m_registry; + }; + +} // end namespace Catch + +namespace Catch { + + namespace { + + class RegistryHub : public IRegistryHub, public IMutableRegistryHub { + + RegistryHub( RegistryHub const& ); + void operator=( RegistryHub const& ); + + public: // IRegistryHub + RegistryHub() { + } + virtual IReporterRegistry const& getReporterRegistry() const CATCH_OVERRIDE { + return m_reporterRegistry; + } + virtual ITestCaseRegistry const& getTestCaseRegistry() const CATCH_OVERRIDE { + return m_testCaseRegistry; + } + virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() CATCH_OVERRIDE { + return m_exceptionTranslatorRegistry; + } + virtual ITagAliasRegistry const& getTagAliasRegistry() const CATCH_OVERRIDE { + return m_tagAliasRegistry; + } + + public: // IMutableRegistryHub + virtual void registerReporter( std::string const& name, Ptr const& factory ) CATCH_OVERRIDE { + m_reporterRegistry.registerReporter( name, factory ); + } + virtual void registerListener( Ptr const& factory ) CATCH_OVERRIDE { + m_reporterRegistry.registerListener( factory ); + } + virtual void registerTest( TestCase const& testInfo ) CATCH_OVERRIDE { + m_testCaseRegistry.registerTest( testInfo ); + } + virtual void registerTranslator( const IExceptionTranslator* translator ) CATCH_OVERRIDE { + m_exceptionTranslatorRegistry.registerTranslator( translator ); + } + virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) CATCH_OVERRIDE { + m_tagAliasRegistry.add( alias, tag, lineInfo ); + } + + private: + TestRegistry m_testCaseRegistry; + ReporterRegistry m_reporterRegistry; + ExceptionTranslatorRegistry m_exceptionTranslatorRegistry; + TagAliasRegistry m_tagAliasRegistry; + }; + + // Single, global, instance + inline RegistryHub*& getTheRegistryHub() { + static RegistryHub* theRegistryHub = CATCH_NULL; + if( !theRegistryHub ) + theRegistryHub = new RegistryHub(); + return theRegistryHub; + } + } + + IRegistryHub& getRegistryHub() { + return *getTheRegistryHub(); + } + IMutableRegistryHub& getMutableRegistryHub() { + return *getTheRegistryHub(); + } + void cleanUp() { + delete getTheRegistryHub(); + getTheRegistryHub() = CATCH_NULL; + cleanUpContext(); + } + std::string translateActiveException() { + return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException(); + } + +} // end namespace Catch + +// #included from: catch_notimplemented_exception.hpp +#define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_HPP_INCLUDED + +#include + +namespace Catch { + + NotImplementedException::NotImplementedException( SourceLineInfo const& lineInfo ) + : m_lineInfo( lineInfo ) { + std::ostringstream oss; + oss << lineInfo << ": function "; + oss << "not implemented"; + m_what = oss.str(); + } + + const char* NotImplementedException::what() const CATCH_NOEXCEPT { + return m_what.c_str(); + } + +} // end namespace Catch + +// #included from: catch_context_impl.hpp +#define TWOBLUECUBES_CATCH_CONTEXT_IMPL_HPP_INCLUDED + +// #included from: catch_stream.hpp +#define TWOBLUECUBES_CATCH_STREAM_HPP_INCLUDED + +#include +#include +#include + +namespace Catch { + + template + class StreamBufImpl : public StreamBufBase { + char data[bufferSize]; + WriterF m_writer; + + public: + StreamBufImpl() { + setp( data, data + sizeof(data) ); + } + + ~StreamBufImpl() CATCH_NOEXCEPT { + sync(); + } + + private: + int overflow( int c ) { + sync(); + + if( c != EOF ) { + if( pbase() == epptr() ) + m_writer( std::string( 1, static_cast( c ) ) ); + else + sputc( static_cast( c ) ); + } + return 0; + } + + int sync() { + if( pbase() != pptr() ) { + m_writer( std::string( pbase(), static_cast( pptr() - pbase() ) ) ); + setp( pbase(), epptr() ); + } + return 0; + } + }; + + /////////////////////////////////////////////////////////////////////////// + + FileStream::FileStream( std::string const& filename ) { + m_ofs.open( filename.c_str() ); + if( m_ofs.fail() ) { + std::ostringstream oss; + oss << "Unable to open file: '" << filename << '\''; + throw std::domain_error( oss.str() ); + } + } + + std::ostream& FileStream::stream() const { + return m_ofs; + } + + struct OutputDebugWriter { + + void operator()( std::string const&str ) { + writeToDebugConsole( str ); + } + }; + + DebugOutStream::DebugOutStream() + : m_streamBuf( new StreamBufImpl() ), + m_os( m_streamBuf.get() ) + {} + + std::ostream& DebugOutStream::stream() const { + return m_os; + } + + // Store the streambuf from cout up-front because + // cout may get redirected when running tests + CoutStream::CoutStream() + : m_os( Catch::cout().rdbuf() ) + {} + + std::ostream& CoutStream::stream() const { + return m_os; + } + +#ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions + std::ostream& cout() { + return std::cout; + } + std::ostream& cerr() { + return std::cerr; + } +#endif +} + +namespace Catch { + + class Context : public IMutableContext { + + Context() : m_config( CATCH_NULL ), m_runner( CATCH_NULL ), m_resultCapture( CATCH_NULL ) {} + Context( Context const& ); + void operator=( Context const& ); + + public: + virtual ~Context() { + deleteAllValues( m_generatorsByTestName ); + } + + public: // IContext + virtual IResultCapture* getResultCapture() { + return m_resultCapture; + } + virtual IRunner* getRunner() { + return m_runner; + } + virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) { + return getGeneratorsForCurrentTest() + .getGeneratorInfo( fileInfo, totalSize ) + .getCurrentIndex(); + } + virtual bool advanceGeneratorsForCurrentTest() { + IGeneratorsForTest* generators = findGeneratorsForCurrentTest(); + return generators && generators->moveNext(); + } + + virtual Ptr getConfig() const { + return m_config; + } + + public: // IMutableContext + virtual void setResultCapture( IResultCapture* resultCapture ) { + m_resultCapture = resultCapture; + } + virtual void setRunner( IRunner* runner ) { + m_runner = runner; + } + virtual void setConfig( Ptr const& config ) { + m_config = config; + } + + friend IMutableContext& getCurrentMutableContext(); + + private: + IGeneratorsForTest* findGeneratorsForCurrentTest() { + std::string testName = getResultCapture()->getCurrentTestName(); + + std::map::const_iterator it = + m_generatorsByTestName.find( testName ); + return it != m_generatorsByTestName.end() + ? it->second + : CATCH_NULL; + } + + IGeneratorsForTest& getGeneratorsForCurrentTest() { + IGeneratorsForTest* generators = findGeneratorsForCurrentTest(); + if( !generators ) { + std::string testName = getResultCapture()->getCurrentTestName(); + generators = createGeneratorsForTest(); + m_generatorsByTestName.insert( std::make_pair( testName, generators ) ); + } + return *generators; + } + + private: + Ptr m_config; + IRunner* m_runner; + IResultCapture* m_resultCapture; + std::map m_generatorsByTestName; + }; + + namespace { + Context* currentContext = CATCH_NULL; + } + IMutableContext& getCurrentMutableContext() { + if( !currentContext ) + currentContext = new Context(); + return *currentContext; + } + IContext& getCurrentContext() { + return getCurrentMutableContext(); + } + + void cleanUpContext() { + delete currentContext; + currentContext = CATCH_NULL; + } +} + +// #included from: catch_console_colour_impl.hpp +#define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_IMPL_HPP_INCLUDED + +// #included from: catch_errno_guard.hpp +#define TWOBLUECUBES_CATCH_ERRNO_GUARD_HPP_INCLUDED + +#include + +namespace Catch { + + class ErrnoGuard { + public: + ErrnoGuard():m_oldErrno(errno){} + ~ErrnoGuard() { errno = m_oldErrno; } + private: + int m_oldErrno; + }; + +} + +namespace Catch { + namespace { + + struct IColourImpl { + virtual ~IColourImpl() {} + virtual void use( Colour::Code _colourCode ) = 0; + }; + + struct NoColourImpl : IColourImpl { + void use( Colour::Code ) {} + + static IColourImpl* instance() { + static NoColourImpl s_instance; + return &s_instance; + } + }; + + } // anon namespace +} // namespace Catch + +#if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI ) +# ifdef CATCH_PLATFORM_WINDOWS +# define CATCH_CONFIG_COLOUR_WINDOWS +# else +# define CATCH_CONFIG_COLOUR_ANSI +# endif +#endif + +#if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) ///////////////////////////////////////// + +namespace Catch { +namespace { + + class Win32ColourImpl : public IColourImpl { + public: + Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) ) + { + CONSOLE_SCREEN_BUFFER_INFO csbiInfo; + GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo ); + originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY ); + originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY ); + } + + virtual void use( Colour::Code _colourCode ) { + switch( _colourCode ) { + case Colour::None: return setTextAttribute( originalForegroundAttributes ); + case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); + case Colour::Red: return setTextAttribute( FOREGROUND_RED ); + case Colour::Green: return setTextAttribute( FOREGROUND_GREEN ); + case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE ); + case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN ); + case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN ); + case Colour::Grey: return setTextAttribute( 0 ); + + case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY ); + case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED ); + case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN ); + case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); + + case Colour::Bright: throw std::logic_error( "not a colour" ); + } + } + + private: + void setTextAttribute( WORD _textAttribute ) { + SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes ); + } + HANDLE stdoutHandle; + WORD originalForegroundAttributes; + WORD originalBackgroundAttributes; + }; + + IColourImpl* platformColourInstance() { + static Win32ColourImpl s_instance; + + Ptr config = getCurrentContext().getConfig(); + UseColour::YesOrNo colourMode = config + ? config->useColour() + : UseColour::Auto; + if( colourMode == UseColour::Auto ) + colourMode = !isDebuggerActive() + ? UseColour::Yes + : UseColour::No; + return colourMode == UseColour::Yes + ? &s_instance + : NoColourImpl::instance(); + } + +} // end anon namespace +} // end namespace Catch + +#elif defined( CATCH_CONFIG_COLOUR_ANSI ) ////////////////////////////////////// + +#include + +namespace Catch { +namespace { + + // use POSIX/ ANSI console terminal codes + // Thanks to Adam Strzelecki for original contribution + // (http://github.com/nanoant) + // https://github.com/philsquared/Catch/pull/131 + class PosixColourImpl : public IColourImpl { + public: + virtual void use( Colour::Code _colourCode ) { + switch( _colourCode ) { + case Colour::None: + case Colour::White: return setColour( "[0m" ); + case Colour::Red: return setColour( "[0;31m" ); + case Colour::Green: return setColour( "[0;32m" ); + case Colour::Blue: return setColour( "[0;34m" ); + case Colour::Cyan: return setColour( "[0;36m" ); + case Colour::Yellow: return setColour( "[0;33m" ); + case Colour::Grey: return setColour( "[1;30m" ); + + case Colour::LightGrey: return setColour( "[0;37m" ); + case Colour::BrightRed: return setColour( "[1;31m" ); + case Colour::BrightGreen: return setColour( "[1;32m" ); + case Colour::BrightWhite: return setColour( "[1;37m" ); + + case Colour::Bright: throw std::logic_error( "not a colour" ); + } + } + static IColourImpl* instance() { + static PosixColourImpl s_instance; + return &s_instance; + } + + private: + void setColour( const char* _escapeCode ) { + Catch::cout() << '\033' << _escapeCode; + } + }; + + IColourImpl* platformColourInstance() { + ErrnoGuard guard; + Ptr config = getCurrentContext().getConfig(); + UseColour::YesOrNo colourMode = config + ? config->useColour() + : UseColour::Auto; + if( colourMode == UseColour::Auto ) + colourMode = (!isDebuggerActive() && isatty(STDOUT_FILENO) ) + ? UseColour::Yes + : UseColour::No; + return colourMode == UseColour::Yes + ? PosixColourImpl::instance() + : NoColourImpl::instance(); + } + +} // end anon namespace +} // end namespace Catch + +#else // not Windows or ANSI /////////////////////////////////////////////// + +namespace Catch { + + static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); } + +} // end namespace Catch + +#endif // Windows/ ANSI/ None + +namespace Catch { + + Colour::Colour( Code _colourCode ) : m_moved( false ) { use( _colourCode ); } + Colour::Colour( Colour const& _other ) : m_moved( false ) { const_cast( _other ).m_moved = true; } + Colour::~Colour(){ if( !m_moved ) use( None ); } + + void Colour::use( Code _colourCode ) { + static IColourImpl* impl = platformColourInstance(); + impl->use( _colourCode ); + } + +} // end namespace Catch + +// #included from: catch_generators_impl.hpp +#define TWOBLUECUBES_CATCH_GENERATORS_IMPL_HPP_INCLUDED + +#include +#include +#include + +namespace Catch { + + struct GeneratorInfo : IGeneratorInfo { + + GeneratorInfo( std::size_t size ) + : m_size( size ), + m_currentIndex( 0 ) + {} + + bool moveNext() { + if( ++m_currentIndex == m_size ) { + m_currentIndex = 0; + return false; + } + return true; + } + + std::size_t getCurrentIndex() const { + return m_currentIndex; + } + + std::size_t m_size; + std::size_t m_currentIndex; + }; + + /////////////////////////////////////////////////////////////////////////// + + class GeneratorsForTest : public IGeneratorsForTest { + + public: + ~GeneratorsForTest() { + deleteAll( m_generatorsInOrder ); + } + + IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) { + std::map::const_iterator it = m_generatorsByName.find( fileInfo ); + if( it == m_generatorsByName.end() ) { + IGeneratorInfo* info = new GeneratorInfo( size ); + m_generatorsByName.insert( std::make_pair( fileInfo, info ) ); + m_generatorsInOrder.push_back( info ); + return *info; + } + return *it->second; + } + + bool moveNext() { + std::vector::const_iterator it = m_generatorsInOrder.begin(); + std::vector::const_iterator itEnd = m_generatorsInOrder.end(); + for(; it != itEnd; ++it ) { + if( (*it)->moveNext() ) + return true; + } + return false; + } + + private: + std::map m_generatorsByName; + std::vector m_generatorsInOrder; + }; + + IGeneratorsForTest* createGeneratorsForTest() + { + return new GeneratorsForTest(); + } + +} // end namespace Catch + +// #included from: catch_assertionresult.hpp +#define TWOBLUECUBES_CATCH_ASSERTIONRESULT_HPP_INCLUDED + +namespace Catch { + + AssertionInfo::AssertionInfo( std::string const& _macroName, + SourceLineInfo const& _lineInfo, + std::string const& _capturedExpression, + ResultDisposition::Flags _resultDisposition ) + : macroName( _macroName ), + lineInfo( _lineInfo ), + capturedExpression( _capturedExpression ), + resultDisposition( _resultDisposition ) + {} + + AssertionResult::AssertionResult() {} + + AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data ) + : m_info( info ), + m_resultData( data ) + {} + + AssertionResult::~AssertionResult() {} + + // Result was a success + bool AssertionResult::succeeded() const { + return Catch::isOk( m_resultData.resultType ); + } + + // Result was a success, or failure is suppressed + bool AssertionResult::isOk() const { + return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition ); + } + + ResultWas::OfType AssertionResult::getResultType() const { + return m_resultData.resultType; + } + + bool AssertionResult::hasExpression() const { + return !m_info.capturedExpression.empty(); + } + + bool AssertionResult::hasMessage() const { + return !m_resultData.message.empty(); + } + + std::string AssertionResult::getExpression() const { + if( isFalseTest( m_info.resultDisposition ) ) + return '!' + m_info.capturedExpression; + else + return m_info.capturedExpression; + } + std::string AssertionResult::getExpressionInMacro() const { + if( m_info.macroName.empty() ) + return m_info.capturedExpression; + else + return m_info.macroName + "( " + m_info.capturedExpression + " )"; + } + + bool AssertionResult::hasExpandedExpression() const { + return hasExpression() && getExpandedExpression() != getExpression(); + } + + std::string AssertionResult::getExpandedExpression() const { + return m_resultData.reconstructExpression(); + } + + std::string AssertionResult::getMessage() const { + return m_resultData.message; + } + SourceLineInfo AssertionResult::getSourceInfo() const { + return m_info.lineInfo; + } + + std::string AssertionResult::getTestMacroName() const { + return m_info.macroName; + } + + void AssertionResult::discardDecomposedExpression() const { + m_resultData.decomposedExpression = CATCH_NULL; + } + + void AssertionResult::expandDecomposedExpression() const { + m_resultData.reconstructExpression(); + } + +} // end namespace Catch + +// #included from: catch_test_case_info.hpp +#define TWOBLUECUBES_CATCH_TEST_CASE_INFO_HPP_INCLUDED + +#include + +namespace Catch { + + inline TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) { + if( startsWith( tag, '.' ) || + tag == "hide" || + tag == "!hide" ) + return TestCaseInfo::IsHidden; + else if( tag == "!throws" ) + return TestCaseInfo::Throws; + else if( tag == "!shouldfail" ) + return TestCaseInfo::ShouldFail; + else if( tag == "!mayfail" ) + return TestCaseInfo::MayFail; + else if( tag == "!nonportable" ) + return TestCaseInfo::NonPortable; + else + return TestCaseInfo::None; + } + inline bool isReservedTag( std::string const& tag ) { + return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( tag[0] ); + } + inline void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) { + if( isReservedTag( tag ) ) { + std::ostringstream ss; + ss << Colour(Colour::Red) + << "Tag name [" << tag << "] not allowed.\n" + << "Tag names starting with non alpha-numeric characters are reserved\n" + << Colour(Colour::FileName) + << _lineInfo << '\n'; + throw std::runtime_error(ss.str()); + } + } + + TestCase makeTestCase( ITestCase* _testCase, + std::string const& _className, + std::string const& _name, + std::string const& _descOrTags, + SourceLineInfo const& _lineInfo ) + { + bool isHidden( startsWith( _name, "./" ) ); // Legacy support + + // Parse out tags + std::set tags; + std::string desc, tag; + bool inTag = false; + for( std::size_t i = 0; i < _descOrTags.size(); ++i ) { + char c = _descOrTags[i]; + if( !inTag ) { + if( c == '[' ) + inTag = true; + else + desc += c; + } + else { + if( c == ']' ) { + TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag ); + if( prop == TestCaseInfo::IsHidden ) + isHidden = true; + else if( prop == TestCaseInfo::None ) + enforceNotReservedTag( tag, _lineInfo ); + + tags.insert( tag ); + tag.clear(); + inTag = false; + } + else + tag += c; + } + } + if( isHidden ) { + tags.insert( "hide" ); + tags.insert( "." ); + } + + TestCaseInfo info( _name, _className, desc, tags, _lineInfo ); + return TestCase( _testCase, info ); + } + + void setTags( TestCaseInfo& testCaseInfo, std::set const& tags ) + { + testCaseInfo.tags = tags; + testCaseInfo.lcaseTags.clear(); + + std::ostringstream oss; + for( std::set::const_iterator it = tags.begin(), itEnd = tags.end(); it != itEnd; ++it ) { + oss << '[' << *it << ']'; + std::string lcaseTag = toLower( *it ); + testCaseInfo.properties = static_cast( testCaseInfo.properties | parseSpecialTag( lcaseTag ) ); + testCaseInfo.lcaseTags.insert( lcaseTag ); + } + testCaseInfo.tagsAsString = oss.str(); + } + + TestCaseInfo::TestCaseInfo( std::string const& _name, + std::string const& _className, + std::string const& _description, + std::set const& _tags, + SourceLineInfo const& _lineInfo ) + : name( _name ), + className( _className ), + description( _description ), + lineInfo( _lineInfo ), + properties( None ) + { + setTags( *this, _tags ); + } + + TestCaseInfo::TestCaseInfo( TestCaseInfo const& other ) + : name( other.name ), + className( other.className ), + description( other.description ), + tags( other.tags ), + lcaseTags( other.lcaseTags ), + tagsAsString( other.tagsAsString ), + lineInfo( other.lineInfo ), + properties( other.properties ) + {} + + bool TestCaseInfo::isHidden() const { + return ( properties & IsHidden ) != 0; + } + bool TestCaseInfo::throws() const { + return ( properties & Throws ) != 0; + } + bool TestCaseInfo::okToFail() const { + return ( properties & (ShouldFail | MayFail ) ) != 0; + } + bool TestCaseInfo::expectedToFail() const { + return ( properties & (ShouldFail ) ) != 0; + } + + TestCase::TestCase( ITestCase* testCase, TestCaseInfo const& info ) : TestCaseInfo( info ), test( testCase ) {} + + TestCase::TestCase( TestCase const& other ) + : TestCaseInfo( other ), + test( other.test ) + {} + + TestCase TestCase::withName( std::string const& _newName ) const { + TestCase other( *this ); + other.name = _newName; + return other; + } + + void TestCase::swap( TestCase& other ) { + test.swap( other.test ); + name.swap( other.name ); + className.swap( other.className ); + description.swap( other.description ); + tags.swap( other.tags ); + lcaseTags.swap( other.lcaseTags ); + tagsAsString.swap( other.tagsAsString ); + std::swap( TestCaseInfo::properties, static_cast( other ).properties ); + std::swap( lineInfo, other.lineInfo ); + } + + void TestCase::invoke() const { + test->invoke(); + } + + bool TestCase::operator == ( TestCase const& other ) const { + return test.get() == other.test.get() && + name == other.name && + className == other.className; + } + + bool TestCase::operator < ( TestCase const& other ) const { + return name < other.name; + } + TestCase& TestCase::operator = ( TestCase const& other ) { + TestCase temp( other ); + swap( temp ); + return *this; + } + + TestCaseInfo const& TestCase::getTestCaseInfo() const + { + return *this; + } + +} // end namespace Catch + +// #included from: catch_version.hpp +#define TWOBLUECUBES_CATCH_VERSION_HPP_INCLUDED + +namespace Catch { + + Version::Version + ( unsigned int _majorVersion, + unsigned int _minorVersion, + unsigned int _patchNumber, + char const * const _branchName, + unsigned int _buildNumber ) + : majorVersion( _majorVersion ), + minorVersion( _minorVersion ), + patchNumber( _patchNumber ), + branchName( _branchName ), + buildNumber( _buildNumber ) + {} + + std::ostream& operator << ( std::ostream& os, Version const& version ) { + os << version.majorVersion << '.' + << version.minorVersion << '.' + << version.patchNumber; + // branchName is never null -> 0th char is \0 if it is empty + if (version.branchName[0]) { + os << '-' << version.branchName + << '.' << version.buildNumber; + } + return os; + } + + inline Version libraryVersion() { + static Version version( 1, 9, 4, "", 0 ); + return version; + } + +} + +// #included from: catch_message.hpp +#define TWOBLUECUBES_CATCH_MESSAGE_HPP_INCLUDED + +namespace Catch { + + MessageInfo::MessageInfo( std::string const& _macroName, + SourceLineInfo const& _lineInfo, + ResultWas::OfType _type ) + : macroName( _macroName ), + lineInfo( _lineInfo ), + type( _type ), + sequence( ++globalCount ) + {} + + // This may need protecting if threading support is added + unsigned int MessageInfo::globalCount = 0; + + //////////////////////////////////////////////////////////////////////////// + + ScopedMessage::ScopedMessage( MessageBuilder const& builder ) + : m_info( builder.m_info ) + { + m_info.message = builder.m_stream.str(); + getResultCapture().pushScopedMessage( m_info ); + } + ScopedMessage::ScopedMessage( ScopedMessage const& other ) + : m_info( other.m_info ) + {} + + ScopedMessage::~ScopedMessage() { + if ( !std::uncaught_exception() ){ + getResultCapture().popScopedMessage(m_info); + } + } + +} // end namespace Catch + +// #included from: catch_legacy_reporter_adapter.hpp +#define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_HPP_INCLUDED + +// #included from: catch_legacy_reporter_adapter.h +#define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_H_INCLUDED + +namespace Catch +{ + // Deprecated + struct IReporter : IShared { + virtual ~IReporter(); + + virtual bool shouldRedirectStdout() const = 0; + + virtual void StartTesting() = 0; + virtual void EndTesting( Totals const& totals ) = 0; + virtual void StartGroup( std::string const& groupName ) = 0; + virtual void EndGroup( std::string const& groupName, Totals const& totals ) = 0; + virtual void StartTestCase( TestCaseInfo const& testInfo ) = 0; + virtual void EndTestCase( TestCaseInfo const& testInfo, Totals const& totals, std::string const& stdOut, std::string const& stdErr ) = 0; + virtual void StartSection( std::string const& sectionName, std::string const& description ) = 0; + virtual void EndSection( std::string const& sectionName, Counts const& assertions ) = 0; + virtual void NoAssertionsInSection( std::string const& sectionName ) = 0; + virtual void NoAssertionsInTestCase( std::string const& testName ) = 0; + virtual void Aborted() = 0; + virtual void Result( AssertionResult const& result ) = 0; + }; + + class LegacyReporterAdapter : public SharedImpl + { + public: + LegacyReporterAdapter( Ptr const& legacyReporter ); + virtual ~LegacyReporterAdapter(); + + virtual ReporterPreferences getPreferences() const; + virtual void noMatchingTestCases( std::string const& ); + virtual void testRunStarting( TestRunInfo const& ); + virtual void testGroupStarting( GroupInfo const& groupInfo ); + virtual void testCaseStarting( TestCaseInfo const& testInfo ); + virtual void sectionStarting( SectionInfo const& sectionInfo ); + virtual void assertionStarting( AssertionInfo const& ); + virtual bool assertionEnded( AssertionStats const& assertionStats ); + virtual void sectionEnded( SectionStats const& sectionStats ); + virtual void testCaseEnded( TestCaseStats const& testCaseStats ); + virtual void testGroupEnded( TestGroupStats const& testGroupStats ); + virtual void testRunEnded( TestRunStats const& testRunStats ); + virtual void skipTest( TestCaseInfo const& ); + + private: + Ptr m_legacyReporter; + }; +} + +namespace Catch +{ + LegacyReporterAdapter::LegacyReporterAdapter( Ptr const& legacyReporter ) + : m_legacyReporter( legacyReporter ) + {} + LegacyReporterAdapter::~LegacyReporterAdapter() {} + + ReporterPreferences LegacyReporterAdapter::getPreferences() const { + ReporterPreferences prefs; + prefs.shouldRedirectStdOut = m_legacyReporter->shouldRedirectStdout(); + return prefs; + } + + void LegacyReporterAdapter::noMatchingTestCases( std::string const& ) {} + void LegacyReporterAdapter::testRunStarting( TestRunInfo const& ) { + m_legacyReporter->StartTesting(); + } + void LegacyReporterAdapter::testGroupStarting( GroupInfo const& groupInfo ) { + m_legacyReporter->StartGroup( groupInfo.name ); + } + void LegacyReporterAdapter::testCaseStarting( TestCaseInfo const& testInfo ) { + m_legacyReporter->StartTestCase( testInfo ); + } + void LegacyReporterAdapter::sectionStarting( SectionInfo const& sectionInfo ) { + m_legacyReporter->StartSection( sectionInfo.name, sectionInfo.description ); + } + void LegacyReporterAdapter::assertionStarting( AssertionInfo const& ) { + // Not on legacy interface + } + + bool LegacyReporterAdapter::assertionEnded( AssertionStats const& assertionStats ) { + if( assertionStats.assertionResult.getResultType() != ResultWas::Ok ) { + for( std::vector::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end(); + it != itEnd; + ++it ) { + if( it->type == ResultWas::Info ) { + ResultBuilder rb( it->macroName.c_str(), it->lineInfo, "", ResultDisposition::Normal ); + rb << it->message; + rb.setResultType( ResultWas::Info ); + AssertionResult result = rb.build(); + m_legacyReporter->Result( result ); + } + } + } + m_legacyReporter->Result( assertionStats.assertionResult ); + return true; + } + void LegacyReporterAdapter::sectionEnded( SectionStats const& sectionStats ) { + if( sectionStats.missingAssertions ) + m_legacyReporter->NoAssertionsInSection( sectionStats.sectionInfo.name ); + m_legacyReporter->EndSection( sectionStats.sectionInfo.name, sectionStats.assertions ); + } + void LegacyReporterAdapter::testCaseEnded( TestCaseStats const& testCaseStats ) { + m_legacyReporter->EndTestCase + ( testCaseStats.testInfo, + testCaseStats.totals, + testCaseStats.stdOut, + testCaseStats.stdErr ); + } + void LegacyReporterAdapter::testGroupEnded( TestGroupStats const& testGroupStats ) { + if( testGroupStats.aborting ) + m_legacyReporter->Aborted(); + m_legacyReporter->EndGroup( testGroupStats.groupInfo.name, testGroupStats.totals ); + } + void LegacyReporterAdapter::testRunEnded( TestRunStats const& testRunStats ) { + m_legacyReporter->EndTesting( testRunStats.totals ); + } + void LegacyReporterAdapter::skipTest( TestCaseInfo const& ) { + } +} + +// #included from: catch_timer.hpp + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wc++11-long-long" +#endif + +#ifdef CATCH_PLATFORM_WINDOWS + +#else + +#include + +#endif + +namespace Catch { + + namespace { +#ifdef CATCH_PLATFORM_WINDOWS + UInt64 getCurrentTicks() { + static UInt64 hz=0, hzo=0; + if (!hz) { + QueryPerformanceFrequency( reinterpret_cast( &hz ) ); + QueryPerformanceCounter( reinterpret_cast( &hzo ) ); + } + UInt64 t; + QueryPerformanceCounter( reinterpret_cast( &t ) ); + return ((t-hzo)*1000000)/hz; + } +#else + UInt64 getCurrentTicks() { + timeval t; + gettimeofday(&t,CATCH_NULL); + return static_cast( t.tv_sec ) * 1000000ull + static_cast( t.tv_usec ); + } +#endif + } + + void Timer::start() { + m_ticks = getCurrentTicks(); + } + unsigned int Timer::getElapsedMicroseconds() const { + return static_cast(getCurrentTicks() - m_ticks); + } + unsigned int Timer::getElapsedMilliseconds() const { + return static_cast(getElapsedMicroseconds()/1000); + } + double Timer::getElapsedSeconds() const { + return getElapsedMicroseconds()/1000000.0; + } + +} // namespace Catch + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif +// #included from: catch_common.hpp +#define TWOBLUECUBES_CATCH_COMMON_HPP_INCLUDED + +#include +#include + +namespace Catch { + + bool startsWith( std::string const& s, std::string const& prefix ) { + return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin()); + } + bool startsWith( std::string const& s, char prefix ) { + return !s.empty() && s[0] == prefix; + } + bool endsWith( std::string const& s, std::string const& suffix ) { + return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin()); + } + bool endsWith( std::string const& s, char suffix ) { + return !s.empty() && s[s.size()-1] == suffix; + } + bool contains( std::string const& s, std::string const& infix ) { + return s.find( infix ) != std::string::npos; + } + char toLowerCh(char c) { + return static_cast( std::tolower( c ) ); + } + void toLowerInPlace( std::string& s ) { + std::transform( s.begin(), s.end(), s.begin(), toLowerCh ); + } + std::string toLower( std::string const& s ) { + std::string lc = s; + toLowerInPlace( lc ); + return lc; + } + std::string trim( std::string const& str ) { + static char const* whitespaceChars = "\n\r\t "; + std::string::size_type start = str.find_first_not_of( whitespaceChars ); + std::string::size_type end = str.find_last_not_of( whitespaceChars ); + + return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string(); + } + + bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) { + bool replaced = false; + std::size_t i = str.find( replaceThis ); + while( i != std::string::npos ) { + replaced = true; + str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() ); + if( i < str.size()-withThis.size() ) + i = str.find( replaceThis, i+withThis.size() ); + else + i = std::string::npos; + } + return replaced; + } + + pluralise::pluralise( std::size_t count, std::string const& label ) + : m_count( count ), + m_label( label ) + {} + + std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) { + os << pluraliser.m_count << ' ' << pluraliser.m_label; + if( pluraliser.m_count != 1 ) + os << 's'; + return os; + } + + SourceLineInfo::SourceLineInfo() : file(""), line( 0 ){} + SourceLineInfo::SourceLineInfo( char const* _file, std::size_t _line ) + : file( _file ), + line( _line ) + {} + bool SourceLineInfo::empty() const { + return file[0] == '\0'; + } + bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const { + return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0); + } + bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const { + return line < other.line || ( line == other.line && (std::strcmp(file, other.file) < 0)); + } + + void seedRng( IConfig const& config ) { + if( config.rngSeed() != 0 ) + std::srand( config.rngSeed() ); + } + unsigned int rngSeed() { + return getCurrentContext().getConfig()->rngSeed(); + } + + std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) { +#ifndef __GNUG__ + os << info.file << '(' << info.line << ')'; +#else + os << info.file << ':' << info.line; +#endif + return os; + } + + void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo ) { + std::ostringstream oss; + oss << locationInfo << ": Internal Catch error: '" << message << '\''; + if( alwaysTrue() ) + throw std::logic_error( oss.str() ); + } +} + +// #included from: catch_section.hpp +#define TWOBLUECUBES_CATCH_SECTION_HPP_INCLUDED + +namespace Catch { + + SectionInfo::SectionInfo + ( SourceLineInfo const& _lineInfo, + std::string const& _name, + std::string const& _description ) + : name( _name ), + description( _description ), + lineInfo( _lineInfo ) + {} + + Section::Section( SectionInfo const& info ) + : m_info( info ), + m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) ) + { + m_timer.start(); + } + + Section::~Section() { + if( m_sectionIncluded ) { + SectionEndInfo endInfo( m_info, m_assertions, m_timer.getElapsedSeconds() ); + if( std::uncaught_exception() ) + getResultCapture().sectionEndedEarly( endInfo ); + else + getResultCapture().sectionEnded( endInfo ); + } + } + + // This indicates whether the section should be executed or not + Section::operator bool() const { + return m_sectionIncluded; + } + +} // end namespace Catch + +// #included from: catch_debugger.hpp +#define TWOBLUECUBES_CATCH_DEBUGGER_HPP_INCLUDED + +#ifdef CATCH_PLATFORM_MAC + + #include + #include + #include + #include + #include + + namespace Catch{ + + // The following function is taken directly from the following technical note: + // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html + + // Returns true if the current process is being debugged (either + // running under the debugger or has a debugger attached post facto). + bool isDebuggerActive(){ + + int mib[4]; + struct kinfo_proc info; + size_t size; + + // Initialize the flags so that, if sysctl fails for some bizarre + // reason, we get a predictable result. + + info.kp_proc.p_flag = 0; + + // Initialize mib, which tells sysctl the info we want, in this case + // we're looking for information about a specific process ID. + + mib[0] = CTL_KERN; + mib[1] = KERN_PROC; + mib[2] = KERN_PROC_PID; + mib[3] = getpid(); + + // Call sysctl. + + size = sizeof(info); + if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, CATCH_NULL, 0) != 0 ) { + Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl; + return false; + } + + // We're being debugged if the P_TRACED flag is set. + + return ( (info.kp_proc.p_flag & P_TRACED) != 0 ); + } + } // namespace Catch + +#elif defined(CATCH_PLATFORM_LINUX) + #include + #include + + namespace Catch{ + // The standard POSIX way of detecting a debugger is to attempt to + // ptrace() the process, but this needs to be done from a child and not + // this process itself to still allow attaching to this process later + // if wanted, so is rather heavy. Under Linux we have the PID of the + // "debugger" (which doesn't need to be gdb, of course, it could also + // be strace, for example) in /proc/$PID/status, so just get it from + // there instead. + bool isDebuggerActive(){ + // Libstdc++ has a bug, where std::ifstream sets errno to 0 + // This way our users can properly assert over errno values + ErrnoGuard guard; + std::ifstream in("/proc/self/status"); + for( std::string line; std::getline(in, line); ) { + static const int PREFIX_LEN = 11; + if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) { + // We're traced if the PID is not 0 and no other PID starts + // with 0 digit, so it's enough to check for just a single + // character. + return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0'; + } + } + + return false; + } + } // namespace Catch +#elif defined(_MSC_VER) + extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); + namespace Catch { + bool isDebuggerActive() { + return IsDebuggerPresent() != 0; + } + } +#elif defined(__MINGW32__) + extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); + namespace Catch { + bool isDebuggerActive() { + return IsDebuggerPresent() != 0; + } + } +#else + namespace Catch { + inline bool isDebuggerActive() { return false; } + } +#endif // Platform + +#ifdef CATCH_PLATFORM_WINDOWS + + namespace Catch { + void writeToDebugConsole( std::string const& text ) { + ::OutputDebugStringA( text.c_str() ); + } + } +#else + namespace Catch { + void writeToDebugConsole( std::string const& text ) { + // !TBD: Need a version for Mac/ XCode and other IDEs + Catch::cout() << text; + } + } +#endif // Platform + +// #included from: catch_tostring.hpp +#define TWOBLUECUBES_CATCH_TOSTRING_HPP_INCLUDED + +namespace Catch { + +namespace Detail { + + const std::string unprintableString = "{?}"; + + namespace { + const int hexThreshold = 255; + + struct Endianness { + enum Arch { Big, Little }; + + static Arch which() { + union _{ + int asInt; + char asChar[sizeof (int)]; + } u; + + u.asInt = 1; + return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little; + } + }; + } + + std::string rawMemoryToString( const void *object, std::size_t size ) + { + // Reverse order for little endian architectures + int i = 0, end = static_cast( size ), inc = 1; + if( Endianness::which() == Endianness::Little ) { + i = end-1; + end = inc = -1; + } + + unsigned char const *bytes = static_cast(object); + std::ostringstream os; + os << "0x" << std::setfill('0') << std::hex; + for( ; i != end; i += inc ) + os << std::setw(2) << static_cast(bytes[i]); + return os.str(); + } +} + +std::string toString( std::string const& value ) { + std::string s = value; + if( getCurrentContext().getConfig()->showInvisibles() ) { + for(size_t i = 0; i < s.size(); ++i ) { + std::string subs; + switch( s[i] ) { + case '\n': subs = "\\n"; break; + case '\t': subs = "\\t"; break; + default: break; + } + if( !subs.empty() ) { + s = s.substr( 0, i ) + subs + s.substr( i+1 ); + ++i; + } + } + } + return '"' + s + '"'; +} +std::string toString( std::wstring const& value ) { + + std::string s; + s.reserve( value.size() ); + for(size_t i = 0; i < value.size(); ++i ) + s += value[i] <= 0xff ? static_cast( value[i] ) : '?'; + return Catch::toString( s ); +} + +std::string toString( const char* const value ) { + return value ? Catch::toString( std::string( value ) ) : std::string( "{null string}" ); +} + +std::string toString( char* const value ) { + return Catch::toString( static_cast( value ) ); +} + +std::string toString( const wchar_t* const value ) +{ + return value ? Catch::toString( std::wstring(value) ) : std::string( "{null string}" ); +} + +std::string toString( wchar_t* const value ) +{ + return Catch::toString( static_cast( value ) ); +} + +std::string toString( int value ) { + std::ostringstream oss; + oss << value; + if( value > Detail::hexThreshold ) + oss << " (0x" << std::hex << value << ')'; + return oss.str(); +} + +std::string toString( unsigned long value ) { + std::ostringstream oss; + oss << value; + if( value > Detail::hexThreshold ) + oss << " (0x" << std::hex << value << ')'; + return oss.str(); +} + +std::string toString( unsigned int value ) { + return Catch::toString( static_cast( value ) ); +} + +template +std::string fpToString( T value, int precision ) { + std::ostringstream oss; + oss << std::setprecision( precision ) + << std::fixed + << value; + std::string d = oss.str(); + std::size_t i = d.find_last_not_of( '0' ); + if( i != std::string::npos && i != d.size()-1 ) { + if( d[i] == '.' ) + i++; + d = d.substr( 0, i+1 ); + } + return d; +} + +std::string toString( const double value ) { + return fpToString( value, 10 ); +} +std::string toString( const float value ) { + return fpToString( value, 5 ) + 'f'; +} + +std::string toString( bool value ) { + return value ? "true" : "false"; +} + +std::string toString( char value ) { + if ( value == '\r' ) + return "'\\r'"; + if ( value == '\f' ) + return "'\\f'"; + if ( value == '\n' ) + return "'\\n'"; + if ( value == '\t' ) + return "'\\t'"; + if ( '\0' <= value && value < ' ' ) + return toString( static_cast( value ) ); + char chstr[] = "' '"; + chstr[1] = value; + return chstr; +} + +std::string toString( signed char value ) { + return toString( static_cast( value ) ); +} + +std::string toString( unsigned char value ) { + return toString( static_cast( value ) ); +} + +#ifdef CATCH_CONFIG_CPP11_LONG_LONG +std::string toString( long long value ) { + std::ostringstream oss; + oss << value; + if( value > Detail::hexThreshold ) + oss << " (0x" << std::hex << value << ')'; + return oss.str(); +} +std::string toString( unsigned long long value ) { + std::ostringstream oss; + oss << value; + if( value > Detail::hexThreshold ) + oss << " (0x" << std::hex << value << ')'; + return oss.str(); +} +#endif + +#ifdef CATCH_CONFIG_CPP11_NULLPTR +std::string toString( std::nullptr_t ) { + return "nullptr"; +} +#endif + +#ifdef __OBJC__ + std::string toString( NSString const * const& nsstring ) { + if( !nsstring ) + return "nil"; + return "@" + toString([nsstring UTF8String]); + } + std::string toString( NSString * CATCH_ARC_STRONG const& nsstring ) { + if( !nsstring ) + return "nil"; + return "@" + toString([nsstring UTF8String]); + } + std::string toString( NSObject* const& nsObject ) { + return toString( [nsObject description] ); + } +#endif + +} // end namespace Catch + +// #included from: catch_result_builder.hpp +#define TWOBLUECUBES_CATCH_RESULT_BUILDER_HPP_INCLUDED + +namespace Catch { + + std::string capturedExpressionWithSecondArgument( std::string const& capturedExpression, std::string const& secondArg ) { + return secondArg.empty() || secondArg == "\"\"" + ? capturedExpression + : capturedExpression + ", " + secondArg; + } + ResultBuilder::ResultBuilder( char const* macroName, + SourceLineInfo const& lineInfo, + char const* capturedExpression, + ResultDisposition::Flags resultDisposition, + char const* secondArg ) + : m_assertionInfo( macroName, lineInfo, capturedExpressionWithSecondArgument( capturedExpression, secondArg ), resultDisposition ), + m_shouldDebugBreak( false ), + m_shouldThrow( false ), + m_guardException( false ) + {} + + ResultBuilder::~ResultBuilder() { +#if defined(CATCH_CONFIG_FAST_COMPILE) + if ( m_guardException ) { + m_stream.oss << "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE"; + captureResult( ResultWas::ThrewException ); + getCurrentContext().getResultCapture()->exceptionEarlyReported(); + } +#endif + } + + ResultBuilder& ResultBuilder::setResultType( ResultWas::OfType result ) { + m_data.resultType = result; + return *this; + } + ResultBuilder& ResultBuilder::setResultType( bool result ) { + m_data.resultType = result ? ResultWas::Ok : ResultWas::ExpressionFailed; + return *this; + } + + void ResultBuilder::endExpression( DecomposedExpression const& expr ) { + AssertionResult result = build( expr ); + handleResult( result ); + } + + void ResultBuilder::useActiveException( ResultDisposition::Flags resultDisposition ) { + m_assertionInfo.resultDisposition = resultDisposition; + m_stream.oss << Catch::translateActiveException(); + captureResult( ResultWas::ThrewException ); + } + + void ResultBuilder::captureResult( ResultWas::OfType resultType ) { + setResultType( resultType ); + captureExpression(); + } + + void ResultBuilder::captureExpectedException( std::string const& expectedMessage ) { + if( expectedMessage.empty() ) + captureExpectedException( Matchers::Impl::MatchAllOf() ); + else + captureExpectedException( Matchers::Equals( expectedMessage ) ); + } + + void ResultBuilder::captureExpectedException( Matchers::Impl::MatcherBase const& matcher ) { + + assert( !isFalseTest( m_assertionInfo.resultDisposition ) ); + AssertionResultData data = m_data; + data.resultType = ResultWas::Ok; + data.reconstructedExpression = m_assertionInfo.capturedExpression; + + std::string actualMessage = Catch::translateActiveException(); + if( !matcher.match( actualMessage ) ) { + data.resultType = ResultWas::ExpressionFailed; + data.reconstructedExpression = actualMessage; + } + AssertionResult result( m_assertionInfo, data ); + handleResult( result ); + } + + void ResultBuilder::captureExpression() { + AssertionResult result = build(); + handleResult( result ); + } + + void ResultBuilder::handleResult( AssertionResult const& result ) + { + getResultCapture().assertionEnded( result ); + + if( !result.isOk() ) { + if( getCurrentContext().getConfig()->shouldDebugBreak() ) + m_shouldDebugBreak = true; + if( getCurrentContext().getRunner()->aborting() || (m_assertionInfo.resultDisposition & ResultDisposition::Normal) ) + m_shouldThrow = true; + } + } + + void ResultBuilder::react() { +#if defined(CATCH_CONFIG_FAST_COMPILE) + if (m_shouldDebugBreak) { + /////////////////////////////////////////////////////////////////// + // To inspect the state during test, you need to go one level up the callstack + // To go back to the test and change execution, jump over the throw statement + /////////////////////////////////////////////////////////////////// + CATCH_BREAK_INTO_DEBUGGER(); + } +#endif + if( m_shouldThrow ) + throw Catch::TestFailureException(); + } + + bool ResultBuilder::shouldDebugBreak() const { return m_shouldDebugBreak; } + bool ResultBuilder::allowThrows() const { return getCurrentContext().getConfig()->allowThrows(); } + + AssertionResult ResultBuilder::build() const + { + return build( *this ); + } + + // CAVEAT: The returned AssertionResult stores a pointer to the argument expr, + // a temporary DecomposedExpression, which in turn holds references to + // operands, possibly temporary as well. + // It should immediately be passed to handleResult; if the expression + // needs to be reported, its string expansion must be composed before + // the temporaries are destroyed. + AssertionResult ResultBuilder::build( DecomposedExpression const& expr ) const + { + assert( m_data.resultType != ResultWas::Unknown ); + AssertionResultData data = m_data; + + // Flip bool results if FalseTest flag is set + if( isFalseTest( m_assertionInfo.resultDisposition ) ) { + data.negate( expr.isBinaryExpression() ); + } + + data.message = m_stream.oss.str(); + data.decomposedExpression = &expr; // for lazy reconstruction + return AssertionResult( m_assertionInfo, data ); + } + + void ResultBuilder::reconstructExpression( std::string& dest ) const { + dest = m_assertionInfo.capturedExpression; + } + + void ResultBuilder::setExceptionGuard() { + m_guardException = true; + } + void ResultBuilder::unsetExceptionGuard() { + m_guardException = false; + } + +} // end namespace Catch + +// #included from: catch_tag_alias_registry.hpp +#define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_HPP_INCLUDED + +namespace Catch { + + TagAliasRegistry::~TagAliasRegistry() {} + + Option TagAliasRegistry::find( std::string const& alias ) const { + std::map::const_iterator it = m_registry.find( alias ); + if( it != m_registry.end() ) + return it->second; + else + return Option(); + } + + std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const { + std::string expandedTestSpec = unexpandedTestSpec; + for( std::map::const_iterator it = m_registry.begin(), itEnd = m_registry.end(); + it != itEnd; + ++it ) { + std::size_t pos = expandedTestSpec.find( it->first ); + if( pos != std::string::npos ) { + expandedTestSpec = expandedTestSpec.substr( 0, pos ) + + it->second.tag + + expandedTestSpec.substr( pos + it->first.size() ); + } + } + return expandedTestSpec; + } + + void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) { + + if( !startsWith( alias, "[@" ) || !endsWith( alias, ']' ) ) { + std::ostringstream oss; + oss << Colour( Colour::Red ) + << "error: tag alias, \"" << alias << "\" is not of the form [@alias name].\n" + << Colour( Colour::FileName ) + << lineInfo << '\n'; + throw std::domain_error( oss.str().c_str() ); + } + if( !m_registry.insert( std::make_pair( alias, TagAlias( tag, lineInfo ) ) ).second ) { + std::ostringstream oss; + oss << Colour( Colour::Red ) + << "error: tag alias, \"" << alias << "\" already registered.\n" + << "\tFirst seen at " + << Colour( Colour::Red ) << find(alias)->lineInfo << '\n' + << Colour( Colour::Red ) << "\tRedefined at " + << Colour( Colour::FileName) << lineInfo << '\n'; + throw std::domain_error( oss.str().c_str() ); + } + } + + ITagAliasRegistry::~ITagAliasRegistry() {} + + ITagAliasRegistry const& ITagAliasRegistry::get() { + return getRegistryHub().getTagAliasRegistry(); + } + + RegistrarForTagAliases::RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) { + getMutableRegistryHub().registerTagAlias( alias, tag, lineInfo ); + } + +} // end namespace Catch + +// #included from: catch_matchers_string.hpp + +namespace Catch { +namespace Matchers { + + namespace StdString { + + CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity ) + : m_caseSensitivity( caseSensitivity ), + m_str( adjustString( str ) ) + {} + std::string CasedString::adjustString( std::string const& str ) const { + return m_caseSensitivity == CaseSensitive::No + ? toLower( str ) + : str; + } + std::string CasedString::caseSensitivitySuffix() const { + return m_caseSensitivity == CaseSensitive::No + ? " (case insensitive)" + : std::string(); + } + + StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator ) + : m_comparator( comparator ), + m_operation( operation ) { + } + + std::string StringMatcherBase::describe() const { + std::string description; + description.reserve(5 + m_operation.size() + m_comparator.m_str.size() + + m_comparator.caseSensitivitySuffix().size()); + description += m_operation; + description += ": \""; + description += m_comparator.m_str; + description += "\""; + description += m_comparator.caseSensitivitySuffix(); + return description; + } + + EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {} + + bool EqualsMatcher::match( std::string const& source ) const { + return m_comparator.adjustString( source ) == m_comparator.m_str; + } + + ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {} + + bool ContainsMatcher::match( std::string const& source ) const { + return contains( m_comparator.adjustString( source ), m_comparator.m_str ); + } + + StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {} + + bool StartsWithMatcher::match( std::string const& source ) const { + return startsWith( m_comparator.adjustString( source ), m_comparator.m_str ); + } + + EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {} + + bool EndsWithMatcher::match( std::string const& source ) const { + return endsWith( m_comparator.adjustString( source ), m_comparator.m_str ); + } + + } // namespace StdString + + StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) { + return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) ); + } + StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) { + return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) ); + } + StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) { + return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) ); + } + StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) { + return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) ); + } + +} // namespace Matchers +} // namespace Catch +// #included from: ../reporters/catch_reporter_multi.hpp +#define TWOBLUECUBES_CATCH_REPORTER_MULTI_HPP_INCLUDED + +namespace Catch { + +class MultipleReporters : public SharedImpl { + typedef std::vector > Reporters; + Reporters m_reporters; + +public: + void add( Ptr const& reporter ) { + m_reporters.push_back( reporter ); + } + +public: // IStreamingReporter + + virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE { + return m_reporters[0]->getPreferences(); + } + + virtual void noMatchingTestCases( std::string const& spec ) CATCH_OVERRIDE { + for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it ) + (*it)->noMatchingTestCases( spec ); + } + + virtual void testRunStarting( TestRunInfo const& testRunInfo ) CATCH_OVERRIDE { + for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it ) + (*it)->testRunStarting( testRunInfo ); + } + + virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE { + for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it ) + (*it)->testGroupStarting( groupInfo ); + } + + virtual void testCaseStarting( TestCaseInfo const& testInfo ) CATCH_OVERRIDE { + for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it ) + (*it)->testCaseStarting( testInfo ); + } + + virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE { + for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it ) + (*it)->sectionStarting( sectionInfo ); + } + + virtual void assertionStarting( AssertionInfo const& assertionInfo ) CATCH_OVERRIDE { + for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it ) + (*it)->assertionStarting( assertionInfo ); + } + + // The return value indicates if the messages buffer should be cleared: + virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE { + bool clearBuffer = false; + for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it ) + clearBuffer |= (*it)->assertionEnded( assertionStats ); + return clearBuffer; + } + + virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE { + for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it ) + (*it)->sectionEnded( sectionStats ); + } + + virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE { + for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it ) + (*it)->testCaseEnded( testCaseStats ); + } + + virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE { + for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it ) + (*it)->testGroupEnded( testGroupStats ); + } + + virtual void testRunEnded( TestRunStats const& testRunStats ) CATCH_OVERRIDE { + for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it ) + (*it)->testRunEnded( testRunStats ); + } + + virtual void skipTest( TestCaseInfo const& testInfo ) CATCH_OVERRIDE { + for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it ) + (*it)->skipTest( testInfo ); + } + + virtual MultipleReporters* tryAsMulti() CATCH_OVERRIDE { + return this; + } + +}; + +Ptr addReporter( Ptr const& existingReporter, Ptr const& additionalReporter ) { + Ptr resultingReporter; + + if( existingReporter ) { + MultipleReporters* multi = existingReporter->tryAsMulti(); + if( !multi ) { + multi = new MultipleReporters; + resultingReporter = Ptr( multi ); + if( existingReporter ) + multi->add( existingReporter ); + } + else + resultingReporter = existingReporter; + multi->add( additionalReporter ); + } + else + resultingReporter = additionalReporter; + + return resultingReporter; +} + +} // end namespace Catch + +// #included from: ../reporters/catch_reporter_xml.hpp +#define TWOBLUECUBES_CATCH_REPORTER_XML_HPP_INCLUDED + +// #included from: catch_reporter_bases.hpp +#define TWOBLUECUBES_CATCH_REPORTER_BASES_HPP_INCLUDED + +#include +#include +#include +#include + +namespace Catch { + + namespace { + // Because formatting using c++ streams is stateful, drop down to C is required + // Alternatively we could use stringstream, but its performance is... not good. + std::string getFormattedDuration( double duration ) { + // Max exponent + 1 is required to represent the whole part + // + 1 for decimal point + // + 3 for the 3 decimal places + // + 1 for null terminator + const size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1; + char buffer[maxDoubleSize]; + + // Save previous errno, to prevent sprintf from overwriting it + ErrnoGuard guard; +#ifdef _MSC_VER + sprintf_s(buffer, "%.3f", duration); +#else + sprintf(buffer, "%.3f", duration); +#endif + return std::string(buffer); + } + } + + struct StreamingReporterBase : SharedImpl { + + StreamingReporterBase( ReporterConfig const& _config ) + : m_config( _config.fullConfig() ), + stream( _config.stream() ) + { + m_reporterPrefs.shouldRedirectStdOut = false; + } + + virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE { + return m_reporterPrefs; + } + + virtual ~StreamingReporterBase() CATCH_OVERRIDE; + + virtual void noMatchingTestCases( std::string const& ) CATCH_OVERRIDE {} + + virtual void testRunStarting( TestRunInfo const& _testRunInfo ) CATCH_OVERRIDE { + currentTestRunInfo = _testRunInfo; + } + virtual void testGroupStarting( GroupInfo const& _groupInfo ) CATCH_OVERRIDE { + currentGroupInfo = _groupInfo; + } + + virtual void testCaseStarting( TestCaseInfo const& _testInfo ) CATCH_OVERRIDE { + currentTestCaseInfo = _testInfo; + } + virtual void sectionStarting( SectionInfo const& _sectionInfo ) CATCH_OVERRIDE { + m_sectionStack.push_back( _sectionInfo ); + } + + virtual void sectionEnded( SectionStats const& /* _sectionStats */ ) CATCH_OVERRIDE { + m_sectionStack.pop_back(); + } + virtual void testCaseEnded( TestCaseStats const& /* _testCaseStats */ ) CATCH_OVERRIDE { + currentTestCaseInfo.reset(); + } + virtual void testGroupEnded( TestGroupStats const& /* _testGroupStats */ ) CATCH_OVERRIDE { + currentGroupInfo.reset(); + } + virtual void testRunEnded( TestRunStats const& /* _testRunStats */ ) CATCH_OVERRIDE { + currentTestCaseInfo.reset(); + currentGroupInfo.reset(); + currentTestRunInfo.reset(); + } + + virtual void skipTest( TestCaseInfo const& ) CATCH_OVERRIDE { + // Don't do anything with this by default. + // It can optionally be overridden in the derived class. + } + + Ptr m_config; + std::ostream& stream; + + LazyStat currentTestRunInfo; + LazyStat currentGroupInfo; + LazyStat currentTestCaseInfo; + + std::vector m_sectionStack; + ReporterPreferences m_reporterPrefs; + }; + + struct CumulativeReporterBase : SharedImpl { + template + struct Node : SharedImpl<> { + explicit Node( T const& _value ) : value( _value ) {} + virtual ~Node() {} + + typedef std::vector > ChildNodes; + T value; + ChildNodes children; + }; + struct SectionNode : SharedImpl<> { + explicit SectionNode( SectionStats const& _stats ) : stats( _stats ) {} + virtual ~SectionNode(); + + bool operator == ( SectionNode const& other ) const { + return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo; + } + bool operator == ( Ptr const& other ) const { + return operator==( *other ); + } + + SectionStats stats; + typedef std::vector > ChildSections; + typedef std::vector Assertions; + ChildSections childSections; + Assertions assertions; + std::string stdOut; + std::string stdErr; + }; + + struct BySectionInfo { + BySectionInfo( SectionInfo const& other ) : m_other( other ) {} + BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {} + bool operator() ( Ptr const& node ) const { + return node->stats.sectionInfo.lineInfo == m_other.lineInfo; + } + private: + void operator=( BySectionInfo const& ); + SectionInfo const& m_other; + }; + + typedef Node TestCaseNode; + typedef Node TestGroupNode; + typedef Node TestRunNode; + + CumulativeReporterBase( ReporterConfig const& _config ) + : m_config( _config.fullConfig() ), + stream( _config.stream() ) + { + m_reporterPrefs.shouldRedirectStdOut = false; + } + ~CumulativeReporterBase(); + + virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE { + return m_reporterPrefs; + } + + virtual void testRunStarting( TestRunInfo const& ) CATCH_OVERRIDE {} + virtual void testGroupStarting( GroupInfo const& ) CATCH_OVERRIDE {} + + virtual void testCaseStarting( TestCaseInfo const& ) CATCH_OVERRIDE {} + + virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE { + SectionStats incompleteStats( sectionInfo, Counts(), 0, false ); + Ptr node; + if( m_sectionStack.empty() ) { + if( !m_rootSection ) + m_rootSection = new SectionNode( incompleteStats ); + node = m_rootSection; + } + else { + SectionNode& parentNode = *m_sectionStack.back(); + SectionNode::ChildSections::const_iterator it = + std::find_if( parentNode.childSections.begin(), + parentNode.childSections.end(), + BySectionInfo( sectionInfo ) ); + if( it == parentNode.childSections.end() ) { + node = new SectionNode( incompleteStats ); + parentNode.childSections.push_back( node ); + } + else + node = *it; + } + m_sectionStack.push_back( node ); + m_deepestSection = node; + } + + virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE {} + + virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE { + assert( !m_sectionStack.empty() ); + SectionNode& sectionNode = *m_sectionStack.back(); + sectionNode.assertions.push_back( assertionStats ); + // AssertionResult holds a pointer to a temporary DecomposedExpression, + // which getExpandedExpression() calls to build the expression string. + // Our section stack copy of the assertionResult will likely outlive the + // temporary, so it must be expanded or discarded now to avoid calling + // a destroyed object later. + prepareExpandedExpression( sectionNode.assertions.back().assertionResult ); + return true; + } + virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE { + assert( !m_sectionStack.empty() ); + SectionNode& node = *m_sectionStack.back(); + node.stats = sectionStats; + m_sectionStack.pop_back(); + } + virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE { + Ptr node = new TestCaseNode( testCaseStats ); + assert( m_sectionStack.size() == 0 ); + node->children.push_back( m_rootSection ); + m_testCases.push_back( node ); + m_rootSection.reset(); + + assert( m_deepestSection ); + m_deepestSection->stdOut = testCaseStats.stdOut; + m_deepestSection->stdErr = testCaseStats.stdErr; + } + virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE { + Ptr node = new TestGroupNode( testGroupStats ); + node->children.swap( m_testCases ); + m_testGroups.push_back( node ); + } + virtual void testRunEnded( TestRunStats const& testRunStats ) CATCH_OVERRIDE { + Ptr node = new TestRunNode( testRunStats ); + node->children.swap( m_testGroups ); + m_testRuns.push_back( node ); + testRunEndedCumulative(); + } + virtual void testRunEndedCumulative() = 0; + + virtual void skipTest( TestCaseInfo const& ) CATCH_OVERRIDE {} + + virtual void prepareExpandedExpression( AssertionResult& result ) const { + if( result.isOk() ) + result.discardDecomposedExpression(); + else + result.expandDecomposedExpression(); + } + + Ptr m_config; + std::ostream& stream; + std::vector m_assertions; + std::vector > > m_sections; + std::vector > m_testCases; + std::vector > m_testGroups; + + std::vector > m_testRuns; + + Ptr m_rootSection; + Ptr m_deepestSection; + std::vector > m_sectionStack; + ReporterPreferences m_reporterPrefs; + + }; + + template + char const* getLineOfChars() { + static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0}; + if( !*line ) { + std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 ); + line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0; + } + return line; + } + + struct TestEventListenerBase : StreamingReporterBase { + TestEventListenerBase( ReporterConfig const& _config ) + : StreamingReporterBase( _config ) + {} + + virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE {} + virtual bool assertionEnded( AssertionStats const& ) CATCH_OVERRIDE { + return false; + } + }; + +} // end namespace Catch + +// #included from: ../internal/catch_reporter_registrars.hpp +#define TWOBLUECUBES_CATCH_REPORTER_REGISTRARS_HPP_INCLUDED + +namespace Catch { + + template + class LegacyReporterRegistrar { + + class ReporterFactory : public IReporterFactory { + virtual IStreamingReporter* create( ReporterConfig const& config ) const { + return new LegacyReporterAdapter( new T( config ) ); + } + + virtual std::string getDescription() const { + return T::getDescription(); + } + }; + + public: + + LegacyReporterRegistrar( std::string const& name ) { + getMutableRegistryHub().registerReporter( name, new ReporterFactory() ); + } + }; + + template + class ReporterRegistrar { + + class ReporterFactory : public SharedImpl { + + // *** Please Note ***: + // - If you end up here looking at a compiler error because it's trying to register + // your custom reporter class be aware that the native reporter interface has changed + // to IStreamingReporter. The "legacy" interface, IReporter, is still supported via + // an adapter. Just use REGISTER_LEGACY_REPORTER to take advantage of the adapter. + // However please consider updating to the new interface as the old one is now + // deprecated and will probably be removed quite soon! + // Please contact me via github if you have any questions at all about this. + // In fact, ideally, please contact me anyway to let me know you've hit this - as I have + // no idea who is actually using custom reporters at all (possibly no-one!). + // The new interface is designed to minimise exposure to interface changes in the future. + virtual IStreamingReporter* create( ReporterConfig const& config ) const { + return new T( config ); + } + + virtual std::string getDescription() const { + return T::getDescription(); + } + }; + + public: + + ReporterRegistrar( std::string const& name ) { + getMutableRegistryHub().registerReporter( name, new ReporterFactory() ); + } + }; + + template + class ListenerRegistrar { + + class ListenerFactory : public SharedImpl { + + virtual IStreamingReporter* create( ReporterConfig const& config ) const { + return new T( config ); + } + virtual std::string getDescription() const { + return std::string(); + } + }; + + public: + + ListenerRegistrar() { + getMutableRegistryHub().registerListener( new ListenerFactory() ); + } + }; +} + +#define INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) \ + namespace{ Catch::LegacyReporterRegistrar catch_internal_RegistrarFor##reporterType( name ); } + +#define INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) \ + namespace{ Catch::ReporterRegistrar catch_internal_RegistrarFor##reporterType( name ); } + +// Deprecated - use the form without INTERNAL_ +#define INTERNAL_CATCH_REGISTER_LISTENER( listenerType ) \ + namespace{ Catch::ListenerRegistrar catch_internal_RegistrarFor##listenerType; } + +#define CATCH_REGISTER_LISTENER( listenerType ) \ + namespace{ Catch::ListenerRegistrar catch_internal_RegistrarFor##listenerType; } + +// #included from: ../internal/catch_xmlwriter.hpp +#define TWOBLUECUBES_CATCH_XMLWRITER_HPP_INCLUDED + +#include +#include +#include +#include + +namespace Catch { + + class XmlEncode { + public: + enum ForWhat { ForTextNodes, ForAttributes }; + + XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes ) + : m_str( str ), + m_forWhat( forWhat ) + {} + + void encodeTo( std::ostream& os ) const { + + // Apostrophe escaping not necessary if we always use " to write attributes + // (see: http://www.w3.org/TR/xml/#syntax) + + for( std::size_t i = 0; i < m_str.size(); ++ i ) { + char c = m_str[i]; + switch( c ) { + case '<': os << "<"; break; + case '&': os << "&"; break; + + case '>': + // See: http://www.w3.org/TR/xml/#syntax + if( i > 2 && m_str[i-1] == ']' && m_str[i-2] == ']' ) + os << ">"; + else + os << c; + break; + + case '\"': + if( m_forWhat == ForAttributes ) + os << """; + else + os << c; + break; + + default: + // Escape control chars - based on contribution by @espenalb in PR #465 and + // by @mrpi PR #588 + if ( ( c >= 0 && c < '\x09' ) || ( c > '\x0D' && c < '\x20') || c=='\x7F' ) { + // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 + os << "\\x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2) + << static_cast( c ); + } + else + os << c; + } + } + } + + friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) { + xmlEncode.encodeTo( os ); + return os; + } + + private: + std::string m_str; + ForWhat m_forWhat; + }; + + class XmlWriter { + public: + + class ScopedElement { + public: + ScopedElement( XmlWriter* writer ) + : m_writer( writer ) + {} + + ScopedElement( ScopedElement const& other ) + : m_writer( other.m_writer ){ + other.m_writer = CATCH_NULL; + } + + ~ScopedElement() { + if( m_writer ) + m_writer->endElement(); + } + + ScopedElement& writeText( std::string const& text, bool indent = true ) { + m_writer->writeText( text, indent ); + return *this; + } + + template + ScopedElement& writeAttribute( std::string const& name, T const& attribute ) { + m_writer->writeAttribute( name, attribute ); + return *this; + } + + private: + mutable XmlWriter* m_writer; + }; + + XmlWriter() + : m_tagIsOpen( false ), + m_needsNewline( false ), + m_os( Catch::cout() ) + { + writeDeclaration(); + } + + XmlWriter( std::ostream& os ) + : m_tagIsOpen( false ), + m_needsNewline( false ), + m_os( os ) + { + writeDeclaration(); + } + + ~XmlWriter() { + while( !m_tags.empty() ) + endElement(); + } + + XmlWriter& startElement( std::string const& name ) { + ensureTagClosed(); + newlineIfNecessary(); + m_os << m_indent << '<' << name; + m_tags.push_back( name ); + m_indent += " "; + m_tagIsOpen = true; + return *this; + } + + ScopedElement scopedElement( std::string const& name ) { + ScopedElement scoped( this ); + startElement( name ); + return scoped; + } + + XmlWriter& endElement() { + newlineIfNecessary(); + m_indent = m_indent.substr( 0, m_indent.size()-2 ); + if( m_tagIsOpen ) { + m_os << "/>"; + m_tagIsOpen = false; + } + else { + m_os << m_indent << ""; + } + m_os << std::endl; + m_tags.pop_back(); + return *this; + } + + XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ) { + if( !name.empty() && !attribute.empty() ) + m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"'; + return *this; + } + + XmlWriter& writeAttribute( std::string const& name, bool attribute ) { + m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"'; + return *this; + } + + template + XmlWriter& writeAttribute( std::string const& name, T const& attribute ) { + std::ostringstream oss; + oss << attribute; + return writeAttribute( name, oss.str() ); + } + + XmlWriter& writeText( std::string const& text, bool indent = true ) { + if( !text.empty() ){ + bool tagWasOpen = m_tagIsOpen; + ensureTagClosed(); + if( tagWasOpen && indent ) + m_os << m_indent; + m_os << XmlEncode( text ); + m_needsNewline = true; + } + return *this; + } + + XmlWriter& writeComment( std::string const& text ) { + ensureTagClosed(); + m_os << m_indent << ""; + m_needsNewline = true; + return *this; + } + + void writeStylesheetRef( std::string const& url ) { + m_os << "\n"; + } + + XmlWriter& writeBlankLine() { + ensureTagClosed(); + m_os << '\n'; + return *this; + } + + void ensureTagClosed() { + if( m_tagIsOpen ) { + m_os << ">" << std::endl; + m_tagIsOpen = false; + } + } + + private: + XmlWriter( XmlWriter const& ); + void operator=( XmlWriter const& ); + + void writeDeclaration() { + m_os << "\n"; + } + + void newlineIfNecessary() { + if( m_needsNewline ) { + m_os << std::endl; + m_needsNewline = false; + } + } + + bool m_tagIsOpen; + bool m_needsNewline; + std::vector m_tags; + std::string m_indent; + std::ostream& m_os; + }; + +} +// #included from: catch_reenable_warnings.h + +#define TWOBLUECUBES_CATCH_REENABLE_WARNINGS_H_INCLUDED + +#ifdef __clang__ +# ifdef __ICC // icpc defines the __clang__ macro +# pragma warning(pop) +# else +# pragma clang diagnostic pop +# endif +#elif defined __GNUC__ +# pragma GCC diagnostic pop +#endif + + +namespace Catch { + class XmlReporter : public StreamingReporterBase { + public: + XmlReporter( ReporterConfig const& _config ) + : StreamingReporterBase( _config ), + m_xml(_config.stream()), + m_sectionDepth( 0 ) + { + m_reporterPrefs.shouldRedirectStdOut = true; + } + + virtual ~XmlReporter() CATCH_OVERRIDE; + + static std::string getDescription() { + return "Reports test results as an XML document"; + } + + virtual std::string getStylesheetRef() const { + return std::string(); + } + + void writeSourceInfo( SourceLineInfo const& sourceInfo ) { + m_xml + .writeAttribute( "filename", sourceInfo.file ) + .writeAttribute( "line", sourceInfo.line ); + } + + public: // StreamingReporterBase + + virtual void noMatchingTestCases( std::string const& s ) CATCH_OVERRIDE { + StreamingReporterBase::noMatchingTestCases( s ); + } + + virtual void testRunStarting( TestRunInfo const& testInfo ) CATCH_OVERRIDE { + StreamingReporterBase::testRunStarting( testInfo ); + std::string stylesheetRef = getStylesheetRef(); + if( !stylesheetRef.empty() ) + m_xml.writeStylesheetRef( stylesheetRef ); + m_xml.startElement( "Catch" ); + if( !m_config->name().empty() ) + m_xml.writeAttribute( "name", m_config->name() ); + } + + virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE { + StreamingReporterBase::testGroupStarting( groupInfo ); + m_xml.startElement( "Group" ) + .writeAttribute( "name", groupInfo.name ); + } + + virtual void testCaseStarting( TestCaseInfo const& testInfo ) CATCH_OVERRIDE { + StreamingReporterBase::testCaseStarting(testInfo); + m_xml.startElement( "TestCase" ) + .writeAttribute( "name", trim( testInfo.name ) ) + .writeAttribute( "description", testInfo.description ) + .writeAttribute( "tags", testInfo.tagsAsString ); + + writeSourceInfo( testInfo.lineInfo ); + + if ( m_config->showDurations() == ShowDurations::Always ) + m_testCaseTimer.start(); + m_xml.ensureTagClosed(); + } + + virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE { + StreamingReporterBase::sectionStarting( sectionInfo ); + if( m_sectionDepth++ > 0 ) { + m_xml.startElement( "Section" ) + .writeAttribute( "name", trim( sectionInfo.name ) ) + .writeAttribute( "description", sectionInfo.description ); + writeSourceInfo( sectionInfo.lineInfo ); + m_xml.ensureTagClosed(); + } + } + + virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE { } + + virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE { + + AssertionResult const& result = assertionStats.assertionResult; + + bool includeResults = m_config->includeSuccessfulResults() || !result.isOk(); + + if( includeResults ) { + // Print any info messages in tags. + for( std::vector::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end(); + it != itEnd; + ++it ) { + if( it->type == ResultWas::Info ) { + m_xml.scopedElement( "Info" ) + .writeText( it->message ); + } else if ( it->type == ResultWas::Warning ) { + m_xml.scopedElement( "Warning" ) + .writeText( it->message ); + } + } + } + + // Drop out if result was successful but we're not printing them. + if( !includeResults && result.getResultType() != ResultWas::Warning ) + return true; + + // Print the expression if there is one. + if( result.hasExpression() ) { + m_xml.startElement( "Expression" ) + .writeAttribute( "success", result.succeeded() ) + .writeAttribute( "type", result.getTestMacroName() ); + + writeSourceInfo( result.getSourceInfo() ); + + m_xml.scopedElement( "Original" ) + .writeText( result.getExpression() ); + m_xml.scopedElement( "Expanded" ) + .writeText( result.getExpandedExpression() ); + } + + // And... Print a result applicable to each result type. + switch( result.getResultType() ) { + case ResultWas::ThrewException: + m_xml.startElement( "Exception" ); + writeSourceInfo( result.getSourceInfo() ); + m_xml.writeText( result.getMessage() ); + m_xml.endElement(); + break; + case ResultWas::FatalErrorCondition: + m_xml.startElement( "FatalErrorCondition" ); + writeSourceInfo( result.getSourceInfo() ); + m_xml.writeText( result.getMessage() ); + m_xml.endElement(); + break; + case ResultWas::Info: + m_xml.scopedElement( "Info" ) + .writeText( result.getMessage() ); + break; + case ResultWas::Warning: + // Warning will already have been written + break; + case ResultWas::ExplicitFailure: + m_xml.startElement( "Failure" ); + writeSourceInfo( result.getSourceInfo() ); + m_xml.writeText( result.getMessage() ); + m_xml.endElement(); + break; + default: + break; + } + + if( result.hasExpression() ) + m_xml.endElement(); + + return true; + } + + virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE { + StreamingReporterBase::sectionEnded( sectionStats ); + if( --m_sectionDepth > 0 ) { + XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" ); + e.writeAttribute( "successes", sectionStats.assertions.passed ); + e.writeAttribute( "failures", sectionStats.assertions.failed ); + e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk ); + + if ( m_config->showDurations() == ShowDurations::Always ) + e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds ); + + m_xml.endElement(); + } + } + + virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE { + StreamingReporterBase::testCaseEnded( testCaseStats ); + XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" ); + e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() ); + + if ( m_config->showDurations() == ShowDurations::Always ) + e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() ); + + if( !testCaseStats.stdOut.empty() ) + m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false ); + if( !testCaseStats.stdErr.empty() ) + m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false ); + + m_xml.endElement(); + } + + virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE { + StreamingReporterBase::testGroupEnded( testGroupStats ); + // TODO: Check testGroupStats.aborting and act accordingly. + m_xml.scopedElement( "OverallResults" ) + .writeAttribute( "successes", testGroupStats.totals.assertions.passed ) + .writeAttribute( "failures", testGroupStats.totals.assertions.failed ) + .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk ); + m_xml.endElement(); + } + + virtual void testRunEnded( TestRunStats const& testRunStats ) CATCH_OVERRIDE { + StreamingReporterBase::testRunEnded( testRunStats ); + m_xml.scopedElement( "OverallResults" ) + .writeAttribute( "successes", testRunStats.totals.assertions.passed ) + .writeAttribute( "failures", testRunStats.totals.assertions.failed ) + .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk ); + m_xml.endElement(); + } + + private: + Timer m_testCaseTimer; + XmlWriter m_xml; + int m_sectionDepth; + }; + + INTERNAL_CATCH_REGISTER_REPORTER( "xml", XmlReporter ) + +} // end namespace Catch + +// #included from: ../reporters/catch_reporter_junit.hpp +#define TWOBLUECUBES_CATCH_REPORTER_JUNIT_HPP_INCLUDED + +#include + +namespace Catch { + + namespace { + std::string getCurrentTimestamp() { + // Beware, this is not reentrant because of backward compatibility issues + // Also, UTC only, again because of backward compatibility (%z is C++11) + time_t rawtime; + std::time(&rawtime); + const size_t timeStampSize = sizeof("2017-01-16T17:06:45Z"); + +#ifdef _MSC_VER + std::tm timeInfo = {}; + gmtime_s(&timeInfo, &rawtime); +#else + std::tm* timeInfo; + timeInfo = std::gmtime(&rawtime); +#endif + + char timeStamp[timeStampSize]; + const char * const fmt = "%Y-%m-%dT%H:%M:%SZ"; + +#ifdef _MSC_VER + std::strftime(timeStamp, timeStampSize, fmt, &timeInfo); +#else + std::strftime(timeStamp, timeStampSize, fmt, timeInfo); +#endif + return std::string(timeStamp); + } + + } + + class JunitReporter : public CumulativeReporterBase { + public: + JunitReporter( ReporterConfig const& _config ) + : CumulativeReporterBase( _config ), + xml( _config.stream() ), + m_okToFail( false ) + { + m_reporterPrefs.shouldRedirectStdOut = true; + } + + virtual ~JunitReporter() CATCH_OVERRIDE; + + static std::string getDescription() { + return "Reports test results in an XML format that looks like Ant's junitreport target"; + } + + virtual void noMatchingTestCases( std::string const& /*spec*/ ) CATCH_OVERRIDE {} + + virtual void testRunStarting( TestRunInfo const& runInfo ) CATCH_OVERRIDE { + CumulativeReporterBase::testRunStarting( runInfo ); + xml.startElement( "testsuites" ); + } + + virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE { + suiteTimer.start(); + stdOutForSuite.str(""); + stdErrForSuite.str(""); + unexpectedExceptions = 0; + CumulativeReporterBase::testGroupStarting( groupInfo ); + } + + virtual void testCaseStarting( TestCaseInfo const& testCaseInfo ) CATCH_OVERRIDE { + m_okToFail = testCaseInfo.okToFail(); + } + virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE { + if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail ) + unexpectedExceptions++; + return CumulativeReporterBase::assertionEnded( assertionStats ); + } + + virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE { + stdOutForSuite << testCaseStats.stdOut; + stdErrForSuite << testCaseStats.stdErr; + CumulativeReporterBase::testCaseEnded( testCaseStats ); + } + + virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE { + double suiteTime = suiteTimer.getElapsedSeconds(); + CumulativeReporterBase::testGroupEnded( testGroupStats ); + writeGroup( *m_testGroups.back(), suiteTime ); + } + + virtual void testRunEndedCumulative() CATCH_OVERRIDE { + xml.endElement(); + } + + void writeGroup( TestGroupNode const& groupNode, double suiteTime ) { + XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" ); + TestGroupStats const& stats = groupNode.value; + xml.writeAttribute( "name", stats.groupInfo.name ); + xml.writeAttribute( "errors", unexpectedExceptions ); + xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions ); + xml.writeAttribute( "tests", stats.totals.assertions.total() ); + xml.writeAttribute( "hostname", "tbd" ); // !TBD + if( m_config->showDurations() == ShowDurations::Never ) + xml.writeAttribute( "time", "" ); + else + xml.writeAttribute( "time", suiteTime ); + xml.writeAttribute( "timestamp", getCurrentTimestamp() ); + + // Write test cases + for( TestGroupNode::ChildNodes::const_iterator + it = groupNode.children.begin(), itEnd = groupNode.children.end(); + it != itEnd; + ++it ) + writeTestCase( **it ); + + xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite.str() ), false ); + xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite.str() ), false ); + } + + void writeTestCase( TestCaseNode const& testCaseNode ) { + TestCaseStats const& stats = testCaseNode.value; + + // All test cases have exactly one section - which represents the + // test case itself. That section may have 0-n nested sections + assert( testCaseNode.children.size() == 1 ); + SectionNode const& rootSection = *testCaseNode.children.front(); + + std::string className = stats.testInfo.className; + + if( className.empty() ) { + if( rootSection.childSections.empty() ) + className = "global"; + } + writeSection( className, "", rootSection ); + } + + void writeSection( std::string const& className, + std::string const& rootName, + SectionNode const& sectionNode ) { + std::string name = trim( sectionNode.stats.sectionInfo.name ); + if( !rootName.empty() ) + name = rootName + '/' + name; + + if( !sectionNode.assertions.empty() || + !sectionNode.stdOut.empty() || + !sectionNode.stdErr.empty() ) { + XmlWriter::ScopedElement e = xml.scopedElement( "testcase" ); + if( className.empty() ) { + xml.writeAttribute( "classname", name ); + xml.writeAttribute( "name", "root" ); + } + else { + xml.writeAttribute( "classname", className ); + xml.writeAttribute( "name", name ); + } + xml.writeAttribute( "time", Catch::toString( sectionNode.stats.durationInSeconds ) ); + + writeAssertions( sectionNode ); + + if( !sectionNode.stdOut.empty() ) + xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false ); + if( !sectionNode.stdErr.empty() ) + xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false ); + } + for( SectionNode::ChildSections::const_iterator + it = sectionNode.childSections.begin(), + itEnd = sectionNode.childSections.end(); + it != itEnd; + ++it ) + if( className.empty() ) + writeSection( name, "", **it ); + else + writeSection( className, name, **it ); + } + + void writeAssertions( SectionNode const& sectionNode ) { + for( SectionNode::Assertions::const_iterator + it = sectionNode.assertions.begin(), itEnd = sectionNode.assertions.end(); + it != itEnd; + ++it ) + writeAssertion( *it ); + } + void writeAssertion( AssertionStats const& stats ) { + AssertionResult const& result = stats.assertionResult; + if( !result.isOk() ) { + std::string elementName; + switch( result.getResultType() ) { + case ResultWas::ThrewException: + case ResultWas::FatalErrorCondition: + elementName = "error"; + break; + case ResultWas::ExplicitFailure: + elementName = "failure"; + break; + case ResultWas::ExpressionFailed: + elementName = "failure"; + break; + case ResultWas::DidntThrowException: + elementName = "failure"; + break; + + // We should never see these here: + case ResultWas::Info: + case ResultWas::Warning: + case ResultWas::Ok: + case ResultWas::Unknown: + case ResultWas::FailureBit: + case ResultWas::Exception: + elementName = "internalError"; + break; + } + + XmlWriter::ScopedElement e = xml.scopedElement( elementName ); + + xml.writeAttribute( "message", result.getExpandedExpression() ); + xml.writeAttribute( "type", result.getTestMacroName() ); + + std::ostringstream oss; + if( !result.getMessage().empty() ) + oss << result.getMessage() << '\n'; + for( std::vector::const_iterator + it = stats.infoMessages.begin(), + itEnd = stats.infoMessages.end(); + it != itEnd; + ++it ) + if( it->type == ResultWas::Info ) + oss << it->message << '\n'; + + oss << "at " << result.getSourceInfo(); + xml.writeText( oss.str(), false ); + } + } + + XmlWriter xml; + Timer suiteTimer; + std::ostringstream stdOutForSuite; + std::ostringstream stdErrForSuite; + unsigned int unexpectedExceptions; + bool m_okToFail; + }; + + INTERNAL_CATCH_REGISTER_REPORTER( "junit", JunitReporter ) + +} // end namespace Catch + +// #included from: ../reporters/catch_reporter_console.hpp +#define TWOBLUECUBES_CATCH_REPORTER_CONSOLE_HPP_INCLUDED + +#include +#include + +namespace Catch { + + struct ConsoleReporter : StreamingReporterBase { + ConsoleReporter( ReporterConfig const& _config ) + : StreamingReporterBase( _config ), + m_headerPrinted( false ) + {} + + virtual ~ConsoleReporter() CATCH_OVERRIDE; + static std::string getDescription() { + return "Reports test results as plain lines of text"; + } + + virtual void noMatchingTestCases( std::string const& spec ) CATCH_OVERRIDE { + stream << "No test cases matched '" << spec << '\'' << std::endl; + } + + virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE { + } + + virtual bool assertionEnded( AssertionStats const& _assertionStats ) CATCH_OVERRIDE { + AssertionResult const& result = _assertionStats.assertionResult; + + bool includeResults = m_config->includeSuccessfulResults() || !result.isOk(); + + // Drop out if result was successful but we're not printing them. + if( !includeResults && result.getResultType() != ResultWas::Warning ) + return false; + + lazyPrint(); + + AssertionPrinter printer( stream, _assertionStats, includeResults ); + printer.print(); + stream << std::endl; + return true; + } + + virtual void sectionStarting( SectionInfo const& _sectionInfo ) CATCH_OVERRIDE { + m_headerPrinted = false; + StreamingReporterBase::sectionStarting( _sectionInfo ); + } + virtual void sectionEnded( SectionStats const& _sectionStats ) CATCH_OVERRIDE { + if( _sectionStats.missingAssertions ) { + lazyPrint(); + Colour colour( Colour::ResultError ); + if( m_sectionStack.size() > 1 ) + stream << "\nNo assertions in section"; + else + stream << "\nNo assertions in test case"; + stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl; + } + if( m_config->showDurations() == ShowDurations::Always ) { + stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl; + } + if( m_headerPrinted ) { + m_headerPrinted = false; + } + StreamingReporterBase::sectionEnded( _sectionStats ); + } + + virtual void testCaseEnded( TestCaseStats const& _testCaseStats ) CATCH_OVERRIDE { + StreamingReporterBase::testCaseEnded( _testCaseStats ); + m_headerPrinted = false; + } + virtual void testGroupEnded( TestGroupStats const& _testGroupStats ) CATCH_OVERRIDE { + if( currentGroupInfo.used ) { + printSummaryDivider(); + stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n"; + printTotals( _testGroupStats.totals ); + stream << '\n' << std::endl; + } + StreamingReporterBase::testGroupEnded( _testGroupStats ); + } + virtual void testRunEnded( TestRunStats const& _testRunStats ) CATCH_OVERRIDE { + printTotalsDivider( _testRunStats.totals ); + printTotals( _testRunStats.totals ); + stream << std::endl; + StreamingReporterBase::testRunEnded( _testRunStats ); + } + + private: + + class AssertionPrinter { + void operator= ( AssertionPrinter const& ); + public: + AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages ) + : stream( _stream ), + stats( _stats ), + result( _stats.assertionResult ), + colour( Colour::None ), + message( result.getMessage() ), + messages( _stats.infoMessages ), + printInfoMessages( _printInfoMessages ) + { + switch( result.getResultType() ) { + case ResultWas::Ok: + colour = Colour::Success; + passOrFail = "PASSED"; + //if( result.hasMessage() ) + if( _stats.infoMessages.size() == 1 ) + messageLabel = "with message"; + if( _stats.infoMessages.size() > 1 ) + messageLabel = "with messages"; + break; + case ResultWas::ExpressionFailed: + if( result.isOk() ) { + colour = Colour::Success; + passOrFail = "FAILED - but was ok"; + } + else { + colour = Colour::Error; + passOrFail = "FAILED"; + } + if( _stats.infoMessages.size() == 1 ) + messageLabel = "with message"; + if( _stats.infoMessages.size() > 1 ) + messageLabel = "with messages"; + break; + case ResultWas::ThrewException: + colour = Colour::Error; + passOrFail = "FAILED"; + messageLabel = "due to unexpected exception with "; + if (_stats.infoMessages.size() == 1) + messageLabel += "message"; + if (_stats.infoMessages.size() > 1) + messageLabel += "messages"; + break; + case ResultWas::FatalErrorCondition: + colour = Colour::Error; + passOrFail = "FAILED"; + messageLabel = "due to a fatal error condition"; + break; + case ResultWas::DidntThrowException: + colour = Colour::Error; + passOrFail = "FAILED"; + messageLabel = "because no exception was thrown where one was expected"; + break; + case ResultWas::Info: + messageLabel = "info"; + break; + case ResultWas::Warning: + messageLabel = "warning"; + break; + case ResultWas::ExplicitFailure: + passOrFail = "FAILED"; + colour = Colour::Error; + if( _stats.infoMessages.size() == 1 ) + messageLabel = "explicitly with message"; + if( _stats.infoMessages.size() > 1 ) + messageLabel = "explicitly with messages"; + break; + // These cases are here to prevent compiler warnings + case ResultWas::Unknown: + case ResultWas::FailureBit: + case ResultWas::Exception: + passOrFail = "** internal error **"; + colour = Colour::Error; + break; + } + } + + void print() const { + printSourceInfo(); + if( stats.totals.assertions.total() > 0 ) { + if( result.isOk() ) + stream << '\n'; + printResultType(); + printOriginalExpression(); + printReconstructedExpression(); + } + else { + stream << '\n'; + } + printMessage(); + } + + private: + void printResultType() const { + if( !passOrFail.empty() ) { + Colour colourGuard( colour ); + stream << passOrFail << ":\n"; + } + } + void printOriginalExpression() const { + if( result.hasExpression() ) { + Colour colourGuard( Colour::OriginalExpression ); + stream << " "; + stream << result.getExpressionInMacro(); + stream << '\n'; + } + } + void printReconstructedExpression() const { + if( result.hasExpandedExpression() ) { + stream << "with expansion:\n"; + Colour colourGuard( Colour::ReconstructedExpression ); + stream << Text( result.getExpandedExpression(), TextAttributes().setIndent(2) ) << '\n'; + } + } + void printMessage() const { + if( !messageLabel.empty() ) + stream << messageLabel << ':' << '\n'; + for( std::vector::const_iterator it = messages.begin(), itEnd = messages.end(); + it != itEnd; + ++it ) { + // If this assertion is a warning ignore any INFO messages + if( printInfoMessages || it->type != ResultWas::Info ) + stream << Text( it->message, TextAttributes().setIndent(2) ) << '\n'; + } + } + void printSourceInfo() const { + Colour colourGuard( Colour::FileName ); + stream << result.getSourceInfo() << ": "; + } + + std::ostream& stream; + AssertionStats const& stats; + AssertionResult const& result; + Colour::Code colour; + std::string passOrFail; + std::string messageLabel; + std::string message; + std::vector messages; + bool printInfoMessages; + }; + + void lazyPrint() { + + if( !currentTestRunInfo.used ) + lazyPrintRunInfo(); + if( !currentGroupInfo.used ) + lazyPrintGroupInfo(); + + if( !m_headerPrinted ) { + printTestCaseAndSectionHeader(); + m_headerPrinted = true; + } + } + void lazyPrintRunInfo() { + stream << '\n' << getLineOfChars<'~'>() << '\n'; + Colour colour( Colour::SecondaryText ); + stream << currentTestRunInfo->name + << " is a Catch v" << libraryVersion() << " host application.\n" + << "Run with -? for options\n\n"; + + if( m_config->rngSeed() != 0 ) + stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n"; + + currentTestRunInfo.used = true; + } + void lazyPrintGroupInfo() { + if( !currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1 ) { + printClosedHeader( "Group: " + currentGroupInfo->name ); + currentGroupInfo.used = true; + } + } + void printTestCaseAndSectionHeader() { + assert( !m_sectionStack.empty() ); + printOpenHeader( currentTestCaseInfo->name ); + + if( m_sectionStack.size() > 1 ) { + Colour colourGuard( Colour::Headers ); + + std::vector::const_iterator + it = m_sectionStack.begin()+1, // Skip first section (test case) + itEnd = m_sectionStack.end(); + for( ; it != itEnd; ++it ) + printHeaderString( it->name, 2 ); + } + + SourceLineInfo lineInfo = m_sectionStack.back().lineInfo; + + if( !lineInfo.empty() ){ + stream << getLineOfChars<'-'>() << '\n'; + Colour colourGuard( Colour::FileName ); + stream << lineInfo << '\n'; + } + stream << getLineOfChars<'.'>() << '\n' << std::endl; + } + + void printClosedHeader( std::string const& _name ) { + printOpenHeader( _name ); + stream << getLineOfChars<'.'>() << '\n'; + } + void printOpenHeader( std::string const& _name ) { + stream << getLineOfChars<'-'>() << '\n'; + { + Colour colourGuard( Colour::Headers ); + printHeaderString( _name ); + } + } + + // if string has a : in first line will set indent to follow it on + // subsequent lines + void printHeaderString( std::string const& _string, std::size_t indent = 0 ) { + std::size_t i = _string.find( ": " ); + if( i != std::string::npos ) + i+=2; + else + i = 0; + stream << Text( _string, TextAttributes() + .setIndent( indent+i) + .setInitialIndent( indent ) ) << '\n'; + } + + struct SummaryColumn { + + SummaryColumn( std::string const& _label, Colour::Code _colour ) + : label( _label ), + colour( _colour ) + {} + SummaryColumn addRow( std::size_t count ) { + std::ostringstream oss; + oss << count; + std::string row = oss.str(); + for( std::vector::iterator it = rows.begin(); it != rows.end(); ++it ) { + while( it->size() < row.size() ) + *it = ' ' + *it; + while( it->size() > row.size() ) + row = ' ' + row; + } + rows.push_back( row ); + return *this; + } + + std::string label; + Colour::Code colour; + std::vector rows; + + }; + + void printTotals( Totals const& totals ) { + if( totals.testCases.total() == 0 ) { + stream << Colour( Colour::Warning ) << "No tests ran\n"; + } + else if( totals.assertions.total() > 0 && totals.testCases.allPassed() ) { + stream << Colour( Colour::ResultSuccess ) << "All tests passed"; + stream << " (" + << pluralise( totals.assertions.passed, "assertion" ) << " in " + << pluralise( totals.testCases.passed, "test case" ) << ')' + << '\n'; + } + else { + + std::vector columns; + columns.push_back( SummaryColumn( "", Colour::None ) + .addRow( totals.testCases.total() ) + .addRow( totals.assertions.total() ) ); + columns.push_back( SummaryColumn( "passed", Colour::Success ) + .addRow( totals.testCases.passed ) + .addRow( totals.assertions.passed ) ); + columns.push_back( SummaryColumn( "failed", Colour::ResultError ) + .addRow( totals.testCases.failed ) + .addRow( totals.assertions.failed ) ); + columns.push_back( SummaryColumn( "failed as expected", Colour::ResultExpectedFailure ) + .addRow( totals.testCases.failedButOk ) + .addRow( totals.assertions.failedButOk ) ); + + printSummaryRow( "test cases", columns, 0 ); + printSummaryRow( "assertions", columns, 1 ); + } + } + void printSummaryRow( std::string const& label, std::vector const& cols, std::size_t row ) { + for( std::vector::const_iterator it = cols.begin(); it != cols.end(); ++it ) { + std::string value = it->rows[row]; + if( it->label.empty() ) { + stream << label << ": "; + if( value != "0" ) + stream << value; + else + stream << Colour( Colour::Warning ) << "- none -"; + } + else if( value != "0" ) { + stream << Colour( Colour::LightGrey ) << " | "; + stream << Colour( it->colour ) + << value << ' ' << it->label; + } + } + stream << '\n'; + } + + static std::size_t makeRatio( std::size_t number, std::size_t total ) { + std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number/ total : 0; + return ( ratio == 0 && number > 0 ) ? 1 : ratio; + } + static std::size_t& findMax( std::size_t& i, std::size_t& j, std::size_t& k ) { + if( i > j && i > k ) + return i; + else if( j > k ) + return j; + else + return k; + } + + void printTotalsDivider( Totals const& totals ) { + if( totals.testCases.total() > 0 ) { + std::size_t failedRatio = makeRatio( totals.testCases.failed, totals.testCases.total() ); + std::size_t failedButOkRatio = makeRatio( totals.testCases.failedButOk, totals.testCases.total() ); + std::size_t passedRatio = makeRatio( totals.testCases.passed, totals.testCases.total() ); + while( failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH-1 ) + findMax( failedRatio, failedButOkRatio, passedRatio )++; + while( failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH-1 ) + findMax( failedRatio, failedButOkRatio, passedRatio )--; + + stream << Colour( Colour::Error ) << std::string( failedRatio, '=' ); + stream << Colour( Colour::ResultExpectedFailure ) << std::string( failedButOkRatio, '=' ); + if( totals.testCases.allPassed() ) + stream << Colour( Colour::ResultSuccess ) << std::string( passedRatio, '=' ); + else + stream << Colour( Colour::Success ) << std::string( passedRatio, '=' ); + } + else { + stream << Colour( Colour::Warning ) << std::string( CATCH_CONFIG_CONSOLE_WIDTH-1, '=' ); + } + stream << '\n'; + } + void printSummaryDivider() { + stream << getLineOfChars<'-'>() << '\n'; + } + + private: + bool m_headerPrinted; + }; + + INTERNAL_CATCH_REGISTER_REPORTER( "console", ConsoleReporter ) + +} // end namespace Catch + +// #included from: ../reporters/catch_reporter_compact.hpp +#define TWOBLUECUBES_CATCH_REPORTER_COMPACT_HPP_INCLUDED + +namespace Catch { + + struct CompactReporter : StreamingReporterBase { + + CompactReporter( ReporterConfig const& _config ) + : StreamingReporterBase( _config ) + {} + + virtual ~CompactReporter(); + + static std::string getDescription() { + return "Reports test results on a single line, suitable for IDEs"; + } + + virtual ReporterPreferences getPreferences() const { + ReporterPreferences prefs; + prefs.shouldRedirectStdOut = false; + return prefs; + } + + virtual void noMatchingTestCases( std::string const& spec ) { + stream << "No test cases matched '" << spec << '\'' << std::endl; + } + + virtual void assertionStarting( AssertionInfo const& ) {} + + virtual bool assertionEnded( AssertionStats const& _assertionStats ) { + AssertionResult const& result = _assertionStats.assertionResult; + + bool printInfoMessages = true; + + // Drop out if result was successful and we're not printing those + if( !m_config->includeSuccessfulResults() && result.isOk() ) { + if( result.getResultType() != ResultWas::Warning ) + return false; + printInfoMessages = false; + } + + AssertionPrinter printer( stream, _assertionStats, printInfoMessages ); + printer.print(); + + stream << std::endl; + return true; + } + + virtual void sectionEnded(SectionStats const& _sectionStats) CATCH_OVERRIDE { + if (m_config->showDurations() == ShowDurations::Always) { + stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl; + } + } + + virtual void testRunEnded( TestRunStats const& _testRunStats ) { + printTotals( _testRunStats.totals ); + stream << '\n' << std::endl; + StreamingReporterBase::testRunEnded( _testRunStats ); + } + + private: + class AssertionPrinter { + void operator= ( AssertionPrinter const& ); + public: + AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages ) + : stream( _stream ) + , stats( _stats ) + , result( _stats.assertionResult ) + , messages( _stats.infoMessages ) + , itMessage( _stats.infoMessages.begin() ) + , printInfoMessages( _printInfoMessages ) + {} + + void print() { + printSourceInfo(); + + itMessage = messages.begin(); + + switch( result.getResultType() ) { + case ResultWas::Ok: + printResultType( Colour::ResultSuccess, passedString() ); + printOriginalExpression(); + printReconstructedExpression(); + if ( ! result.hasExpression() ) + printRemainingMessages( Colour::None ); + else + printRemainingMessages(); + break; + case ResultWas::ExpressionFailed: + if( result.isOk() ) + printResultType( Colour::ResultSuccess, failedString() + std::string( " - but was ok" ) ); + else + printResultType( Colour::Error, failedString() ); + printOriginalExpression(); + printReconstructedExpression(); + printRemainingMessages(); + break; + case ResultWas::ThrewException: + printResultType( Colour::Error, failedString() ); + printIssue( "unexpected exception with message:" ); + printMessage(); + printExpressionWas(); + printRemainingMessages(); + break; + case ResultWas::FatalErrorCondition: + printResultType( Colour::Error, failedString() ); + printIssue( "fatal error condition with message:" ); + printMessage(); + printExpressionWas(); + printRemainingMessages(); + break; + case ResultWas::DidntThrowException: + printResultType( Colour::Error, failedString() ); + printIssue( "expected exception, got none" ); + printExpressionWas(); + printRemainingMessages(); + break; + case ResultWas::Info: + printResultType( Colour::None, "info" ); + printMessage(); + printRemainingMessages(); + break; + case ResultWas::Warning: + printResultType( Colour::None, "warning" ); + printMessage(); + printRemainingMessages(); + break; + case ResultWas::ExplicitFailure: + printResultType( Colour::Error, failedString() ); + printIssue( "explicitly" ); + printRemainingMessages( Colour::None ); + break; + // These cases are here to prevent compiler warnings + case ResultWas::Unknown: + case ResultWas::FailureBit: + case ResultWas::Exception: + printResultType( Colour::Error, "** internal error **" ); + break; + } + } + + private: + // Colour::LightGrey + + static Colour::Code dimColour() { return Colour::FileName; } + +#ifdef CATCH_PLATFORM_MAC + static const char* failedString() { return "FAILED"; } + static const char* passedString() { return "PASSED"; } +#else + static const char* failedString() { return "failed"; } + static const char* passedString() { return "passed"; } +#endif + + void printSourceInfo() const { + Colour colourGuard( Colour::FileName ); + stream << result.getSourceInfo() << ':'; + } + + void printResultType( Colour::Code colour, std::string const& passOrFail ) const { + if( !passOrFail.empty() ) { + { + Colour colourGuard( colour ); + stream << ' ' << passOrFail; + } + stream << ':'; + } + } + + void printIssue( std::string const& issue ) const { + stream << ' ' << issue; + } + + void printExpressionWas() { + if( result.hasExpression() ) { + stream << ';'; + { + Colour colour( dimColour() ); + stream << " expression was:"; + } + printOriginalExpression(); + } + } + + void printOriginalExpression() const { + if( result.hasExpression() ) { + stream << ' ' << result.getExpression(); + } + } + + void printReconstructedExpression() const { + if( result.hasExpandedExpression() ) { + { + Colour colour( dimColour() ); + stream << " for: "; + } + stream << result.getExpandedExpression(); + } + } + + void printMessage() { + if ( itMessage != messages.end() ) { + stream << " '" << itMessage->message << '\''; + ++itMessage; + } + } + + void printRemainingMessages( Colour::Code colour = dimColour() ) { + if ( itMessage == messages.end() ) + return; + + // using messages.end() directly yields compilation error: + std::vector::const_iterator itEnd = messages.end(); + const std::size_t N = static_cast( std::distance( itMessage, itEnd ) ); + + { + Colour colourGuard( colour ); + stream << " with " << pluralise( N, "message" ) << ':'; + } + + for(; itMessage != itEnd; ) { + // If this assertion is a warning ignore any INFO messages + if( printInfoMessages || itMessage->type != ResultWas::Info ) { + stream << " '" << itMessage->message << '\''; + if ( ++itMessage != itEnd ) { + Colour colourGuard( dimColour() ); + stream << " and"; + } + } + } + } + + private: + std::ostream& stream; + AssertionStats const& stats; + AssertionResult const& result; + std::vector messages; + std::vector::const_iterator itMessage; + bool printInfoMessages; + }; + + // Colour, message variants: + // - white: No tests ran. + // - red: Failed [both/all] N test cases, failed [both/all] M assertions. + // - white: Passed [both/all] N test cases (no assertions). + // - red: Failed N tests cases, failed M assertions. + // - green: Passed [both/all] N tests cases with M assertions. + + std::string bothOrAll( std::size_t count ) const { + return count == 1 ? std::string() : count == 2 ? "both " : "all " ; + } + + void printTotals( const Totals& totals ) const { + if( totals.testCases.total() == 0 ) { + stream << "No tests ran."; + } + else if( totals.testCases.failed == totals.testCases.total() ) { + Colour colour( Colour::ResultError ); + const std::string qualify_assertions_failed = + totals.assertions.failed == totals.assertions.total() ? + bothOrAll( totals.assertions.failed ) : std::string(); + stream << + "Failed " << bothOrAll( totals.testCases.failed ) + << pluralise( totals.testCases.failed, "test case" ) << ", " + "failed " << qualify_assertions_failed << + pluralise( totals.assertions.failed, "assertion" ) << '.'; + } + else if( totals.assertions.total() == 0 ) { + stream << + "Passed " << bothOrAll( totals.testCases.total() ) + << pluralise( totals.testCases.total(), "test case" ) + << " (no assertions)."; + } + else if( totals.assertions.failed ) { + Colour colour( Colour::ResultError ); + stream << + "Failed " << pluralise( totals.testCases.failed, "test case" ) << ", " + "failed " << pluralise( totals.assertions.failed, "assertion" ) << '.'; + } + else { + Colour colour( Colour::ResultSuccess ); + stream << + "Passed " << bothOrAll( totals.testCases.passed ) + << pluralise( totals.testCases.passed, "test case" ) << + " with " << pluralise( totals.assertions.passed, "assertion" ) << '.'; + } + } + }; + + INTERNAL_CATCH_REGISTER_REPORTER( "compact", CompactReporter ) + +} // end namespace Catch + +namespace Catch { + // These are all here to avoid warnings about not having any out of line + // virtual methods + NonCopyable::~NonCopyable() {} + IShared::~IShared() {} + IStream::~IStream() CATCH_NOEXCEPT {} + FileStream::~FileStream() CATCH_NOEXCEPT {} + CoutStream::~CoutStream() CATCH_NOEXCEPT {} + DebugOutStream::~DebugOutStream() CATCH_NOEXCEPT {} + StreamBufBase::~StreamBufBase() CATCH_NOEXCEPT {} + IContext::~IContext() {} + IResultCapture::~IResultCapture() {} + ITestCase::~ITestCase() {} + ITestCaseRegistry::~ITestCaseRegistry() {} + IRegistryHub::~IRegistryHub() {} + IMutableRegistryHub::~IMutableRegistryHub() {} + IExceptionTranslator::~IExceptionTranslator() {} + IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() {} + IReporter::~IReporter() {} + IReporterFactory::~IReporterFactory() {} + IReporterRegistry::~IReporterRegistry() {} + IStreamingReporter::~IStreamingReporter() {} + AssertionStats::~AssertionStats() {} + SectionStats::~SectionStats() {} + TestCaseStats::~TestCaseStats() {} + TestGroupStats::~TestGroupStats() {} + TestRunStats::~TestRunStats() {} + CumulativeReporterBase::SectionNode::~SectionNode() {} + CumulativeReporterBase::~CumulativeReporterBase() {} + + StreamingReporterBase::~StreamingReporterBase() {} + ConsoleReporter::~ConsoleReporter() {} + CompactReporter::~CompactReporter() {} + IRunner::~IRunner() {} + IMutableContext::~IMutableContext() {} + IConfig::~IConfig() {} + XmlReporter::~XmlReporter() {} + JunitReporter::~JunitReporter() {} + TestRegistry::~TestRegistry() {} + FreeFunctionTestCase::~FreeFunctionTestCase() {} + IGeneratorInfo::~IGeneratorInfo() {} + IGeneratorsForTest::~IGeneratorsForTest() {} + WildcardPattern::~WildcardPattern() {} + TestSpec::Pattern::~Pattern() {} + TestSpec::NamePattern::~NamePattern() {} + TestSpec::TagPattern::~TagPattern() {} + TestSpec::ExcludedPattern::~ExcludedPattern() {} + Matchers::Impl::MatcherUntypedBase::~MatcherUntypedBase() {} + + void Config::dummy() {} + + namespace TestCaseTracking { + ITracker::~ITracker() {} + TrackerBase::~TrackerBase() {} + SectionTracker::~SectionTracker() {} + IndexTracker::~IndexTracker() {} + } +} + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#endif + +#ifdef CATCH_CONFIG_MAIN +// #included from: internal/catch_default_main.hpp +#define TWOBLUECUBES_CATCH_DEFAULT_MAIN_HPP_INCLUDED + +#ifndef __OBJC__ + +#if defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN) +// Standard C/C++ Win32 Unicode wmain entry point +extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) { +#else +// Standard C/C++ main entry point +int main (int argc, char * argv[]) { +#endif + + int result = Catch::Session().run( argc, argv ); + return ( result < 0xff ? result : 0xff ); +} + +#else // __OBJC__ + +// Objective-C entry point +int main (int argc, char * const argv[]) { +#if !CATCH_ARC_ENABLED + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; +#endif + + Catch::registerTestMethods(); + int result = Catch::Session().run( argc, (char* const*)argv ); + +#if !CATCH_ARC_ENABLED + [pool drain]; +#endif + + return ( result < 0xff ? result : 0xff ); +} + +#endif // __OBJC__ + +#endif + +#ifdef CLARA_CONFIG_MAIN_NOT_DEFINED +# undef CLARA_CONFIG_MAIN +#endif + +////// + +// If this config identifier is defined then all CATCH macros are prefixed with CATCH_ +#ifdef CATCH_CONFIG_PREFIX_ALL + +#if defined(CATCH_CONFIG_FAST_COMPILE) +#define CATCH_REQUIRE( expr ) INTERNAL_CATCH_TEST_NO_TRY( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, expr ) +#define CATCH_REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST_NO_TRY( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, expr ) +#else +#define CATCH_REQUIRE( expr ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, expr ) +#define CATCH_REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, expr ) +#endif + +#define CATCH_REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", expr ) +#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) +#define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) +#define CATCH_REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, expr ) + +#define CATCH_CHECK( expr ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, expr ) +#define CATCH_CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, expr ) +#define CATCH_CHECKED_IF( expr ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, expr ) +#define CATCH_CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, expr ) +#define CATCH_CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, expr ) + +#define CATCH_CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", expr ) +#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) +#define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) +#define CATCH_CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, expr ) + +#define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) + +#if defined(CATCH_CONFIG_FAST_COMPILE) +#define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT_NO_TRY( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) +#else +#define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) +#endif + +#define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg ) +#define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) +#define CATCH_SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg ) +#define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CATCH_CAPTURE", #msg " := " << Catch::toString(msg) ) +#define CATCH_SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CATCH_CAPTURE", #msg " := " << Catch::toString(msg) ) + +#ifdef CATCH_CONFIG_VARIADIC_MACROS + #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) + #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) + #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) + #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) + #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) + #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) + #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) + #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) +#else + #define CATCH_TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description ) + #define CATCH_TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description ) + #define CATCH_METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description ) + #define CATCH_REGISTER_TEST_CASE( function, name, description ) INTERNAL_CATCH_REGISTER_TESTCASE( function, name, description ) + #define CATCH_SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description ) + #define CATCH_FAIL( msg ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, msg ) + #define CATCH_FAIL_CHECK( msg ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, msg ) + #define CATCH_SUCCEED( msg ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, msg ) +#endif +#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" ) + +#define CATCH_REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) +#define CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) + +#define CATCH_GENERATE( expr) INTERNAL_CATCH_GENERATE( expr ) + +// "BDD-style" convenience wrappers +#ifdef CATCH_CONFIG_VARIADIC_MACROS +#define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ ) +#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) +#else +#define CATCH_SCENARIO( name, tags ) CATCH_TEST_CASE( "Scenario: " name, tags ) +#define CATCH_SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags ) +#endif +#define CATCH_GIVEN( desc ) CATCH_SECTION( std::string( "Given: ") + desc, "" ) +#define CATCH_WHEN( desc ) CATCH_SECTION( std::string( " When: ") + desc, "" ) +#define CATCH_AND_WHEN( desc ) CATCH_SECTION( std::string( " And: ") + desc, "" ) +#define CATCH_THEN( desc ) CATCH_SECTION( std::string( " Then: ") + desc, "" ) +#define CATCH_AND_THEN( desc ) CATCH_SECTION( std::string( " And: ") + desc, "" ) + +// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required +#else + +#if defined(CATCH_CONFIG_FAST_COMPILE) +#define REQUIRE( expr ) INTERNAL_CATCH_TEST_NO_TRY( "REQUIRE", Catch::ResultDisposition::Normal, expr ) +#define REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST_NO_TRY( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, expr ) + +#else +#define REQUIRE( expr ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, expr ) +#define REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, expr ) +#endif + +#define REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", expr ) +#define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) +#define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) +#define REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, expr ) + +#define CHECK( expr ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, expr ) +#define CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, expr ) +#define CHECKED_IF( expr ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, expr ) +#define CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, expr ) +#define CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, expr ) + +#define CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", expr ) +#define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) +#define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) +#define CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, expr ) + +#define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) + +#if defined(CATCH_CONFIG_FAST_COMPILE) +#define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT_NO_TRY( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) +#else +#define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) +#endif + +#define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg ) +#define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) +#define SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg ) +#define CAPTURE( msg ) INTERNAL_CATCH_INFO( "CAPTURE", #msg " := " << Catch::toString(msg) ) +#define SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CAPTURE", #msg " := " << Catch::toString(msg) ) + +#ifdef CATCH_CONFIG_VARIADIC_MACROS +#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) +#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) +#define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) +#define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) +#define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) +#define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) +#define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) +#define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) +#else +#define TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description ) + #define TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description ) + #define METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description ) + #define REGISTER_TEST_CASE( method, name, description ) INTERNAL_CATCH_REGISTER_TESTCASE( method, name, description ) + #define SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description ) + #define FAIL( msg ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, msg ) + #define FAIL_CHECK( msg ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, msg ) + #define SUCCEED( msg ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, msg ) +#endif +#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" ) + +#define REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) +#define REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) + +#define GENERATE( expr) INTERNAL_CATCH_GENERATE( expr ) + +#endif + +#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) + +// "BDD-style" convenience wrappers +#ifdef CATCH_CONFIG_VARIADIC_MACROS +#define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ ) +#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) +#else +#define SCENARIO( name, tags ) TEST_CASE( "Scenario: " name, tags ) +#define SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags ) +#endif +#define GIVEN( desc ) SECTION( std::string(" Given: ") + desc, "" ) +#define WHEN( desc ) SECTION( std::string(" When: ") + desc, "" ) +#define AND_WHEN( desc ) SECTION( std::string("And when: ") + desc, "" ) +#define THEN( desc ) SECTION( std::string(" Then: ") + desc, "" ) +#define AND_THEN( desc ) SECTION( std::string(" And: ") + desc, "" ) + +using Catch::Detail::Approx; + +#endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED + diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests.cc new file mode 100644 index 0000000..0b8c837 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests.cc @@ -0,0 +1,339 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +#include "../catch/catch.hpp" +#include +#include +#include "t_netcore_generator_functional_tests_helpers.h" + +TEST_CASE( "t_netcore_generator should generate valid enum", "[functional]" ) +{ + string path = "CassandraTest.thrift"; + string name = "netcore"; + map parsed_options = { { "wcf", "wcf" } }; + string option_string = ""; + + t_program* program = new t_program(path, name); + t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string); + + std::pair pair = TestDataGenerator::get_test_enum_data(program); + string expected_result = pair.first; + t_enum* test_enum = pair.second; + + string file_path = test_enum->get_name() + ".cs"; + ofstream out; + out.open(file_path.c_str()); + + REQUIRE_NOTHROW(gen->generate_enum(out, test_enum)); + + out.close(); + + std::ifstream ifs(file_path); + string actual_result((std::istreambuf_iterator(ifs)), (std::istreambuf_iterator())); + std::remove(file_path.c_str()); + + REQUIRE(expected_result == actual_result); + + delete test_enum; + delete gen; + delete program; +} + +TEST_CASE("t_netcore_generator should generate valid void", "[functional]") +{ + string path = "CassandraTest.thrift"; + string name = "netcore"; + map parsed_options = { { "wcf", "wcf" } }; + string option_string = ""; + + t_program* program = new t_program(path, name); + t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string); + + std::pair pair = TestDataGenerator::get_test_void_const_data(gen); + string expected_result = pair.first; + t_const* const_ = pair.second; + vector consts_; + consts_.push_back(const_); + + string file_path = const_->get_name() + ".cs"; + ofstream out; + out.open(file_path.c_str()); + + REQUIRE_THROWS(gen->generate_consts(out, consts_)); + + out.close(); + + std::ifstream ifs(file_path); + string actual_result((std::istreambuf_iterator(ifs)), (std::istreambuf_iterator())); + std::remove(file_path.c_str()); + + delete const_; + delete gen; + delete program; +} + +TEST_CASE("t_netcore_generator should generate valid string with escaping keyword", "[functional]") +{ + string path = "CassandraTest.thrift"; + string name = "netcore"; + map parsed_options = { { "wcf", "wcf" } }; + string option_string = ""; + + t_program* program = new t_program(path, name); + t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string); + gen->init_generator(); + + std::pair pair = TestDataGenerator::get_test_string_const_data(gen); + string expected_result = pair.first; + t_const* const_ = pair.second; + vector consts_; + consts_.push_back(const_); + + string file_path = const_->get_name() + ".cs"; + ofstream out; + out.open(file_path.c_str()); + + REQUIRE_NOTHROW(gen->generate_consts(out, consts_)); + + out.close(); + + std::ifstream ifs(file_path); + string actual_result((std::istreambuf_iterator(ifs)), (std::istreambuf_iterator())); + std::remove(file_path.c_str()); + + REQUIRE(expected_result == actual_result); + + delete const_; + delete gen; + delete program; +} + +TEST_CASE("t_netcore_generator should generate valid bool with escaping keyword", "[functional]") +{ + string path = "CassandraTest.thrift"; + string name = "netcore"; + map parsed_options = { { "wcf", "wcf" } }; + string option_string = ""; + + t_program* program = new t_program(path, name); + t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string); + gen->init_generator(); + + std::pair pair = TestDataGenerator::get_test_bool_const_data(gen); + string expected_result = pair.first; + t_const* const_ = pair.second; + vector consts_; + consts_.push_back(const_); + + string file_path = const_->get_name() + ".cs"; + ofstream out; + out.open(file_path.c_str()); + + REQUIRE_NOTHROW(gen->generate_consts(out, consts_)); + + out.close(); + + std::ifstream ifs(file_path); + string actual_result((std::istreambuf_iterator(ifs)), (std::istreambuf_iterator())); + std::remove(file_path.c_str()); + + REQUIRE(expected_result == actual_result); + + delete const_; + delete gen; + delete program; +} + +TEST_CASE("t_netcore_generator should generate valid sbyte (i8) with escaping keyword", "[functional]") +{ + string path = "CassandraTest.thrift"; + string name = "netcore"; + map parsed_options = { { "wcf", "wcf" } }; + string option_string = ""; + + t_program* program = new t_program(path, name); + t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string); + gen->init_generator(); + + std::pair pair = TestDataGenerator::get_test_i8_const_data(gen); + string expected_result = pair.first; + t_const* const_ = pair.second; + vector consts_; + consts_.push_back(const_); + + string file_path = const_->get_name() + ".cs"; + ofstream out; + out.open(file_path.c_str()); + + REQUIRE_NOTHROW(gen->generate_consts(out, consts_)); + + out.close(); + + std::ifstream ifs(file_path); + string actual_result((std::istreambuf_iterator(ifs)), (std::istreambuf_iterator())); + std::remove(file_path.c_str()); + + REQUIRE(expected_result == actual_result); + + delete const_; + delete gen; + delete program; +} + +TEST_CASE("t_netcore_generator should generate valid short (i16) with escaping keyword", "[functional]") +{ + string path = "CassandraTest.thrift"; + string name = "netcore"; + map parsed_options = { { "wcf", "wcf" } }; + string option_string = ""; + + t_program* program = new t_program(path, name); + t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string); + gen->init_generator(); + + std::pair pair = TestDataGenerator::get_test_i16_const_data(gen); + string expected_result = pair.first; + t_const* const_ = pair.second; + vector consts_; + consts_.push_back(const_); + + string file_path = const_->get_name() + ".cs"; + ofstream out; + out.open(file_path.c_str()); + + REQUIRE_NOTHROW(gen->generate_consts(out, consts_)); + + out.close(); + + std::ifstream ifs(file_path); + string actual_result((std::istreambuf_iterator(ifs)), (std::istreambuf_iterator())); + std::remove(file_path.c_str()); + + REQUIRE(expected_result == actual_result); + + delete const_; + delete gen; + delete program; +} + +TEST_CASE("t_netcore_generator should generate valid integer (i32) with escaping keyword", "[functional]") +{ + string path = "CassandraTest.thrift"; + string name = "netcore"; + map parsed_options = { { "wcf", "wcf" } }; + string option_string = ""; + + t_program* program = new t_program(path, name); + t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string); + gen->init_generator(); + + std::pair pair = TestDataGenerator::get_test_i32_const_data(gen); + string expected_result = pair.first; + t_const* const_ = pair.second; + vector consts_; + consts_.push_back(const_); + + string file_path = const_->get_name() + ".cs"; + ofstream out; + out.open(file_path.c_str()); + + REQUIRE_NOTHROW(gen->generate_consts(out, consts_)); + + out.close(); + + std::ifstream ifs(file_path); + string actual_result((std::istreambuf_iterator(ifs)), (std::istreambuf_iterator())); + std::remove(file_path.c_str()); + + REQUIRE(expected_result == actual_result); + + delete const_; + delete gen; + delete program; +} + +TEST_CASE("t_netcore_generator should generate valid long (i64) with escaping keyword", "[functional]") +{ + string path = "CassandraTest.thrift"; + string name = "netcore"; + map parsed_options = { { "wcf", "wcf" } }; + string option_string = ""; + + t_program* program = new t_program(path, name); + t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string); + gen->init_generator(); + + std::pair pair = TestDataGenerator::get_test_i64_const_data(gen); + string expected_result = pair.first; + t_const* const_ = pair.second; + vector consts_; + consts_.push_back(const_); + + string file_path = const_->get_name() + ".cs"; + ofstream out; + out.open(file_path.c_str()); + + REQUIRE_NOTHROW(gen->generate_consts(out, consts_)); + + out.close(); + + std::ifstream ifs(file_path); + string actual_result((std::istreambuf_iterator(ifs)), (std::istreambuf_iterator())); + std::remove(file_path.c_str()); + + REQUIRE(expected_result == actual_result); + + delete const_; + delete gen; + delete program; +} + +TEST_CASE("t_netcore_generator should generate valid double with escaping keyword", "[functional]") +{ + string path = "CassandraTest.thrift"; + string name = "netcore"; + map parsed_options = { { "wcf", "wcf" } }; + string option_string = ""; + + t_program* program = new t_program(path, name); + t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string); + gen->init_generator(); + + std::pair pair = TestDataGenerator::get_test_double_const_data(gen); + string expected_result = pair.first; + t_const* const_ = pair.second; + vector consts_; + consts_.push_back(const_); + + string file_path = const_->get_name() + ".cs"; + ofstream out; + out.open(file_path.c_str()); + + REQUIRE_NOTHROW(gen->generate_consts(out, consts_)); + + out.close(); + + std::ifstream ifs(file_path); + string actual_result((std::istreambuf_iterator(ifs)), (std::istreambuf_iterator())); + std::remove(file_path.c_str()); + + REQUIRE(expected_result == actual_result); + + delete const_; + delete gen; + delete program; +} diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests_helpers.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests_helpers.cc new file mode 100644 index 0000000..92c170b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests_helpers.cc @@ -0,0 +1,237 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +#include +#include "thrift/common.h" +#include +#include "t_netcore_generator_functional_tests_helpers.h" + +const string TestDataGenerator::DEFAULT_FILE_HEADER = "/**" "\n" + " * Autogenerated by Thrift Compiler ()" "\n" + " *" "\n" + " * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING" "\n" + " * @generated" "\n" + " */"; + +std::pair TestDataGenerator::get_test_enum_data(t_program* program) +{ + string expected_result = DEFAULT_FILE_HEADER + + "\n" + "\n" + "/// \n" + "/// TestDoc\n" + "/// \n" + "public enum TestName\n" + "{\n" + " None = 0,\n" + " First = 1,\n" + " Second = 2,\n" + "}\n"; + + t_enum* enum_ = new t_enum(program); + enum_->set_name("TestName"); + enum_->set_doc("TestDoc"); + enum_->append(new t_enum_value("None", 0)); + enum_->append(new t_enum_value("First", 1)); + enum_->append(new t_enum_value("Second", 2)); + + return std::pair(expected_result, enum_); +} + +std::pair TestDataGenerator::get_test_void_const_data(t_netcore_generator* gen) +{ + string expected_result = DEFAULT_FILE_HEADER; + + t_type* type_ = new t_base_type("void", t_base_type::TYPE_VOID); + type_->set_doc("TestDoc"); + + t_const_value* const_value_ = new t_const_value(); + const_value_->set_string("VoidValue"); + + t_const* const_ = new t_const(type_, "void", const_value_); + const_->set_doc("TestDoc"); + + return std::pair(expected_result, const_); +} + +std::pair TestDataGenerator::get_test_string_const_data(t_netcore_generator* gen) +{ + string expected_result = DEFAULT_FILE_HEADER + "\n" +gen->netcore_type_usings() + + "\n" + "public static class netcoreConstants\n" + "{\n" + " /// \n" + " /// TestDoc\n" + " /// \n" + " public const string @string = \"StringValue\";\n" + "}\n"; + + t_type* type_ = new t_base_type("string", t_base_type::TYPE_STRING); + type_->set_doc("TestDoc"); + + t_const_value* const_value_ = new t_const_value(); + const_value_->set_string("StringValue"); + + t_const* const_ = new t_const(type_, "string", const_value_); + const_->set_doc("TestDoc"); + + return std::pair(expected_result, const_); +} + +std::pair TestDataGenerator::get_test_bool_const_data(t_netcore_generator* gen) +{ + string expected_result = DEFAULT_FILE_HEADER + "\n" +gen->netcore_type_usings() + + "\n" + "public static class netcoreConstants\n" + "{\n" + " /// \n" + " /// TestDoc\n" + " /// \n" + " public const bool @bool = true;\n" + "}\n"; + + t_type* type_ = new t_base_type("bool", t_base_type::TYPE_BOOL); + type_->set_doc("TestDoc"); + + t_const_value* const_value_ = new t_const_value(); + const_value_->set_integer(1); + + t_const* const_ = new t_const(type_, "bool", const_value_); + const_->set_doc("TestDoc"); + + return std::pair(expected_result, const_); +} + +std::pair TestDataGenerator::get_test_i8_const_data(t_netcore_generator* gen) +{ + string expected_result = DEFAULT_FILE_HEADER + "\n" +gen->netcore_type_usings() + + "\n" + "public static class netcoreConstants\n" + "{\n" + " /// \n" + " /// TestDoc\n" + " /// \n" + " public const sbyte @sbyte = 127;\n" + "}\n"; + + t_type* type_ = new t_base_type("I8", t_base_type::TYPE_I8); + type_->set_doc("TestDoc"); + + t_const_value* const_value_ = new t_const_value(); + const_value_->set_integer(127); + + t_const* const_ = new t_const(type_, "sbyte", const_value_); + const_->set_doc("TestDoc"); + + return std::pair(expected_result, const_); +} + +std::pair TestDataGenerator::get_test_i16_const_data(t_netcore_generator* gen) +{ + string expected_result = DEFAULT_FILE_HEADER + "\n" +gen->netcore_type_usings() + + "\n" + "public static class netcoreConstants\n" + "{\n" + " /// \n" + " /// TestDoc\n" + " /// \n" + " public const short @short = 32767;\n" + "}\n"; + + t_type* type_ = new t_base_type("i16", t_base_type::TYPE_I16); + type_->set_doc("TestDoc"); + + t_const_value* const_value_ = new t_const_value(); + const_value_->set_integer(32767); + + t_const* const_ = new t_const(type_, "short", const_value_); + const_->set_doc("TestDoc"); + + return std::pair(expected_result, const_); +} + +std::pair TestDataGenerator::get_test_i32_const_data(t_netcore_generator* gen) +{ + string expected_result = DEFAULT_FILE_HEADER + "\n" +gen->netcore_type_usings() + + "\n" + "public static class netcoreConstants\n" + "{\n" + " /// \n" + " /// TestDoc\n" + " /// \n" + " public const int @int = 2147483647;\n" + "}\n"; + + t_type* type_ = new t_base_type("i32", t_base_type::TYPE_I32); + type_->set_doc("TestDoc"); + + t_const_value* const_value_ = new t_const_value(); + const_value_->set_integer(2147483647); + + t_const* const_ = new t_const(type_, "int", const_value_); + const_->set_doc("TestDoc"); + + return std::pair(expected_result, const_); +} + +std::pair TestDataGenerator::get_test_i64_const_data(t_netcore_generator* gen) +{ + string expected_result = DEFAULT_FILE_HEADER + "\n" +gen->netcore_type_usings() + + "\n" + "public static class netcoreConstants\n" + "{\n" + " /// \n" + " /// TestDoc\n" + " /// \n" + " public const long @long = 9223372036854775807;\n" + "}\n"; + + t_type* type_ = new t_base_type("i64", t_base_type::TYPE_I64); + type_->set_doc("TestDoc"); + + t_const_value* const_value_ = new t_const_value(); + const_value_->set_integer(9223372036854775807); + + t_const* const_ = new t_const(type_, "long", const_value_); + const_->set_doc("TestDoc"); + + return std::pair(expected_result, const_); +} + +std::pair TestDataGenerator::get_test_double_const_data(t_netcore_generator* gen) +{ + string expected_result = DEFAULT_FILE_HEADER + "\n" +gen->netcore_type_usings() + + "\n" + "public static class netcoreConstants\n" + "{\n" + " /// \n" + " /// TestDoc\n" + " /// \n" + " public const double @double = 9.22337e+18;\n" + "}\n"; + + t_type* type_ = new t_base_type("double", t_base_type::TYPE_DOUBLE); + type_->set_doc("TestDoc"); + + t_const_value* const_value_ = new t_const_value(); + const_value_->set_double(9223372036854775807.1); + + t_const* const_ = new t_const(type_, "double", const_value_); + const_->set_doc("TestDoc"); + + return std::pair(expected_result, const_); +} diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests_helpers.h b/vendor/git.apache.org/thrift.git/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests_helpers.h new file mode 100644 index 0000000..c6eaac2 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests_helpers.h @@ -0,0 +1,34 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +#include + +class TestDataGenerator +{ +public: + static const string DEFAULT_FILE_HEADER; + + static std::pair get_test_enum_data(t_program* program); + static std::pair get_test_void_const_data(t_netcore_generator* gen); + static std::pair get_test_string_const_data(t_netcore_generator* gen); + static std::pair get_test_bool_const_data(t_netcore_generator* gen); + static std::pair get_test_i8_const_data(t_netcore_generator* gen); + static std::pair get_test_i16_const_data(t_netcore_generator* gen); + static std::pair get_test_i32_const_data(t_netcore_generator* gen); + static std::pair get_test_i64_const_data(t_netcore_generator* gen); + static std::pair get_test_double_const_data(t_netcore_generator* gen); +}; diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/tests/netcore/t_netcore_generator_helpers_tests.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/tests/netcore/t_netcore_generator_helpers_tests.cc new file mode 100644 index 0000000..0bcbeed --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/tests/netcore/t_netcore_generator_helpers_tests.cc @@ -0,0 +1,209 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +#include "../catch/catch.hpp" +#include +#include + +using std::vector; + +TEST_CASE("t_netcore_generator::netcore_type_usings() without option wcf should return valid namespaces", "[helpers]") +{ + string path = "CassandraTest.thrift"; + string name = "netcore"; + map parsed_options = { { "union", "union" } }; + string option_string = ""; + + string expected_namespaces = "using System;\n" + "using System.Collections;\n" + "using System.Collections.Generic;\n" + "using System.Text;\n" + "using System.IO;\n" + "using System.Threading;\n" + "using System.Threading.Tasks;\n" + "using Thrift;\n" + "using Thrift.Collections;\n" + endl; + + t_program* program = new t_program(path, name); + t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string); + + REQUIRE_FALSE(gen->is_wcf_enabled()); + REQUIRE(gen->netcore_type_usings() == expected_namespaces); + + delete gen; + delete program; +} + +TEST_CASE("t_netcore_generator::netcore_type_usings() with option wcf should return valid namespaces", "[helpers]") +{ + string path = "CassandraTest.thrift"; + string name = "netcore"; + map parsed_options = { { "wcf", "wcf" } }; + string option_string = ""; + + string expected_namespaces_wcf = "using System;\n" + "using System.Collections;\n" + "using System.Collections.Generic;\n" + "using System.Text;\n" + "using System.IO;\n" + "using System.Threading;\n" + "using System.Threading.Tasks;\n" + "using Thrift;\n" + "using Thrift.Collections;\n" + "using System.ServiceModel;\n" + "using System.Runtime.Serialization;\n" + endl; + + t_program* program = new t_program(path, name); + t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string); + + REQUIRE(gen->is_wcf_enabled()); + REQUIRE(gen->netcore_type_usings() == expected_namespaces_wcf); + + delete gen; + delete program; +} + +TEST_CASE("t_netcore_generator should contains latest C# keywords to normalize with @", "[helpers]") +{ + string path = "CassandraTest.thrift"; + string name = "netcore"; + map parsed_options = { { "wcf", "wcf" } }; + string option_string = ""; + vector current_keywords = { + { "abstract" }, + { "as" }, + { "base" }, + { "bool" }, + { "break" }, + { "byte" }, + { "case" }, + { "catch" }, + { "char" }, + { "checked" }, + { "class" }, + { "const" }, + { "continue" }, + { "decimal" }, + { "default" }, + { "delegate" }, + { "do" }, + { "double" }, + { "else" }, + { "enum" }, + { "event" }, + { "explicit" }, + { "extern" }, + { "false" }, + { "finally" }, + { "fixed" }, + { "float" }, + { "for" }, + { "foreach" }, + { "goto" }, + { "if" }, + { "implicit" }, + { "in" }, + { "int" }, + { "interface" }, + { "internal" }, + { "is" }, + { "lock" }, + { "long" }, + { "namespace" }, + { "new" }, + { "null" }, + { "object" }, + { "operator" }, + { "out" }, + { "override" }, + { "params" }, + { "private" }, + { "protected" }, + { "public" }, + { "readonly" }, + { "ref" }, + { "return" }, + { "sbyte" }, + { "sealed" }, + { "short" }, + { "sizeof" }, + { "stackalloc" }, + { "static" }, + { "string" }, + { "struct" }, + { "switch" }, + { "this" }, + { "throw" }, + { "true" }, + { "try" }, + { "typeof" }, + { "uint" }, + { "ulong" }, + { "unchecked" }, + { "unsafe" }, + { "ushort" }, + { "using" }, + { "void" }, + { "volatile" }, + { "while" }, + // Contextual Keywords + { "add" }, + { "alias" }, + { "ascending" }, + { "async" }, + { "await" }, + { "descending" }, + { "dynamic" }, + { "from" }, + { "get" }, + { "global" }, + { "group" }, + { "into" }, + { "join" }, + { "let" }, + { "orderby" }, + { "partial" }, + { "remove" }, + { "select" }, + { "set" }, + { "value" }, + { "var" }, + { "when" }, + { "where" }, + { "yield" } + }; + + string missed_keywords = ""; + + t_program* program = new t_program(path, name); + t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string); + gen->init_generator(); + map generators_keywords = gen->get_keywords_list(); + + for (vector::iterator it = current_keywords.begin(); it != current_keywords.end(); ++it) + { + if (generators_keywords.find(*it) == generators_keywords.end()) + { + missed_keywords = missed_keywords + *it + ","; + } + } + + REQUIRE(missed_keywords == ""); + + delete gen; + delete program; +} diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/tests/netcore/t_netcore_generator_initialization_tests.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/tests/netcore/t_netcore_generator_initialization_tests.cc new file mode 100644 index 0000000..ec17733 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/tests/netcore/t_netcore_generator_initialization_tests.cc @@ -0,0 +1,74 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +#include "../catch/catch.hpp" +#include +#include + +TEST_CASE( "t_netcore_generator should throw error with unknown options", "[initialization]" ) +{ + string path = "CassandraTest.thrift"; + string name = "netcore"; + map parsed_options = { { "keys", "keys" } }; + string option_string = ""; + + t_program* program = new t_program(path, name); + t_netcore_generator* gen = nullptr; + + REQUIRE_THROWS(gen = new t_netcore_generator(program, parsed_options, option_string)); + + delete gen; + delete program; +} + +TEST_CASE("t_netcore_generator should create valid instance with valid options", "[initialization]") +{ + string path = "CassandraTest.thrift"; + string name = "netcore"; + map parsed_options = { { "wcf", "wcf" }, { "nullable", "nullable"} }; + string option_string = ""; + + t_program* program = new t_program(path, name); + t_netcore_generator* gen = nullptr; + + REQUIRE_NOTHROW(gen = new t_netcore_generator(program, parsed_options, option_string)); + REQUIRE(gen != nullptr); + REQUIRE(gen->is_wcf_enabled()); + REQUIRE(gen->is_nullable_enabled()); + REQUIRE_FALSE(gen->is_hashcode_enabled()); + REQUIRE_FALSE(gen->is_serialize_enabled()); + REQUIRE_FALSE(gen->is_union_enabled()); + + delete gen; + delete program; +} + +TEST_CASE("t_netcore_generator should pass init succesfully", "[initialization]") +{ + string path = "CassandraTest.thrift"; + string name = "netcore"; + map parsed_options = { { "wcf", "wcf" },{ "nullable", "nullable" } }; + string option_string = ""; + + t_program* program = new t_program(path, name); + t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string); + + REQUIRE_NOTHROW(gen->init_generator()); + + delete gen; + delete program; +} diff --git a/vendor/git.apache.org/thrift.git/compiler/cpp/tests/tests_main.cc b/vendor/git.apache.org/thrift.git/compiler/cpp/tests/tests_main.cc new file mode 100644 index 0000000..21d09b9 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/compiler/cpp/tests/tests_main.cc @@ -0,0 +1,19 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +#define CATCH_CONFIG_MAIN +#include "catch/catch.hpp" diff --git a/vendor/git.apache.org/thrift.git/composer.json b/vendor/git.apache.org/thrift.git/composer.json index d937bc7..3695b8c 100644 --- a/vendor/git.apache.org/thrift.git/composer.json +++ b/vendor/git.apache.org/thrift.git/composer.json @@ -1,9 +1,11 @@ { "name": "apache/thrift", "description": "Apache Thrift RPC system", - "homepage": "http://thrift.apache.org/", + "homepage": "https://thrift.apache.org/", "type": "library", + "keywords": ["RPC"], "license": "Apache-2.0", + "readme": "README.md", "authors": [ { "name": "Apache Thrift Developers", @@ -16,15 +18,22 @@ "issues": "https://issues.apache.org/jira/browse/THRIFT" }, "require": { - "php": ">=5.3.0" + "php": "^5.5 || ^7.0" + }, + "require-dev": { + "phpunit/phpunit": "~4.8.36", + "squizlabs/php_codesniffer": "3.*" }, "autoload": { - "psr-0": {"Thrift": "lib/php/lib/"} + "psr-4": {"Thrift\\": "lib/php/lib/"} }, - "minimum-stability": "dev", + "autoload-dev": { + "psr-4": {"Test\\Thrift\\": "lib/php/test/"} + }, + "minimum-stability": "stable", "extra": { "branch-alias": { - "dev-master": "0.10.0" + "dev-master": "1.0.x-dev" } } } diff --git a/vendor/git.apache.org/thrift.git/configure.ac b/vendor/git.apache.org/thrift.git/configure.ac index 0972abf..b07b5de 100755 --- a/vendor/git.apache.org/thrift.git/configure.ac +++ b/vendor/git.apache.org/thrift.git/configure.ac @@ -20,7 +20,7 @@ AC_PREREQ(2.65) AC_CONFIG_MACRO_DIR([./aclocal]) -AC_INIT([thrift], [0.10.0]) +AC_INIT([thrift], [0.12.0]) AC_CONFIG_AUX_DIR([.]) @@ -83,6 +83,9 @@ AS_IF([test "x$D_IMPORT_PREFIX" = x], [D_IMPORT_PREFIX="${includedir}/d2"]) AC_ARG_VAR([DMD_LIBEVENT_FLAGS], [DMD flags for linking libevent (auto-detected if not set).]) AC_ARG_VAR([DMD_OPENSSL_FLAGS], [DMD flags for linking OpenSSL (auto-detected if not set).]) +AC_ARG_VAR([THRIFT], [Path to the thrift tool (needed for cross-compilation).]) +AS_IF([test "x$THRIFT" = x], [THRIFT=`pwd`/compiler/cpp/thrift]) + AC_PROG_CC AC_PROG_CPP AC_PROG_CXX @@ -100,9 +103,14 @@ AC_PROG_RANLIB AC_LANG([C++]) AX_CXX_COMPILE_STDCXX_11([noext], [optional]) +if test "$ac_success" = "no"; then + CXXFLAGS="$CXXFLAGS -Wno-variadic-macros -Wno-long-long -Wno-c++11-long-long" +fi AM_EXTRA_RECURSIVE_TARGETS([style]) AC_SUBST(CPPSTYLE_CMD, 'find . -type f \( -iname "*.h" -or -iname "*.cpp" -or -iname "*.cc" -or -iname "*.tcc" \) -printf "Reformatting: %h/%f\n" -exec clang-format -i {} \;') +# ' +# The above comment is to fix editor syntax highlighting AC_ARG_ENABLE([libs], AS_HELP_STRING([--enable-libs], [build the Apache Thrift libraries [default=yes]]), @@ -113,12 +121,15 @@ if test "$enable_libs" = "no"; then have_libs="no" with_cpp="no" with_c_glib="no" + with_cl="no" with_java="no" with_csharp="no" with_python="no" + with_py3="no" with_ruby="no" with_haskell="no" with_haxe="no" + with_dotnetcore="no" with_perl="no" with_php="no" with_php_extension="no" @@ -127,10 +138,11 @@ if test "$enable_libs" = "no"; then with_go="no" with_d="no" with_nodejs="no" + with_nodets="no" with_lua="no" + with_rs="no" fi - AX_THRIFT_LIB(cpp, [C++], yes) have_cpp=no if test "$with_cpp" = "yes"; then @@ -145,8 +157,6 @@ if test "$with_cpp" = "yes"; then have_cpp="yes" fi - AX_CHECK_OPENSSL() - AX_LIB_EVENT([1.0]) have_libevent=$success @@ -197,6 +207,12 @@ if test "$with_c_glib" = "yes"; then fi AM_CONDITIONAL(WITH_C_GLIB, [test "$have_glib2" = "yes" -a "$have_gobject2" = "yes"]) +echo "OpenSSL check" +if test "$have_cpp" = "yes" -o "$have_c_glib" = "yes"; then + echo "Have cpp or c so we check for OpenSSL" + AX_CHECK_OPENSSL() +fi + AX_THRIFT_LIB(csharp, [C#], yes) if test "$with_csharp" = "yes"; then PKG_CHECK_MODULES(MONO, mono >= 2.11.0, mono_2_11=yes, mono_2_11=no) @@ -223,6 +239,7 @@ if test "$with_java" = "yes"; then AX_CHECK_ANT_VERSION($ANT, 1.7) AC_SUBST(CLASSPATH) AC_SUBST(ANT_FLAGS) + AC_SUBST(GRADLE_OPTS) if test "x$JAVA" != "x" && test "x$JAVAC" != "x" && test "x$ANT" != "x" ; then have_java="yes" fi @@ -265,6 +282,18 @@ fi AM_CONDITIONAL(WITH_NODEJS, [test "$have_nodejs" = "yes"]) AM_CONDITIONAL(HAVE_NPM, [test "x$NPM" != "x"]) +AX_THRIFT_LIB(nodets, [Nodets], yes) +have_nodets=no +if test "$with_nodets" = "yes"; then + AC_PATH_PROGS([NODETS], [nodets node]) + AC_PATH_PROG([NPM], [npm]) + if test "x$NODETS" != "x" -a "x$NPM" != "x"; then + have_nodets="yes" + fi +fi +AM_CONDITIONAL(WITH_NODETS, [test "$have_nodets" = "yes"]) +AM_CONDITIONAL(HAVE_NPM, [test "x$NPM" != "x"]) + AX_THRIFT_LIB(lua, [Lua], yes) have_lua=no if test "$with_lua" = "yes"; then @@ -294,6 +323,7 @@ AM_CONDITIONAL(WITH_TWISTED_TEST, [test "$have_trial" = "yes"]) # Find "python3" executable. # It's distro specific and far from ideal but needed to cross test py2-3 at once. # TODO: find "python2" if it's 3.x +have_py3="no" if python --version 2>&1 | grep -q "Python 2"; then AC_PATH_PROGS([PYTHON3], [python3 python3.5 python35 python3.4 python34]) if test -n "$PYTHON3"; then @@ -340,9 +370,6 @@ if test "$with_php_extension" = "yes"; then fi AM_CONDITIONAL(WITH_PHP_EXTENSION, [test "$have_php_extension" = "yes"]) -AC_PATH_PROG([PHPUNIT], [phpunit]) -AM_CONDITIONAL(HAVE_PHPUNIT, [test "x$PHPUNIT" != "x"]) - AX_THRIFT_LIB(dart, [DART], yes) if test "$with_dart" = "yes"; then AC_PATH_PROG([DART], [dart]) @@ -389,6 +416,7 @@ if test "$with_go" = "yes"; then if [[ -x "$GO" ]] ; then AS_IF([test -n "$GO"],[ ax_go_version="1.4" + ax_go17_version="1.7" AC_MSG_CHECKING([for Go version]) golang_version=`$GO version 2>&1 | $SED -e 's/\(go \)\(version \)\(go\)\(@<:@0-9@:>@.@<:@0-9@:>@.@<:@0-9@:>@\)\(@<:@\*@:>@*\).*/\4/'` @@ -401,6 +429,13 @@ if test "$with_go" = "yes"; then : have_go="no" ]) + AX_COMPARE_VERSION([$golang_version],[lt],[$ax_go17_version],[ + : + go_version_lt_17="yes" + ],[ + : + go_version_lt_17="no" + ]) ],[ AC_MSG_WARN([could not find Go ]) have_go="no" @@ -408,7 +443,41 @@ if test "$with_go" = "yes"; then fi fi AM_CONDITIONAL(WITH_GO, [test "$have_go" = "yes"]) +AM_CONDITIONAL([GOVERSION_LT_17], [test "$go_version_lt_17" = "yes"]) +AX_THRIFT_LIB(rs, [Rust], yes) +have_rs="no" +if test "$with_rs" = "yes"; then + AC_PATH_PROG([CARGO], [cargo]) + AC_PATH_PROG([RUSTC], [rustc]) + if [[ -x "$CARGO" ]] && [[ -x "$RUSTC" ]]; then + min_rustc_version="1.13" + + AC_MSG_CHECKING([for rustc version]) + rustc_version=`$RUSTC --version 2>&1 | $SED -e 's/\(rustc \)\([0-9]\)\.\([0-9][0-9]*\)\.\([0-9][0-9]*\).*/\2.\3/'` + AC_MSG_RESULT($rustc_version) + AC_SUBST([rustc_version],[$rustc_version]) + + AX_COMPARE_VERSION([$min_rustc_version],[le],[$rustc_version],[ + : + have_rs="yes" + ],[ + : + have_rs="no" + ]) + fi +fi +AM_CONDITIONAL(WITH_RS, [test "$have_rs" = "yes"]) + +AX_THRIFT_LIB(cl, [Common Lisp], yes) +have_cl="no" +if test "$with_cl" = "yes"; then + AC_PATH_PROG([SBCL], [sbcl]) + if test "x$SBCL" != "x"; then + have_cl="yes" + fi +fi +AM_CONDITIONAL(WITH_CL, [test "$have_cl" = "yes"]) AX_THRIFT_LIB(haxe, [Haxe], yes) if test "$with_haxe" = "yes"; then @@ -420,6 +489,16 @@ fi AM_CONDITIONAL(WITH_HAXE, [test "$have_haxe" = "yes"]) +AX_THRIFT_LIB(dotnetcore, [.NET Core], yes) +if test "$with_dotnetcore" = "yes"; then + AC_PATH_PROG([DOTNETCORE], [dotnet]) + if [[ -x "$DOTNETCORE" ]] ; then + AX_PROG_DOTNETCORE_VERSION( [2.0.0], have_dotnetcore="yes", have_dotnetcore="no") + fi +fi +AM_CONDITIONAL(WITH_DOTNETCORE, [test "$have_dotnetcore" = "yes"]) + + AX_THRIFT_LIB(d, [D], yes) if test "$with_d" = "yes"; then AX_DMD @@ -460,7 +539,7 @@ linker flags for OPTLINK. Please set DMD_LIBEVENT_FLAGS manually.]) else AX_LIB_EVENT([2.0]) if test "$success" = "yes"; then - DMD_LIBEVENT_FLAGS=$(echo "$LIBEVENT_LDFLAGS $LIBEVENT_LIBS" | \ + DMD_LIBEVENT_FLAGS=$(echo "-fuse-ld=gold $LIBEVENT_LDFLAGS $LIBEVENT_LIBS" | \ sed -e 's/^ *//g;s/ *$//g;s/^\(.\)/-L\1/g;s/ */ -L/g') with_d_event_tests="yes" else @@ -484,7 +563,7 @@ linker flags for OPTLINK. Please set DMD_OPENSSL_FLAGS manually.]) else AX_CHECK_OPENSSL([with_d_ssl_tests="yes"]) if test "$with_d_ssl_tests" = "yes"; then - DMD_OPENSSL_FLAGS=$(echo "$OPENSSL_LDFLAGS $OPENSSL_LIBS" | \ + DMD_OPENSSL_FLAGS=$(echo "-fuse-ld=gold $OPENSSL_LDFLAGS $OPENSSL_LIBS" | \ sed -e 's/^ *//g;s/ *$//g;s/^\(.\)/-L\1/g;s/ */ -L/g') else AC_MSG_WARN([D OpenSSL interface present, but OpenSSL library not found.]) @@ -517,8 +596,8 @@ fi AM_CONDITIONAL(WITH_TESTS, [test "$have_tests" = "yes"]) AC_ARG_ENABLE([plugin], - AS_HELP_STRING([--enable-plugin], [build compiler plugin support [default=yes]]), - [], enable_plugin=yes + AS_HELP_STRING([--enable-plugin], [build compiler plugin support [default=no]]), + [], enable_plugin=no ) have_plugin=yes if test "$have_cpp" = "no" ; then @@ -527,9 +606,7 @@ fi if test "$enable_plugin" = "no"; then have_plugin="no" fi -if test "$have_plugin" = "yes" ; then - AC_CONFIG_LINKS([compiler/cpp/test/plugin/t_cpp_generator.cc:compiler/cpp/src/thrift/generate/t_cpp_generator.cc]) -fi +AC_CONFIG_LINKS([compiler/cpp/test/plugin/t_cpp_generator.cc:compiler/cpp/src/thrift/generate/t_cpp_generator.cc]) AM_CONDITIONAL(WITH_PLUGIN, [test "$have_plugin" = "yes"]) AC_ARG_ENABLE([tutorial], @@ -571,11 +648,14 @@ AC_CHECK_HEADERS([limits.h]) AC_CHECK_HEADERS([netdb.h]) AC_CHECK_HEADERS([netinet/in.h]) AC_CHECK_HEADERS([pthread.h]) +AC_CHECK_HEADERS([signal.h]) AC_CHECK_HEADERS([stddef.h]) AC_CHECK_HEADERS([stdlib.h]) +AC_CHECK_HEADERS([sys/ioctl.h]) AC_CHECK_HEADERS([sys/socket.h]) AC_CHECK_HEADERS([sys/time.h]) AC_CHECK_HEADERS([sys/un.h]) +AC_CHECK_HEADERS([poll.h]) AC_CHECK_HEADERS([sys/poll.h]) AC_CHECK_HEADERS([sys/resource.h]) AC_CHECK_HEADERS([unistd.h]) @@ -608,7 +688,7 @@ AC_TYPE_UINT16_T AC_TYPE_UINT32_T AC_TYPE_UINT64_T AC_TYPE_UINT8_T -AC_CHECK_TYPES([ptrdiff_t], [], [exit 1]) +AC_CHECK_TYPES([ptrdiff_t], [], [echo "ptrdiff_t not found or g++ not installed - cannot continue" && exit 1]) AC_STRUCT_TM @@ -733,6 +813,7 @@ AC_CONFIG_FILES([ compiler/cpp/test/Makefile compiler/cpp/src/thrift/version.h lib/Makefile + lib/cl/Makefile lib/cpp/Makefile lib/cpp/test/Makefile lib/cpp/thrift-nb.pc @@ -757,7 +838,9 @@ AC_CONFIG_FILES([ lib/js/test/Makefile lib/json/Makefile lib/json/test/Makefile + lib/netcore/Makefile lib/nodejs/Makefile + lib/nodets/Makefile lib/perl/Makefile lib/perl/test/Makefile lib/php/Makefile @@ -765,12 +848,15 @@ AC_CONFIG_FILES([ lib/dart/Makefile lib/py/Makefile lib/rb/Makefile + lib/rs/Makefile + lib/rs/test/Makefile lib/lua/Makefile lib/xml/Makefile lib/xml/test/Makefile test/Makefile test/features/Makefile test/c_glib/Makefile + test/cl/Makefile test/cpp/Makefile test/csharp/Makefile test/erl/Makefile @@ -778,6 +864,7 @@ AC_CONFIG_FILES([ test/haxe/Makefile test/hs/Makefile test/lua/Makefile + test/netcore/Makefile test/php/Makefile test/dart/Makefile test/perl/Makefile @@ -785,8 +872,10 @@ AC_CONFIG_FILES([ test/py.twisted/Makefile test/py.tornado/Makefile test/rb/Makefile + test/rs/Makefile tutorial/Makefile tutorial/c_glib/Makefile + tutorial/cl/Makefile tutorial/cpp/Makefile tutorial/d/Makefile tutorial/go/Makefile @@ -794,12 +883,14 @@ AC_CONFIG_FILES([ tutorial/hs/Makefile tutorial/java/Makefile tutorial/js/Makefile + tutorial/netcore/Makefile tutorial/nodejs/Makefile tutorial/dart/Makefile tutorial/py/Makefile tutorial/py.twisted/Makefile tutorial/py.tornado/Makefile tutorial/rb/Makefile + tutorial/rs/Makefile ]) if test "$have_cpp" = "yes" ; then MAYBE_CPP="cpp" ; else MAYBE_CPP="" ; fi @@ -830,10 +921,18 @@ if test "$have_go" = "yes" ; then MAYBE_GO="go" ; else MAYBE_GO="" ; fi AC_SUBST([MAYBE_GO]) if test "$have_nodejs" = "yes" ; then MAYBE_NODEJS="nodejs" ; else MAYBE_NODEJS="" ; fi AC_SUBST([MAYBE_NODEJS]) +if test "$have_nodets" = "yes" ; then MAYBE_NODETS="nodets" ; else MAYBE_NODETS="" ; fi +AC_SUBST([MAYBE_NODETS]) if test "$have_erlang" = "yes" ; then MAYBE_ERLANG="erl" ; else MAYBE_ERLANG="" ; fi AC_SUBST([MAYBE_ERLANG]) if test "$have_lua" = "yes" ; then MAYBE_LUA="lua" ; else MAYBE_LUA="" ; fi AC_SUBST([MAYBE_LUA]) +if test "$have_rs" = "yes" ; then MAYBE_RS="rs" ; else MAYBE_RS="" ; fi +AC_SUBST([MAYBE_RS]) +if test "$have_dotnetcore" = "yes" ; then MAYBE_DOTNETCORE="netcore" ; else MAYBE_DOTNETCORE="" ; fi +AC_SUBST([MAYBE_DOTNETCORE]) +if test "$have_cl" = "yes" ; then MAYBE_CL="cl" ; else MAYBE_CL="" ; fi +AC_SUBST([MAYBE_CL]) AC_OUTPUT @@ -841,99 +940,49 @@ AC_OUTPUT echo echo "$PACKAGE $VERSION" echo -echo "Building Plugin Support ...... : $have_plugin" -echo "Building C++ Library ......... : $have_cpp" echo "Building C (GLib) Library .... : $have_c_glib" -echo "Building Java Library ........ : $have_java" -echo "Building C# Library .......... : $have_csharp" -echo "Building Python Library ...... : $have_python" -echo "Building Ruby Library ........ : $have_ruby" -echo "Building Haxe Library ........ : $have_haxe" -echo "Building Haskell Library ..... : $have_haskell" -echo "Building Perl Library ........ : $have_perl" -echo "Building PHP Library ......... : $have_php" +echo "Building C# (Mono) Library ... : $have_csharp" +echo "Building C++ Library ......... : $have_cpp" +echo "Building Common Lisp Library.. : $have_cl" +echo "Building D Library ........... : $have_d" echo "Building Dart Library ........ : $have_dart" +echo "Building dotnetcore Library .. : $have_dotnetcore" echo "Building Erlang Library ...... : $have_erlang" echo "Building Go Library .......... : $have_go" -echo "Building D Library ........... : $have_d" -echo "Building NodeJS Library ...... : $have_nodejs" +echo "Building Haskell Library ..... : $have_haskell" +echo "Building Haxe Library ........ : $have_haxe" +echo "Building Java Library ........ : $have_java" echo "Building Lua Library ......... : $have_lua" +echo "Building NodeJS Library ...... : $have_nodejs" +echo "Building Perl Library ........ : $have_perl" +echo "Building PHP Library ......... : $have_php" +echo "Building Plugin Support ...... : $have_plugin" +echo "Building Python Library ...... : $have_python" +echo "Building Py3 Library ......... : $have_py3" +echo "Building Ruby Library ........ : $have_ruby" +echo "Building Rust Library ........ : $have_rs" -if test "$have_cpp" = "yes" ; then - echo - echo "C++ Library:" - echo " Build TZlibTransport ...... : $have_zlib" - echo " Build TNonblockingServer .. : $have_libevent" - echo " Build TQTcpServer (Qt4) .... : $have_qt" - echo " Build TQTcpServer (Qt5) .... : $have_qt5" -fi -if test "$have_java" = "yes" ; then - echo - echo "Java Library:" - echo " Using javac ............... : $JAVAC" - echo " Using java ................ : $JAVA" - echo " Using ant ................. : $ANT" -fi if test "$have_csharp" = "yes" ; then echo echo "C# Library:" echo " Using .NET 3.5 ............ : $net_3_5" + echo " Using mono version ........ : $($MCS --version | head -1)" fi -if test "$have_python" = "yes" ; then +if test "$have_cpp" = "yes" ; then echo - echo "Python Library:" - echo " Using Python .............. : $PYTHON" - if test "$have_py3" = "yes" ; then - echo " Using Python3 ............. : $PYTHON3" - fi - if test "$have_trial" = "yes"; then - echo " Using trial ............... : $TRIAL" - fi + echo "C++ Library:" + echo " C++ compiler .............. : $CXX" + echo " Build TZlibTransport ...... : $have_zlib" + echo " Build TNonblockingServer .. : $have_libevent" + echo " Build TQTcpServer (Qt4) ... : $have_qt" + echo " Build TQTcpServer (Qt5) ... : $have_qt5" + echo " C++ compiler version ...... : $($CXX --version | head -1)" fi -if test "$have_php" = "yes" ; then +if test "$have_cl" = "yes" ; then echo - echo "PHP Library:" - echo " Using php-config .......... : $PHP_CONFIG" -fi -if test "$have_dart" = "yes" ; then - echo - echo "Dart Library:" - echo " Using Dart ................ : $DART" - echo " Using Pub ................. : $DARTPUB" -fi -if test "$have_ruby" = "yes" ; then - echo - echo "Ruby Library:" - echo " Using Ruby ................ : $RUBY" -fi -if test "$have_haskell" = "yes" ; then - echo - echo "Haskell Library:" - echo " Using Haskell ............. : $RUNHASKELL" - echo " Using Cabal ............... : $CABAL" -fi -if test "$have_haxe" = "yes" ; then - echo - echo "Haxe Library:" - echo " Using Haxe ................ : $HAXE" - echo " Using Haxe version ........ : $HAXE_VERSION" -fi -if test "$have_perl" = "yes" ; then - echo - echo "Perl Library:" - echo " Using Perl ................ : $PERL" -fi -if test "$have_erlang" = "yes" ; then - echo - echo "Erlang Library:" - echo " Using erlc ................ : $ERLC" - echo " Using rebar ............... : $REBAR" -fi -if test "$have_go" = "yes" ; then - echo - echo "Go Library:" - echo " Using Go................... : $GO" - echo " Using Go version........... : $($GO version)" + echo "Common Lisp Library:" + echo " Using Common Lisp ......... : $SBCL" + echo " Using Common Lisp version . : $($SBCL --version)" fi if test "$have_d" = "yes" ; then echo @@ -941,6 +990,61 @@ if test "$have_d" = "yes" ; then echo " Using D Compiler .......... : $DMD" echo " Building D libevent tests . : $with_d_event_tests" echo " Building D SSL tests ...... : $with_d_ssl_tests" + echo " Using D version ........... : $($DMD --version | head -1)" +fi +if test "$have_dart" = "yes" ; then + echo + echo "Dart Library:" + echo " Using Dart ................ : $DART" + echo " Using Pub ................. : $DARTPUB" + echo " Using Dart version ........ : $($DART --version 2>&1)" +fi +if test "$have_dotnetcore" = "yes" ; then + echo + echo ".NET Core Library:" + echo " Using .NET Core ........... : $DOTNETCORE" + echo " Using .NET Core version ... : $DOTNETCORE_VERSION" +fi +if test "$have_erlang" = "yes" ; then + echo + echo "Erlang Library:" + echo " Using erlc ................ : $ERLC" + echo " Using rebar ............... : $REBAR" + echo " Using erlc version ........ : $($ERL -eval 'erlang:display(erlang:system_info(otp_release)), halt().' -noshell | tr -d '\"')" +fi +if test "$have_go" = "yes" ; then + echo + echo "Go Library:" + echo " Using Go................... : $GO" + echo " Using Go version........... : $($GO version)" +fi +if test "$have_haskell" = "yes" ; then + echo + echo "Haskell Library:" + echo " Using Cabal ............... : $CABAL" + echo " Using Haskell ............. : $RUNHASKELL" + echo " Using Haskell version ..... : $($RUNHASKELL --version)" +fi +if test "$have_haxe" = "yes" ; then + echo + echo "Haxe Library:" + echo " Using Haxe ................ : $HAXE" + echo " Using Haxe version ........ : $HAXE_VERSION" +fi +if test "$have_java" = "yes" ; then + echo + echo "Java Library:" + echo " Using gradlew ............. : lib/java/gradlew" + echo " Using java ................ : $JAVA" + echo " Using javac ............... : $JAVAC" + echo " Using Gradle version ...... : $(lib/java/gradlew --version --quiet | grep Gradle 2>&1)" + echo " Using java version ........ : $($JAVA -version 2>&1 | grep 'version ')" +fi +if test "$have_lua" = "yes" ; then + echo + echo "Lua Library:" + echo " Using Lua ................. : $LUA" + echo " Using Lua version.......... : $($LUA -v)" fi if test "$have_nodejs" = "yes" ; then echo @@ -948,12 +1052,46 @@ if test "$have_nodejs" = "yes" ; then echo " Using NodeJS .............. : $NODEJS" echo " Using NodeJS version....... : $($NODEJS --version)" fi -if test "$have_lua" = "yes" ; then +if test "$have_perl" = "yes" ; then echo - echo "Lua Library:" - echo " Using Lua .............. : $LUA" + echo "Perl Library:" + echo " Using Perl ................ : $PERL" + echo " Using Perl version ........ : $($PERL -v | grep 'version ')" +fi +if test "$have_php" = "yes" ; then + echo + echo "PHP Library:" + echo " Using php-config .......... : $PHP_CONFIG" + echo " Using php version ......... : $($PHP --version | head -1)" +fi +if test "$have_python" = "yes" ; then + echo + echo "Python Library:" + echo " Using Python .............. : $PYTHON" + echo " Using Python version ...... : $($PYTHON --version 2>&1)" + if test "$have_py3" = "yes" ; then + echo " Using Python3 ............. : $PYTHON3" + echo " Using Python3 version ..... : $($PYTHON3 --version)" + fi + if test "$have_trial" = "yes"; then + echo " Using trial ............... : $TRIAL" + fi +fi +if test "$have_ruby" = "yes" ; then + echo + echo "Ruby Library:" + echo " Using Ruby ................ : $RUBY" + echo " Using Ruby version ........ : $($RUBY --version)" +fi +if test "$have_rs" = "yes" ; then + echo + echo "Rust Library:" + echo " Using Cargo................ : $CARGO" + echo " Using rustc................ : $RUSTC" + echo " Using Rust version......... : $($RUSTC --version)" fi echo echo "If something is missing that you think should be present," echo "please skim the output of configure to find the missing" echo "component. Details are present in config.log." +echo diff --git a/vendor/git.apache.org/thrift.git/contrib/Rebus/Properties/AssemblyInfo.cs b/vendor/git.apache.org/thrift.git/contrib/Rebus/Properties/AssemblyInfo.cs index e476eab..dde7813 100644 --- a/vendor/git.apache.org/thrift.git/contrib/Rebus/Properties/AssemblyInfo.cs +++ b/vendor/git.apache.org/thrift.git/contrib/Rebus/Properties/AssemblyInfo.cs @@ -34,5 +34,5 @@ using System.Runtime.InteropServices; [assembly: Guid("0af10984-40d3-453d-b1e5-421529e8c7e2")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyVersion("0.12.0.0")] +[assembly: AssemblyFileVersion("0.12.0.0")] diff --git a/vendor/git.apache.org/thrift.git/contrib/fb303/cpp/FacebookBase.h b/vendor/git.apache.org/thrift.git/contrib/fb303/cpp/FacebookBase.h index 2159c95..daa5246 100644 --- a/vendor/git.apache.org/thrift.git/contrib/fb303/cpp/FacebookBase.h +++ b/vendor/git.apache.org/thrift.git/contrib/fb303/cpp/FacebookBase.h @@ -22,6 +22,7 @@ #include "FacebookService.h" +#include #include #include diff --git a/vendor/git.apache.org/thrift.git/contrib/fb303/if/fb303.thrift b/vendor/git.apache.org/thrift.git/contrib/fb303/if/fb303.thrift index 66c8315..89bd6eb 100644 --- a/vendor/git.apache.org/thrift.git/contrib/fb303/if/fb303.thrift +++ b/vendor/git.apache.org/thrift.git/contrib/fb303/if/fb303.thrift @@ -24,6 +24,7 @@ namespace java com.facebook.fb303 namespace cpp facebook.fb303 namespace perl Facebook.FB303 +namespace netcore Facebook.FB303.Test /** * Common status reporting mechanism across all services diff --git a/vendor/git.apache.org/thrift.git/contrib/fb303/java/build.properties b/vendor/git.apache.org/thrift.git/contrib/fb303/java/build.properties new file mode 100644 index 0000000..8463668 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/contrib/fb303/java/build.properties @@ -0,0 +1,5 @@ +# Maven Ant tasks Jar details +mvn.ant.task.version=2.1.3 +mvn.repo=http://repo1.maven.org/maven2 +mvn.ant.task.url=${mvn.repo}/org/apache/maven/maven-ant-tasks/${mvn.ant.task.version} +mvn.ant.task.jar=maven-ant-tasks-${mvn.ant.task.version}.jar diff --git a/vendor/git.apache.org/thrift.git/contrib/fb303/java/build.xml b/vendor/git.apache.org/thrift.git/contrib/fb303/java/build.xml index 8f2fa51..591a4cb 100755 --- a/vendor/git.apache.org/thrift.git/contrib/fb303/java/build.xml +++ b/vendor/git.apache.org/thrift.git/contrib/fb303/java/build.xml @@ -7,9 +7,9 @@ to you 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 @@ -26,20 +26,20 @@ - + + - + - + - @@ -74,8 +74,12 @@ - - + + + + + + @@ -120,19 +124,19 @@ - - diff --git a/vendor/git.apache.org/thrift.git/contrib/fb303/py/fb303_scripts/fb303_simple_mgmt.py b/vendor/git.apache.org/thrift.git/contrib/fb303/py/fb303_scripts/fb303_simple_mgmt.py index 4b1c257..5c8f409 100644 --- a/vendor/git.apache.org/thrift.git/contrib/fb303/py/fb303_scripts/fb303_simple_mgmt.py +++ b/vendor/git.apache.org/thrift.git/contrib/fb303/py/fb303_scripts/fb303_simple_mgmt.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one @@ -19,6 +19,7 @@ # under the License. # +from __future__ import print_function import sys import os from optparse import OptionParser @@ -57,24 +58,20 @@ def service_ctrl( msg = fb_status_string(status) if (len(status_details)): msg += " - %s" % status_details - print msg - - if (status == fb_status.ALIVE): - return 2 - else: - return 3 + print(msg) + return 2 if status == fb_status.ALIVE else 3 except: - print "Failed to get status" + print("Failed to get status") return 3 # scalar commands if command in ["version", "alive", "name"]: try: result = fb303_wrapper(command, port, trans_factory, prot_factory) - print result + print(result) return 0 except: - print "failed to get ", command + print("failed to get ", command) return 3 # counters @@ -82,10 +79,10 @@ def service_ctrl( try: counters = fb303_wrapper('counters', port, trans_factory, prot_factory) for counter in counters: - print "%s: %d" % (counter, counters[counter]) + print("%s: %d" % (counter.encode('utf-8'), counters[counter])) return 0 except: - print "failed to get counters" + print("failed to get counters") return 3 # Only root should be able to run the following commands @@ -96,19 +93,19 @@ def service_ctrl( fb303_wrapper(command, port, trans_factory, prot_factory) return 0 except: - print "failed to tell the service to ", command + print("failed to tell the service to ", command) return 3 else: if command in ["stop", "reload"]: - print "root privileges are required to stop or reload the service." + print("root privileges are required to stop or reload the service.") return 4 - print "The following commands are available:" + print("The following commands are available:") for command in ["counters", "name", "version", "alive", "status"]: - print "\t%s" % command - print "The following commands are available for users with root privileges:" + print("\t%s" % command) + print("The following commands are available for users with root privileges:") for command in ["stop", "reload"]: - print "\t%s" % command + print("\t%s" % command) return 0 diff --git a/vendor/git.apache.org/thrift.git/contrib/fb303/py/setup.py b/vendor/git.apache.org/thrift.git/contrib/fb303/py/setup.py index f5b9bb3..12d2d5c 100644 --- a/vendor/git.apache.org/thrift.git/contrib/fb303/py/setup.py +++ b/vendor/git.apache.org/thrift.git/contrib/fb303/py/setup.py @@ -26,7 +26,7 @@ except: from distutils.core import setup, Extension, Command setup(name='thrift_fb303', - version='0.10.0', + version='0.12.0', description='Python bindings for the Apache Thrift FB303', author=['Thrift Developers'], author_email=['dev@thrift.apache.org'], diff --git a/vendor/git.apache.org/thrift.git/contrib/thrift-maven-plugin/pom.xml b/vendor/git.apache.org/thrift.git/contrib/thrift-maven-plugin/pom.xml index 7973e69..e11fbbf 100644 --- a/vendor/git.apache.org/thrift.git/contrib/thrift-maven-plugin/pom.xml +++ b/vendor/git.apache.org/thrift.git/contrib/thrift-maven-plugin/pom.xml @@ -7,9 +7,9 @@ to you 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 @@ -17,8 +17,8 @@ specific language governing permissions and limitations under the License. --> - @@ -27,7 +27,7 @@ thrift-maven-plugin maven-plugin thrift-maven-plugin - 0.10.0 + 0.12.0 @@ -77,6 +77,12 @@ plexus-utils 3.0.14 + + org.mockito + mockito-all + 1.10.19 + test + ${basedir}/../.. diff --git a/vendor/git.apache.org/thrift.git/contrib/thrift-maven-plugin/src/main/java/org/apache/thrift/maven/AbstractThriftMojo.java b/vendor/git.apache.org/thrift.git/contrib/thrift-maven-plugin/src/main/java/org/apache/thrift/maven/AbstractThriftMojo.java index 0913c77..869be95 100644 --- a/vendor/git.apache.org/thrift.git/contrib/thrift-maven-plugin/src/main/java/org/apache/thrift/maven/AbstractThriftMojo.java +++ b/vendor/git.apache.org/thrift.git/contrib/thrift-maven-plugin/src/main/java/org/apache/thrift/maven/AbstractThriftMojo.java @@ -117,7 +117,7 @@ abstract class AbstractThriftMojo extends AbstractMojo { * @parameter default-value="${localRepository}" * @required */ - private ArtifactRepository localRepository; + protected ArtifactRepository localRepository; /** * Set this to {@code false} to disable hashing of dependent jar paths. @@ -129,7 +129,7 @@ abstract class AbstractThriftMojo extends AbstractMojo { * @parameter default-value="true" * @required */ - private boolean hashDependentPaths; + protected boolean hashDependentPaths; /** * @parameter @@ -229,7 +229,7 @@ abstract class AbstractThriftMojo extends AbstractMojo { checkNotNull(generator, "generator"); final File thriftSourceRoot = getThriftSourceRoot(); checkNotNull(thriftSourceRoot); - checkArgument(!thriftSourceRoot.isFile(), "thriftSourceRoot is a file, not a diretory"); + checkArgument(!thriftSourceRoot.isFile(), "thriftSourceRoot is a file, not a directory"); checkNotNull(temporaryThriftFileDirectory, "temporaryThriftFileDirectory"); checkState(!temporaryThriftFileDirectory.isFile(), "temporaryThriftFileDirectory is a file, not a directory"); final File outputDirectory = getOutputDirectory(); @@ -268,7 +268,9 @@ abstract class AbstractThriftMojo extends AbstractMojo { if (temporaryThriftFileDirectory.exists()) { cleanDirectory(temporaryThriftFileDirectory); } + Set thriftDirectories = newHashSet(); + for (File classpathElementFile : classpathElementFiles) { // for some reason under IAM, we receive poms as dependent files // I am excluding .xml rather than including .jar as there may be other extensions in use (sar, har, zip) @@ -283,18 +285,27 @@ abstract class AbstractThriftMojo extends AbstractMojo { throw new IllegalArgumentException(format( "%s was not a readable artifact", classpathElementFile)); } + + /** + * Copy each .thrift file found in the JAR into a temporary directory, preserving the + * directory path it had relative to its containing JAR. Add the resulting root directory + * (unique for each JAR processed) to the set of thrift include directories to use when + * compiling. + */ for (JarEntry jarEntry : list(classpathJar.entries())) { final String jarEntryName = jarEntry.getName(); if (jarEntry.getName().endsWith(THRIFT_FILE_SUFFIX)) { + final String truncatedJarPath = truncatePath(classpathJar.getName()); + final File thriftRootDirectory = new File(temporaryThriftFileDirectory, truncatedJarPath); final File uncompressedCopy = - new File(new File(temporaryThriftFileDirectory, - truncatePath(classpathJar.getName())), jarEntryName); + new File(thriftRootDirectory, jarEntryName); uncompressedCopy.getParentFile().mkdirs(); copyStreamToFile(new RawInputStreamFacade(classpathJar .getInputStream(jarEntry)), uncompressedCopy); - thriftDirectories.add(uncompressedCopy.getParentFile()); + thriftDirectories.add(thriftRootDirectory); } } + } else if (classpathElementFile.isDirectory()) { File[] thriftFiles = classpathElementFile.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { @@ -307,6 +318,7 @@ abstract class AbstractThriftMojo extends AbstractMojo { } } } + return ImmutableSet.copyOf(thriftDirectories); } @@ -319,15 +331,6 @@ abstract class AbstractThriftMojo extends AbstractMojo { return ImmutableSet.copyOf(thriftFilesInDirectory); } - ImmutableSet findThriftFilesInDirectories(Iterable directories) throws IOException { - checkNotNull(directories); - Set thriftFiles = newHashSet(); - for (File directory : directories) { - thriftFiles.addAll(findThriftFilesInDirectory(directory)); - } - return ImmutableSet.copyOf(thriftFiles); - } - /** * Truncates the path of jar files so that they are relative to the local repository. * diff --git a/vendor/git.apache.org/thrift.git/contrib/thrift-maven-plugin/src/main/java/org/apache/thrift/maven/ThriftTestCompileMojo.java b/vendor/git.apache.org/thrift.git/contrib/thrift-maven-plugin/src/main/java/org/apache/thrift/maven/ThriftTestCompileMojo.java index fb89d96..1b1d99e 100644 --- a/vendor/git.apache.org/thrift.git/contrib/thrift-maven-plugin/src/main/java/org/apache/thrift/maven/ThriftTestCompileMojo.java +++ b/vendor/git.apache.org/thrift.git/contrib/thrift-maven-plugin/src/main/java/org/apache/thrift/maven/ThriftTestCompileMojo.java @@ -23,6 +23,7 @@ import java.io.File; import java.util.List; import org.apache.maven.artifact.Artifact; import com.google.common.collect.ImmutableList; +import org.apache.maven.artifact.repository.ArtifactRepository; /** * @phase generate-test-sources @@ -71,4 +72,22 @@ public final class ThriftTestCompileMojo extends AbstractThriftMojo { protected File getThriftSourceRoot() { return thriftTestSourceRoot; } + + /** + * Set the local maven ArtifactRepository. Exposed only to allow testing outside of Maven itself. + * + * @param localRepository local ArtifactRepository + */ + public void setLocalMavenRepository(final ArtifactRepository localRepository) { + this.localRepository = localRepository; + } + + /** + * Set the option to hash dependent JAR paths. Exposed only to allow testing outside of Maven itself. + * + * @param hashDependentPaths whether or not to hash paths to dependent JARs + */ + public void setHashDependentPaths(final boolean hashDependentPaths) { + this.hashDependentPaths = hashDependentPaths; + } } diff --git a/vendor/git.apache.org/thrift.git/contrib/thrift-maven-plugin/src/test/java/org/apache/thrift/maven/TestAbstractThriftMojo.java b/vendor/git.apache.org/thrift.git/contrib/thrift-maven-plugin/src/test/java/org/apache/thrift/maven/TestAbstractThriftMojo.java new file mode 100644 index 0000000..c117671 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/contrib/thrift-maven-plugin/src/test/java/org/apache/thrift/maven/TestAbstractThriftMojo.java @@ -0,0 +1,102 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ +package org.apache.thrift.maven; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import org.apache.maven.artifact.repository.ArtifactRepository; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +import java.io.File; +import java.util.Set; + +import static junit.framework.TestCase.assertEquals; + + +public class TestAbstractThriftMojo { + + private ThriftTestCompileMojo mojo; + private File testRootDir; + private ArtifactRepository mavenRepository; + + + @Before + public void setUp() throws Exception { + final File tmpDir = new File(System.getProperty("java.io.tmpdir")); + testRootDir = new File(tmpDir, "thrift-test"); + + // the truncatePath method assumes a maven repository, but it only cares about the base dir + mavenRepository = Mockito.mock(ArtifactRepository.class); + Mockito.when(mavenRepository.getBasedir()).thenReturn("/test/maven/repo/basedir"); + + mojo = new ThriftTestCompileMojo(); + mojo.setLocalMavenRepository(mavenRepository); + } + + @Test + public void testMakeThriftPathFromJars() throws Throwable { + final File temporaryThriftFileDirectory = testRootDir; + + // The SharedIdl.jar file contains the same idl/shared.thrift and idl/tutorial.thrift hierarchy + // used by other tests. It's used here to represent a dependency of the project maven is building, + // one that is contributing .thrift IDL files as well as any other artifacts. + final Iterable classpathElementFiles = Lists.newArrayList( + new File("src/test/resources/dependency-jar-test/SharedIdl.jar") + ); + + final Set thriftDirectories = mojo.makeThriftPathFromJars(temporaryThriftFileDirectory, classpathElementFiles); + + // The results should be a path to a directory named after the JAR itself (assuming no path hashing, + // but see below for a separate test of that) representing the root of a hierarchy containing thrift + // files, suitable for providing to the thrift compiler as an include directory. In this case, that + // means it points to the directory containing the "idl" hierarchy rather than to the idl directory + // itself. + final Set expected = Sets.newHashSet( + new File(testRootDir, "src/test/resources/dependency-jar-test/SharedIdl.jar") + ); + + assertEquals("makeThriftPathFromJars should return thrift IDL base path from within JAR", expected, thriftDirectories); + } + + @Test + public void testTruncatePath() throws Throwable { + // JAR path is unrelated to maven repo, and should be unchanged + assertEquals("/path/to/somejar.jar", mojo.truncatePath("/path/to/somejar.jar")); + + // JAR path is within maven repo, and should be made relative to the repo + assertEquals("path/to/somejar.jar", mojo.truncatePath("/test/maven/repo/basedir/path/to/somejar.jar")); + + // JAR path contains forward slashes that should be normalized + assertEquals("/path/to/somejar.jar", mojo.truncatePath("\\path\\to\\somejar.jar")); + } + + @Test + public void testTruncatePathWithDependentPathHashing() throws Throwable { + mojo.setHashDependentPaths(true); + + // hashDependentPaths set to true, the JAR path is immediately hashed (MD5) and converted to a hex string + + assertEquals("1c85950987b23493462cf3c261d9510a", mojo.truncatePath("/path/to/somejar.jar")); + assertEquals("39fc2b4c34cb6cb0da38bed5d8b5fc67", mojo.truncatePath("/test/maven/repo/basedir/path/to/somejar.jar")); + assertEquals("25b6924f5b0e19486d0ff88448e999d5", mojo.truncatePath("\\path\\to\\somejar.jar")); + } + +} diff --git a/vendor/git.apache.org/thrift.git/contrib/thrift.spec b/vendor/git.apache.org/thrift.git/contrib/thrift.spec index ccd35a5..1fe0f9c 100644 --- a/vendor/git.apache.org/thrift.git/contrib/thrift.spec +++ b/vendor/git.apache.org/thrift.git/contrib/thrift.spec @@ -28,7 +28,7 @@ Name: thrift License: Apache License v2.0 Group: Development Summary: RPC and serialization framework -Version: 0.10.0 +Version: 0.12.0 Release: 0 URL: http://thrift.apache.org Packager: Thrift Developers @@ -234,5 +234,5 @@ umask 007 /sbin/ldconfig > /dev/null 2>&1 %changelog -* Wed Oct 10 2012 Thrift Dev +* Wed Oct 10 2012 Thrift Dev - Thrift 0.9.0 release. diff --git a/vendor/git.apache.org/thrift.git/contrib/vagrant/centos-6.5/README.md b/vendor/git.apache.org/thrift.git/contrib/vagrant/centos-6.5/README.md index 76dca44..91ae67f 100644 --- a/vendor/git.apache.org/thrift.git/contrib/vagrant/centos-6.5/README.md +++ b/vendor/git.apache.org/thrift.git/contrib/vagrant/centos-6.5/README.md @@ -11,7 +11,7 @@ This will download and launch the base box VM under VirtualBox and run the Apach $ vagrant ssh [vagrant@thrift ~]$ cd /thrift [vagrant@thrift thrift]$ compiler/cpp/thrift --version - Thrift version 1.0.0-dev + Thrift version 0.12.0 The provisioning script (inside the Vagrantfile) runs ./bootstrap.sh, ./configure, make and make check, but does not install thrift. To install thrift run "make install". diff --git a/vendor/git.apache.org/thrift.git/contrib/zeromq/TZmqServer.cpp b/vendor/git.apache.org/thrift.git/contrib/zeromq/TZmqServer.cpp index f031458..4df6c92 100644 --- a/vendor/git.apache.org/thrift.git/contrib/zeromq/TZmqServer.cpp +++ b/vendor/git.apache.org/thrift.git/contrib/zeromq/TZmqServer.cpp @@ -21,7 +21,7 @@ #include #include -using boost::shared_ptr; +using apache::thrift::stdcxx::shared_ptr; using apache::thrift::transport::TMemoryBuffer; using apache::thrift::protocol::TProtocol; diff --git a/vendor/git.apache.org/thrift.git/contrib/zeromq/TZmqServer.h b/vendor/git.apache.org/thrift.git/contrib/zeromq/TZmqServer.h index a840c86..43f86c0 100644 --- a/vendor/git.apache.org/thrift.git/contrib/zeromq/TZmqServer.h +++ b/vendor/git.apache.org/thrift.git/contrib/zeromq/TZmqServer.h @@ -28,7 +28,7 @@ namespace apache { namespace thrift { namespace server { class TZmqServer : public TServer { public: TZmqServer( - boost::shared_ptr processor, + apache::thrift::stdcxx::shared_ptr processor, zmq::context_t& ctx, const std::string& endpoint, int type) : TServer(processor) , processor_(processor) @@ -56,7 +56,7 @@ class TZmqServer : public TServer { } private: - boost::shared_ptr processor_; + apache::thrift::stdcxx::shared_ptr processor_; int zmq_type_; zmq::socket_t sock_; }; diff --git a/vendor/git.apache.org/thrift.git/contrib/zeromq/csharp/ThriftZMQ.csproj b/vendor/git.apache.org/thrift.git/contrib/zeromq/csharp/ThriftZMQ.csproj index ef2dbc3..9143a69 100755 --- a/vendor/git.apache.org/thrift.git/contrib/zeromq/csharp/ThriftZMQ.csproj +++ b/vendor/git.apache.org/thrift.git/contrib/zeromq/csharp/ThriftZMQ.csproj @@ -3,7 +3,7 @@ Debug x86 - 0.10.0 + 9.0.21022 2.0 {17C63B90-DFD7-42AC-A7B0-749E6876C0A1} Exe @@ -25,7 +25,7 @@ false true 0 - 0.10.0.%2a + 0.12.0 false false true @@ -88,4 +88,4 @@ - \ No newline at end of file + diff --git a/vendor/git.apache.org/thrift.git/contrib/zeromq/test-client.cpp b/vendor/git.apache.org/thrift.git/contrib/zeromq/test-client.cpp index d2fc56c..70a331e 100644 --- a/vendor/git.apache.org/thrift.git/contrib/zeromq/test-client.cpp +++ b/vendor/git.apache.org/thrift.git/contrib/zeromq/test-client.cpp @@ -6,7 +6,7 @@ #include "TZmqClient.h" #include "Storage.h" -using boost::shared_ptr; +using apache::thrift::stdcxx::shared_ptr; using apache::thrift::transport::TZmqClient; using apache::thrift::protocol::TBinaryProtocol; @@ -17,7 +17,7 @@ int main(int argc, char** argv) { if (argc > 1) { incr = atoi(argv[1]); if (incr) { - socktype = ZMQ_DOWNSTREAM; + socktype = ZMQ_PUSH; endpoint = "tcp://127.0.0.1:9091"; } } diff --git a/vendor/git.apache.org/thrift.git/contrib/zeromq/test-client.py b/vendor/git.apache.org/thrift.git/contrib/zeromq/test-client.py index 753b132..d51216e 100755 --- a/vendor/git.apache.org/thrift.git/contrib/zeromq/test-client.py +++ b/vendor/git.apache.org/thrift.git/contrib/zeromq/test-client.py @@ -15,7 +15,7 @@ def main(args): if len(args) > 1: incr = int(args[1]) if incr: - socktype = zmq.DOWNSTREAM + socktype = zmq.PUSH endpoint = "tcp://127.0.0.1:9091" ctx = zmq.Context() @@ -29,7 +29,7 @@ def main(args): time.sleep(0.05) else: value = client.get() - print value + print(value) if __name__ == "__main__": diff --git a/vendor/git.apache.org/thrift.git/contrib/zeromq/test-receiver.cpp b/vendor/git.apache.org/thrift.git/contrib/zeromq/test-receiver.cpp index 8fe69da..60791ac 100644 --- a/vendor/git.apache.org/thrift.git/contrib/zeromq/test-receiver.cpp +++ b/vendor/git.apache.org/thrift.git/contrib/zeromq/test-receiver.cpp @@ -2,7 +2,7 @@ #include "TZmqServer.h" #include "Storage.h" -using boost::shared_ptr; +using apache::thrift::stdcxx::shared_ptr; using apache::thrift::TProcessor; using apache::thrift::server::TZmqServer; using apache::thrift::server::TZmqMultiServer; diff --git a/vendor/git.apache.org/thrift.git/contrib/zeromq/test-sender.cpp b/vendor/git.apache.org/thrift.git/contrib/zeromq/test-sender.cpp index 6b0eef1..8928db3 100644 --- a/vendor/git.apache.org/thrift.git/contrib/zeromq/test-sender.cpp +++ b/vendor/git.apache.org/thrift.git/contrib/zeromq/test-sender.cpp @@ -6,7 +6,7 @@ #include "TZmqClient.h" #include "Storage.h" -using boost::shared_ptr; +using apache::thrift::stdcxx::shared_ptr; using apache::thrift::transport::TZmqClient; using apache::thrift::protocol::TBinaryProtocol; diff --git a/vendor/git.apache.org/thrift.git/contrib/zeromq/test-server.cpp b/vendor/git.apache.org/thrift.git/contrib/zeromq/test-server.cpp index c624b0d..baa1451 100644 --- a/vendor/git.apache.org/thrift.git/contrib/zeromq/test-server.cpp +++ b/vendor/git.apache.org/thrift.git/contrib/zeromq/test-server.cpp @@ -2,7 +2,7 @@ #include "TZmqServer.h" #include "Storage.h" -using boost::shared_ptr; +using apache::thrift::stdcxx::shared_ptr; using apache::thrift::TProcessor; using apache::thrift::server::TZmqServer; using apache::thrift::server::TZmqMultiServer; @@ -33,7 +33,7 @@ int main(int argc, char *argv[]) { zmq::context_t ctx(1); TZmqServer reqrep_server(processor, ctx, "tcp://0.0.0.0:9090", ZMQ_REP); - TZmqServer oneway_server(processor, ctx, "tcp://0.0.0.0:9091", ZMQ_UPSTREAM); + TZmqServer oneway_server(processor, ctx, "tcp://0.0.0.0:9091", ZMQ_PULL); TZmqMultiServer multiserver; multiserver.servers().push_back(&reqrep_server); multiserver.servers().push_back(&oneway_server); diff --git a/vendor/git.apache.org/thrift.git/contrib/zeromq/test-server.py b/vendor/git.apache.org/thrift.git/contrib/zeromq/test-server.py index c7804d3..d89b37b 100755 --- a/vendor/git.apache.org/thrift.git/contrib/zeromq/test-server.py +++ b/vendor/git.apache.org/thrift.git/contrib/zeromq/test-server.py @@ -22,7 +22,7 @@ def main(): ctx = zmq.Context() reqrep_server = TZmqServer.TZmqServer(processor, ctx, "tcp://0.0.0.0:9090", zmq.REP) - oneway_server = TZmqServer.TZmqServer(processor, ctx, "tcp://0.0.0.0:9091", zmq.UPSTREAM) + oneway_server = TZmqServer.TZmqServer(processor, ctx, "tcp://0.0.0.0:9091", zmq.PULL) multiserver = TZmqServer.TZmqMultiServer() multiserver.servers.append(reqrep_server) multiserver.servers.append(oneway_server) diff --git a/vendor/git.apache.org/thrift.git/debian/changelog b/vendor/git.apache.org/thrift.git/debian/changelog index 640480e..5c8545f 100644 --- a/vendor/git.apache.org/thrift.git/debian/changelog +++ b/vendor/git.apache.org/thrift.git/debian/changelog @@ -1,8 +1,26 @@ +thrift (0.12.0) stable; urgency=low + + * update to 0.12.0 + + -- Jake Farrell Wed, 15 Oct 2018 12:00:00 -0500 + +thrift (0.11.0) stable; urgency=low + + * update to 0.11.0 + + -- Jake Farrell Wed, 07 Dec 2017 20:07:00 -0500 + thrift (0.10.0) stable; urgency=low * update to 0.10.0 - -- Jake Farrell Mon, 12 Dec 2016 12:00:00 -0500 + -- Jake Farrell Wed, 03 Jan 2017 16:52:00 -0500 + +thrift (0.9.3) stable; urgency=low + + * update to 0.9.3 + + -- Jake Farrell Wed, 11 Oct 2015 17:22:00 -0500 thrift (0.9.0) stable; urgency=low diff --git a/vendor/git.apache.org/thrift.git/debian/control b/vendor/git.apache.org/thrift.git/debian/control index 43e7a0f..cb8a376 100644 --- a/vendor/git.apache.org/thrift.git/debian/control +++ b/vendor/git.apache.org/thrift.git/debian/control @@ -3,12 +3,12 @@ Section: devel Priority: extra Build-Depends: debhelper (>= 9), build-essential, mono-mcs, python-dev, ant, mono-devel, libmono-system-web4.0-cil, erlang-base, ruby-dev | ruby1.9.1-dev, ruby-bundler ,autoconf, automake, - pkg-config, libtool, bison, flex, libboost-dev | libboost1.53-dev, + pkg-config, libtool, bison, flex, libboost-dev | libboost1.53-dev | libboost1.63-all-dev, python-all, python-setuptools, python-all-dev, python-all-dbg, python3-all, python3-setuptools, python3-all-dev, python3-all-dbg, openjdk-7-jdk | openjdk-8-jdk | default-jdk, - libboost-test-dev | libboost-test1.53-dev, libevent-dev, libssl-dev, perl (>= 5.8.0-7), - php5 | php7.0, php5-dev | php7.0-dev, libglib2.0-dev, qtchooser, qtbase5-dev-tools + libboost-test-dev | libboost-test1.53-dev | libboost-test1.63-dev, libevent-dev, libssl-dev, perl (>= 5.8.0-7), + php (>= 5), php-dev (>= 5), libglib2.0-dev, qtchooser, qtbase5-dev-tools Maintainer: Thrift Developer's Homepage: http://thrift.apache.org/ Vcs-Git: https://git-wip-us.apache.org/repos/asf/thrift.git @@ -166,6 +166,17 @@ Description: Thrift C++ library This package contains the runtime libraries needed for C++ applications using Thrift. +Package: libthrift0-dbg +Architecture: any +Section: debug +Depends: ${shlibs:Depends}, ${misc:Depends}, libthrift0 (= ${binary:Version}) +Description: Thrift C++ library debug symbols + Thrift is a software framework for scalable cross-language services + development. It combines a software stack with a code generation engine to + build services that work efficiently and seamlessly. + . + This package contains the debug symbols for the Thrift C++ runtime libraries. + Package: libthrift-dev Architecture: any Section: libdevel diff --git a/vendor/git.apache.org/thrift.git/debian/rules b/vendor/git.apache.org/thrift.git/debian/rules index adecf07..9b436d9 100755 --- a/vendor/git.apache.org/thrift.git/debian/rules +++ b/vendor/git.apache.org/thrift.git/debian/rules @@ -29,7 +29,7 @@ configure-stamp: # Add here commands to configure the package. if [ -f bootstrap.sh ]; then $(CURDIR)/bootstrap.sh; fi - $(CURDIR)/configure --prefix=/usr + $(CURDIR)/configure --prefix=/usr --enable-plugin=no touch configure-stamp @@ -42,12 +42,12 @@ build: build-arch build-indep build-arch: build-arch-stamp $(CURDIR)/compiler/cpp/thrift build-arch-stamp: configure-stamp - # Compile C++ library - $(MAKE) -C $(CURDIR)/lib/cpp - # Compile compiler $(MAKE) -C $(CURDIR)/compiler/cpp + # Compile C++ library + $(MAKE) -C $(CURDIR)/lib/cpp + # Compile C (glib) library $(MAKE) -C $(CURDIR)/lib/c_glib @@ -73,7 +73,7 @@ build-indep-stamp: configure-stamp $(CURDIR)/compiler/cpp/thrift # Java cd $(CURDIR)/lib/java && \ - ant + ./gradlew --no-daemon -Prelease=true jar # C# $(MAKE) -C $(CURDIR)/lib/csharp @@ -113,7 +113,7 @@ install-indep: # Java mkdir -p $(CURDIR)/debian/libthrift-java/usr/share/java/ && \ - cp $(CURDIR)/lib/java/build/libthrift*.jar \ + cp $(CURDIR)/lib/java/build/libs/libthrift*.jar \ $(CURDIR)/debian/libthrift-java/usr/share/java/ # Ruby @@ -130,7 +130,8 @@ install-indep: # Perl $(MAKE) -C $(CURDIR)/lib/perl install DESTDIR=$(CURDIR)/debian/libthrift-perl - mv $(CURDIR)/debian/libthrift-perl/usr/local/lib/perl5 $(CURDIR)/debian/libthrift-perl/usr/lib + mkdir -p $(CURDIR)/debian/libthrift-perl/usr/share + mv $(CURDIR)/debian/libthrift-perl/usr/local/lib/perl5 $(CURDIR)/debian/libthrift-perl/usr/share rmdir $(CURDIR)/debian/libthrift-perl/usr/local/lib rmdir $(CURDIR)/debian/libthrift-perl/usr/local @@ -201,9 +202,10 @@ binary-common: dh_installexamples dh_installman dh_link + dh_strip -plibthrift0 --dbg-package=libthrift0-dbg dh_strip -ppython-thrift --dbg-package=python-thrift-dbg dh_strip -ppython3-thrift --dbg-package=python3-thrift-dbg - dh_strip -pthrift-compiler -plibthrift0 + dh_strip -pthrift-compiler dh_compress dh_fixperms dh_makeshlibs diff --git a/vendor/git.apache.org/thrift.git/doap.rdf b/vendor/git.apache.org/thrift.git/doap.rdf index 14a8d66..cd4aecc 100755 --- a/vendor/git.apache.org/thrift.git/doap.rdf +++ b/vendor/git.apache.org/thrift.git/doap.rdf @@ -1,8 +1,8 @@ - + - + - + + - + - + @@ -52,12 +53,13 @@ + - + @@ -69,10 +71,10 @@ - @@ -108,19 +110,19 @@ - - @@ -176,5 +178,5 @@ - + diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/CMakeLists.txt b/vendor/git.apache.org/thrift.git/lib/c_glib/CMakeLists.txt index dd9892c..3743a68 100644 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/CMakeLists.txt +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/CMakeLists.txt @@ -33,9 +33,12 @@ set(thrift_c_glib_SOURCES src/thrift/c_glib/thrift_application_exception.c src/thrift/c_glib/processor/thrift_processor.c src/thrift/c_glib/processor/thrift_dispatch_processor.c + src/thrift/c_glib/processor/thrift_multiplexed_processor.c src/thrift/c_glib/protocol/thrift_protocol.c src/thrift/c_glib/protocol/thrift_protocol_factory.c + src/thrift/c_glib/protocol/thrift_protocol_decorator.c src/thrift/c_glib/protocol/thrift_binary_protocol.c + src/thrift/c_glib/protocol/thrift_stored_message_protocol.c src/thrift/c_glib/protocol/thrift_binary_protocol_factory.c src/thrift/c_glib/protocol/thrift_compact_protocol.c src/thrift/c_glib/protocol/thrift_compact_protocol_factory.c @@ -54,6 +57,17 @@ set(thrift_c_glib_SOURCES src/thrift/c_glib/server/thrift_simple_server.c ) +# If OpenSSL is not found just ignore the OpenSSL stuff +find_package(OpenSSL) +if(OPENSSL_FOUND AND WITH_OPENSSL) + list( APPEND thriftcpp_SOURCES + src/thrift/c_glib/transport/thrift_ssl_socket.c + ) + include_directories(SYSTEM "${OPENSSL_INCLUDE_DIR}") + list(APPEND SYSLIBS "${OPENSSL_LIBRARIES}") +endif() + + # Contains the thrift specific ADD_LIBRARY_THRIFT and TARGET_LINK_LIBRARIES_THRIFT include(ThriftMacros) diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/Makefile.am b/vendor/git.apache.org/thrift.git/lib/c_glib/Makefile.am index 452f6a4..49b5b23 100755 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/Makefile.am +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/Makefile.am @@ -34,9 +34,13 @@ libthrift_c_glib_la_SOURCES = src/thrift/c_glib/thrift.c \ src/thrift/c_glib/thrift_application_exception.c \ src/thrift/c_glib/processor/thrift_processor.c \ src/thrift/c_glib/processor/thrift_dispatch_processor.c \ + src/thrift/c_glib/processor/thrift_multiplexed_processor.c \ src/thrift/c_glib/protocol/thrift_protocol.c \ + src/thrift/c_glib/protocol/thrift_protocol_decorator.c \ src/thrift/c_glib/protocol/thrift_protocol_factory.c \ src/thrift/c_glib/protocol/thrift_binary_protocol.c \ + src/thrift/c_glib/protocol/thrift_stored_message_protocol.c \ + src/thrift/c_glib/protocol/thrift_multiplexed_protocol.c \ src/thrift/c_glib/protocol/thrift_binary_protocol_factory.c \ src/thrift/c_glib/protocol/thrift_compact_protocol.c \ src/thrift/c_glib/protocol/thrift_compact_protocol_factory.c \ @@ -45,6 +49,7 @@ libthrift_c_glib_la_SOURCES = src/thrift/c_glib/thrift.c \ src/thrift/c_glib/transport/thrift_buffered_transport_factory.c \ src/thrift/c_glib/transport/thrift_framed_transport_factory.c \ src/thrift/c_glib/transport/thrift_socket.c \ + src/thrift/c_glib/transport/thrift_ssl_socket.c \ src/thrift/c_glib/transport/thrift_server_transport.c \ src/thrift/c_glib/transport/thrift_server_socket.c \ src/thrift/c_glib/transport/thrift_buffered_transport.c \ @@ -54,7 +59,8 @@ libthrift_c_glib_la_SOURCES = src/thrift/c_glib/thrift.c \ src/thrift/c_glib/server/thrift_server.c \ src/thrift/c_glib/server/thrift_simple_server.c -libthrift_c_glib_la_CFLAGS = $(AM_CFLAGS) $(GLIB_CFLAGS) +libthrift_c_glib_la_CFLAGS = $(AM_CFLAGS) $(GLIB_CFLAGS) $(GOBJECT_CFLAGS) $(OPENSSL_INCLUDES) +libthrift_c_glib_la_LDFLAGS = $(AM_LDFLAGS) $(GLIB_LIBS) $(GOBJECT_LIBS) $(OPENSSL_LDFLAGS) $(OPENSSL_LIBS) include_thriftdir = $(includedir)/thrift/c_glib include_thrift_HEADERS = \ @@ -65,11 +71,15 @@ include_thrift_HEADERS = \ include_protocoldir = $(include_thriftdir)/protocol include_protocol_HEADERS = src/thrift/c_glib/protocol/thrift_protocol.h \ + src/thrift/c_glib/protocol/thrift_protocol_decorator.h \ src/thrift/c_glib/protocol/thrift_protocol_factory.h \ src/thrift/c_glib/protocol/thrift_binary_protocol.h \ src/thrift/c_glib/protocol/thrift_binary_protocol_factory.h \ src/thrift/c_glib/protocol/thrift_compact_protocol.h \ - src/thrift/c_glib/protocol/thrift_compact_protocol_factory.h + src/thrift/c_glib/protocol/thrift_compact_protocol_factory.h \ + src/thrift/c_glib/protocol/thrift_multiplexed_protocol.h \ + src/thrift/c_glib/protocol/thrift_stored_message_protocol.h + include_transportdir = $(include_thriftdir)/transport include_transport_HEADERS = src/thrift/c_glib/transport/thrift_buffered_transport.h \ @@ -79,6 +89,8 @@ include_transport_HEADERS = src/thrift/c_glib/transport/thrift_buffered_transpor src/thrift/c_glib/transport/thrift_server_socket.h \ src/thrift/c_glib/transport/thrift_server_transport.h \ src/thrift/c_glib/transport/thrift_socket.h \ + src/thrift/c_glib/transport/thrift_platform_socket.h \ + src/thrift/c_glib/transport/thrift_ssl_socket.h \ src/thrift/c_glib/transport/thrift_transport.h \ src/thrift/c_glib/transport/thrift_transport_factory.h \ src/thrift/c_glib/transport/thrift_buffered_transport_factory.h \ @@ -90,7 +102,8 @@ include_server_HEADERS = src/thrift/c_glib/server/thrift_server.h \ include_processordir = $(include_thriftdir)/processor include_processor_HEADERS = src/thrift/c_glib/processor/thrift_processor.h \ - src/thrift/c_glib/processor/thrift_dispatch_processor.h + src/thrift/c_glib/processor/thrift_dispatch_processor.h \ + src/thrift/c_glib/processor/thrift_multiplexed_processor.h EXTRA_DIST = \ diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/README.md b/vendor/git.apache.org/thrift.git/lib/c_glib/README.md index fd70d08..dd84f3d 100644 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/README.md +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/README.md @@ -32,3 +32,18 @@ Dependencies GLib http://www.gtk.org/ +Breaking Changes +================ + +0.12.0 +------ + +The compiler's handling of namespaces when generating the name of types, +functions and header files has been improved. This means code written to use +classes generated by previous versions of the compiler may need to be updated to +reflect the proper convention for class names, which is + +- A lowercase, [snake-case](https://en.wikipedia.org/wiki/Snake_case) + representation of the class' namespace, followed by +- An underscore and +- A lowercase, snake-case representation of the class' name. diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/processor/thrift_multiplexed_processor.c b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/processor/thrift_multiplexed_processor.c new file mode 100644 index 0000000..68a0f4d --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/processor/thrift_multiplexed_processor.c @@ -0,0 +1,346 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ +#include +#include + +#include +#include +#include +#include +#include +#include + +G_DEFINE_TYPE(ThriftMultiplexedProcessor, thrift_multiplexed_processor, THRIFT_TYPE_PROCESSOR) + + +enum +{ + PROP_THRIFT_MULTIPLEXED_PROCESSOR_DEFAULT_SERVICE_NAME = 1, + PROP_THRIFT_MULTIPLEXED_PROCESSOR_END +}; + +static GParamSpec *thrift_multiplexed_processor_obj_properties[PROP_THRIFT_MULTIPLEXED_PROCESSOR_END] = { NULL, }; + + +static gboolean +thrift_multiplexed_processor_register_processor_impl(ThriftProcessor *processor, const gchar * multiplexed_processor_name, ThriftProcessor * multiplexed_processor , GError **error) +{ + ThriftMultiplexedProcessor *self = THRIFT_MULTIPLEXED_PROCESSOR(processor); + g_hash_table_replace(self->multiplexed_services, + g_strdup(multiplexed_processor_name), + g_object_ref (multiplexed_processor)); + + /* Make first registered become default */ + if(!self->default_processor_name){ + self->default_processor_name = g_strdup(multiplexed_processor_name); + } + return TRUE; +} + + +static gboolean +thrift_multiplexed_processor_process_impl (ThriftProcessor *processor, ThriftProtocol *in, + ThriftProtocol *out, GError **error) +{ + gboolean retval = FALSE; + gboolean token_error = FALSE; + ThriftApplicationException *xception; + ThriftStoredMessageProtocol *stored_message_protocol = NULL; + ThriftMessageType message_type; + ThriftMultiplexedProcessor *self = THRIFT_MULTIPLEXED_PROCESSOR(processor); + ThriftProcessor *multiplexed_processor = NULL; + ThriftTransport *transport; + char *token=NULL; + int token_index=0; + char *state=NULL; + gchar *fname=NULL; + gint32 seqid, result; + + /* FIXME It seems that previous processor is not managing error correctly */ + if(*error!=NULL) { + g_debug ("thrift_multiplexed_processor: last error not removed: %s", + *error != NULL ? (*error)->message : "(null)"); + g_clear_error (error); + } + + + THRIFT_PROTOCOL_GET_CLASS(in)->read_message_begin(in, &fname, &message_type, &seqid, error); + + if(!(message_type == T_CALL || message_type == T_ONEWAY)) { + g_set_error (error, + THRIFT_MULTIPLEXED_PROCESSOR_ERROR, + THRIFT_MULTIPLEXED_PROCESSOR_ERROR_MESSAGE_TYPE, + "message type invalid for this processor"); + }else{ + /* Split by the token */ + for (token = strtok_r(fname, THRIFT_MULTIPLEXED_PROTOCOL_DEFAULT_SEPARATOR, &state), + token_index=0; + token != NULL && !token_error; + token = strtok_r(NULL, THRIFT_MULTIPLEXED_PROTOCOL_DEFAULT_SEPARATOR, &state), + token_index++) + { + switch(token_index){ + case 0: + /* It should be the service name */ + multiplexed_processor = g_hash_table_lookup(self->multiplexed_services, token); + if(multiplexed_processor==NULL){ + token_error=TRUE; + } + break; + case 1: + /* It should be the function name */ + stored_message_protocol = g_object_new (THRIFT_TYPE_STORED_MESSAGE_PROTOCOL, + "protocol", in, + "name", token, + "type", message_type, + "seqid", seqid, + NULL); + break; + default: + g_set_error (error, + THRIFT_MULTIPLEXED_PROCESSOR_ERROR, + THRIFT_MULTIPLEXED_PROCESSOR_ERROR_MESSAGE_WRONGLY_MULTIPLEXED, + "the message has more tokens than expected!"); + token_error=TRUE; + break; + } + } + /* Set default */ + if(!stored_message_protocol && + !multiplexed_processor && + token_index==1 && self->default_processor_name){ + /* It should be the service name */ + multiplexed_processor = g_hash_table_lookup(self->multiplexed_services, self->default_processor_name); + if(multiplexed_processor==NULL){ + g_set_error (error, + THRIFT_MULTIPLEXED_PROCESSOR_ERROR, + THRIFT_MULTIPLEXED_PROCESSOR_ERROR_SERVICE_UNAVAILABLE, + "service %s not available on this processor", + self->default_processor_name); + }else{ + /* Set the message name to the original name */ + stored_message_protocol = g_object_new (THRIFT_TYPE_STORED_MESSAGE_PROTOCOL, + "protocol", in, + "name", fname, + "type", message_type, + "seqid", seqid, + NULL); + } + + } + + if(stored_message_protocol!=NULL && multiplexed_processor!=NULL){ + retval = THRIFT_PROCESSOR_GET_CLASS (multiplexed_processor)->process (multiplexed_processor, (ThriftProtocol *) stored_message_protocol, out, error) ; + }else{ + if(!error) + g_set_error (error, + THRIFT_MULTIPLEXED_PROCESSOR_ERROR, + THRIFT_MULTIPLEXED_PROCESSOR_ERROR_SERVICE_UNAVAILABLE, + "service %s is not multiplexed in this processor", + fname); + } + + + } + + if(!retval){ + /* By default, return an application exception to the client indicating the + method name is not recognized. */ + /* Copied from dispach processor */ + + if ((thrift_protocol_skip (in, T_STRUCT, error) < 0) || + (thrift_protocol_read_message_end (in, error) < 0)) + return retval; + + g_object_get (in, "transport", &transport, NULL); + result = thrift_transport_read_end (transport, error); + g_object_unref (transport); + if (result < 0) { + /* We must free fname */ + g_free(fname); + return retval; + } + + if (thrift_protocol_write_message_begin (out, + fname, + T_EXCEPTION, + seqid, + error) < 0){ + /* We must free fname */ + g_free(fname); + + return retval; + } + + + xception = + g_object_new (THRIFT_TYPE_APPLICATION_EXCEPTION, + "type", THRIFT_APPLICATION_EXCEPTION_ERROR_UNKNOWN_METHOD, + "message", (*error)->message, + NULL); + result = thrift_struct_write (THRIFT_STRUCT (xception), + out, + error); + g_object_unref (xception); + if ((result < 0) || + (thrift_protocol_write_message_end (out, error) < 0)) + return retval; + + g_object_get (out, "transport", &transport, NULL); + retval = + ((thrift_transport_write_end (transport, error) >= 0) && + (thrift_transport_flush (transport, error) >= 0)); + g_object_unref (transport); + }else{ + /* The protocol now has a copy we can free it */ + g_free(fname); + + } + + /* + FIXME This makes everything fail, I don't know why. + if(stored_message_protocol!=NULL){ + // After its use we must free it + g_object_unref(stored_message_protocol); + } + */ + return retval; +} + +/* define the GError domain for Thrift transports */ +GQuark +thrift_multiplexed_processor_error_quark (void) +{ + return g_quark_from_static_string (THRIFT_MULTIPLEXED_PROCESSOR_ERROR_DOMAIN); +} + + +static void +thrift_multiplexed_processor_set_property (GObject *object, + guint property_id, + const GValue *value, + GParamSpec *pspec) +{ + ThriftMultiplexedProcessor *self = THRIFT_MULTIPLEXED_PROCESSOR (object); + + switch (property_id) + { + case PROP_THRIFT_MULTIPLEXED_PROCESSOR_DEFAULT_SERVICE_NAME: + self->default_processor_name = g_value_dup_string (value); + break; + + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +thrift_multiplexed_processor_get_property (GObject *object, + guint property_id, + GValue *value, + GParamSpec *pspec) +{ + ThriftMultiplexedProcessor *self = THRIFT_MULTIPLEXED_PROCESSOR (object); + + switch (property_id) + { + case PROP_THRIFT_MULTIPLEXED_PROCESSOR_DEFAULT_SERVICE_NAME: + g_value_set_string (value, self->default_processor_name); + break; + + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +/* destructor */ +static void +thrift_multiplexed_processor_finalize (GObject *object) +{ + ThriftMultiplexedProcessor *self = THRIFT_MULTIPLEXED_PROCESSOR(object); + + /* Free our multiplexed hash table */ + g_hash_table_unref (self->multiplexed_services); + self->multiplexed_services = NULL; + + if(self->default_processor_name){ + g_free(self->default_processor_name); + self->default_processor_name=NULL; + } + + /* Chain up to parent */ + if (G_OBJECT_CLASS (thrift_multiplexed_processor_parent_class)->finalize) + (*G_OBJECT_CLASS (thrift_multiplexed_processor_parent_class)->finalize) (object); +} + +/* class initializer for ThriftMultiplexedProcessor */ +static void +thrift_multiplexed_processor_class_init (ThriftMultiplexedProcessorClass *cls) +{ + /* Override */ + THRIFT_PROCESSOR_CLASS(cls)->process = thrift_multiplexed_processor_process_impl; + GObjectClass *gobject_class = G_OBJECT_CLASS (cls); + + /* Object methods */ + gobject_class->set_property = thrift_multiplexed_processor_set_property; + gobject_class->get_property = thrift_multiplexed_processor_get_property; + gobject_class->finalize = thrift_multiplexed_processor_finalize; + + /* Class methods */ + cls->register_processor = thrift_multiplexed_processor_register_processor_impl; + + + thrift_multiplexed_processor_obj_properties[PROP_THRIFT_MULTIPLEXED_PROCESSOR_DEFAULT_SERVICE_NAME] = + g_param_spec_string ("default", + "Default service name the protocol points to where no multiplexed client used", + "Set the default service name", + NULL, + (G_PARAM_READWRITE)); + + g_object_class_install_properties (gobject_class, + PROP_THRIFT_MULTIPLEXED_PROCESSOR_END, + thrift_multiplexed_processor_obj_properties); + +} + +static void +thrift_multiplexed_processor_init (ThriftMultiplexedProcessor *self) +{ + + /* Create our multiplexed services hash table */ + self->multiplexed_services = g_hash_table_new_full ( + g_str_hash, + g_str_equal, + g_free, + g_object_unref); + self->default_processor_name = NULL; +} + + +gboolean +thrift_multiplexed_processor_register_processor(ThriftProcessor *processor, const gchar * multiplexed_processor_name, ThriftProcessor * multiplexed_processor , GError **error) +{ + return THRIFT_MULTIPLEXED_PROCESSOR_GET_CLASS(processor)->register_processor(processor, multiplexed_processor_name, multiplexed_processor, error); +} + + diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/processor/thrift_multiplexed_processor.h b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/processor/thrift_multiplexed_processor.h new file mode 100644 index 0000000..6406616 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/processor/thrift_multiplexed_processor.h @@ -0,0 +1,114 @@ +/* + * thrift_multiplexed_processor.h + * + * Created on: 14 sept. 2017 + * Author: gaguilar + */ + +#ifndef _THRIFT_MULTIPLEXED_MULTIPLEXED_PROCESSOR_H_ +#define _THRIFT_MULTIPLEXED_MULTIPLEXED_PROCESSOR_H_ + + +#include + +#include + + +G_BEGIN_DECLS + +/*! \file thrift_multiplexed_processor.h + * \brief The multiplexed processor for c_glib. + */ + +/* type macros */ +#define THRIFT_TYPE_MULTIPLEXED_PROCESSOR (thrift_multiplexed_processor_get_type ()) +#define THRIFT_MULTIPLEXED_PROCESSOR(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), THRIFT_TYPE_MULTIPLEXED_PROCESSOR, ThriftMultiplexedProcessor)) +#define THRIFT_IS_MULTIPLEXED_PROCESSOR(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), THRIFT_TYPE_MULTIPLEXED_PROCESSOR)) +#define THRIFT_MULTIPLEXED_PROCESSOR_CLASS(c) (G_TYPE_CHECK_CLASS_CAST ((c), THRIFT_TYPE_MULTIPLEXED_PROCESSOR, ThriftMultiplexedProcessorClass)) +#define THRIFT_IS_MULTIPLEXED_PROCESSOR_CLASS(c) (G_TYPE_CHECK_CLASS_TYPE ((c), THRIFT_TYPE_MULTIPLEXED_PROCESSOR)) +#define THRIFT_MULTIPLEXED_PROCESSOR_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), THRIFT_TYPE_MULTIPLEXED_PROCESSOR, ThriftMultiplexedProcessorClass)) + +/* define the GError domain string */ +#define THRIFT_MULTIPLEXED_PROCESSOR_ERROR_DOMAIN "thrift-multiplexed-processor-error-quark" + + +/*! + * Thrift MultiplexedProcessor object + */ +struct _ThriftMultiplexedProcessor +{ + ThriftProcessor parent; + + /* private */ + gchar * default_processor_name; + GHashTable *multiplexed_services; +}; +typedef struct _ThriftMultiplexedProcessor ThriftMultiplexedProcessor; + +/*! + * Thrift MultiplexedProcessor class + */ +struct _ThriftMultiplexedProcessorClass +{ + ThriftProcessorClass parent; + + gboolean (* register_processor) (ThriftProcessor *self, const gchar * multiplexed_processor_name, ThriftProcessor * multiplexed_processor , GError **error); + +}; +typedef struct _ThriftMultiplexedProcessorClass ThriftMultiplexedProcessorClass; + +/* used by THRIFT_TYPE_MULTIPLEXED_PROCESSOR */ +GType thrift_multiplexed_processor_get_type (void); + +/*! + * Processes the request. + * \public \memberof ThriftMultiplexedProcessorClass + */ +gboolean thrift_multiplexed_processor_process (ThriftMultiplexedProcessor *processor, + ThriftProtocol *in, ThriftProtocol *out, + GError **error); + + +/* Public API */ + +/** + * @brief Registers a processor in the multiplexed processor under its name. It + * will take a reference to the processor so refcount will be incremented. + * It will also be decremented on object destruction. + * + * The first registered processor becomes default. But you can override it with + * "default" property. + * + * It returns a compliant error if it cannot be registered. + * + * @param processor Pointer to the multiplexed processor. + * @param multiplexed_processor_name Name of the processor you want to register + * @param multiplexed_processor Pointer to implemented processor you want multiplex. + * @param error Error object where we should store errors. + * + * @see https://developer.gnome.org/glib/stable/glib-Error-Reporting.html#g-set-error + */ +gboolean thrift_multiplexed_processor_register_processor(ThriftProcessor *processor, const gchar * multiplexed_processor_name, ThriftProcessor * multiplexed_processor , GError **error); + + +/* define error/exception types */ +typedef enum +{ + THRIFT_MULTIPLEXED_PROCESSOR_ERROR_UNKNOWN, + THRIFT_MULTIPLEXED_PROCESSOR_ERROR_SERVICE_UNAVAILABLE, + THRIFT_MULTIPLEXED_PROCESSOR_ERROR_MESSAGE_TYPE, + THRIFT_MULTIPLEXED_PROCESSOR_ERROR_MESSAGE_WRONGLY_MULTIPLEXED, + THRIFT_MULTIPLEXED_PROCESSOR_ERROR_SEND, + THRIFT_MULTIPLEXED_PROCESSOR_ERROR_RECEIVE, + THRIFT_MULTIPLEXED_PROCESSOR_ERROR_CLOSE +} ThriftMultiplexedProcessorError; + + +GQuark thrift_multiplexed_processor_error_quark (void); +#define THRIFT_MULTIPLEXED_PROCESSOR_ERROR (thrift_multiplexed_processor_error_quark ()) + + +G_END_DECLS + + +#endif /* _THRIFT_MULTIPLEXED_MULTIPLEXED_PROCESSOR_H_ */ diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_binary_protocol.c b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_binary_protocol.c index 48a2c5c..7c2d017 100644 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_binary_protocol.c +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_binary_protocol.c @@ -784,11 +784,18 @@ thrift_binary_protocol_read_string (ThriftProtocol *protocol, } xfer += ret; - if (read_len > 0) - { - /* allocate the memory for the string */ - len = (guint32) read_len + 1; /* space for null terminator */ - *str = g_new0 (gchar, len); + if (read_len < 0) { + g_set_error (error, THRIFT_PROTOCOL_ERROR, + THRIFT_PROTOCOL_ERROR_NEGATIVE_SIZE, + "got negative size of %d", read_len); + *str = NULL; + return -1; + } + + /* allocate the memory for the string */ + len = (guint32) read_len + 1; /* space for null terminator */ + *str = g_new0 (gchar, len); + if (read_len > 0) { if ((ret = thrift_transport_read_all (protocol->transport, *str, read_len, error)) < 0) @@ -800,7 +807,7 @@ thrift_binary_protocol_read_string (ThriftProtocol *protocol, } xfer += ret; } else { - *str = NULL; + **str = 0; } return xfer; diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_compact_protocol.c b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_compact_protocol.c index 87b6b30..cae4749 100644 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_compact_protocol.c +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_compact_protocol.c @@ -120,7 +120,7 @@ thrift_bitwise_cast_gdouble (const guint64 v) static guint64 i64_to_zigzag (const gint64 l) { - return (l << 1) ^ (l >> 63); + return (((guint64)l) << 1) ^ (l >> 63); } /** @@ -130,7 +130,7 @@ i64_to_zigzag (const gint64 l) static guint32 i32_to_zigzag (const gint32 n) { - return (n << 1) ^ (n >> 31); + return (((guint32)n) << 1) ^ (n >> 31); } /** @@ -1388,9 +1388,17 @@ thrift_compact_protocol_read_string (ThriftProtocol *protocol, return -1; } + if (read_len < 0) { + g_set_error (error, THRIFT_PROTOCOL_ERROR, + THRIFT_PROTOCOL_ERROR_NEGATIVE_SIZE, + "got negative size of %d", read_len); + *str = NULL; + return -1; + } + + /* allocate the memory as an array of unsigned char for binary data */ + *str = g_new0 (gchar, read_len + 1); if (read_len > 0) { - /* allocate the memory as an array of unsigned char for binary data */ - *str = g_new0 (gchar, read_len + 1); if ((ret = thrift_transport_read_all (protocol->transport, *str, read_len, error)) < 0) { @@ -1399,16 +1407,8 @@ thrift_compact_protocol_read_string (ThriftProtocol *protocol, return -1; } xfer += ret; - - } else if (read_len == 0) { - *str = NULL; - } else { - g_set_error (error, THRIFT_PROTOCOL_ERROR, - THRIFT_PROTOCOL_ERROR_NEGATIVE_SIZE, - "got negative size of %d", read_len); - *str = NULL; - return -1; + **str = 0; } return xfer; diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_multiplexed_protocol.c b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_multiplexed_protocol.c new file mode 100644 index 0000000..727f4a8 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_multiplexed_protocol.c @@ -0,0 +1,158 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +#include +#include +#include +#include + +#include +#include +#include +#include + + +enum +{ + PROP_THRIFT_MULTIPLEXED_PROTOCOL_SERVICE_NAME = 1, + PROP_THRIFT_MULTIPLEXED_PROTOCOL_END +}; + +G_DEFINE_TYPE(ThriftMultiplexedProtocol, thrift_multiplexed_protocol, THRIFT_TYPE_PROTOCOL_DECORATOR) + + +static GParamSpec *thrift_multiplexed_protocol_obj_properties[PROP_THRIFT_MULTIPLEXED_PROTOCOL_END] = { NULL, }; + +gint32 +thrift_multiplexed_protocol_write_message_begin (ThriftMultiplexedProtocol *protocol, + const gchar *name, const ThriftMessageType message_type, + const gint32 seqid, GError **error) +{ + gint32 ret; + gchar *service_name = NULL; + g_return_val_if_fail (THRIFT_IS_MULTIPLEXED_PROTOCOL (protocol), -1); + + ThriftMultiplexedProtocol *self = THRIFT_MULTIPLEXED_PROTOCOL (protocol); + ThriftMultiplexedProtocolClass *multiplexClass = THRIFT_MULTIPLEXED_PROTOCOL_GET_CLASS(self); + + if( (message_type == T_CALL || message_type == T_ONEWAY) && self->service_name != NULL) { + service_name = g_strdup_printf("%s%s%s", self->service_name, THRIFT_MULTIPLEXED_PROTOCOL_DEFAULT_SEPARATOR, name); + }else{ + service_name = g_strdup(name); + } + + /* relay to the protocol_decorator */ + ret = thrift_protocol_decorator_write_message_begin(protocol, service_name, message_type, seqid, error); + + g_free(service_name); + + return ret; +} + + +static void +thrift_multiplexed_protocol_set_property (GObject *object, + guint property_id, + const GValue *value, + GParamSpec *pspec) +{ + ThriftMultiplexedProtocol *self = THRIFT_MULTIPLEXED_PROTOCOL (object); + + switch (property_id) + { + case PROP_THRIFT_MULTIPLEXED_PROTOCOL_SERVICE_NAME: + self->service_name = g_value_dup_string (value); + break; + + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +thrift_multiplexed_protocol_get_property (GObject *object, + guint property_id, + GValue *value, + GParamSpec *pspec) +{ + ThriftMultiplexedProtocol *self = THRIFT_MULTIPLEXED_PROTOCOL (object); + + switch (property_id) + { + case PROP_THRIFT_MULTIPLEXED_PROTOCOL_SERVICE_NAME: + g_value_set_string (value, self->service_name); + break; + + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + + +static void +thrift_multiplexed_protocol_init (ThriftMultiplexedProtocol *protocol) +{ + protocol->service_name = NULL; +} + +static void +thrift_multiplexed_protocol_finalize (GObject *gobject) +{ + ThriftMultiplexedProtocol *self = THRIFT_MULTIPLEXED_PROTOCOL (gobject); + + if (self->service_name) { + g_free(self->service_name); + self->service_name = NULL; + } + + /* Always chain up to the parent class; as with dispose(), finalize() + * is guaranteed to exist on the parent's class virtual function table + */ + G_OBJECT_CLASS (thrift_multiplexed_protocol_parent_class)->finalize(gobject); +} + + +/* initialize the class */ +static void +thrift_multiplexed_protocol_class_init (ThriftMultiplexedProtocolClass *klass) +{ + ThriftProtocolClass *cls = THRIFT_PROTOCOL_CLASS (klass); + GObjectClass *object_class = G_OBJECT_CLASS (klass); + + cls->write_message_begin = thrift_multiplexed_protocol_write_message_begin; + + object_class->set_property = thrift_multiplexed_protocol_set_property; + object_class->get_property = thrift_multiplexed_protocol_get_property; + object_class->finalize = thrift_multiplexed_protocol_finalize; + + thrift_multiplexed_protocol_obj_properties[PROP_THRIFT_MULTIPLEXED_PROTOCOL_SERVICE_NAME] = + g_param_spec_string ("service-name", + "Service name the protocol points to", + "Set the service name", + NULL, + (G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE)); + + g_object_class_install_properties (object_class, + PROP_THRIFT_MULTIPLEXED_PROTOCOL_END, + thrift_multiplexed_protocol_obj_properties); +} diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_multiplexed_protocol.h b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_multiplexed_protocol.h new file mode 100644 index 0000000..c6e08fb --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_multiplexed_protocol.h @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +#ifndef _THRIFT_MULTIPLEXED_PROTOCOL_H +#define _THRIFT_MULTIPLEXED_PROTOCOL_H + +#include + +#include +#include +#include + +G_BEGIN_DECLS + +/*! \file thrift_multiplexed_protocol.h + * \brief Multiplexed protocol implementation of a Thrift protocol. Implements the + * ThriftProtocol interface. + */ + +/* type macros */ +#define THRIFT_TYPE_MULTIPLEXED_PROTOCOL (thrift_multiplexed_protocol_get_type ()) +#define THRIFT_MULTIPLEXED_PROTOCOL(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), THRIFT_TYPE_MULTIPLEXED_PROTOCOL, ThriftMultiplexedProtocol)) +#define THRIFT_IS_MULTIPLEXED_PROTOCOL(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), THRIFT_TYPE_MULTIPLEXED_PROTOCOL)) +#define THRIFT_MULTIPLEXED_PROTOCOL_CLASS(c) (G_TYPE_CHECK_CLASS_CAST ((c), THRIFT_TYPE_MULTIPLEXED_PROTOCOL, ThriftMultiplexedProtocolClass)) +#define THRIFT_IS_MULTIPLEXED_PROTOCOL_CLASS(c) (G_TYPE_CHECK_CLASS_TYPE ((c), THRIFT_TYPE_MULTIPLEXED_PROTOCOL)) +#define THRIFT_MULTIPLEXED_PROTOCOL_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), THRIFT_TYPE_MULTIPLEXED_PROTOCOL, ThriftMultiplexedProtocolClass)) + +/* constant */ +#define THRIFT_MULTIPLEXED_PROTOCOL_DEFAULT_SEPARATOR ":" + +typedef struct _ThriftMultiplexedProtocol ThriftMultiplexedProtocol; + + + +/*! + * Thrift Multiplexed Protocol instance. + */ +struct _ThriftMultiplexedProtocol +{ + ThriftProtocolDecorator parent; + + gchar *service_name; +}; + +typedef struct _ThriftMultiplexedProtocolClass ThriftMultiplexedProtocolClass; + +/*! + * Thrift Multiplexed Protocol class. + */ +struct _ThriftMultiplexedProtocolClass +{ + ThriftProtocolDecoratorClass parent; +}; + +/* used by THRIFT_TYPE_MULTIPLEXED_PROTOCOL */ +GType thrift_multiplexed_protocol_get_type (void); + +G_END_DECLS + +#endif /* _THRIFT_MULTIPLEXED_PROTOCOL_H */ diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_protocol.c b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_protocol.c index 8a560a9..8296a8c 100644 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_protocol.c +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_protocol.c @@ -61,15 +61,15 @@ thrift_protocol_set_property (GObject *object, guint property_id, switch (property_id) { case PROP_THRIFT_PROTOCOL_TRANSPORT: - protocol->transport = g_value_get_object (value); + protocol->transport = g_value_dup_object (value); break; } } gint32 -thrift_protocol_write_message_begin (ThriftProtocol *protocol, - const gchar *name, +thrift_protocol_write_message_begin (ThriftProtocol *protocol, + const gchar *name, const ThriftMessageType message_type, const gint32 seqid, GError **error) { @@ -243,7 +243,7 @@ thrift_protocol_write_binary (ThriftProtocol *protocol, const gpointer buf, len, error); } -gint32 +gint32 thrift_protocol_read_message_begin (ThriftProtocol *protocol, gchar **name, ThriftMessageType *message_type, @@ -254,7 +254,7 @@ thrift_protocol_read_message_begin (ThriftProtocol *protocol, seqid, error); } -gint32 +gint32 thrift_protocol_read_message_end (ThriftProtocol *protocol, GError **error) { @@ -262,7 +262,7 @@ thrift_protocol_read_message_end (ThriftProtocol *protocol, error); } -gint32 +gint32 thrift_protocol_read_struct_begin (ThriftProtocol *protocol, gchar **name, GError **error) @@ -279,7 +279,7 @@ thrift_protocol_read_struct_end (ThriftProtocol *protocol, GError **error) error); } -gint32 +gint32 thrift_protocol_read_field_begin (ThriftProtocol *protocol, gchar **name, ThriftType *field_type, @@ -293,7 +293,7 @@ thrift_protocol_read_field_begin (ThriftProtocol *protocol, error); } -gint32 +gint32 thrift_protocol_read_field_end (ThriftProtocol *protocol, GError **error) { @@ -301,7 +301,7 @@ thrift_protocol_read_field_end (ThriftProtocol *protocol, error); } -gint32 +gint32 thrift_protocol_read_map_begin (ThriftProtocol *protocol, ThriftType *key_type, ThriftType *value_type, guint32 *size, @@ -311,17 +311,17 @@ thrift_protocol_read_map_begin (ThriftProtocol *protocol, key_type, value_type, size, - error); + error); } -gint32 +gint32 thrift_protocol_read_map_end (ThriftProtocol *protocol, GError **error) { return THRIFT_PROTOCOL_GET_CLASS (protocol)->read_map_end (protocol, error); } -gint32 +gint32 thrift_protocol_read_list_begin (ThriftProtocol *protocol, ThriftType *element_type, guint32 *size, GError **error) @@ -412,7 +412,7 @@ thrift_protocol_read_string (ThriftProtocol *protocol, } gint32 -thrift_protocol_read_binary (ThriftProtocol *protocol, gpointer *buf, +thrift_protocol_read_binary (ThriftProtocol *protocol, gpointer *buf, guint32 *len, GError **error) { return THRIFT_PROTOCOL_GET_CLASS (protocol)->read_binary (protocol, buf, @@ -465,7 +465,7 @@ thrift_protocol_skip (ThriftProtocol *protocol, ThriftType type, GError **error) } case T_STRUCT: { - guint32 result = 0; + gint32 result = 0; gchar *name; gint16 fid; ThriftType ftype; @@ -475,6 +475,10 @@ thrift_protocol_skip (ThriftProtocol *protocol, ThriftType type, GError **error) { result += thrift_protocol_read_field_begin (protocol, &name, &ftype, &fid, error); + if (result < 0) + { + return result; + } if (ftype == T_STOP) { break; @@ -487,7 +491,7 @@ thrift_protocol_skip (ThriftProtocol *protocol, ThriftType type, GError **error) } case T_SET: { - guint32 result = 0; + gint32 result = 0; ThriftType elem_type; guint32 i, size; result += thrift_protocol_read_set_begin (protocol, &elem_type, &size, @@ -501,7 +505,7 @@ thrift_protocol_skip (ThriftProtocol *protocol, ThriftType type, GError **error) } case T_MAP: { - guint32 result = 0; + gint32 result = 0; ThriftType elem_type; ThriftType key_type; guint32 i, size; @@ -517,7 +521,7 @@ thrift_protocol_skip (ThriftProtocol *protocol, ThriftType type, GError **error) } case T_LIST: { - guint32 result = 0; + gint32 result = 0; ThriftType elem_type; guint32 i, size; result += thrift_protocol_read_list_begin (protocol, &elem_type, &size, @@ -548,6 +552,20 @@ thrift_protocol_init (ThriftProtocol *protocol) protocol->transport = NULL; } +static void +thrift_protocol_dispose (GObject *gobject) +{ + ThriftProtocol *self = THRIFT_PROTOCOL (gobject); + + g_clear_object(&self->transport); + + /* Always chain up to the parent class; there is no need to check if + * the parent class implements the dispose() virtual function: it is + * always guaranteed to do so + */ + G_OBJECT_CLASS (thrift_protocol_parent_class)->dispose(gobject); +} + static void thrift_protocol_class_init (ThriftProtocolClass *cls) { @@ -555,6 +573,7 @@ thrift_protocol_class_init (ThriftProtocolClass *cls) gobject_class->get_property = thrift_protocol_get_property; gobject_class->set_property = thrift_protocol_set_property; + gobject_class->dispose = thrift_protocol_dispose; g_object_class_install_property (gobject_class, PROP_THRIFT_PROTOCOL_TRANSPORT, diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_protocol_decorator.c b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_protocol_decorator.c new file mode 100644 index 0000000..03f9420 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_protocol_decorator.c @@ -0,0 +1,623 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +#include +#include +#include +#include + +#include +#include +#include +#include + +G_DEFINE_TYPE(ThriftProtocolDecorator, thrift_protocol_decorator, THRIFT_TYPE_PROTOCOL) + + +enum +{ + PROP_THRIFT_TYPE_PROTOCOL_DECORATOR_CONCRETE_PROTOCOL = 1, + PROP_THRIFT_TYPE_PROTOCOL_DECORATOR_END +}; + +static GParamSpec *thrift_protocol_decorator_obj_properties[PROP_THRIFT_TYPE_PROTOCOL_DECORATOR_END] = { NULL, }; + + + + + +gint32 +thrift_protocol_decorator_write_message_begin (ThriftProtocol *protocol, + const gchar *name, + const ThriftMessageType message_type, + const gint32 seqid, GError **error) +{ + + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + ThriftProtocolClass *proto = THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol); + + g_debug("Concrete protocol %p | %p", (void *)self->concrete_protocol, (void *)proto); + + return proto->write_message_begin (self->concrete_protocol, name, + message_type, seqid, + error); +} + +gint32 +thrift_protocol_decorator_write_message_end (ThriftProtocol *protocol, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->write_message_end (self->concrete_protocol, + error); +} + +gint32 +thrift_protocol_decorator_write_struct_begin (ThriftProtocol *protocol, const gchar *name, + GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->write_struct_begin (self->concrete_protocol, + name, error); +} + +gint32 +thrift_protocol_decorator_write_struct_end (ThriftProtocol *protocol, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->write_struct_end (self->concrete_protocol, + error); +} + +gint32 +thrift_protocol_decorator_write_field_begin (ThriftProtocol *protocol, + const gchar *name, + const ThriftType field_type, + const gint16 field_id, + GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->write_field_begin (self->concrete_protocol, + name, field_type, + field_id, error); +} + +gint32 +thrift_protocol_decorator_write_field_end (ThriftProtocol *protocol, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->write_field_end (self->concrete_protocol, + error); +} + +gint32 +thrift_protocol_decorator_write_field_stop (ThriftProtocol *protocol, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->write_field_stop (self->concrete_protocol, + error); +} + +gint32 +thrift_protocol_decorator_write_map_begin (ThriftProtocol *protocol, + const ThriftType key_type, + const ThriftType value_type, + const guint32 size, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->write_map_begin (self->concrete_protocol, + key_type, value_type, + size, error); +} + +gint32 +thrift_protocol_decorator_write_map_end (ThriftProtocol *protocol, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->write_map_end (self->concrete_protocol, + error); +} + +gint32 +thrift_protocol_decorator_write_list_begin (ThriftProtocol *protocol, + const ThriftType element_type, + const guint32 size, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->write_list_begin (self->concrete_protocol, + element_type, size, + error); +} + +gint32 +thrift_protocol_decorator_write_list_end (ThriftProtocol *protocol, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->write_list_end (self->concrete_protocol, + error); +} + +gint32 +thrift_protocol_decorator_write_set_begin (ThriftProtocol *protocol, + const ThriftType element_type, + const guint32 size, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->write_set_begin (self->concrete_protocol, + element_type, size, + error); +} + +gint32 +thrift_protocol_decorator_write_set_end (ThriftProtocol *protocol, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->write_set_end (self->concrete_protocol, + error); +} + +gint32 +thrift_protocol_decorator_write_bool (ThriftProtocol *protocol, + const gboolean value, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->write_bool (self->concrete_protocol, value, + error); +} + +gint32 +thrift_protocol_decorator_write_byte (ThriftProtocol *protocol, const gint8 value, + GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->write_byte (self->concrete_protocol, value, + error); +} + +gint32 +thrift_protocol_decorator_write_i16 (ThriftProtocol *protocol, const gint16 value, + GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->write_i16 (self->concrete_protocol, value, + error); +} + +gint32 +thrift_protocol_decorator_write_i32 (ThriftProtocol *protocol, const gint32 value, + GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->write_i32 (self->concrete_protocol, value, + error); +} + +gint32 +thrift_protocol_decorator_write_i64 (ThriftProtocol *protocol, const gint64 value, + GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->write_i64 (self->concrete_protocol, value, + error); +} + +gint32 +thrift_protocol_decorator_write_double (ThriftProtocol *protocol, + const gdouble value, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->write_double (self->concrete_protocol, + value, error); +} + +gint32 +thrift_protocol_decorator_write_string (ThriftProtocol *protocol, + const gchar *str, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->write_string (self->concrete_protocol, str, + error); +} + +gint32 +thrift_protocol_decorator_write_binary (ThriftProtocol *protocol, const gpointer buf, + const guint32 len, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->write_binary (self->concrete_protocol, buf, + len, error); +} + +gint32 +thrift_protocol_decorator_read_message_begin (ThriftProtocol *protocol, + gchar **name, + ThriftMessageType *message_type, + gint32 *seqid, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->read_message_begin (self->concrete_protocol, + name, message_type, + seqid, error); +} + +gint32 +thrift_protocol_decorator_read_message_end (ThriftProtocol *protocol, + GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->read_message_end (self->concrete_protocol, + error); +} + +gint32 +thrift_protocol_decorator_read_struct_begin (ThriftProtocol *protocol, + gchar **name, + GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->read_struct_begin (self->concrete_protocol, + name, + error); +} + +gint32 +thrift_protocol_decorator_read_struct_end (ThriftProtocol *protocol, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->read_struct_end (self->concrete_protocol, + error); +} + +gint32 +thrift_protocol_decorator_read_field_begin (ThriftProtocol *protocol, + gchar **name, + ThriftType *field_type, + gint16 *field_id, + GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->read_field_begin (self->concrete_protocol, + name, + field_type, + field_id, + error); +} + +gint32 +thrift_protocol_decorator_read_field_end (ThriftProtocol *protocol, + GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->read_field_end (self->concrete_protocol, + error); +} + +gint32 +thrift_protocol_decorator_read_map_begin (ThriftProtocol *protocol, + ThriftType *key_type, + ThriftType *value_type, guint32 *size, + GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->read_map_begin (self->concrete_protocol, + key_type, + value_type, + size, + error); +} + +gint32 +thrift_protocol_decorator_read_map_end (ThriftProtocol *protocol, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->read_map_end (self->concrete_protocol, + error); +} + +gint32 +thrift_protocol_decorator_read_list_begin (ThriftProtocol *protocol, + ThriftType *element_type, + guint32 *size, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->read_list_begin (self->concrete_protocol, + element_type, + size, error); +} + +gint32 +thrift_protocol_decorator_read_list_end (ThriftProtocol *protocol, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->read_list_end (self->concrete_protocol, + error); +} + +gint32 +thrift_protocol_decorator_read_set_begin (ThriftProtocol *protocol, + ThriftType *element_type, + guint32 *size, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->read_set_begin (self->concrete_protocol, + element_type, + size, error); +} + +gint32 +thrift_protocol_decorator_read_set_end (ThriftProtocol *protocol, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->read_set_end (self->concrete_protocol, + error); +} + +gint32 +thrift_protocol_decorator_read_bool (ThriftProtocol *protocol, gboolean *value, + GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->read_bool (self->concrete_protocol, value, + error); +} + +gint32 +thrift_protocol_decorator_read_byte (ThriftProtocol *protocol, gint8 *value, + GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->read_byte (self->concrete_protocol, value, + error); +} + +gint32 +thrift_protocol_decorator_read_i16 (ThriftProtocol *protocol, gint16 *value, + GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->read_i16 (self->concrete_protocol, value, + error); +} + +gint32 +thrift_protocol_decorator_read_i32 (ThriftProtocol *protocol, gint32 *value, + GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->read_i32 (self->concrete_protocol, value, + error); +} + +gint32 +thrift_protocol_decorator_read_i64 (ThriftProtocol *protocol, gint64 *value, + GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->read_i64 (self->concrete_protocol, value, + error); +} + +gint32 +thrift_protocol_decorator_read_double (ThriftProtocol *protocol, + gdouble *value, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->read_double (self->concrete_protocol, value, + error); +} + +gint32 +thrift_protocol_decorator_read_string (ThriftProtocol *protocol, + gchar **str, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->read_string (self->concrete_protocol, str, + error); +} + +gint32 +thrift_protocol_decorator_read_binary (ThriftProtocol *protocol, gpointer *buf, + guint32 *len, GError **error) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (protocol); + + return THRIFT_PROTOCOL_GET_CLASS (self->concrete_protocol)->read_binary (self->concrete_protocol, buf, + len, error); +} + + +static void +thrift_protocol_decorator_set_property (GObject *object, + guint property_id, + const GValue *value, + GParamSpec *pspec) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (object); + + switch (property_id) + { + case PROP_THRIFT_TYPE_PROTOCOL_DECORATOR_CONCRETE_PROTOCOL: + self->concrete_protocol = g_value_dup_object (value); + break; + + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +thrift_protocol_decorator_get_property (GObject *object, + guint property_id, + GValue *value, + GParamSpec *pspec) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (object); + + switch (property_id) + { + case PROP_THRIFT_TYPE_PROTOCOL_DECORATOR_CONCRETE_PROTOCOL: + g_value_set_object (value, self->concrete_protocol); + break; + + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + + +ThriftProtocol * +thrift_protocol_decorator_get_concrete_protocol(ThriftProtocolDecorator *protocol) +{ + ThriftProtocol *retval = NULL; + if(!THRIFT_IS_PROTOCOL_DECORATOR(protocol)){ + g_warning("The type is not protocol decorator"); + return NULL; + } + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR(protocol); + g_debug("Getting concrete protocol from %p -> %p", (void *)self, (void *)self->concrete_protocol); + + return retval; +} + + +static void +thrift_protocol_decorator_init (ThriftProtocolDecorator *protocol) +{ + protocol->concrete_protocol = NULL; +} + +static void +thrift_protocol_decorator_dispose (GObject *gobject) +{ + ThriftProtocolDecorator *self = THRIFT_PROTOCOL_DECORATOR (gobject); + + g_clear_object(&self->concrete_protocol); + + /* Always chain up to the parent class; there is no need to check if + * the parent class implements the dispose() virtual function: it is + * always guaranteed to do so + */ + G_OBJECT_CLASS (thrift_protocol_decorator_parent_class)->dispose(gobject); +} + +/* initialize the class */ +static void +thrift_protocol_decorator_class_init (ThriftProtocolDecoratorClass *klass) +{ + ThriftProtocolClass *cls = THRIFT_PROTOCOL_CLASS (klass); + GObjectClass *object_class = G_OBJECT_CLASS (klass); + object_class->set_property = thrift_protocol_decorator_set_property; + object_class->get_property = thrift_protocol_decorator_get_property; + object_class->dispose = thrift_protocol_decorator_dispose; + + thrift_protocol_decorator_obj_properties[PROP_THRIFT_TYPE_PROTOCOL_DECORATOR_CONCRETE_PROTOCOL] = + g_param_spec_object ("protocol", + "Protocol", + "Set the protocol to be implemented", THRIFT_TYPE_PROTOCOL, + (G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE)); + + g_object_class_install_properties (object_class, + PROP_THRIFT_TYPE_PROTOCOL_DECORATOR_END, + thrift_protocol_decorator_obj_properties); + + g_debug("Current decorator write_message_begin addr %p, new %p", cls->write_message_begin, thrift_protocol_decorator_write_message_begin); + + cls->write_message_begin = thrift_protocol_decorator_write_message_begin; + cls->write_message_end = thrift_protocol_decorator_write_message_end; + cls->write_struct_begin = thrift_protocol_decorator_write_struct_begin; + cls->write_struct_end = thrift_protocol_decorator_write_struct_end; + cls->write_field_begin = thrift_protocol_decorator_write_field_begin; + cls->write_field_end = thrift_protocol_decorator_write_field_end; + cls->write_field_stop = thrift_protocol_decorator_write_field_stop; + cls->write_map_begin = thrift_protocol_decorator_write_map_begin; + cls->write_map_end = thrift_protocol_decorator_write_map_end; + cls->write_list_begin = thrift_protocol_decorator_write_list_begin; + cls->write_list_end = thrift_protocol_decorator_write_list_end; + cls->write_set_begin = thrift_protocol_decorator_write_set_begin; + cls->write_set_end = thrift_protocol_decorator_write_set_end; + cls->write_bool = thrift_protocol_decorator_write_bool; + cls->write_byte = thrift_protocol_decorator_write_byte; + cls->write_i16 = thrift_protocol_decorator_write_i16; + cls->write_i32 = thrift_protocol_decorator_write_i32; + cls->write_i64 = thrift_protocol_decorator_write_i64; + cls->write_double = thrift_protocol_decorator_write_double; + cls->write_string = thrift_protocol_decorator_write_string; + cls->write_binary = thrift_protocol_decorator_write_binary; + cls->read_message_begin = thrift_protocol_decorator_read_message_begin; + cls->read_message_end = thrift_protocol_decorator_read_message_end; + cls->read_struct_begin = thrift_protocol_decorator_read_struct_begin; + cls->read_struct_end = thrift_protocol_decorator_read_struct_end; + cls->read_field_begin = thrift_protocol_decorator_read_field_begin; + cls->read_field_end = thrift_protocol_decorator_read_field_end; + cls->read_map_begin = thrift_protocol_decorator_read_map_begin; + cls->read_map_end = thrift_protocol_decorator_read_map_end; + cls->read_list_begin = thrift_protocol_decorator_read_list_begin; + cls->read_list_end = thrift_protocol_decorator_read_list_end; + cls->read_set_begin = thrift_protocol_decorator_read_set_begin; + cls->read_set_end = thrift_protocol_decorator_read_set_end; + cls->read_bool = thrift_protocol_decorator_read_bool; + cls->read_byte = thrift_protocol_decorator_read_byte; + cls->read_i16 = thrift_protocol_decorator_read_i16; + cls->read_i32 = thrift_protocol_decorator_read_i32; + cls->read_i64 = thrift_protocol_decorator_read_i64; + cls->read_double = thrift_protocol_decorator_read_double; + cls->read_string = thrift_protocol_decorator_read_string; + cls->read_binary = thrift_protocol_decorator_read_binary; +} diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_protocol_decorator.h b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_protocol_decorator.h new file mode 100644 index 0000000..13b6af2 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_protocol_decorator.h @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +#ifndef _THRIFT_PROTOCOL_DECORATOR_H +#define _THRIFT_PROTOCOL_DECORATOR_H + +#include + +#include +#include + +G_BEGIN_DECLS + +/*! \file thrift_protocol_decorator.h + * \brief Multiplexed protocol implementation of a Thrift protocol. Implements the + * ThriftProtocol interface. + */ + +/* type macros */ +#define THRIFT_TYPE_PROTOCOL_DECORATOR (thrift_protocol_decorator_get_type ()) +#define THRIFT_PROTOCOL_DECORATOR(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), THRIFT_TYPE_PROTOCOL_DECORATOR, ThriftProtocolDecorator)) +#define THRIFT_IS_PROTOCOL_DECORATOR(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), THRIFT_TYPE_PROTOCOL_DECORATOR)) +#define THRIFT_PROTOCOL_DECORATOR_CLASS(c) (G_TYPE_CHECK_CLASS_CAST ((c), THRIFT_TYPE_PROTOCOL_DECORATOR, ThriftProtocolDecoratorClass)) +#define THRIFT_IS_PROTOCOL_DECORATOR_CLASS(c) (G_TYPE_CHECK_CLASS_TYPE ((c), THRIFT_TYPE_PROTOCOL_DECORATOR)) +#define THRIFT_PROTOCOL_DECORATOR_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), THRIFT_TYPE_PROTOCOL_DECORATOR, ThriftProtocolDecoratorClass)) + +typedef struct _ThriftProtocolDecorator ThriftProtocolDecorator; + + +/*! + * Thrift Protocol Decorator instance. + */ +struct _ThriftProtocolDecorator +{ + ThriftProtocol parent; + + ThriftProtocol *concrete_protocol; +}; + +typedef struct _ThriftProtocolDecoratorClass ThriftProtocolDecoratorClass; + +/*! + * Thrift Protocol Decorator class. + */ +struct _ThriftProtocolDecoratorClass +{ + ThriftProtocolClass parent; + +}; + +/* used by THRIFT_TYPE_PROTOCOL_DECORATOR */ +GType thrift_protocol_decorator_get_type (void); + +G_END_DECLS + +#endif /* _THRIFT_PROTOCOL_DECORATOR_H */ diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_stored_message_protocol.c b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_stored_message_protocol.c new file mode 100644 index 0000000..a0d560b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_stored_message_protocol.c @@ -0,0 +1,192 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +#include +#include +#include +#include + +#include +#include +#include +#include + + +enum +{ + PROP_THRIFT_STORED_MESSAGE_PROTOCOL_MESSAGE_NAME = 1, + PROP_THRIFT_STORED_MESSAGE_PROTOCOL_MESSAGE_TYPE, + PROP_THRIFT_STORED_MESSAGE_PROTOCOL_SEQUENCE_ID, + PROP_THRIFT_STORED_MESSAGE_PROTOCOL_TRANSPORT, /* TODO ugly hack */ + PROP_THRIFT_STORED_MESSAGE_PROTOCOL_END +}; + +G_DEFINE_TYPE(ThriftStoredMessageProtocol, thrift_stored_message_protocol, THRIFT_TYPE_PROTOCOL_DECORATOR) + + +static GParamSpec *thrift_stored_message_protocol_obj_properties[PROP_THRIFT_STORED_MESSAGE_PROTOCOL_END] = { NULL, }; + +gint32 +thrift_stored_message_protocol_read_message_begin (ThriftProtocol *protocol, + gchar **name, + ThriftMessageType *message_type, + gint32 *seqid, GError **error) +{ + gint32 ret = 0; + g_return_val_if_fail (THRIFT_IS_STORED_MESSAGE_PROTOCOL (protocol), -1); + THRIFT_UNUSED_VAR (error); + + ThriftStoredMessageProtocol *self = THRIFT_STORED_MESSAGE_PROTOCOL (protocol); + + /* We return the stored values on construction */ + *name = self->name; + *message_type = self->mtype; + *seqid = self->seqid; + + return ret; +} + + +static void +thrift_stored_message_protocol_set_property (GObject *object, + guint property_id, + const GValue *value, + GParamSpec *pspec) +{ + ThriftStoredMessageProtocol *self = THRIFT_STORED_MESSAGE_PROTOCOL (object); + + switch (property_id) + { + case PROP_THRIFT_STORED_MESSAGE_PROTOCOL_MESSAGE_NAME: + self->name = g_value_dup_string (value); + break; + case PROP_THRIFT_STORED_MESSAGE_PROTOCOL_MESSAGE_TYPE: + self->mtype = g_value_get_int (value); + break; + case PROP_THRIFT_STORED_MESSAGE_PROTOCOL_SEQUENCE_ID: + self->seqid = g_value_get_int (value); + break; + + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +thrift_stored_message_protocol_get_property (GObject *object, + guint property_id, + GValue *value, + GParamSpec *pspec) +{ + ThriftStoredMessageProtocol *self = THRIFT_STORED_MESSAGE_PROTOCOL (object); + ThriftProtocolDecorator *decorator = THRIFT_PROTOCOL_DECORATOR (object); + ThriftTransport *transport=NULL; + switch (property_id) + { + case PROP_THRIFT_STORED_MESSAGE_PROTOCOL_MESSAGE_NAME: + g_value_set_string (value, self->name); + break; + case PROP_THRIFT_STORED_MESSAGE_PROTOCOL_TRANSPORT: + /* FIXME Since we don't override properties in the decorator as it should + we just override the properties that we know are used */ + g_object_get(decorator->concrete_protocol,pspec->name, &transport, NULL); + g_value_set_pointer (value, transport); + break; + + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + + +static void +thrift_stored_message_protocol_init (ThriftStoredMessageProtocol *protocol) +{ + protocol->name = NULL; +} + +static void +thrift_stored_message_protocol_finalize (GObject *gobject) +{ + ThriftStoredMessageProtocol *self = THRIFT_STORED_MESSAGE_PROTOCOL (gobject); + + if (self->name) { + g_free(self->name); + self->name = NULL; + } + + /* Always chain up to the parent class; as with dispose(), finalize() + * is guaranteed to exist on the parent's class virtual function table + */ + G_OBJECT_CLASS (thrift_stored_message_protocol_parent_class)->finalize(gobject); +} + + +/* initialize the class */ +static void +thrift_stored_message_protocol_class_init (ThriftStoredMessageProtocolClass *klass) +{ + ThriftProtocolClass *cls = THRIFT_PROTOCOL_CLASS (klass); + GObjectClass *object_class = G_OBJECT_CLASS (klass); + + cls->read_message_begin = thrift_stored_message_protocol_read_message_begin; + + object_class->set_property = thrift_stored_message_protocol_set_property; + object_class->get_property = thrift_stored_message_protocol_get_property; + object_class->finalize = thrift_stored_message_protocol_finalize; + + thrift_stored_message_protocol_obj_properties[PROP_THRIFT_STORED_MESSAGE_PROTOCOL_MESSAGE_NAME] = + g_param_spec_string ("name", + "Service name the protocol points to", + "Set the service name", + NULL, + (G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE)); + thrift_stored_message_protocol_obj_properties[PROP_THRIFT_STORED_MESSAGE_PROTOCOL_MESSAGE_TYPE] = + g_param_spec_int ("type", + "Message type in the wire", + "Set the message type in the wire", + T_CALL, T_ONEWAY, + T_CALL, + (G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE)); + thrift_stored_message_protocol_obj_properties[PROP_THRIFT_STORED_MESSAGE_PROTOCOL_SEQUENCE_ID] = + g_param_spec_int ("seqid", + "Sequence id type in the wire", + "Set the Sequence id in the wire", + 0, G_MAXINT, + 0, + (G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE)); + + /* TODO Ugly hack, in theory we must override all properties from underlaying + protocol */ + thrift_stored_message_protocol_obj_properties[PROP_THRIFT_STORED_MESSAGE_PROTOCOL_TRANSPORT] = + g_param_spec_pointer ("transport", + "Transport on the underlaying implementation", + "Transport of decorated protocol", + G_PARAM_READABLE); + + + + g_object_class_install_properties (object_class, + PROP_THRIFT_STORED_MESSAGE_PROTOCOL_END, + thrift_stored_message_protocol_obj_properties); +} diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_stored_message_protocol.h b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_stored_message_protocol.h new file mode 100644 index 0000000..88782ac --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/protocol/thrift_stored_message_protocol.h @@ -0,0 +1,78 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +#ifndef _THRIFT_STORED_MESSAGE_PROTOCOL_H +#define _THRIFT_STORED_MESSAGE_PROTOCOL_H + +#include + +#include +#include +#include + +G_BEGIN_DECLS + +/*! \file thrift_stored_message_protocol.h + * \brief StoredMessage protocol implementation of a pre-stored message header + * on Thrift protocol. Implements the ThriftProtocol interface. + */ + +/* type macros */ +#define THRIFT_TYPE_STORED_MESSAGE_PROTOCOL (thrift_stored_message_protocol_get_type ()) +#define THRIFT_STORED_MESSAGE_PROTOCOL(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), THRIFT_TYPE_STORED_MESSAGE_PROTOCOL, ThriftStoredMessageProtocol)) +#define THRIFT_IS_STORED_MESSAGE_PROTOCOL(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), THRIFT_TYPE_STORED_MESSAGE_PROTOCOL)) +#define THRIFT_STORED_MESSAGE_PROTOCOL_CLASS(c) (G_TYPE_CHECK_CLASS_CAST ((c), THRIFT_TYPE_STORED_MESSAGE_PROTOCOL, ThriftStoredMessageProtocolClass)) +#define THRIFT_IS_STORED_MESSAGE_PROTOCOL_CLASS(c) (G_TYPE_CHECK_CLASS_TYPE ((c), THRIFT_TYPE_STORED_MESSAGE_PROTOCOL)) +#define THRIFT_STORED_MESSAGE_PROTOCOL_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), THRIFT_TYPE_STORED_MESSAGE_PROTOCOL, ThriftStoredMessageProtocolClass)) + +/* constant */ +#define THRIFT_STORED_MESSAGE_PROTOCOL_DEFAULT_SEPARATOR ":" + +typedef struct _ThriftStoredMessageProtocol ThriftStoredMessageProtocol; + + + +/*! + * Thrift StoredMessage Protocol instance. + */ +struct _ThriftStoredMessageProtocol +{ + ThriftProtocolDecorator parent; + + gchar *name; + ThriftMessageType mtype; + gint32 seqid; +}; + +typedef struct _ThriftStoredMessageProtocolClass ThriftStoredMessageProtocolClass; + +/*! + * Thrift StoredMessage Protocol class. + */ +struct _ThriftStoredMessageProtocolClass +{ + ThriftProtocolDecoratorClass parent; +}; + +/* used by THRIFT_TYPE_STORED_MESSAGE_PROTOCOL */ +GType thrift_stored_message_protocol_get_type (void); + +G_END_DECLS + +#endif /* _THRIFT_STORED_MESSAGE_PROTOCOL_H */ diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/server/thrift_server.c b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/server/thrift_server.c index e8aff45..ccf9153 100644 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/server/thrift_server.c +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/server/thrift_server.c @@ -76,22 +76,22 @@ thrift_server_set_property (GObject *object, guint property_id, switch (property_id) { case PROP_THRIFT_SERVER_PROCESSOR: - server->processor = g_value_get_object (value); + server->processor = g_value_dup_object (value); break; case PROP_THRIFT_SERVER_SERVER_TRANSPORT: - server->server_transport = g_value_get_object (value); + server->server_transport = g_value_dup_object (value); break; case PROP_THRIFT_SERVER_INPUT_TRANSPORT_FACTORY: - server->input_transport_factory = g_value_get_object (value); + server->input_transport_factory = g_value_dup_object (value); break; case PROP_THRIFT_SERVER_OUTPUT_TRANSPORT_FACTORY: - server->output_transport_factory = g_value_get_object (value); + server->output_transport_factory = g_value_dup_object (value); break; case PROP_THRIFT_SERVER_INPUT_PROTOCOL_FACTORY: - server->input_protocol_factory = g_value_get_object (value); + server->input_protocol_factory = g_value_dup_object (value); break; case PROP_THRIFT_SERVER_OUTPUT_PROTOCOL_FACTORY: - server->output_protocol_factory = g_value_get_object (value); + server->output_protocol_factory = g_value_dup_object (value); break; } } @@ -120,7 +120,27 @@ thrift_server_init (ThriftServer *server) server->output_protocol_factory = NULL; } -/* class initializer for ThriftServer +static void +thrift_server_dispose (GObject *gobject) +{ + ThriftServer *self = THRIFT_SERVER (gobject); + + g_clear_object(&self->output_protocol_factory); + g_clear_object(&self->input_protocol_factory); + g_clear_object(&self->output_transport_factory); + g_clear_object(&self->input_transport_factory); + g_clear_object(&self->server_transport); + g_clear_object(&self->processor); + + /* Always chain up to the parent class; there is no need to check if + * the parent class implements the dispose() virtual function: it is + * always guaranteed to do so + */ + G_OBJECT_CLASS (thrift_server_parent_class)->dispose(gobject); +} + +/* + * class initializer for ThriftServer * TODO: implement ServerEventHandler as a GClosure */ static void @@ -130,6 +150,7 @@ thrift_server_class_init (ThriftServerClass *cls) gobject_class->get_property = thrift_server_get_property; gobject_class->set_property = thrift_server_set_property; + gobject_class->dispose = thrift_server_dispose; g_object_class_install_property (gobject_class, PROP_THRIFT_SERVER_PROCESSOR, diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_buffered_transport.c b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_buffered_transport.c index ede28cf..0ab3e93 100644 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_buffered_transport.c +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_buffered_transport.c @@ -17,7 +17,6 @@ * under the License. */ -#include #include #include #include @@ -84,7 +83,7 @@ thrift_buffered_transport_read_slow (ThriftTransport *transport, gpointer buf, guint32 have = t->r_buf->len; /* we shouldn't hit this unless the buffer doesn't have enough to read */ - assert (t->r_buf->len < want); + g_assert (t->r_buf->len < want); /* first copy what we have in our buffer. */ if (have > 0) diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_framed_transport.c b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_framed_transport.c index 4c8b71f..c548246 100644 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_framed_transport.c +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_framed_transport.c @@ -17,7 +17,6 @@ * under the License. */ -#include #include #include #include @@ -120,7 +119,7 @@ thrift_framed_transport_read_slow (ThriftTransport *transport, gpointer buf, gint32 result = -1; /* we shouldn't hit this unless the buffer doesn't have enough to read */ - assert (t->r_buf->len < want); + g_assert (t->r_buf->len < want); /* first copy what we have in our buffer, if there is anything left */ if (have > 0) diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_memory_buffer.c b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_memory_buffer.c index b96db35..91818e9 100644 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_memory_buffer.c +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_memory_buffer.c @@ -17,7 +17,6 @@ * under the License. */ -#include #include #include #include diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_platform_socket.h b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_platform_socket.h new file mode 100644 index 0000000..ede60f1 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_platform_socket.h @@ -0,0 +1,120 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +/* clang-format off */ + +#ifndef _THRIFT_TRANSPORT_PLATFORM_SOCKET_H_ +# define _THRIFT_TRANSPORT_PLATFORM_SOCKET_H_ + +#ifdef _WIN32 +# define THRIFT_GET_SOCKET_ERROR ::WSAGetLastError() +# define THRIFT_ERRNO (*_errno()) +# define THRIFT_EINPROGRESS WSAEINPROGRESS +# define THRIFT_EAGAIN WSAEWOULDBLOCK +# define THRIFT_EINTR WSAEINTR +# define THRIFT_ECONNRESET WSAECONNRESET +# define THRIFT_ENOTCONN WSAENOTCONN +# define THRIFT_ETIMEDOUT WSAETIMEDOUT +# define THRIFT_EWOULDBLOCK WSAEWOULDBLOCK +# define THRIFT_EPIPE WSAECONNRESET +# define THRIFT_NO_SOCKET_CACHING SO_EXCLUSIVEADDRUSE +# define THRIFT_INVALID_SOCKET INVALID_SOCKET +# define THRIFT_SOCKETPAIR thrift_socketpair +# define THRIFT_FCNTL thrift_fcntl +# define THRIFT_O_NONBLOCK 1 +# define THRIFT_F_GETFL 0 +# define THRIFT_F_SETFL 1 +# define THRIFT_GETTIMEOFDAY thrift_gettimeofday +# define THRIFT_CLOSESOCKET closesocket +# define THRIFT_CLOSE _close +# define THRIFT_OPEN _open +# define THRIFT_FTRUNCATE _chsize_s +# define THRIFT_FSYNC _commit +# define THRIFT_LSEEK _lseek +# define THRIFT_WRITE _write +# define THRIFT_READ _read +# define THRIFT_FSTAT _fstat +# define THRIFT_STAT _stat +# ifdef _WIN32_WCE +# define THRIFT_GAI_STRERROR(...) thrift_wstr2str(gai_strerrorW(__VA_ARGS__)) +# else +# define THRIFT_GAI_STRERROR gai_strerrorA +# endif +# define THRIFT_SSIZET ptrdiff_t +# define THRIFT_SNPRINTF _snprintf +# define THRIFT_SLEEP_SEC thrift_sleep +# define THRIFT_SLEEP_USEC thrift_usleep +# define THRIFT_TIMESPEC thrift_timespec +# define THRIFT_CTIME_R thrift_ctime_r +# define THRIFT_POLL thrift_poll +# if WINVER <= 0x0502 /* XP, Server2003 */ +# define THRIFT_POLLFD thrift_pollfd +# define THRIFT_POLLIN 0x0300 +# define THRIFT_POLLOUT 0x0010 +# else /* Vista, Win7... */ +# define THRIFT_POLLFD pollfd +# define THRIFT_POLLIN POLLIN +# define THRIFT_POLLOUT POLLOUT +# endif /* WINVER */ +# define THRIFT_SHUT_RDWR SD_BOTH +#else /* not _WIN32 */ +# include +# define THRIFT_GET_SOCKET_ERROR errno +# define THRIFT_ERRNO errno +# define THRIFT_EINTR EINTR +# define THRIFT_EINPROGRESS EINPROGRESS +# define THRIFT_ECONNRESET ECONNRESET +# define THRIFT_ENOTCONN ENOTCONN +# define THRIFT_ETIMEDOUT ETIMEDOUT +# define THRIFT_EWOULDBLOCK EWOULDBLOCK +# define THRIFT_EAGAIN EAGAIN +# define THRIFT_EPIPE EPIPE +# define THRIFT_NO_SOCKET_CACHING SO_REUSEADDR +# define THRIFT_INVALID_SOCKET (-1) +# define THRIFT_SOCKETPAIR socketpair +# define THRIFT_FCNTL fcntl +# define THRIFT_O_NONBLOCK O_NONBLOCK +# define THRIFT_F_GETFL F_GETFL +# define THRIFT_F_SETFL F_SETFL +# define THRIFT_GETTIMEOFDAY gettimeofday +# define THRIFT_CLOSESOCKET close +# define THRIFT_CLOSE close +# define THRIFT_OPEN open +# define THRIFT_FTRUNCATE ftruncate +# define THRIFT_FSYNC fsync +# define THRIFT_LSEEK lseek +# define THRIFT_WRITE write +# define THRIFT_READ read +# define THRIFT_STAT stat +# define THRIFT_FSTAT fstat +# define THRIFT_GAI_STRERROR gai_strerror +# define THRIFT_SSIZET ssize_t +# define THRIFT_SNPRINTF snprintf +# define THRIFT_SLEEP_SEC sleep +# define THRIFT_SLEEP_USEC usleep +# define THRIFT_TIMESPEC timespec +# define THRIFT_CTIME_R ctime_r +# define THRIFT_POLL poll +# define THRIFT_POLLFD pollfd +# define THRIFT_POLLIN POLLIN +# define THRIFT_POLLOUT POLLOUT +# define THRIFT_SHUT_RDWR SHUT_RDWR +#endif + +#endif /* _THRIFT_TRANSPORT_PLATFORM_SOCKET_H_ */ diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_server_socket.c b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_server_socket.c index 6fc6ab3..6ea897c 100644 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_server_socket.c +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_server_socket.c @@ -224,12 +224,12 @@ thrift_server_socket_class_init (ThriftServerSocketClass *cls) "port (construct)", "Set the port to listen to", 0, /* min */ - 65534, /* max */ + 65535, /* max */ 9090, /* default by convention */ G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE); g_object_class_install_property (gobject_class, - PROP_THRIFT_SERVER_SOCKET_PORT, + PROP_THRIFT_SERVER_SOCKET_PORT, param_spec); param_spec = g_param_spec_uint ("backlog", diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_server_socket.h b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_server_socket.h index f072cb0..fd04954 100644 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_server_socket.h +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_server_socket.h @@ -49,7 +49,7 @@ struct _ThriftServerSocket ThriftServerTransport parent; /* private */ - gshort port; + guint port; gshort backlog; int sd; guint8 *buf; diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_socket.c b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_socket.c index 07ee2cb..6dd0f0d 100644 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_socket.c +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_socket.c @@ -95,6 +95,25 @@ thrift_socket_peek (ThriftTransport *transport, GError **error) return result; } + +/* implements thrift_transport_close */ +gboolean +thrift_socket_close (ThriftTransport *transport, GError **error) +{ + ThriftSocket *socket = THRIFT_SOCKET (transport); + + if (close (socket->sd) == -1) + { + g_set_error (error, THRIFT_TRANSPORT_ERROR, THRIFT_TRANSPORT_ERROR_CLOSE, + "unable to close socket - %s", + strerror(errno)); + return FALSE; + } + + socket->sd = THRIFT_INVALID_SOCKET; + return TRUE; +} + /* implements thrift_transport_open */ gboolean thrift_socket_open (ThriftTransport *transport, GError **error) @@ -128,8 +147,8 @@ thrift_socket_open (ThriftTransport *transport, GError **error) /* create a socket structure */ memset (&pin, 0, sizeof(pin)); pin.sin_family = AF_INET; - pin.sin_addr.s_addr = ((struct in_addr *) (hp->h_addr))->s_addr; - pin.sin_port = htons (tsocket->port); + pin.sin_addr.s_addr = ((struct in_addr *) (hp->h_addr_list[0]))->s_addr; + pin.sin_port = htons (tsocket->port); /* create the socket */ if ((tsocket->sd = socket (AF_INET, SOCK_STREAM, 0)) == -1) @@ -144,7 +163,8 @@ thrift_socket_open (ThriftTransport *transport, GError **error) /* open a connection */ if (connect (tsocket->sd, (struct sockaddr *) &pin, sizeof(pin)) == -1) { - g_set_error (error, THRIFT_TRANSPORT_ERROR, THRIFT_TRANSPORT_ERROR_CONNECT, + thrift_socket_close(tsocket, NULL); + g_set_error (error, THRIFT_TRANSPORT_ERROR, THRIFT_TRANSPORT_ERROR_CONNECT, "failed to connect to host %s:%d - %s", tsocket->hostname, tsocket->port, strerror(errno)); return FALSE; @@ -153,23 +173,6 @@ thrift_socket_open (ThriftTransport *transport, GError **error) return TRUE; } -/* implements thrift_transport_close */ -gboolean -thrift_socket_close (ThriftTransport *transport, GError **error) -{ - ThriftSocket *socket = THRIFT_SOCKET (transport); - - if (close (socket->sd) == -1) - { - g_set_error (error, THRIFT_TRANSPORT_ERROR, THRIFT_TRANSPORT_ERROR_CLOSE, - "unable to close socket - %s", - strerror(errno)); - return FALSE; - } - - socket->sd = THRIFT_INVALID_SOCKET; - return TRUE; -} /* implements thrift_transport_read */ gint32 @@ -210,7 +213,7 @@ thrift_socket_read_end (ThriftTransport *transport, GError **error) /* implements thrift_transport_write */ gboolean -thrift_socket_write (ThriftTransport *transport, const gpointer buf, +thrift_socket_write (ThriftTransport *transport, const gpointer buf, const guint32 len, GError **error) { gint ret = 0; @@ -315,6 +318,9 @@ thrift_socket_set_property (GObject *object, guint property_id, switch (property_id) { case PROP_THRIFT_SOCKET_HOSTNAME: + if (socket->hostname) { + g_free(socket->hostname); + } socket->hostname = g_strdup (g_value_get_string (value)); break; case PROP_THRIFT_SOCKET_PORT: @@ -347,8 +353,8 @@ thrift_socket_class_init (ThriftSocketClass *cls) param_spec = g_param_spec_uint ("port", "port (construct)", "Set the port of the remote host", - 0, /* min */ - 65534, /* max */ + 0u, /* min */ + 65535u, /* max */ 9090, /* default by convention */ G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE); diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_socket.h b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_socket.h index 981577d..2f6f67d 100644 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_socket.h +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_socket.h @@ -50,11 +50,8 @@ struct _ThriftSocket /* private */ gchar *hostname; - gshort port; + guint port; int sd; - guint8 *buf; - guint32 buf_size; - guint32 buf_len; }; typedef struct _ThriftSocketClass ThriftSocketClass; diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_ssl_socket.c b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_ssl_socket.c new file mode 100644 index 0000000..ee55406 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_ssl_socket.c @@ -0,0 +1,806 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + + +#if defined(WIN32) +#define MUTEX_TYPE HANDLE +#define MUTEX_SETUP(x) (x) = CreateMutex(NULL, FALSE, NULL) +#define MUTEX_CLEANUP(x) CloseHandle(x) +#define MUTEX_LOCK(x) WaitForSingleObject((x), INFINITE) +#define MUTEX_UNLOCK(x) ReleaseMutex(x) +#else +#define MUTEX_TYPE pthread_mutex_t +#define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL) +#define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x)) +#define MUTEX_LOCK(x) pthread_mutex_lock(&(x)) +#define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x)) +#endif + +#define OPENSSL_VERSION_NO_THREAD_ID 0x10000000L + + +/* object properties */ +enum _ThriftSSLSocketProperties +{ + PROP_THRIFT_SSL_SOCKET_CONTEXT = 3, + PROP_THRIFT_SSL_SELF_SIGNED +}; + +/* To hold a global state management of openssl for all instances */ +static gboolean thrift_ssl_socket_openssl_initialized=FALSE; +/* This array will store all of the mutexes available to OpenSSL. */ +static MUTEX_TYPE *thrift_ssl_socket_global_mutex_buf=NULL; + + +/** + * OpenSSL uniq id function. + * + * @return thread id + */ +static unsigned long thrift_ssl_socket_static_id_function(void) +{ +#if defined(WIN32) + return GetCurrentThreadId(); +#else + return ((unsigned long) pthread_self()); +#endif +} + +static void thrift_ssl_socket_static_locking_callback(int mode, int n, const char* unk, int id) { + if (mode & CRYPTO_LOCK) + MUTEX_LOCK(thrift_ssl_socket_global_mutex_buf[n]); + else + MUTEX_UNLOCK(thrift_ssl_socket_global_mutex_buf[n]); +} + +static int thrift_ssl_socket_static_thread_setup(void) +{ + int i; + + thrift_ssl_socket_global_mutex_buf = malloc(CRYPTO_num_locks() * sizeof(MUTEX_TYPE)); + if (!thrift_ssl_socket_global_mutex_buf) + return 0; + for (i = 0; i < CRYPTO_num_locks( ); i++) + MUTEX_SETUP(thrift_ssl_socket_global_mutex_buf[i]); + CRYPTO_set_id_callback(thrift_ssl_socket_static_id_function); + CRYPTO_set_locking_callback(thrift_ssl_socket_static_locking_callback); + return 1; +} + +static int thrift_ssl_socket_static_thread_cleanup(void) +{ + int i; + if (!thrift_ssl_socket_global_mutex_buf) + return 0; + CRYPTO_set_id_callback(NULL); + CRYPTO_set_locking_callback(NULL); + for (i = 0; i < CRYPTO_num_locks( ); i++) + MUTEX_CLEANUP(thrift_ssl_socket_global_mutex_buf[i]); + free(thrift_ssl_socket_global_mutex_buf); + thrift_ssl_socket_global_mutex_buf = NULL; + return 1; +} + +/* +static void* thrift_ssl_socket_dyn_lock_create_callback(const char* unk, int id) { + g_print("We should create a lock\n"); + return NULL; +} + +static void thrift_ssl_socket_dyn_lock_callback(int mode, void* lock, const char* unk, int id) { + if (lock != NULL) { + if (mode & CRYPTO_LOCK) { + g_printf("We should lock thread %d\n"); + } else { + g_printf("We should unlock thread %d\n"); + } + } +} + +static void thrift_ssl_socket_dyn_lock_destroy_callback(void* lock, const char* unk, int id) { + g_printf("We must destroy the lock\n"); +} + */ + + +G_DEFINE_TYPE(ThriftSSLSocket, thrift_ssl_socket, THRIFT_TYPE_SOCKET) + + + +/** + * When there's a thread context attached, we pass the SSL socket context so it + * can check if the error is outside SSL, on I/O for example + * @param socket + * @param error_msg + * @param thrift_error_no + * @param ssl_error + * @param error + */ +static +void thrift_ssl_socket_get_ssl_error(ThriftSSLSocket *socket, const guchar *error_msg, guint thrift_error_no, int ssl_error, GError **error) +{ + unsigned long error_code; + char buffer[1024]; + int buffer_size=1024; + gboolean first_error = TRUE; + int ssl_error_type = SSL_get_error(socket->ssl, ssl_error); + if(ssl_error_type>0){ + switch(ssl_error_type){ + case SSL_ERROR_SSL: + buffer_size-=snprintf(buffer, buffer_size, "SSL %s: ", error_msg); + while ((error_code = ERR_get_error()) != 0 && buffer_size>1) { + const char* reason = ERR_reason_error_string(error_code); + if(reason!=NULL){ + if(!first_error) { + buffer_size-=snprintf(buffer+(1024-buffer_size), buffer_size, "\n\t"); + first_error=FALSE; + } + buffer_size-=snprintf(buffer+(1024-buffer_size), buffer_size, "%lX(%s) -> %s", error_code, reason, SSL_state_string(socket->ssl)); + } + } + break; + case SSL_ERROR_SYSCALL: + buffer_size-=snprintf(buffer, buffer_size, "%s: ", error_msg); + buffer_size-=snprintf(buffer+(1024-buffer_size), buffer_size, "%lX -> %s", errno, strerror(errno)); + break; + case SSL_ERROR_WANT_READ: + buffer_size-=snprintf(buffer, buffer_size, "%s: ", error_msg); + buffer_size-=snprintf(buffer+(1024-buffer_size), buffer_size, "%lX -> %s", ssl_error_type, "Error while reading from underlaying layer"); + break; + case SSL_ERROR_WANT_WRITE: + buffer_size-=snprintf(buffer, buffer_size, "%s: ", error_msg); + buffer_size-=snprintf(buffer+(1024-buffer_size), buffer_size, "%lX -> %s", ssl_error_type, "Error while writting to underlaying layer"); + break; + + } + g_set_error (error, THRIFT_TRANSPORT_ERROR, + thrift_error_no, "%s", buffer); + } +} + +/** + * For global SSL errors + * @param error_msg + * @param thrift_error_no + * @param error + */ +static +void thrift_ssl_socket_get_error(const guchar *error_msg, guint thrift_error_no, GError **error) +{ + unsigned long error_code; + while ((error_code = ERR_get_error()) != 0) { + const char* reason = ERR_reason_error_string(error_code); + if (reason == NULL) { + g_set_error (error, THRIFT_TRANSPORT_ERROR, + thrift_error_no, + "SSL error %lX: %s", error_code, error_msg); + }else{ + g_set_error (error, THRIFT_TRANSPORT_ERROR, + thrift_error_no, + "SSL error %lX %s: %s", error_code,reason, error_msg); + } + } +} + + + +/* implements thrift_transport_is_open */ +gboolean +thrift_ssl_socket_is_open (ThriftTransport *transport) +{ + return thrift_socket_is_open(transport); +} + +/* overrides thrift_transport_peek */ +gboolean +thrift_ssl_socket_peek (ThriftTransport *transport, GError **error) +{ + gboolean retval = FALSE; + ThriftSSLSocket *ssl_socket = THRIFT_SSL_SOCKET (transport); + if (thrift_ssl_socket_is_open (transport)) + { + int rc; + gchar byte; + rc = SSL_peek(ssl_socket->ssl, &byte, 1); + if (rc < 0) { + thrift_ssl_socket_get_ssl_error(ssl_socket, "Check socket data", + THRIFT_SSL_SOCKET_ERROR_SSL, rc, error); + } + if (rc == 0) { + ERR_clear_error(); + } + retval = (rc > 0); + } + return retval; +} + +/* implements thrift_transport_open */ +gboolean +thrift_ssl_socket_open (ThriftTransport *transport, GError **error) +{ + ERR_clear_error(); + + if (!thrift_socket_open(transport, error)) { + return FALSE; + } + + if (!THRIFT_SSL_SOCKET_GET_CLASS(transport)->handle_handshake(transport, error)) { + thrift_ssl_socket_close(transport, NULL); + return FALSE; + } + + return TRUE; +} + +/* implements thrift_transport_close */ +gboolean +thrift_ssl_socket_close (ThriftTransport *transport, GError **error) +{ + gboolean retval = FALSE; + ThriftSSLSocket *ssl_socket = THRIFT_SSL_SOCKET(transport); + if(ssl_socket!=NULL && ssl_socket->ssl) { + int rc = SSL_shutdown(ssl_socket->ssl); +/* if (rc < 0) { + int errno_copy = THRIFT_SSL_SOCKET_ERROR_SSL; + }*/ + SSL_free(ssl_socket->ssl); + ssl_socket->ssl = NULL; + ERR_remove_state(0); + } + return thrift_socket_close(transport, error); +} + +/* implements thrift_transport_read */ +gint32 +thrift_ssl_socket_read (ThriftTransport *transport, gpointer buf, + guint32 len, GError **error) +{ + guint maxRecvRetries_ = 10; + ThriftSSLSocket *ssl_socket = THRIFT_SSL_SOCKET (transport); + guint bytes = 0; + guint retries = 0; + ThriftSocket *socket = THRIFT_SOCKET (transport); + g_return_val_if_fail (socket->sd != THRIFT_INVALID_SOCKET && ssl_socket->ssl!=NULL, FALSE); + + for (retries=0; retries < maxRecvRetries_; retries++) { + bytes = SSL_read(ssl_socket->ssl, buf, len); + if (bytes >= 0) + break; + int errno_copy = THRIFT_GET_SOCKET_ERROR; + if (SSL_get_error(ssl_socket->ssl, bytes) == SSL_ERROR_SYSCALL) { + if (ERR_get_error() == 0 && errno_copy == THRIFT_EINTR) { + continue; + } + }else{ + thrift_ssl_socket_get_ssl_error(ssl_socket, "Receive error", + THRIFT_SSL_SOCKET_ERROR_SSL, bytes, error); + + } + return -1; + } + return bytes; +} + +/* implements thrift_transport_read_end + * called when write is complete. nothing to do on our end. */ +gboolean +thrift_ssl_socket_read_end (ThriftTransport *transport, GError **error) +{ + /* satisfy -Wall */ + THRIFT_UNUSED_VAR (transport); + THRIFT_UNUSED_VAR (error); + return TRUE; +} + +/* implements thrift_transport_write */ +gboolean +thrift_ssl_socket_write (ThriftTransport *transport, const gpointer buf, + const guint32 len, GError **error) +{ + ThriftSSLSocket *ssl_socket = THRIFT_SSL_SOCKET (transport); + gint ret = 0; + guint sent = 0; + ThriftSocket *socket = THRIFT_SOCKET (transport); + g_return_val_if_fail (socket->sd != THRIFT_INVALID_SOCKET && ssl_socket->ssl!=NULL, FALSE); + + while (sent < len) + { + ret = SSL_write (ssl_socket->ssl, (guint8 *)buf + sent, len - sent); + if (ret < 0) + { + thrift_ssl_socket_get_ssl_error(ssl_socket, "Send error", + THRIFT_SSL_SOCKET_ERROR_SSL, ret, error); + return FALSE; + } + sent += ret; + } + + return sent==len; +} + +/* implements thrift_transport_write_end + * called when write is complete. nothing to do on our end. */ +gboolean +thrift_ssl_socket_write_end (ThriftTransport *transport, GError **error) +{ + /* satisfy -Wall */ + THRIFT_UNUSED_VAR (transport); + THRIFT_UNUSED_VAR (error); + return TRUE; +} + +/* implements thrift_transport_flush + * flush pending data. since we are not buffered, this is a no-op */ +gboolean +thrift_ssl_socket_flush (ThriftTransport *transport, GError **error) +{ + ThriftSSLSocket *ssl_socket = THRIFT_SSL_SOCKET (transport); + gint ret = 0; + guint sent = 0; + + ThriftSocket *socket = THRIFT_SOCKET (transport); + g_return_val_if_fail (socket->sd != THRIFT_INVALID_SOCKET && ssl_socket->ssl!=NULL, FALSE); + + BIO* bio = SSL_get_wbio(ssl_socket->ssl); + if (bio == NULL) { + g_set_error (error, THRIFT_TRANSPORT_ERROR, + THRIFT_TRANSPORT_ERROR_SEND, + "failed to flush, wbio returned null"); + return FALSE; + } + if (BIO_flush(bio) != 1) { + g_set_error (error, THRIFT_TRANSPORT_ERROR, + THRIFT_TRANSPORT_ERROR_SEND, + "failed to flush it returned error"); + return FALSE; + } + return TRUE; +} + + +gboolean +thrift_ssl_socket_handle_handshake(ThriftTransport * transport, GError **error) +{ + ThriftSSLSocket *ssl_socket = THRIFT_SSL_SOCKET (transport); + ThriftSocket *socket = THRIFT_SOCKET (transport); + g_return_val_if_fail (thrift_transport_is_open (transport), FALSE); + + if(THRIFT_SSL_SOCKET_GET_CLASS(ssl_socket)->create_ssl_context(transport, error)){ + /*Context created*/ + SSL_set_fd(ssl_socket->ssl, socket->sd); + int rc; + if(ssl_socket->server){ + rc = SSL_accept(ssl_socket->ssl); + }else{ + rc = SSL_connect(ssl_socket->ssl); + } + if (rc <= 0) { + thrift_ssl_socket_get_ssl_error(ssl_socket, "Error while connect/bind", THRIFT_SSL_SOCKET_ERROR_CONNECT_BIND, rc, error); + return FALSE; + } + }else + return FALSE; + + return thrift_ssl_socket_authorize(transport, error); +} + +gboolean +thrift_ssl_socket_create_ssl_context(ThriftTransport * transport, GError **error) +{ + ThriftSSLSocket *socket = THRIFT_SSL_SOCKET (transport); + + if(socket->ctx!=NULL){ + if(socket->ssl!=NULL) { + return TRUE; + } + + socket->ssl = SSL_new(socket->ctx); + if (socket->ssl == NULL) { + g_set_error (error, THRIFT_TRANSPORT_ERROR, + THRIFT_SSL_SOCKET_ERROR_TRANSPORT, + "Unable to create default SSL context"); + return FALSE; + } + } + + return TRUE; +} + + +gboolean thrift_ssl_load_cert_from_file(ThriftSSLSocket *ssl_socket, const char *file_name) +{ + char error_buffer[255]; + if (!thrift_ssl_socket_openssl_initialized) { + g_error("OpenSSL is not initialized yet"); + return FALSE; + } + int rc = SSL_CTX_load_verify_locations(ssl_socket->ctx, file_name, NULL); + if (rc != 1) { /*verify authentication result*/ + ERR_error_string_n(ERR_get_error(), error_buffer, 254); + g_warning("Load of certificates failed: %s!", error_buffer); + return FALSE; + } + return TRUE; +} + + +gboolean thrift_ssl_load_cert_from_buffer(ThriftSSLSocket *ssl_socket, const char chain_certs[]) +{ + gboolean retval = FALSE; + /* Load chain of certs*/ + X509 *cacert=NULL; + BIO *mem = BIO_new_mem_buf(chain_certs,strlen(chain_certs)); + X509_STORE *cert_store = SSL_CTX_get_cert_store(ssl_socket->ctx); + + if(cert_store!=NULL){ + int index = 0; + while ((cacert = PEM_read_bio_X509(mem, NULL, 0, NULL))!=NULL) { + if(cacert) { + X509_STORE_add_cert(cert_store, cacert); + X509_free(cacert); + cacert=NULL; + } /* Free immediately */ + index++; + } + retval=TRUE; + } + BIO_free(mem); + return retval; +} + +gboolean +thrift_ssl_socket_authorize(ThriftTransport * transport, GError **error) +{ + ThriftSocket *socket = THRIFT_SOCKET (transport); + ThriftSSLSocket *ssl_socket = THRIFT_SSL_SOCKET (transport); + ThriftSSLSocketClass *cls = THRIFT_SSL_SOCKET_GET_CLASS(ssl_socket); + gboolean authorization_result = FALSE; + + if(cls!=NULL && ssl_socket->ssl!=NULL){ + int rc = SSL_get_verify_result(ssl_socket->ssl); + if (rc != X509_V_OK) { /* verify authentication result */ + if (rc == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT && ssl_socket->allow_selfsigned) { + g_debug("The certificate is a self-signed certificate and configuration allows it"); + } else { + g_set_error (error, + THRIFT_TRANSPORT_ERROR, + THRIFT_SSL_SOCKET_ERROR_SSL_CERT_VALIDATION_FAILED, + "The certificate verification failed: %s (%d)", X509_verify_cert_error_string(rc), rc); + return FALSE; + } + } + + X509* cert = SSL_get_peer_certificate(ssl_socket->ssl); + if (cert == NULL) { + if (SSL_get_verify_mode(ssl_socket->ssl) & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) { + g_set_error (error, + THRIFT_TRANSPORT_ERROR, + THRIFT_SSL_SOCKET_ERROR_SSL_CERT_VALIDATION_FAILED, + "No certificate present. Are you connecting SSL server?"); + return FALSE; + } + g_debug("No certificate required"); + return TRUE; + } + + /* certificate is present, since we don't support access manager we are done */ + if (cls->authorize_peer == NULL) { + X509_free(cert); + g_debug("Certificate presented but we're not checking it"); + return TRUE; + } else { + /* both certificate and access manager are present */ + struct sockaddr_storage sa; + socklen_t saLength = sizeof(struct sockaddr_storage); + if (getpeername(socket->sd, (struct sockaddr*)&sa, &saLength) != 0) { + sa.ss_family = AF_UNSPEC; + } + authorization_result = cls->authorize_peer(transport, cert, &sa, error); + } + if(cert != NULL) { + X509_free(cert); + } + } + + return authorization_result; +} + + +/* initializes the instance */ +static void +thrift_ssl_socket_init (ThriftSSLSocket *socket) +{ + GError *error = NULL; + socket->ssl = NULL; + socket->ctx = thrift_ssl_socket_context_initialize(SSLTLS, &error); + if(socket->ctx == NULL) { + g_info("The SSL context was not automatically initialized with protocol %d", SSLTLS); + if(error!=NULL){ + g_info("Reported reason %s", error->message); + g_error_free (error); + } + } + socket->server = FALSE; + socket->allow_selfsigned = FALSE; + +} + +/* destructor */ +static void +thrift_ssl_socket_finalize (GObject *object) +{ + ThriftSSLSocket *socket = THRIFT_SSL_SOCKET (object); + GError *error=NULL; + if(socket!=NULL){ + g_debug("Instance %p destroyed", (void *)socket); + if(socket->ssl != NULL) + { + thrift_ssl_socket_close(THRIFT_TRANSPORT(object), &error); + socket->ssl=NULL; + } + + if(socket->ctx!=NULL){ + g_debug("Freeing the context for the instance"); + SSL_CTX_free(socket->ctx); + socket->ctx=NULL; + } + } + + if (G_OBJECT_CLASS (thrift_ssl_socket_parent_class)->finalize) + (*G_OBJECT_CLASS (thrift_ssl_socket_parent_class)->finalize) (object); +} + +/* property accessor */ +void +thrift_ssl_socket_get_property (GObject *object, guint property_id, + GValue *value, GParamSpec *pspec) +{ + ThriftSSLSocket *socket = THRIFT_SSL_SOCKET (object); + THRIFT_UNUSED_VAR (pspec); + + switch (property_id) + { + case PROP_THRIFT_SSL_SOCKET_CONTEXT: + g_value_set_pointer (value, socket->ctx); + break; + } +} + +/* property mutator */ +void +thrift_ssl_socket_set_property (GObject *object, guint property_id, + const GValue *value, GParamSpec *pspec) +{ + ThriftSSLSocket *socket = THRIFT_SSL_SOCKET (object); + + THRIFT_UNUSED_VAR (pspec); + switch (property_id) + { + case PROP_THRIFT_SSL_SOCKET_CONTEXT: + if(socket->ctx!=NULL){ + g_debug("Freeing the context since we are setting a new one"); + SSL_CTX_free(socket->ctx); + } + socket->ctx = g_value_get_pointer(value); /* We copy the context */ + break; + + case PROP_THRIFT_SSL_SELF_SIGNED: + socket->allow_selfsigned = g_value_get_boolean(value); + break; + default: + g_warning("Trying to set property %i that doesn't exists!", property_id); + /* thrift_socket_set_property(object, property_id, value, pspec); */ + break; + } +} + +void +thrift_ssl_socket_initialize_openssl(void) +{ + if(thrift_ssl_socket_openssl_initialized){ + return; + } + thrift_ssl_socket_openssl_initialized=TRUE; + SSL_library_init(); + ERR_load_crypto_strings(); + SSL_load_error_strings(); + ERR_load_BIO_strings(); + + /* Setup locking */ + g_debug("We setup %d threads locks", thrift_ssl_socket_static_thread_setup()); + + /* dynamic locking + CRYPTO_set_dynlock_create_callback(thrift_ssl_socket_dyn_lock_create_callback); + CRYPTO_set_dynlock_lock_callback(thrift_ssl_socket_dyn_lock_callback); + CRYPTO_set_dynlock_destroy_callback(thrift_ssl_socket_dyn_lock_destroy_callback); + */ +} + + +void thrift_ssl_socket_finalize_openssl(void) +{ + if (!thrift_ssl_socket_openssl_initialized) { + return; + } + thrift_ssl_socket_openssl_initialized = FALSE; + + g_debug("We cleared %d threads locks", thrift_ssl_socket_static_thread_cleanup()); + /* Not supported + CRYPTO_set_locking_callback(NULL); + CRYPTO_set_dynlock_create_callback(NULL); + CRYPTO_set_dynlock_lock_callback(NULL); + CRYPTO_set_dynlock_destroy_callback(NULL); + */ + ERR_free_strings(); + EVP_cleanup(); + CRYPTO_cleanup_all_ex_data(); + ERR_remove_state(0); +} + + +/* initializes the class */ +static void +thrift_ssl_socket_class_init (ThriftSSLSocketClass *cls) +{ + ThriftTransportClass *ttc = THRIFT_TRANSPORT_CLASS (cls); + GObjectClass *gobject_class = G_OBJECT_CLASS (cls); + GParamSpec *param_spec = NULL; + + g_debug("Initialization of ThriftSSLSocketClass"); + /* setup accessors and mutators */ + gobject_class->get_property = thrift_ssl_socket_get_property; + gobject_class->set_property = thrift_ssl_socket_set_property; + param_spec = g_param_spec_pointer ("ssl_context", + "SSLContext", + "Set the SSL context for handshake with the remote host", + G_PARAM_READWRITE); + g_object_class_install_property (gobject_class, PROP_THRIFT_SSL_SOCKET_CONTEXT, + param_spec); + param_spec = g_param_spec_boolean ("ssl_accept_selfsigned", + "Accept Self Signed", + "Whether or not accept self signed certificate", + FALSE, + G_PARAM_READWRITE); + g_object_class_install_property (gobject_class, PROP_THRIFT_SSL_SELF_SIGNED, + param_spec); + /* Class methods */ + cls->handle_handshake = thrift_ssl_socket_handle_handshake; + cls->create_ssl_context = thrift_ssl_socket_create_ssl_context; + + /* Override */ + gobject_class->finalize = thrift_ssl_socket_finalize; + ttc->is_open = thrift_ssl_socket_is_open; + ttc->peek = thrift_ssl_socket_peek; + ttc->open = thrift_ssl_socket_open; + ttc->close = thrift_ssl_socket_close; + ttc->read = thrift_ssl_socket_read; + ttc->read_end = thrift_ssl_socket_read_end; + ttc->write = thrift_ssl_socket_write; + ttc->write_end = thrift_ssl_socket_write_end; + ttc->flush = thrift_ssl_socket_flush; +} + + +/* + * Public API + */ +ThriftSSLSocket* +thrift_ssl_socket_new(ThriftSSLSocketProtocol ssl_protocol, GError **error) +{ + ThriftSSLSocket *thriftSSLSocket = NULL; + SSL_CTX *ssl_context = NULL; + /* Create the context */ + if((ssl_context=thrift_ssl_socket_context_initialize(ssl_protocol, error))==NULL){ + g_warning("We cannot initialize context for protocol %d", ssl_protocol); + return thriftSSLSocket; + } + + /* FIXME if the protocol is different? */ + thriftSSLSocket = g_object_new (THRIFT_TYPE_SSL_SOCKET, "ssl_context", ssl_context, NULL); + return thriftSSLSocket; +} + +ThriftSSLSocket* +thrift_ssl_socket_new_with_host(ThriftSSLSocketProtocol ssl_protocol, gchar *hostname, guint port, GError **error) +{ + ThriftSSLSocket *thriftSSLSocket = NULL; + SSL_CTX *ssl_context = NULL; + /* Create the context */ + if((ssl_context=thrift_ssl_socket_context_initialize(ssl_protocol, error))==NULL){ + /* FIXME Do error control */ + return thriftSSLSocket; + } + /* FIXME if the protocol is different? */ + thriftSSLSocket = g_object_new (THRIFT_TYPE_SSL_SOCKET, "ssl_context", ssl_context, "hostname", hostname, "port", port, NULL); + return thriftSSLSocket; +} + +void thrift_ssl_socket_set_manager(ThriftSSLSocket *ssl_socket, AUTHORIZATION_MANAGER_CALLBACK callback) +{ + ThriftSSLSocketClass *sslSocketClass = THRIFT_SSL_SOCKET_GET_CLASS (ssl_socket); + if(sslSocketClass){ + sslSocketClass->authorize_peer = callback; + } +} + + +SSL_CTX* +thrift_ssl_socket_context_initialize(ThriftSSLSocketProtocol ssl_protocol, GError **error) +{ + SSL_CTX* context = NULL; + switch(ssl_protocol){ + case SSLTLS: + context = SSL_CTX_new(SSLv23_method()); + break; +#ifndef OPENSSL_NO_SSL3 + case SSLv3: + context = SSL_CTX_new(SSLv3_method()); + break; +#endif + case TLSv1_0: + context = SSL_CTX_new(TLSv1_method()); + break; + case TLSv1_1: + context = SSL_CTX_new(TLSv1_1_method()); + break; + case TLSv1_2: + context = SSL_CTX_new(TLSv1_2_method()); + break; + default: + g_set_error (error, THRIFT_TRANSPORT_ERROR, + THRIFT_SSL_SOCKET_ERROR_CIPHER_NOT_AVAILABLE, + "The SSL protocol is unknown for %d", ssl_protocol); + return NULL; + break; + } + + if (context == NULL) { + thrift_ssl_socket_get_error("No cipher overlay", THRIFT_SSL_SOCKET_ERROR_CIPHER_NOT_AVAILABLE, error); + return NULL; + } + SSL_CTX_set_mode(context, SSL_MODE_AUTO_RETRY); + + /* Disable horribly insecure SSLv2 and SSLv3 protocols but allow a handshake + with older clients so they get a graceful denial. */ + if (ssl_protocol == SSLTLS) { + SSL_CTX_set_options(context, SSL_OP_NO_SSLv2); + SSL_CTX_set_options(context, SSL_OP_NO_SSLv3); /* THRIFT-3164 */ + } + + return context; +} + diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_ssl_socket.h b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_ssl_socket.h new file mode 100644 index 0000000..0ca465a --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/src/thrift/c_glib/transport/thrift_ssl_socket.h @@ -0,0 +1,218 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +#ifndef _THRIFT_SSL_SOCKET_H +#define _THRIFT_SSL_SOCKET_H + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +G_BEGIN_DECLS + +/*! \file thrift_ssl_socket.h + * \brief SSL Socket implementation of a Thrift transport. Subclasses the + * ThriftSocket class. Based on plain openssl. + * In the future we should take a look to https://issues.apache.org/jira/browse/THRIFT-1016 + */ + +/* type macros */ +#define THRIFT_TYPE_SSL_SOCKET (thrift_ssl_socket_get_type ()) +#define THRIFT_SSL_SOCKET(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), THRIFT_TYPE_SSL_SOCKET, ThriftSSLSocket)) +#define THRIFT_IS_SSL_SOCKET(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), THRIFT_TYPE_SSL_SOCKET)) +#define THRIFT_SSL_SOCKET_CLASS(c) (G_TYPE_CHECK_CLASS_CAST ((c), THRIFT_TYPE_SSL_SOCKET, ThriftSSLSocketClass)) +#define THRIFT_IS_SSL_SOCKET_CLASS(c) (G_TYPE_CHECK_CLASS_TYPE ((c), THRIFT_TYPE_SSL_SOCKET)) +#define THRIFT_SSL_SOCKET_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), THRIFT_TYPE_SSL_SOCKET, ThriftSSLSocketClass)) + + +/* define error/exception types */ +typedef enum +{ + THRIFT_SSL_SOCKET_ERROR_TRANSPORT=7, + THRIFT_SSL_SOCKET_ERROR_CONNECT_BIND, + THRIFT_SSL_SOCKET_ERROR_CIPHER_NOT_AVAILABLE, + THRIFT_SSL_SOCKET_ERROR_SSL, + THRIFT_SSL_SOCKET_ERROR_SSL_CERT_VALIDATION_FAILED +} ThriftSSLSocketError; + + +typedef struct _ThriftSSLSocket ThriftSSLSocket; + +/*! + * Thrift SSL Socket instance. + */ +struct _ThriftSSLSocket +{ + ThriftSocket parent; + + /* private */ + SSL *ssl; + SSL_CTX* ctx; + gboolean server; + gboolean allow_selfsigned; +}; + +typedef struct _ThriftSSLSocketClass ThriftSSLSocketClass; +typedef gboolean (* AUTHORIZATION_MANAGER_CALLBACK) (ThriftTransport * transport, X509 *cert, struct sockaddr_storage *addr, GError **error); + +/*! + * Thrift Socket class. + */ +struct _ThriftSSLSocketClass +{ + ThriftSocketClass parent; + + gboolean (* handle_handshake) (ThriftTransport * transport, GError **error); + gboolean (* create_ssl_context) (ThriftTransport * transport, GError **error); + gboolean (* authorize_peer) (ThriftTransport * transport, X509 *cert, struct sockaddr_storage *addr, GError **error); + + /* Padding to allow adding up to 12 new virtual functions without + * breaking ABI. */ + gpointer padding[12]; +}; + +enum _ThriftSSLSocketProtocol { + SSLTLS = 0, /* Supports SSLv2 and SSLv3 handshake but only negotiates at TLSv1_0 or later. */ +/*SSLv2 = 1, HORRIBLY INSECURE! */ + SSLv3 = 2, /* Supports SSLv3 only - also horribly insecure! */ + TLSv1_0 = 3, /* Supports TLSv1_0 or later. */ + TLSv1_1 = 4, /* Supports TLSv1_1 or later. */ + TLSv1_2 = 5, /* Supports TLSv1_2 or later. */ + LATEST = TLSv1_2 +}; +typedef enum _ThriftSSLSocketProtocol ThriftSSLSocketProtocol; + + +/* Internal functions */ +SSL_CTX* +thrift_ssl_socket_context_initialize(ThriftSSLSocketProtocol ssl_protocol, GError **error); + + +/* used by THRIFT_TYPE_SSL_SOCKET */ +GType thrift_ssl_socket_get_type (void); + +/* Public API */ + +/** + * @brief Set a pinning manager instead of the default one. + * + * The pinning manager will be used during the SSL handshake to check certificate + * and pinning parameters. + * + * @param ssl_socket SSL Socket to operate on. + * @param callback function that will take the control while validating pinning + * + */ +void thrift_ssl_socket_set_manager(ThriftSSLSocket *ssl_socket, AUTHORIZATION_MANAGER_CALLBACK callback); + +/* This is the SSL API */ +/** + * Convenience function to create a new SSL context with the protocol specified + * and assign this new context to the created ThriftSSLSocket with specified host:port. + * @param ssl_protocol + * @param hostname + * @param port + * @param error + * @return + */ +ThriftSSLSocket* +thrift_ssl_socket_new_with_host(ThriftSSLSocketProtocol ssl_protocol, gchar *hostname, guint port, GError **error); + +/** + * Convenience function to create a new SSL context with the protocol specified + * and assign this new context to the created ThriftSSLSocket. + * @param ssl_protocol + * @param error + * @return + */ +ThriftSSLSocket* +thrift_ssl_socket_new(ThriftSSLSocketProtocol ssl_protocol, GError **error); + +/** + * Load a certificate chain from a PEM file. + * @param ssl_socket The ssl socket + * @param file_name The file name of the PEM certificate chain + * @return + */ +gboolean +thrift_ssl_load_cert_from_file(ThriftSSLSocket *ssl_socket, const char *file_name); + +/** + * Load a certificate chain from memory + * @param ssl_socket the ssl socket + * @param chain_certs the buffer to load PEM from + * @return + */ +gboolean +thrift_ssl_load_cert_from_buffer(ThriftSSLSocket *ssl_socket, const char chain_certs[]); + +/** + * Check if the ssl socket is open and ready to send and receive + * @param transport + * @return true if open + */ +gboolean +thrift_ssl_socket_is_open (ThriftTransport *transport); + + +/** + * Open connection if required and set the socket to be ready to send and receive + * @param transport + * @param error + * @return true if operation was correct + */ +gboolean +thrift_ssl_socket_open (ThriftTransport *transport, GError **error); + + +/** + * @brief Initialization function + * + * It will initialize OpenSSL function. This initialization will be done app + * wide. So if you want to initialize it by yourself you should not call it. + * But it means you must handle OpenSSL initialization and handle locking. + * + * It should be called before anything else. + * + * + */ +void +thrift_ssl_socket_initialize_openssl(void); +/** + * @brief Finalization function + * + * It clears all resources initialized in initialize function. + * + * It should be called after anything else. + * + * + */ +void +thrift_ssl_socket_finalize_openssl(void); + +G_END_DECLS +#endif diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/test/CMakeLists.txt b/vendor/git.apache.org/thrift.git/lib/c_glib/test/CMakeLists.txt index 2c87dbc..fb3e41c 100644 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/test/CMakeLists.txt +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/test/CMakeLists.txt @@ -111,6 +111,8 @@ include_directories("${PROJECT_SOURCE_DIR}/test/c_glib/src" "${CMAKE_CURRENT_BIN add_executable(testthrifttest testthrifttest.c ${PROJECT_SOURCE_DIR}/test/c_glib/src/thrift_test_handler.c ${PROJECT_SOURCE_DIR}/test/c_glib/src/thrift_test_handler.h + ${PROJECT_SOURCE_DIR}/test/c_glib/src/thrift_second_service_handler.c + ${PROJECT_SOURCE_DIR}/test/c_glib/src/thrift_second_service_handler.h gen-c_glib/t_test_thrift_test_types.h) target_link_libraries(testthrifttest testgenc) add_test(NAME testthrifttest COMMAND testthrifttest) diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/test/Makefile.am b/vendor/git.apache.org/thrift.git/lib/c_glib/test/Makefile.am index 3dc5418..5e9d2ea 100755 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/test/Makefile.am +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/test/Makefile.am @@ -37,16 +37,17 @@ BUILT_SOURCES = \ gen-c_glib/t_test_thrift_test_types.h AM_CPPFLAGS = -I../src -I./gen-c_glib -AM_CFLAGS = -g -Wall -Wextra -pedantic $(GLIB_CFLAGS) $(GOBJECT_CFLAGS) \ +AM_CFLAGS = -g -Wall -Wextra -pedantic $(GLIB_CFLAGS) $(GOBJECT_CFLAGS) $(OPENSSL_INCLUDES) \ @GCOV_CFLAGS@ AM_CXXFLAGS = $(AM_CFLAGS) -AM_LDFLAGS = $(GLIB_LIBS) $(GOBJECT_LIBS) @GCOV_LDFLAGS@ +AM_LDFLAGS = $(GLIB_LIBS) $(GOBJECT_LIBS) $(OPENSSL_LIBS) @GCOV_LDFLAGS@ check_PROGRAMS = \ testserialization \ testapplicationexception \ testcontainertest \ testtransportsocket \ + testtransportsslsocket \ testbinaryprotocol \ testcompactprotocol \ testbufferedtransport \ @@ -100,6 +101,16 @@ testtransportsocket_LDADD = \ $(top_builddir)/lib/c_glib/src/thrift/c_glib/transport/libthrift_c_glib_la-thrift_server_transport.o \ $(top_builddir)/lib/c_glib/src/thrift/c_glib/transport/libthrift_c_glib_la-thrift_server_socket.o + +testtransportsslsocket_SOURCES = testtransportsslsocket.c +testtransportsslsocket_LDADD = \ + $(top_builddir)/lib/c_glib/src/thrift/c_glib/transport/libthrift_c_glib_la-thrift_transport.o \ + $(top_builddir)/lib/c_glib/src/thrift/c_glib/transport/libthrift_c_glib_la-thrift_socket.o \ + $(top_builddir)/lib/c_glib/src/thrift/c_glib/transport/libthrift_c_glib_la-thrift_buffered_transport.o \ + $(top_builddir)/lib/c_glib/src/thrift/c_glib/transport/libthrift_c_glib_la-thrift_server_transport.o \ + $(top_builddir)/lib/c_glib/src/thrift/c_glib/transport/libthrift_c_glib_la-thrift_server_socket.o + + testbinaryprotocol_SOURCES = testbinaryprotocol.c testbinaryprotocol_LDADD = \ $(top_builddir)/lib/c_glib/src/thrift/c_glib/protocol/libthrift_c_glib_la-thrift_protocol.o \ @@ -226,8 +237,6 @@ nodist_libtestgencpp_la_SOURCES = \ gen-cpp/ThriftTest_types.h libtestgencpp_la_CPPFLAGS = -I../../cpp/src $(BOOST_CPPFLAGS) -I./gen-cpp -THRIFT = $(top_builddir)/compiler/cpp/thrift - gen-c_glib/t_test_container_test_types.c gen-c_glib/t_test_container_test_types.h gen-c_glib/t_test_container_service.c gen-c_glib/t_test_container_service.h: ContainerTest.thrift $(THRIFT) $(THRIFT) --gen c_glib $< diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testbinaryprotocol.c b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testbinaryprotocol.c index 7ca5150..14f4fb0 100755 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testbinaryprotocol.c +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testbinaryprotocol.c @@ -19,7 +19,7 @@ /* Disable string-function optimizations when glibc is used, as these produce compiler warnings about string length when a string function is used inside - a call to assert () */ + a call to g_assert () */ #ifdef __GLIBC__ #include #define __NO_STRING_INLINES 1 @@ -28,7 +28,6 @@ #include #include #include -#include #include #include #include @@ -96,7 +95,7 @@ test_create_and_destroy(void) /* create an object and then destroy it */ object = g_object_new (THRIFT_TYPE_BINARY_PROTOCOL, NULL); - assert (object != NULL); + g_assert (object != NULL); g_object_unref (object); } @@ -110,11 +109,11 @@ test_initialize(void) /* create a ThriftTransport */ tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", "port", 51188, NULL); - assert (tsocket != NULL); + g_assert (tsocket != NULL); /* create a ThriftBinaryProtocol using the Transport */ protocol = g_object_new (THRIFT_TYPE_BINARY_PROTOCOL, "transport", tsocket, NULL); - assert (protocol != NULL); + g_assert (protocol != NULL); /* fetch the properties */ g_object_get (G_OBJECT(protocol), "transport", &temp, NULL); g_object_unref (temp); @@ -139,7 +138,7 @@ test_read_and_write_primitives(void) /* fork a server from the client */ pid = fork (); - assert (pid >= 0); + g_assert (pid >= 0); if (pid == 0) { @@ -155,47 +154,48 @@ test_read_and_write_primitives(void) "port", port, NULL); transport = THRIFT_TRANSPORT (tsocket); thrift_transport_open (transport, NULL); - assert (thrift_transport_is_open (transport)); + g_assert (thrift_transport_is_open (transport)); /* create a ThriftBinaryTransport */ tb = g_object_new (THRIFT_TYPE_BINARY_PROTOCOL, "transport", tsocket, NULL); protocol = THRIFT_PROTOCOL (tb); - assert (protocol != NULL); + g_assert (protocol != NULL); /* write a bunch of primitives */ - assert (thrift_binary_protocol_write_bool (protocol, TEST_BOOL, NULL) > 0); - assert (thrift_binary_protocol_write_byte (protocol, TEST_BYTE, NULL) > 0); - assert (thrift_binary_protocol_write_i16 (protocol, TEST_I16, NULL) > 0); - assert (thrift_binary_protocol_write_i32 (protocol, TEST_I32, NULL) > 0); - assert (thrift_binary_protocol_write_i64 (protocol, TEST_I64, NULL) > 0); - assert (thrift_binary_protocol_write_double (protocol, + g_assert (thrift_binary_protocol_write_bool (protocol, TEST_BOOL, NULL) > 0); + g_assert (thrift_binary_protocol_write_byte (protocol, TEST_BYTE, NULL) > 0); + g_assert (thrift_binary_protocol_write_i16 (protocol, TEST_I16, NULL) > 0); + g_assert (thrift_binary_protocol_write_i32 (protocol, TEST_I32, NULL) > 0); + g_assert (thrift_binary_protocol_write_i64 (protocol, TEST_I64, NULL) > 0); + g_assert (thrift_binary_protocol_write_double (protocol, TEST_DOUBLE, NULL) > 0); - assert (thrift_binary_protocol_write_string (protocol, + g_assert (thrift_binary_protocol_write_string (protocol, TEST_STRING, NULL) > 0); - assert (thrift_binary_protocol_write_binary (protocol, binary, + g_assert (thrift_binary_protocol_write_string (protocol, "", NULL) > 0); + g_assert (thrift_binary_protocol_write_binary (protocol, binary, len, NULL) > 0); - assert (thrift_binary_protocol_write_binary (protocol, NULL, 0, NULL) > 0); - assert (thrift_binary_protocol_write_binary (protocol, binary, + g_assert (thrift_binary_protocol_write_binary (protocol, NULL, 0, NULL) > 0); + g_assert (thrift_binary_protocol_write_binary (protocol, binary, len, NULL) > 0); /* test write errors */ transport_write_error = 1; - assert (thrift_binary_protocol_write_byte (protocol, TEST_BYTE, + g_assert (thrift_binary_protocol_write_byte (protocol, TEST_BYTE, NULL) == -1); - assert (thrift_binary_protocol_write_i16 (protocol, TEST_I16, NULL) == -1); - assert (thrift_binary_protocol_write_i32 (protocol, TEST_I32, NULL) == -1); - assert (thrift_binary_protocol_write_i64 (protocol, TEST_I64, NULL) == -1); - assert (thrift_binary_protocol_write_double (protocol, TEST_DOUBLE, + g_assert (thrift_binary_protocol_write_i16 (protocol, TEST_I16, NULL) == -1); + g_assert (thrift_binary_protocol_write_i32 (protocol, TEST_I32, NULL) == -1); + g_assert (thrift_binary_protocol_write_i64 (protocol, TEST_I64, NULL) == -1); + g_assert (thrift_binary_protocol_write_double (protocol, TEST_DOUBLE, NULL) == -1); - assert (thrift_binary_protocol_write_binary (protocol, binary, len, + g_assert (thrift_binary_protocol_write_binary (protocol, binary, len, NULL) == -1); transport_write_error = 0; /* test binary partial failure */ transport_write_count = 0; transport_write_error_at = 1; - assert (thrift_binary_protocol_write_binary (protocol, binary, + g_assert (thrift_binary_protocol_write_binary (protocol, binary, len, NULL) == -1); transport_write_error_at = -1; @@ -203,8 +203,8 @@ test_read_and_write_primitives(void) thrift_transport_close (transport, NULL); g_object_unref (tsocket); g_object_unref (protocol); - assert (wait (&status) == pid); - assert (status == 0); + g_assert (wait (&status) == pid); + g_assert (status == 0); } } @@ -221,7 +221,7 @@ test_read_and_write_complex_types (void) /* fork a server from the client */ pid = fork (); - assert (pid >= 0); + g_assert (pid >= 0); if (pid == 0) { @@ -237,33 +237,33 @@ test_read_and_write_complex_types (void) "port", port, NULL); transport = THRIFT_TRANSPORT (tsocket); thrift_transport_open (transport, NULL); - assert (thrift_transport_is_open (transport)); + g_assert (thrift_transport_is_open (transport)); /* create a ThriftBinaryTransport */ tb = g_object_new (THRIFT_TYPE_BINARY_PROTOCOL, "transport", tsocket, NULL); protocol = THRIFT_PROTOCOL (tb); - assert (protocol != NULL); + g_assert (protocol != NULL); /* test structures */ - assert (thrift_binary_protocol_write_struct_begin (protocol, + g_assert (thrift_binary_protocol_write_struct_begin (protocol, NULL, NULL) == 0); - assert (thrift_binary_protocol_write_struct_end (protocol, NULL) == 0); + g_assert (thrift_binary_protocol_write_struct_end (protocol, NULL) == 0); - assert (thrift_binary_protocol_write_field_begin (protocol, "test", T_VOID, + g_assert (thrift_binary_protocol_write_field_begin (protocol, "test", T_VOID, 1, NULL) > 0); - assert (thrift_binary_protocol_write_field_end (protocol, NULL) == 0); + g_assert (thrift_binary_protocol_write_field_end (protocol, NULL) == 0); /* test write error */ transport_write_error = 1; - assert (thrift_binary_protocol_write_field_begin (protocol, "test", T_VOID, + g_assert (thrift_binary_protocol_write_field_begin (protocol, "test", T_VOID, 1, NULL) == -1); transport_write_error = 0; /* test 2nd write error */ transport_write_count = 0; transport_write_error_at = 1; - assert (thrift_binary_protocol_write_field_begin (protocol, "test", T_VOID, + g_assert (thrift_binary_protocol_write_field_begin (protocol, "test", T_VOID, 1, NULL) == -1); transport_write_error_at = -1; @@ -271,12 +271,12 @@ test_read_and_write_complex_types (void) thrift_binary_protocol_write_byte (protocol, T_VOID, NULL); /* test write_field_stop */ - assert (thrift_binary_protocol_write_field_stop (protocol, NULL) > 0); + g_assert (thrift_binary_protocol_write_field_stop (protocol, NULL) > 0); /* write a map */ - assert (thrift_binary_protocol_write_map_begin (protocol, T_VOID, T_VOID, + g_assert (thrift_binary_protocol_write_map_begin (protocol, T_VOID, T_VOID, 1, NULL) > 0); - assert (thrift_binary_protocol_write_map_end (protocol, NULL) == 0); + g_assert (thrift_binary_protocol_write_map_end (protocol, NULL) == 0); /* test 2nd read failure on a map */ thrift_binary_protocol_write_byte (protocol, T_VOID, NULL); @@ -287,21 +287,21 @@ test_read_and_write_complex_types (void) /* test 1st write failure on a map */ transport_write_error = 1; - assert (thrift_binary_protocol_write_map_begin (protocol, T_VOID, T_VOID, + g_assert (thrift_binary_protocol_write_map_begin (protocol, T_VOID, T_VOID, 1, NULL) == -1); transport_write_error = 0; /* test 2nd write failure on a map */ transport_write_count = 0; transport_write_error_at = 1; - assert (thrift_binary_protocol_write_map_begin (protocol, T_VOID, T_VOID, + g_assert (thrift_binary_protocol_write_map_begin (protocol, T_VOID, T_VOID, 1, NULL) == -1); transport_write_error_at = -1; /* test 3rd write failure on a map */ transport_write_count = 0; transport_write_error_at = 2; - assert (thrift_binary_protocol_write_map_begin (protocol, T_VOID, T_VOID, + g_assert (thrift_binary_protocol_write_map_begin (protocol, T_VOID, T_VOID, 1, NULL) == -1); transport_write_error_at = -1; @@ -311,9 +311,9 @@ test_read_and_write_complex_types (void) thrift_binary_protocol_write_i32 (protocol, -10, NULL); /* test list operations */ - assert (thrift_binary_protocol_write_list_begin (protocol, T_VOID, + g_assert (thrift_binary_protocol_write_list_begin (protocol, T_VOID, 1, NULL) > 0); - assert (thrift_binary_protocol_write_list_end (protocol, NULL) == 0); + g_assert (thrift_binary_protocol_write_list_end (protocol, NULL) == 0); /* test 2nd read failure on a list */ thrift_binary_protocol_write_byte (protocol, T_VOID, NULL); @@ -324,27 +324,27 @@ test_read_and_write_complex_types (void) /* test first write error on a list */ transport_write_error = 1; - assert (thrift_binary_protocol_write_list_begin (protocol, T_VOID, + g_assert (thrift_binary_protocol_write_list_begin (protocol, T_VOID, 1, NULL) == -1); transport_write_error = 0; /* test 2nd write error on a list */ transport_write_count = 0; transport_write_error_at = 1; - assert (thrift_binary_protocol_write_list_begin (protocol, T_VOID, + g_assert (thrift_binary_protocol_write_list_begin (protocol, T_VOID, 1, NULL) == -1); transport_write_error_at = -1; /* test set operation s*/ - assert (thrift_binary_protocol_write_set_begin (protocol, T_VOID, + g_assert (thrift_binary_protocol_write_set_begin (protocol, T_VOID, 1, NULL) > 0); - assert (thrift_binary_protocol_write_set_end (protocol, NULL) == 0); + g_assert (thrift_binary_protocol_write_set_end (protocol, NULL) == 0); /* invalid version */ - assert (thrift_binary_protocol_write_i32 (protocol, -1, NULL) > 0); + g_assert (thrift_binary_protocol_write_i32 (protocol, -1, NULL) > 0); /* sz > 0 for a message */ - assert (thrift_binary_protocol_write_i32 (protocol, 1, NULL) > 0); + g_assert (thrift_binary_protocol_write_i32 (protocol, 1, NULL) > 0); /* send a valid message */ thrift_binary_protocol_write_i32 (protocol, 0x80010000, NULL); @@ -359,26 +359,26 @@ test_read_and_write_complex_types (void) thrift_binary_protocol_write_string (protocol, "test", NULL); /* send a valid message */ - assert (thrift_binary_protocol_write_message_begin (protocol, "test", + g_assert (thrift_binary_protocol_write_message_begin (protocol, "test", T_CALL, 1, NULL) > 0); - assert (thrift_binary_protocol_write_message_end (protocol, NULL) == 0); + g_assert (thrift_binary_protocol_write_message_end (protocol, NULL) == 0); /* send broken writes */ transport_write_error = 1; - assert (thrift_binary_protocol_write_message_begin (protocol, "test", + g_assert (thrift_binary_protocol_write_message_begin (protocol, "test", T_CALL, 1, NULL) == -1); transport_write_error = 0; transport_write_count = 0; transport_write_error_at = 2; - assert (thrift_binary_protocol_write_message_begin (protocol, "test", + g_assert (thrift_binary_protocol_write_message_begin (protocol, "test", T_CALL, 1, NULL) == -1); transport_write_error_at = -1; transport_write_count = 0; transport_write_error_at = 3; - assert (thrift_binary_protocol_write_message_begin (protocol, "test", + g_assert (thrift_binary_protocol_write_message_begin (protocol, "test", T_CALL, 1, NULL) == -1); transport_write_error_at = -1; @@ -386,8 +386,8 @@ test_read_and_write_complex_types (void) thrift_transport_close (transport, NULL); g_object_unref (tsocket); g_object_unref (protocol); - assert (wait (&status) == pid); - assert (status == 0); + g_assert (wait (&status) == pid); + g_assert (status == 0); } } @@ -407,7 +407,7 @@ test_read_and_write_many_frames (void) /* fork a server from the client */ pid = fork (); - assert (pid >= 0); + g_assert (pid >= 0); if (pid == 0) { @@ -421,47 +421,49 @@ test_read_and_write_many_frames (void) /* create a ThriftSocket */ tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", "port", port, NULL); - assert (tsocket != NULL); + g_assert (tsocket != NULL); transport = THRIFT_TRANSPORT (tsocket); /* wrap in a framed transport */ ft = g_object_new (THRIFT_TYPE_FRAMED_TRANSPORT, "transport", transport, "w_buf_size", 1, NULL); - assert (ft != NULL); + g_assert (ft != NULL); transport = THRIFT_TRANSPORT (ft); thrift_transport_open (transport, NULL); - assert (thrift_transport_is_open (transport)); + g_assert (thrift_transport_is_open (transport)); /* create a binary protocol */ tb = g_object_new (THRIFT_TYPE_BINARY_PROTOCOL, "transport", transport, NULL); protocol = THRIFT_PROTOCOL (tb); - assert (protocol != NULL); + g_assert (protocol != NULL); /* write a bunch of primitives */ - assert (thrift_binary_protocol_write_bool (protocol, TEST_BOOL, NULL) > 0); + g_assert (thrift_binary_protocol_write_bool (protocol, TEST_BOOL, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_binary_protocol_write_byte (protocol, TEST_BYTE, NULL) > 0); + g_assert (thrift_binary_protocol_write_byte (protocol, TEST_BYTE, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_binary_protocol_write_i16 (protocol, TEST_I16, NULL) > 0); + g_assert (thrift_binary_protocol_write_i16 (protocol, TEST_I16, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_binary_protocol_write_i32 (protocol, TEST_I32, NULL) > 0); + g_assert (thrift_binary_protocol_write_i32 (protocol, TEST_I32, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_binary_protocol_write_i64 (protocol, TEST_I64, NULL) > 0); + g_assert (thrift_binary_protocol_write_i64 (protocol, TEST_I64, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_binary_protocol_write_double (protocol, + g_assert (thrift_binary_protocol_write_double (protocol, TEST_DOUBLE, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_binary_protocol_write_string (protocol, + g_assert (thrift_binary_protocol_write_string (protocol, TEST_STRING, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_binary_protocol_write_binary (protocol, binary, + g_assert (thrift_binary_protocol_write_string (protocol, "", NULL) > 0); + thrift_transport_flush (transport, NULL); + g_assert (thrift_binary_protocol_write_binary (protocol, binary, len, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_binary_protocol_write_binary (protocol, NULL, 0, NULL) > 0); + g_assert (thrift_binary_protocol_write_binary (protocol, NULL, 0, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_binary_protocol_write_binary (protocol, binary, + g_assert (thrift_binary_protocol_write_binary (protocol, binary, len, NULL) > 0); thrift_transport_flush (transport, NULL); @@ -471,8 +473,8 @@ test_read_and_write_many_frames (void) g_object_unref (ft); g_object_unref (tsocket); g_object_unref (tb); - assert (wait (&status) == pid); - assert (status == 0); + g_assert (wait (&status) == pid); + g_assert (status == 0); } } @@ -491,6 +493,7 @@ thrift_server_primitives (const int port) gint64 value_64 = 0; gdouble value_double = 0; gchar *string = NULL; + gchar *empty_string = NULL; gpointer binary = NULL; guint32 len = 0; void *comparator = (void *) TEST_STRING; @@ -500,61 +503,68 @@ thrift_server_primitives (const int port) transport = THRIFT_SERVER_TRANSPORT (tsocket); thrift_server_transport_listen (transport, NULL); client = thrift_server_transport_accept (transport, NULL); - assert (client != NULL); + g_assert (client != NULL); tbp = g_object_new (THRIFT_TYPE_BINARY_PROTOCOL, "transport", client, NULL); protocol = THRIFT_PROTOCOL (tbp); - assert (thrift_binary_protocol_read_bool (protocol, + g_assert (thrift_binary_protocol_read_bool (protocol, &value_boolean, NULL) > 0); - assert (thrift_binary_protocol_read_byte (protocol, &value_byte, NULL) > 0); - assert (thrift_binary_protocol_read_i16 (protocol, &value_16, NULL) > 0); - assert (thrift_binary_protocol_read_i32 (protocol, &value_32, NULL) > 0); - assert (thrift_binary_protocol_read_i64 (protocol, &value_64, NULL) > 0); - assert (thrift_binary_protocol_read_double (protocol, + g_assert (thrift_binary_protocol_read_byte (protocol, &value_byte, NULL) > 0); + g_assert (thrift_binary_protocol_read_i16 (protocol, &value_16, NULL) > 0); + g_assert (thrift_binary_protocol_read_i32 (protocol, &value_32, NULL) > 0); + g_assert (thrift_binary_protocol_read_i64 (protocol, &value_64, NULL) > 0); + g_assert (thrift_binary_protocol_read_double (protocol, &value_double, NULL) > 0); - assert (thrift_binary_protocol_read_string (protocol, &string, NULL) > 0); - assert (thrift_binary_protocol_read_binary (protocol, &binary, + g_assert (thrift_binary_protocol_read_string (protocol, &string, NULL) > 0); + g_assert (thrift_binary_protocol_read_string (protocol, &empty_string, + NULL) > 0); + g_assert (thrift_binary_protocol_read_binary (protocol, &binary, &len, NULL) > 0); - assert (value_boolean == TEST_BOOL); - assert (value_byte == TEST_BYTE); - assert (value_16 == TEST_I16); - assert (value_32 == TEST_I32); - assert (value_64 == TEST_I64); - assert (value_double == TEST_DOUBLE); - assert (strcmp (TEST_STRING, string) == 0); - assert (memcmp (comparator, binary, len) == 0); + g_assert (value_boolean == TEST_BOOL); + g_assert (value_byte == TEST_BYTE); + g_assert (value_16 == TEST_I16); + g_assert (value_32 == TEST_I32); + g_assert (value_64 == TEST_I64); + g_assert (value_double == TEST_DOUBLE); + g_assert (strcmp (TEST_STRING, string) == 0); + g_assert (strcmp ("", empty_string) == 0); + g_assert (memcmp (comparator, binary, len) == 0); g_free (string); + g_free (empty_string); g_free (binary); - thrift_binary_protocol_read_binary (protocol, &binary, &len, NULL); + g_assert (thrift_binary_protocol_read_binary (protocol, &binary, + &len, NULL) > 0); + g_assert (binary == NULL); + g_assert (len == 0); g_free (binary); transport_read_count = 0; transport_read_error_at = 0; - assert (thrift_binary_protocol_read_binary (protocol, &binary, + g_assert (thrift_binary_protocol_read_binary (protocol, &binary, &len, NULL) == -1); transport_read_error_at = -1; transport_read_count = 0; transport_read_error_at = 1; - assert (thrift_binary_protocol_read_binary (protocol, &binary, + g_assert (thrift_binary_protocol_read_binary (protocol, &binary, &len, NULL) == -1); transport_read_error_at = -1; transport_read_error = 1; - assert (thrift_binary_protocol_read_bool (protocol, + g_assert (thrift_binary_protocol_read_bool (protocol, &value_boolean, NULL) == -1); - assert (thrift_binary_protocol_read_byte (protocol, + g_assert (thrift_binary_protocol_read_byte (protocol, &value_byte, NULL) == -1); - assert (thrift_binary_protocol_read_i16 (protocol, + g_assert (thrift_binary_protocol_read_i16 (protocol, &value_16, NULL) == -1); - assert (thrift_binary_protocol_read_i32 (protocol, &value_32, NULL) == -1); - assert (thrift_binary_protocol_read_i64 (protocol, &value_64, NULL) == -1); - assert (thrift_binary_protocol_read_double (protocol, + g_assert (thrift_binary_protocol_read_i32 (protocol, &value_32, NULL) == -1); + g_assert (thrift_binary_protocol_read_i64 (protocol, &value_64, NULL) == -1); + g_assert (thrift_binary_protocol_read_double (protocol, &value_double, NULL) == -1); transport_read_error = 0; @@ -592,7 +602,7 @@ thrift_server_complex_types (const int port) transport = THRIFT_SERVER_TRANSPORT (tsocket); thrift_server_transport_listen (transport, NULL); client = thrift_server_transport_accept (transport, NULL); - assert (client != NULL); + g_assert (client != NULL); tbp = g_object_new (THRIFT_TYPE_BINARY_PROTOCOL, "transport", client, NULL); @@ -607,7 +617,7 @@ thrift_server_complex_types (const int port) /* test first read error on a field */ transport_read_error = 1; - assert (thrift_binary_protocol_read_field_begin (protocol, + g_assert (thrift_binary_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) == -1); transport_read_error = 0; @@ -618,7 +628,7 @@ thrift_server_complex_types (const int port) /* test 2nd read failure on a field */ transport_read_count = 0; transport_read_error_at = 1; - assert (thrift_binary_protocol_read_field_begin (protocol, + g_assert (thrift_binary_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) == -1); transport_read_error_at = -1; @@ -634,7 +644,7 @@ thrift_server_complex_types (const int port) /* test read failure on a map */ transport_read_count = 0; transport_read_error_at = 0; - assert (thrift_binary_protocol_read_map_begin (protocol, + g_assert (thrift_binary_protocol_read_map_begin (protocol, &key_type, &value_type, &size, NULL) == -1); transport_read_error_at = -1; @@ -642,7 +652,7 @@ thrift_server_complex_types (const int port) /* test 2nd read failure on a map */ transport_read_count = 0; transport_read_error_at = 1; - assert (thrift_binary_protocol_read_map_begin (protocol, + g_assert (thrift_binary_protocol_read_map_begin (protocol, &key_type, &value_type, &size, NULL) == -1); transport_read_error_at = -1; @@ -650,7 +660,7 @@ thrift_server_complex_types (const int port) /* test 3rd read failure on a map */ transport_read_count = 0; transport_read_error_at = 2; - assert (thrift_binary_protocol_read_map_begin (protocol, + g_assert (thrift_binary_protocol_read_map_begin (protocol, &key_type, &value_type, &size, NULL) == -1); transport_read_error_at = -1; @@ -663,7 +673,7 @@ thrift_server_complex_types (const int port) thrift_binary_protocol_read_byte (protocol, &value, NULL); /* test negative map size */ - assert (thrift_binary_protocol_read_map_begin (protocol, + g_assert (thrift_binary_protocol_read_map_begin (protocol, &key_type, &value_type, &size, NULL) == -1); @@ -673,7 +683,7 @@ thrift_server_complex_types (const int port) /* test read failure */ transport_read_error = 1; - assert (thrift_binary_protocol_read_list_begin (protocol, &element_type, + g_assert (thrift_binary_protocol_read_list_begin (protocol, &element_type, &size, NULL) == -1); transport_read_error = 0; @@ -695,23 +705,23 @@ thrift_server_complex_types (const int port) /* broken read */ transport_read_error = 1; - assert (thrift_binary_protocol_read_message_begin (protocol, &message_name, + g_assert (thrift_binary_protocol_read_message_begin (protocol, &message_name, &message_type, &seqid, NULL) == -1); transport_read_error = 0; /* invalid protocol version */ - assert (thrift_binary_protocol_read_message_begin (protocol, &message_name, + g_assert (thrift_binary_protocol_read_message_begin (protocol, &message_name, &message_type, &seqid, NULL) == -1); /* sz > 0 */ - assert (thrift_binary_protocol_read_message_begin (protocol, &message_name, + g_assert (thrift_binary_protocol_read_message_begin (protocol, &message_name, &message_type, &seqid, NULL) > 0); /* read a valid message */ - assert (thrift_binary_protocol_read_message_begin (protocol, &message_name, + g_assert (thrift_binary_protocol_read_message_begin (protocol, &message_name, &message_type, &seqid, NULL) > 0); g_free (message_name); @@ -719,7 +729,7 @@ thrift_server_complex_types (const int port) /* broken 2nd read on a message */ transport_read_count = 0; transport_read_error_at = 1; - assert (thrift_binary_protocol_read_message_begin (protocol, &message_name, + g_assert (thrift_binary_protocol_read_message_begin (protocol, &message_name, &message_type, &seqid, NULL) == -1); transport_read_error_at = -1; @@ -727,19 +737,19 @@ thrift_server_complex_types (const int port) /* broken 3rd read on a message */ transport_read_count = 0; transport_read_error_at = 3; /* read_string does two reads */ - assert (thrift_binary_protocol_read_message_begin (protocol, &message_name, + g_assert (thrift_binary_protocol_read_message_begin (protocol, &message_name, &message_type, &seqid, NULL) == -1); g_free (message_name); transport_read_error_at = -1; /* read a valid message */ - assert (thrift_binary_protocol_read_message_begin (protocol, &message_name, + g_assert (thrift_binary_protocol_read_message_begin (protocol, &message_name, &message_type, &seqid, NULL) > 0); g_free (message_name); - assert (thrift_binary_protocol_read_message_end (protocol, NULL) == 0); + g_assert (thrift_binary_protocol_read_message_end (protocol, NULL) == 0); /* handle 2nd write failure on a message */ thrift_binary_protocol_read_i32 (protocol, &version, NULL); @@ -768,6 +778,7 @@ thrift_server_many_frames (const int port) gint64 value_64 = 0; gdouble value_double = 0; gchar *string = NULL; + gchar *empty_string = NULL; gpointer binary = NULL; guint32 len = 0; void *comparator = (void *) TEST_STRING; @@ -780,34 +791,44 @@ thrift_server_many_frames (const int port) client = g_object_new (THRIFT_TYPE_FRAMED_TRANSPORT, "transport", thrift_server_transport_accept (transport, NULL), "r_buf_size", 1, NULL); - assert (client != NULL); + g_assert (client != NULL); tbp = g_object_new (THRIFT_TYPE_BINARY_PROTOCOL, "transport", client, NULL); protocol = THRIFT_PROTOCOL (tbp); - assert (thrift_binary_protocol_read_bool (protocol, + g_assert (thrift_binary_protocol_read_bool (protocol, &value_boolean, NULL) > 0); - assert (thrift_binary_protocol_read_byte (protocol, &value_byte, NULL) > 0); - assert (thrift_binary_protocol_read_i16 (protocol, &value_16, NULL) > 0); - assert (thrift_binary_protocol_read_i32 (protocol, &value_32, NULL) > 0); - assert (thrift_binary_protocol_read_i64 (protocol, &value_64, NULL) > 0); - assert (thrift_binary_protocol_read_double (protocol, + g_assert (thrift_binary_protocol_read_byte (protocol, &value_byte, NULL) > 0); + g_assert (thrift_binary_protocol_read_i16 (protocol, &value_16, NULL) > 0); + g_assert (thrift_binary_protocol_read_i32 (protocol, &value_32, NULL) > 0); + g_assert (thrift_binary_protocol_read_i64 (protocol, &value_64, NULL) > 0); + g_assert (thrift_binary_protocol_read_double (protocol, &value_double, NULL) > 0); - assert (thrift_binary_protocol_read_string (protocol, &string, NULL) > 0); - assert (thrift_binary_protocol_read_binary (protocol, &binary, + g_assert (thrift_binary_protocol_read_string (protocol, &string, NULL) > 0); + g_assert (thrift_binary_protocol_read_string (protocol, &empty_string, + NULL) > 0); + g_assert (thrift_binary_protocol_read_binary (protocol, &binary, &len, NULL) > 0); - assert (value_boolean == TEST_BOOL); - assert (value_byte == TEST_BYTE); - assert (value_16 == TEST_I16); - assert (value_32 == TEST_I32); - assert (value_64 == TEST_I64); - assert (value_double == TEST_DOUBLE); - assert (strcmp (TEST_STRING, string) == 0); - assert (memcmp (comparator, binary, len) == 0); + g_assert (value_boolean == TEST_BOOL); + g_assert (value_byte == TEST_BYTE); + g_assert (value_16 == TEST_I16); + g_assert (value_32 == TEST_I32); + g_assert (value_64 == TEST_I64); + g_assert (value_double == TEST_DOUBLE); + g_assert (strcmp (TEST_STRING, string) == 0); + g_assert (strcmp ("", empty_string) == 0); + g_assert (memcmp (comparator, binary, len) == 0); g_free (string); + g_free (empty_string); + g_free (binary); + + g_assert (thrift_binary_protocol_read_binary (protocol, &binary, + &len, NULL) > 0); + g_assert (binary == NULL); + g_assert (len == 0); g_free (binary); thrift_transport_read_end (client, NULL); diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testbufferedtransport.c b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testbufferedtransport.c index 3203a66..c6e6b58 100755 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testbufferedtransport.c +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testbufferedtransport.c @@ -17,7 +17,6 @@ * under the License. */ -#include #include #include #include @@ -32,6 +31,7 @@ #include "../src/thrift/c_glib/transport/thrift_buffered_transport.c" static void thrift_server (const int port); +static void thrift_socket_server_open (const int port, int times); /* test object creation and destruction */ static void @@ -43,10 +43,10 @@ test_create_and_destroy(void) GObject *object = NULL; object = g_object_new (THRIFT_TYPE_BUFFERED_TRANSPORT, NULL); - assert (object != NULL); + g_assert (object != NULL); g_object_get (G_OBJECT (object), "transport", &transport, - "r_buf_size", &r_buf_size, - "w_buf_size", &w_buf_size, NULL); + "r_buf_size", &r_buf_size, + "w_buf_size", &w_buf_size, NULL); g_object_unref (object); } @@ -56,35 +56,52 @@ test_open_and_close(void) ThriftSocket *tsocket = NULL; ThriftTransport *transport = NULL; GError *err = NULL; + pid_t pid; + int port = 51199; + int status; - /* create a ThriftSocket */ - tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", - "port", 51188, NULL); + pid = fork (); + g_assert ( pid >= 0 ); - /* create a BufferedTransport wrapper of the Socket */ - transport = g_object_new (THRIFT_TYPE_BUFFERED_TRANSPORT, - "transport", THRIFT_TRANSPORT (tsocket), NULL); + if ( pid == 0 ) + { + /* child listens */ + thrift_socket_server_open (port,1); + exit (0); + } else { + /* parent connects, wait a bit for the socket to be created */ + sleep (1); + /* create a ThriftSocket */ + tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", + "port", port, NULL); - /* this shouldn't work */ - assert (thrift_buffered_transport_open (transport, NULL) == FALSE); - assert (thrift_buffered_transport_is_open (transport) == TRUE); - assert (thrift_buffered_transport_close (transport, NULL) == TRUE); - g_object_unref (transport); - g_object_unref (tsocket); + /* create a BufferedTransport wrapper of the Socket */ + transport = g_object_new (THRIFT_TYPE_BUFFERED_TRANSPORT, + "transport", THRIFT_TRANSPORT (tsocket), NULL); - /* try and underlying socket failure */ - tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost.broken", - NULL); + /* this shouldn't work */ + g_assert (thrift_buffered_transport_open (transport, NULL) == TRUE); + g_assert (thrift_buffered_transport_is_open (transport) == TRUE); + g_assert (thrift_buffered_transport_close (transport, NULL) == TRUE); + g_object_unref (transport); + g_object_unref (tsocket); - /* create a BufferedTransport wrapper of the Socket */ - transport = g_object_new (THRIFT_TYPE_BUFFERED_TRANSPORT, - "transport", THRIFT_TRANSPORT (tsocket), NULL); + /* try and underlying socket failure */ + tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost.broken", + NULL); - assert (thrift_buffered_transport_open (transport, &err) == FALSE); - g_object_unref (transport); - g_object_unref (tsocket); - g_error_free (err); - err = NULL; + /* create a BufferedTransport wrapper of the Socket */ + transport = g_object_new (THRIFT_TYPE_BUFFERED_TRANSPORT, + "transport", THRIFT_TRANSPORT (tsocket), NULL); + + g_assert (thrift_buffered_transport_open (transport, &err) == FALSE); + g_object_unref (transport); + g_object_unref (tsocket); + g_error_free (err); + err = NULL; + g_assert ( wait (&status) == pid ); + g_assert ( status == 0 ); + } } static void @@ -98,60 +115,84 @@ test_read_and_write(void) guchar buf[10] = TEST_DATA; /* a buffer */ pid = fork (); - assert ( pid >= 0 ); + g_assert ( pid >= 0 ); if ( pid == 0 ) - { - /* child listens */ - thrift_server (port); - exit (0); - } else { - /* parent connects, wait a bit for the socket to be created */ - sleep (1); + { + /* child listens */ + thrift_server (port); + exit (0); + } else { + /* parent connects, wait a bit for the socket to be created */ + sleep (1); - tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", - "port", port, NULL); - transport = g_object_new (THRIFT_TYPE_BUFFERED_TRANSPORT, - "transport", THRIFT_TRANSPORT (tsocket), - "w_buf_size", 4, NULL); + tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", + "port", port, NULL); + transport = g_object_new (THRIFT_TYPE_BUFFERED_TRANSPORT, + "transport", THRIFT_TRANSPORT (tsocket), + "w_buf_size", 4, NULL); - assert (thrift_buffered_transport_open (transport, NULL) == TRUE); - assert (thrift_buffered_transport_is_open (transport)); + g_assert (thrift_buffered_transport_open (transport, NULL) == TRUE); + g_assert (thrift_buffered_transport_is_open (transport)); - /* write 10 bytes */ - thrift_buffered_transport_write (transport, buf, 10, NULL); + /* write 10 bytes */ + thrift_buffered_transport_write (transport, buf, 10, NULL); - /* write 1 byte at a time */ - thrift_buffered_transport_write (transport, buf, 1, NULL); - thrift_buffered_transport_write (transport, buf, 1, NULL); - thrift_buffered_transport_write (transport, buf, 1, NULL); + /* write 1 byte at a time */ + thrift_buffered_transport_write (transport, buf, 1, NULL); + thrift_buffered_transport_write (transport, buf, 1, NULL); + thrift_buffered_transport_write (transport, buf, 1, NULL); - /* overflow the buffer */ - thrift_buffered_transport_write (transport, buf, 2, NULL); - thrift_buffered_transport_write (transport, buf, 1, NULL); - thrift_buffered_transport_flush (transport, NULL); + /* overflow the buffer */ + thrift_buffered_transport_write (transport, buf, 2, NULL); + thrift_buffered_transport_write (transport, buf, 1, NULL); + thrift_buffered_transport_flush (transport, NULL); - /* write 1 byte and flush */ - thrift_buffered_transport_write (transport, buf, 1, NULL); - thrift_buffered_transport_flush (transport, NULL); + /* write 1 byte and flush */ + thrift_buffered_transport_write (transport, buf, 1, NULL); + thrift_buffered_transport_flush (transport, NULL); - /* write and overflow buffer with 2 system calls */ - thrift_buffered_transport_write (transport, buf, 1, NULL); - thrift_buffered_transport_write (transport, buf, 3, NULL); + /* write and overflow buffer with 2 system calls */ + thrift_buffered_transport_write (transport, buf, 1, NULL); + thrift_buffered_transport_write (transport, buf, 3, NULL); - /* write 10 bytes */ - thrift_buffered_transport_write (transport, buf, 10, NULL); + /* write 10 bytes */ + thrift_buffered_transport_write (transport, buf, 10, NULL); - thrift_buffered_transport_write_end (transport, NULL); - thrift_buffered_transport_flush (transport, NULL); - thrift_buffered_transport_close (transport, NULL); + thrift_buffered_transport_write_end (transport, NULL); + thrift_buffered_transport_flush (transport, NULL); + thrift_buffered_transport_close (transport, NULL); - g_object_unref (transport); - g_object_unref (tsocket); + g_object_unref (transport); + g_object_unref (tsocket); - assert ( wait (&status) == pid ); - assert ( status == 0 ); + g_assert ( wait (&status) == pid ); + g_assert ( status == 0 ); + } +} + + +static void +thrift_socket_server_open (const int port, int times) +{ + int bytes = 0; + ThriftServerTransport *transport = NULL; + ThriftTransport *client = NULL; + guchar buf[10]; /* a buffer */ + guchar match[10] = TEST_DATA; + int i; + ThriftServerSocket *tsocket = g_object_new (THRIFT_TYPE_SERVER_SOCKET, + "port", port, NULL); + + transport = THRIFT_SERVER_TRANSPORT (tsocket); + thrift_server_transport_listen (transport, NULL); + for(i=0;i= 0 ); + g_assert ( pid >= 0 ); if ( pid == 0 ) - { - /* child listens */ - ThriftServerTransport *transport = NULL; - ThriftTransport *client = NULL; + { + /* child listens */ + ThriftServerTransport *transport = NULL; + ThriftTransport *client = NULL; - ThriftServerSocket *tsocket = g_object_new (THRIFT_TYPE_SERVER_SOCKET, - "port", port, NULL); + ThriftServerSocket *tsocket = g_object_new (THRIFT_TYPE_SERVER_SOCKET, + "port", port, NULL); - transport = THRIFT_SERVER_TRANSPORT (tsocket); - thrift_server_transport_listen (transport, NULL); + transport = THRIFT_SERVER_TRANSPORT (tsocket); + thrift_server_transport_listen (transport, NULL); - /* wrap the client in a BufferedTransport */ - client = g_object_new (THRIFT_TYPE_BUFFERED_TRANSPORT, "transport", - thrift_server_transport_accept (transport, NULL), - "r_buf_size", 5, NULL); - assert (client != NULL); + /* wrap the client in a BufferedTransport */ + client = g_object_new (THRIFT_TYPE_BUFFERED_TRANSPORT, "transport", + thrift_server_transport_accept (transport, NULL), + "r_buf_size", 5, NULL); + g_assert (client != NULL); - /* just close socket */ - thrift_buffered_transport_close (client, NULL); - g_object_unref (client); - g_object_unref (tsocket); - exit (0); - } else { - /* parent connects, wait a bit for the socket to be created */ - sleep (1); + /* just close socket */ + thrift_buffered_transport_close (client, NULL); + g_object_unref (client); + g_object_unref (tsocket); + exit (0); + } else { + /* parent connects, wait a bit for the socket to be created */ + sleep (1); - tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", - "port", port, NULL); - transport = g_object_new (THRIFT_TYPE_BUFFERED_TRANSPORT, - "transport", THRIFT_TRANSPORT (tsocket), - "w_buf_size", 4, NULL); + tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", + "port", port, NULL); + transport = g_object_new (THRIFT_TYPE_BUFFERED_TRANSPORT, + "transport", THRIFT_TRANSPORT (tsocket), + "w_buf_size", 4, NULL); - assert (thrift_buffered_transport_open (transport, NULL) == TRUE); - assert (thrift_buffered_transport_is_open (transport)); + g_assert (thrift_buffered_transport_open (transport, NULL) == TRUE); + g_assert (thrift_buffered_transport_is_open (transport)); - /* recognize disconnection */ - sleep(1); - assert (thrift_buffered_transport_write (transport, buf, 10, NULL) == TRUE); - assert (thrift_buffered_transport_write (transport, buf, 10, NULL) == FALSE); + /* recognize disconnection */ + sleep(1); + g_assert (thrift_buffered_transport_write (transport, buf, 10, NULL) == TRUE); + g_assert (thrift_buffered_transport_write (transport, buf, 10, NULL) == FALSE); - /* write and overflow buffer */ - assert (thrift_buffered_transport_write (transport, buf, 10, NULL) == FALSE); + /* write and overflow buffer */ + g_assert (thrift_buffered_transport_write (transport, buf, 10, NULL) == FALSE); - /* write 1 and flush */ - assert (thrift_buffered_transport_write (transport, buf, 1, NULL) == TRUE); - assert (thrift_buffered_transport_flush (transport, NULL) == FALSE); + /* write 1 and flush */ + g_assert (thrift_buffered_transport_write (transport, buf, 1, NULL) == TRUE); + g_assert (thrift_buffered_transport_flush (transport, NULL) == FALSE); - thrift_buffered_transport_close (transport, NULL); + thrift_buffered_transport_close (transport, NULL); - g_object_unref (transport); - g_object_unref (tsocket); + g_object_unref (transport); + g_object_unref (tsocket); - assert ( wait (&status) == pid ); - assert ( status == 0 ); - } + g_assert ( wait (&status) == pid ); + g_assert ( status == 0 ); + } } int diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testcompactprotocol.c b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testcompactprotocol.c index 9b57a8c..e5ad491 100755 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testcompactprotocol.c +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testcompactprotocol.c @@ -19,7 +19,7 @@ /* Disable string-function optimizations when glibc is used, as these produce compiler warnings about string length when a string function is used inside - a call to assert () */ + a call to g_assert () */ #if !defined(__APPLE__) && !defined(__FreeBSD__) && \ !defined(__OpenBSD__) && !defined(__NetBSD__) #include @@ -32,7 +32,6 @@ #include #include #include -#include #include #include #include @@ -103,7 +102,7 @@ test_create_and_destroy (void) /* create an object and then destroy it */ object = g_object_new (THRIFT_TYPE_COMPACT_PROTOCOL, NULL); - assert (object != NULL); + g_assert (object != NULL); g_object_unref (object); } @@ -117,11 +116,11 @@ test_initialize (void) /* create a ThriftTransport */ tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", "port", 51188, NULL); - assert (tsocket != NULL); + g_assert (tsocket != NULL); /* create a ThriftCompactProtocol using the Transport */ protocol = g_object_new (THRIFT_TYPE_COMPACT_PROTOCOL, "transport", tsocket, NULL); - assert (protocol != NULL); + g_assert (protocol != NULL); /* fetch the properties */ g_object_get (G_OBJECT (protocol), "transport", &temp, NULL); g_object_unref (temp); @@ -146,7 +145,7 @@ test_read_and_write_primitives (void) /* fork a server from the client */ pid = fork (); - assert (pid >= 0); + g_assert (pid >= 0); if (pid == 0) { @@ -162,62 +161,63 @@ test_read_and_write_primitives (void) "port", port, NULL); transport = THRIFT_TRANSPORT (tsocket); thrift_transport_open (transport, NULL); - assert (thrift_transport_is_open (transport)); + g_assert (thrift_transport_is_open (transport)); /* create a ThriftCompactTransport */ tc = g_object_new (THRIFT_TYPE_COMPACT_PROTOCOL, "transport", tsocket, NULL); protocol = THRIFT_PROTOCOL (tc); - assert (protocol != NULL); + g_assert (protocol != NULL); /* write a bunch of primitives */ - assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 0); - assert (thrift_compact_protocol_write_byte (protocol, TEST_BYTE, NULL) > 0); - assert (thrift_compact_protocol_write_i16 (protocol, TEST_I16, NULL) > 0); - assert (thrift_compact_protocol_write_i32 (protocol, TEST_I32, NULL) > 0); - assert (thrift_compact_protocol_write_i64 (protocol, TEST_I64, NULL) > 0); - assert (thrift_compact_protocol_write_i16 (protocol, TEST_NI16, NULL) > 0); - assert (thrift_compact_protocol_write_i32 (protocol, TEST_NI32, NULL) > 0); - assert (thrift_compact_protocol_write_i64 (protocol, TEST_NI64, NULL) > 0); - assert (thrift_compact_protocol_write_i16 (protocol, 2, NULL) > 0); - assert (thrift_compact_protocol_write_i32 (protocol, 2, NULL) > 0); - assert (thrift_compact_protocol_write_i64 (protocol, 2, NULL) > 0); - assert (thrift_compact_protocol_write_i16 (protocol, -2, NULL) > 0); - assert (thrift_compact_protocol_write_i32 (protocol, -2, NULL) > 0); - assert (thrift_compact_protocol_write_i64 (protocol, -2, NULL) > 0); - assert (thrift_compact_protocol_write_double (protocol, + g_assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 0); + g_assert (thrift_compact_protocol_write_byte (protocol, TEST_BYTE, NULL) > 0); + g_assert (thrift_compact_protocol_write_i16 (protocol, TEST_I16, NULL) > 0); + g_assert (thrift_compact_protocol_write_i32 (protocol, TEST_I32, NULL) > 0); + g_assert (thrift_compact_protocol_write_i64 (protocol, TEST_I64, NULL) > 0); + g_assert (thrift_compact_protocol_write_i16 (protocol, TEST_NI16, NULL) > 0); + g_assert (thrift_compact_protocol_write_i32 (protocol, TEST_NI32, NULL) > 0); + g_assert (thrift_compact_protocol_write_i64 (protocol, TEST_NI64, NULL) > 0); + g_assert (thrift_compact_protocol_write_i16 (protocol, 2, NULL) > 0); + g_assert (thrift_compact_protocol_write_i32 (protocol, 2, NULL) > 0); + g_assert (thrift_compact_protocol_write_i64 (protocol, 2, NULL) > 0); + g_assert (thrift_compact_protocol_write_i16 (protocol, -2, NULL) > 0); + g_assert (thrift_compact_protocol_write_i32 (protocol, -2, NULL) > 0); + g_assert (thrift_compact_protocol_write_i64 (protocol, -2, NULL) > 0); + g_assert (thrift_compact_protocol_write_double (protocol, TEST_DOUBLE, NULL) > 0); - assert (thrift_compact_protocol_write_string (protocol, + g_assert (thrift_compact_protocol_write_string (protocol, TEST_STRING, NULL) > 0); - assert (thrift_compact_protocol_write_binary (protocol, binary, + g_assert (thrift_compact_protocol_write_string (protocol, "", NULL) > 0); + g_assert (thrift_compact_protocol_write_binary (protocol, binary, len, NULL) > 0); - assert (thrift_compact_protocol_write_binary (protocol, NULL, 0, NULL) > 0); - assert (thrift_compact_protocol_write_binary (protocol, binary, + g_assert (thrift_compact_protocol_write_binary (protocol, NULL, 0, NULL) > 0); + g_assert (thrift_compact_protocol_write_binary (protocol, binary, len, NULL) > 0); /* test write errors */ transport_write_error = 1; - assert (thrift_compact_protocol_write_byte (protocol, TEST_BYTE, + g_assert (thrift_compact_protocol_write_byte (protocol, TEST_BYTE, NULL) == -1); - assert (thrift_compact_protocol_write_i16 (protocol, TEST_I16, NULL) == -1); - assert (thrift_compact_protocol_write_i32 (protocol, TEST_I32, NULL) == -1); - assert (thrift_compact_protocol_write_i64 (protocol, TEST_I64, NULL) == -1); - assert (thrift_compact_protocol_write_i16 (protocol, TEST_NI16, + g_assert (thrift_compact_protocol_write_i16 (protocol, TEST_I16, NULL) == -1); + g_assert (thrift_compact_protocol_write_i32 (protocol, TEST_I32, NULL) == -1); + g_assert (thrift_compact_protocol_write_i64 (protocol, TEST_I64, NULL) == -1); + g_assert (thrift_compact_protocol_write_i16 (protocol, TEST_NI16, NULL) == -1); - assert (thrift_compact_protocol_write_i32 (protocol, TEST_NI32, + g_assert (thrift_compact_protocol_write_i32 (protocol, TEST_NI32, NULL) == -1); - assert (thrift_compact_protocol_write_i64 (protocol, TEST_NI64, + g_assert (thrift_compact_protocol_write_i64 (protocol, TEST_NI64, NULL) == -1); - assert (thrift_compact_protocol_write_double (protocol, TEST_DOUBLE, + g_assert (thrift_compact_protocol_write_double (protocol, TEST_DOUBLE, NULL) == -1); - assert (thrift_compact_protocol_write_binary (protocol, binary, len, + g_assert (thrift_compact_protocol_write_binary (protocol, binary, len, NULL) == -1); transport_write_error = 0; /* test binary partial failure */ transport_write_count = 0; transport_write_error_at = 1; - assert (thrift_compact_protocol_write_binary (protocol, binary, + g_assert (thrift_compact_protocol_write_binary (protocol, binary, len, NULL) == -1); transport_write_error_at = -1; @@ -225,8 +225,8 @@ test_read_and_write_primitives (void) thrift_transport_close (transport, NULL); g_object_unref (tsocket); g_object_unref (protocol); - assert (wait (&status) == pid); - assert (status == 0); + g_assert (wait (&status) == pid); + g_assert (status == 0); } } @@ -243,7 +243,7 @@ test_read_and_write_complex_types (void) /* fork a server from the client */ pid = fork (); - assert (pid >= 0); + g_assert (pid >= 0); if (pid == 0) { @@ -259,144 +259,144 @@ test_read_and_write_complex_types (void) "port", port, NULL); transport = THRIFT_TRANSPORT (tsocket); thrift_transport_open (transport, NULL); - assert (thrift_transport_is_open (transport)); + g_assert (thrift_transport_is_open (transport)); /* create a ThriftCompactTransport */ tc = g_object_new (THRIFT_TYPE_COMPACT_PROTOCOL, "transport", tsocket, NULL); protocol = THRIFT_PROTOCOL (tc); - assert (protocol != NULL); + g_assert (protocol != NULL); /* test structures */ - assert (thrift_compact_protocol_write_struct_begin (protocol, + g_assert (thrift_compact_protocol_write_struct_begin (protocol, NULL, NULL) == 0); - assert (thrift_compact_protocol_write_struct_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_struct_end (protocol, NULL) == 0); /* test field state w.r.t. deltas */ - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 1, NULL) == 1); - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 16, NULL) == 1); - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 17, NULL) == 1); - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 15, NULL) > 1); - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 30, NULL) == 1); - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 46, NULL) > 1); - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 47, NULL) == 1); /* test fields */ - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 1, NULL) > 1); - assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); /* test field state w.r.t. structs */ - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 1, NULL) > 1); - assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 16, NULL) == 1); - assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); - assert (thrift_compact_protocol_write_struct_begin (protocol, + g_assert (thrift_compact_protocol_write_struct_begin (protocol, NULL, NULL) == 0); - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 17, NULL) > 1); - assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); - assert (thrift_compact_protocol_write_struct_begin (protocol, + g_assert (thrift_compact_protocol_write_struct_begin (protocol, NULL, NULL) == 0); - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 18, NULL) > 1); - assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 19, NULL) == 1); - assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); - assert (thrift_compact_protocol_write_struct_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_struct_end (protocol, NULL) == 0); - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 18, NULL) == 1); - assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 25, NULL) == 1); - assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); - assert (thrift_compact_protocol_write_struct_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_struct_end (protocol, NULL) == 0); - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 17, NULL) == 1); - assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); /* test field state w.r.t. bools */ /* deltas */ /* non-bool field -> bool field -> non-bool field */ - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 18, NULL) == 1); - assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); - assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_BOOL, + g_assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_BOOL, 19, NULL) == 0); - assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, + g_assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) == 1); - assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 20, NULL) == 1); - assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); /* bool -> bool field -> bool */ - assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 0); - assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_BOOL, + g_assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 0); + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_BOOL, 21, NULL) == 0); - assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, + g_assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) == 1); - assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); - assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 0); + g_assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 0); /* no deltas */ /* non-bool field -> bool field -> non-bool field */ - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 1, NULL) > 1); - assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); - assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_BOOL, + g_assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_BOOL, 1, NULL) == 0); - assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 1); - assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 1); + g_assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 1, NULL) > 1); - assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); /* bool -> bool field -> bool */ - assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 0); - assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_BOOL, + g_assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 0); + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_BOOL, 1, NULL) == 0); - assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 1); - assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); - assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 0); + g_assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 1); + g_assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 0); /* test write error */ transport_write_error = 1; - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 1, NULL) == -1); transport_write_error = 0; @@ -404,7 +404,7 @@ test_read_and_write_complex_types (void) /* test 2nd write error */ transport_write_count = 0; transport_write_error_at = 1; - assert (thrift_compact_protocol_write_field_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_field_begin (protocol, "test", T_DOUBLE, 1, NULL) == -1); transport_write_error_at = -1; @@ -413,13 +413,13 @@ test_read_and_write_complex_types (void) thrift_compact_protocol_write_byte (protocol, T_DOUBLE, NULL); /* test write_field_stop */ - assert (thrift_compact_protocol_write_field_stop (protocol, NULL) > 0); + g_assert (thrift_compact_protocol_write_field_stop (protocol, NULL) > 0); /* write a map */ - assert (thrift_compact_protocol_write_map_begin (protocol, T_DOUBLE, + g_assert (thrift_compact_protocol_write_map_begin (protocol, T_DOUBLE, T_DOUBLE, 1, NULL) > 0); - assert (thrift_compact_protocol_write_map_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_map_end (protocol, NULL) == 0); /* test 1st read failure on map---nothing to do on our side */ @@ -428,7 +428,7 @@ test_read_and_write_complex_types (void) /* test 1st write failure on a map */ transport_write_error = 1; - assert (thrift_compact_protocol_write_map_begin (protocol, T_DOUBLE, + g_assert (thrift_compact_protocol_write_map_begin (protocol, T_DOUBLE, T_DOUBLE, 1, NULL) == -1); transport_write_error = 0; @@ -436,7 +436,7 @@ test_read_and_write_complex_types (void) /* test 2nd write failure on a map */ transport_write_count = 0; transport_write_error_at = 1; - assert (thrift_compact_protocol_write_map_begin (protocol, T_DOUBLE, + g_assert (thrift_compact_protocol_write_map_begin (protocol, T_DOUBLE, T_DOUBLE, 1, NULL) == -1); transport_write_error_at = -1; @@ -446,9 +446,9 @@ test_read_and_write_complex_types (void) thrift_compact_protocol_write_byte (protocol, T_DOUBLE, NULL); /* test list operations */ - assert (thrift_compact_protocol_write_list_begin (protocol, T_DOUBLE, + g_assert (thrift_compact_protocol_write_list_begin (protocol, T_DOUBLE, 15, NULL) > 0); - assert (thrift_compact_protocol_write_list_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_list_end (protocol, NULL) == 0); /* test 1st read failure on a small list---nothing to do on our end */ @@ -463,40 +463,40 @@ test_read_and_write_complex_types (void) /* test first write error on a small list */ transport_write_error = 1; - assert (thrift_compact_protocol_write_list_begin (protocol, T_DOUBLE, + g_assert (thrift_compact_protocol_write_list_begin (protocol, T_DOUBLE, 14, NULL) == -1); transport_write_error = 0; /* test first write error on a big list */ transport_write_error = 1; - assert (thrift_compact_protocol_write_list_begin (protocol, T_DOUBLE, + g_assert (thrift_compact_protocol_write_list_begin (protocol, T_DOUBLE, 15, NULL) == -1); transport_write_error = 0; /* test 2nd write error on a big list */ transport_write_count = 0; transport_write_error_at = 1; - assert (thrift_compact_protocol_write_list_begin (protocol, T_DOUBLE, + g_assert (thrift_compact_protocol_write_list_begin (protocol, T_DOUBLE, 15, NULL) == -1); transport_write_error_at = -1; /* test set operation s*/ - assert (thrift_compact_protocol_write_set_begin (protocol, T_DOUBLE, + g_assert (thrift_compact_protocol_write_set_begin (protocol, T_DOUBLE, 1, NULL) > 0); - assert (thrift_compact_protocol_write_set_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_set_end (protocol, NULL) == 0); /* invalid protocol */ - assert (thrift_compact_protocol_write_byte (protocol, 0, NULL) > 0); + g_assert (thrift_compact_protocol_write_byte (protocol, 0, NULL) > 0); /* invalid version */ - assert (thrift_compact_protocol_write_byte (protocol, (gint8) 0x82u, + g_assert (thrift_compact_protocol_write_byte (protocol, (gint8) 0x82u, NULL) > 0); - assert (thrift_compact_protocol_write_byte (protocol, 0, NULL) > 0); + g_assert (thrift_compact_protocol_write_byte (protocol, 0, NULL) > 0); /* send a valid message */ - assert (thrift_compact_protocol_write_byte (protocol, (gint8) 0x82u, + g_assert (thrift_compact_protocol_write_byte (protocol, (gint8) 0x82u, NULL) > 0); - assert (thrift_compact_protocol_write_byte (protocol, 0x01u, NULL) > 0); + g_assert (thrift_compact_protocol_write_byte (protocol, 0x01u, NULL) > 0); thrift_compact_protocol_write_varint32 (tc, 1, NULL); thrift_compact_protocol_write_string (protocol, "test", NULL); @@ -513,32 +513,32 @@ test_read_and_write_complex_types (void) thrift_compact_protocol_write_varint32 (tc, 1, NULL); /* send a valid message */ - assert (thrift_compact_protocol_write_message_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_message_begin (protocol, "test", T_CALL, 1, NULL) > 0); - assert (thrift_compact_protocol_write_message_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_write_message_end (protocol, NULL) == 0); /* send broken writes */ transport_write_error = 1; - assert (thrift_compact_protocol_write_message_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_message_begin (protocol, "test", T_CALL, 1, NULL) == -1); transport_write_error = 0; transport_write_count = 0; transport_write_error_at = 1; - assert (thrift_compact_protocol_write_message_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_message_begin (protocol, "test", T_CALL, 1, NULL) == -1); transport_write_error_at = -1; transport_write_count = 0; transport_write_error_at = 2; - assert (thrift_compact_protocol_write_message_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_message_begin (protocol, "test", T_CALL, 1, NULL) == -1); transport_write_error_at = -1; transport_write_count = 0; transport_write_error_at = 3; - assert (thrift_compact_protocol_write_message_begin (protocol, "test", + g_assert (thrift_compact_protocol_write_message_begin (protocol, "test", T_CALL, 1, NULL) == -1); transport_write_error_at = -1; @@ -546,8 +546,8 @@ test_read_and_write_complex_types (void) thrift_transport_close (transport, NULL); g_object_unref (tsocket); g_object_unref (protocol); - assert (wait (&status) == pid); - assert (status == 0); + g_assert (wait (&status) == pid); + g_assert (status == 0); } } @@ -567,7 +567,7 @@ test_read_and_write_many_frames (void) /* fork a server from the client */ pid = fork (); - assert (pid >= 0); + g_assert (pid >= 0); if (pid == 0) { @@ -581,68 +581,70 @@ test_read_and_write_many_frames (void) /* create a ThriftSocket */ tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", "port", port, NULL); - assert (tsocket != NULL); + g_assert (tsocket != NULL); transport = THRIFT_TRANSPORT (tsocket); /* wrap in a framed transport */ ft = g_object_new (THRIFT_TYPE_FRAMED_TRANSPORT, "transport", transport, "w_buf_size", 1, NULL); - assert (ft != NULL); + g_assert (ft != NULL); transport = THRIFT_TRANSPORT (ft); thrift_transport_open (transport, NULL); - assert (thrift_transport_is_open (transport)); + g_assert (thrift_transport_is_open (transport)); /* create a compact protocol */ tc = g_object_new (THRIFT_TYPE_COMPACT_PROTOCOL, "transport", transport, NULL); protocol = THRIFT_PROTOCOL (tc); - assert (protocol != NULL); + g_assert (protocol != NULL); /* write a bunch of primitives */ - assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, + g_assert (thrift_compact_protocol_write_bool (protocol, TEST_BOOL, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_compact_protocol_write_byte (protocol, TEST_BYTE, + g_assert (thrift_compact_protocol_write_byte (protocol, TEST_BYTE, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_compact_protocol_write_i16 (protocol, TEST_I16, NULL) > 0); + g_assert (thrift_compact_protocol_write_i16 (protocol, TEST_I16, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_compact_protocol_write_i32 (protocol, TEST_I32, NULL) > 0); + g_assert (thrift_compact_protocol_write_i32 (protocol, TEST_I32, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_compact_protocol_write_i64 (protocol, TEST_I64, NULL) > 0); + g_assert (thrift_compact_protocol_write_i64 (protocol, TEST_I64, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_compact_protocol_write_i16 (protocol, TEST_NI16, NULL) > 0); + g_assert (thrift_compact_protocol_write_i16 (protocol, TEST_NI16, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_compact_protocol_write_i32 (protocol, TEST_NI32, NULL) > 0); + g_assert (thrift_compact_protocol_write_i32 (protocol, TEST_NI32, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_compact_protocol_write_i64 (protocol, TEST_NI64, NULL) > 0); + g_assert (thrift_compact_protocol_write_i64 (protocol, TEST_NI64, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_compact_protocol_write_i16 (protocol, 2, NULL) > 0); + g_assert (thrift_compact_protocol_write_i16 (protocol, 2, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_compact_protocol_write_i32 (protocol, 2, NULL) > 0); + g_assert (thrift_compact_protocol_write_i32 (protocol, 2, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_compact_protocol_write_i64 (protocol, 2, NULL) > 0); + g_assert (thrift_compact_protocol_write_i64 (protocol, 2, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_compact_protocol_write_i16 (protocol, -2, NULL) > 0); + g_assert (thrift_compact_protocol_write_i16 (protocol, -2, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_compact_protocol_write_i32 (protocol, -2, NULL) > 0); + g_assert (thrift_compact_protocol_write_i32 (protocol, -2, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_compact_protocol_write_i64 (protocol, -2, NULL) > 0); + g_assert (thrift_compact_protocol_write_i64 (protocol, -2, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_compact_protocol_write_double (protocol, + g_assert (thrift_compact_protocol_write_double (protocol, TEST_DOUBLE, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_compact_protocol_write_string (protocol, + g_assert (thrift_compact_protocol_write_string (protocol, TEST_STRING, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_compact_protocol_write_binary (protocol, binary, + g_assert (thrift_compact_protocol_write_string (protocol, "", NULL) > 0); + thrift_transport_flush (transport, NULL); + g_assert (thrift_compact_protocol_write_binary (protocol, binary, len, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_compact_protocol_write_binary (protocol, NULL, + g_assert (thrift_compact_protocol_write_binary (protocol, NULL, 0, NULL) > 0); thrift_transport_flush (transport, NULL); - assert (thrift_compact_protocol_write_binary (protocol, binary, + g_assert (thrift_compact_protocol_write_binary (protocol, binary, len, NULL) > 0); thrift_transport_flush (transport, NULL); @@ -652,8 +654,8 @@ test_read_and_write_many_frames (void) g_object_unref (ft); g_object_unref (tsocket); g_object_unref (tc); - assert (wait (&status) == pid); - assert (status == 0); + g_assert (wait (&status) == pid); + g_assert (status == 0); } } @@ -677,6 +679,7 @@ thrift_server_primitives (const int port) gint64 value_n64 = 0; gdouble value_double = 0; gchar *string = NULL; + gchar *empty_string = NULL; gpointer binary = NULL; guint32 len = 0; void *comparator = (void *) TEST_STRING; @@ -686,83 +689,90 @@ thrift_server_primitives (const int port) transport = THRIFT_SERVER_TRANSPORT (tsocket); thrift_server_transport_listen (transport, NULL); client = thrift_server_transport_accept (transport, NULL); - assert (client != NULL); + g_assert (client != NULL); tc = g_object_new (THRIFT_TYPE_COMPACT_PROTOCOL, "transport", client, NULL); protocol = THRIFT_PROTOCOL (tc); - assert (thrift_compact_protocol_read_bool (protocol, + g_assert (thrift_compact_protocol_read_bool (protocol, &value_boolean, NULL) > 0); - assert (thrift_compact_protocol_read_byte (protocol, &value_byte, NULL) > 0); - assert (thrift_compact_protocol_read_i16 (protocol, &value_16, NULL) > 0); - assert (thrift_compact_protocol_read_i32 (protocol, &value_32, NULL) > 0); - assert (thrift_compact_protocol_read_i64 (protocol, &value_64, NULL) > 0); - assert (thrift_compact_protocol_read_i16 (protocol, &value_n16, NULL) > 0); - assert (thrift_compact_protocol_read_i32 (protocol, &value_n32, NULL) > 0); - assert (thrift_compact_protocol_read_i64 (protocol, &value_n64, NULL) > 0); - assert (thrift_compact_protocol_read_byte (protocol, &zigzag_p16, NULL) > 0); - assert (thrift_compact_protocol_read_byte (protocol, &zigzag_p32, NULL) > 0); - assert (thrift_compact_protocol_read_byte (protocol, &zigzag_p64, NULL) > 0); - assert (thrift_compact_protocol_read_byte (protocol, &zigzag_n16, NULL) > 0); - assert (thrift_compact_protocol_read_byte (protocol, &zigzag_n32, NULL) > 0); - assert (thrift_compact_protocol_read_byte (protocol, &zigzag_n64, NULL) > 0); - assert (thrift_compact_protocol_read_double (protocol, + g_assert (thrift_compact_protocol_read_byte (protocol, &value_byte, NULL) > 0); + g_assert (thrift_compact_protocol_read_i16 (protocol, &value_16, NULL) > 0); + g_assert (thrift_compact_protocol_read_i32 (protocol, &value_32, NULL) > 0); + g_assert (thrift_compact_protocol_read_i64 (protocol, &value_64, NULL) > 0); + g_assert (thrift_compact_protocol_read_i16 (protocol, &value_n16, NULL) > 0); + g_assert (thrift_compact_protocol_read_i32 (protocol, &value_n32, NULL) > 0); + g_assert (thrift_compact_protocol_read_i64 (protocol, &value_n64, NULL) > 0); + g_assert (thrift_compact_protocol_read_byte (protocol, &zigzag_p16, NULL) > 0); + g_assert (thrift_compact_protocol_read_byte (protocol, &zigzag_p32, NULL) > 0); + g_assert (thrift_compact_protocol_read_byte (protocol, &zigzag_p64, NULL) > 0); + g_assert (thrift_compact_protocol_read_byte (protocol, &zigzag_n16, NULL) > 0); + g_assert (thrift_compact_protocol_read_byte (protocol, &zigzag_n32, NULL) > 0); + g_assert (thrift_compact_protocol_read_byte (protocol, &zigzag_n64, NULL) > 0); + g_assert (thrift_compact_protocol_read_double (protocol, &value_double, NULL) > 0); - assert (thrift_compact_protocol_read_string (protocol, &string, NULL) > 0); - assert (thrift_compact_protocol_read_binary (protocol, &binary, + g_assert (thrift_compact_protocol_read_string (protocol, &string, NULL) > 0); + g_assert (thrift_compact_protocol_read_string (protocol, &empty_string, + NULL) > 0); + g_assert (thrift_compact_protocol_read_binary (protocol, &binary, &len, NULL) > 0); - assert (value_boolean == TEST_BOOL); - assert (value_byte == TEST_BYTE); - assert (value_16 == TEST_I16); - assert (value_32 == TEST_I32); - assert (value_64 == TEST_I64); - assert (value_n16 == TEST_NI16); - assert (value_n32 == TEST_NI32); - assert (value_n64 == TEST_NI64); - assert (zigzag_p16 == 4); - assert (zigzag_p32 == 4); - assert (zigzag_p64 == 4); - assert (zigzag_n16 == 3); - assert (zigzag_n32 == 3); - assert (zigzag_n64 == 3); - assert (value_double == TEST_DOUBLE); - assert (strcmp (TEST_STRING, string) == 0); - assert (memcmp (comparator, binary, len) == 0); + g_assert (value_boolean == TEST_BOOL); + g_assert (value_byte == TEST_BYTE); + g_assert (value_16 == TEST_I16); + g_assert (value_32 == TEST_I32); + g_assert (value_64 == TEST_I64); + g_assert (value_n16 == TEST_NI16); + g_assert (value_n32 == TEST_NI32); + g_assert (value_n64 == TEST_NI64); + g_assert (zigzag_p16 == 4); + g_assert (zigzag_p32 == 4); + g_assert (zigzag_p64 == 4); + g_assert (zigzag_n16 == 3); + g_assert (zigzag_n32 == 3); + g_assert (zigzag_n64 == 3); + g_assert (value_double == TEST_DOUBLE); + g_assert (strcmp (TEST_STRING, string) == 0); + g_assert (strcmp ("", empty_string) == 0); + g_assert (memcmp (comparator, binary, len) == 0); g_free (string); + g_free (empty_string); g_free (binary); - thrift_compact_protocol_read_binary (protocol, &binary, &len, NULL); + g_assert (thrift_compact_protocol_read_binary (protocol, &binary, + &len, NULL) > 0); + g_assert (binary == NULL); + g_assert (len == 0); g_free (binary); transport_read_count = 0; transport_read_error_at = 0; - assert (thrift_compact_protocol_read_binary (protocol, &binary, + g_assert (thrift_compact_protocol_read_binary (protocol, &binary, &len, NULL) == -1); transport_read_error_at = -1; transport_read_count = 0; transport_read_error_at = 1; - assert (thrift_compact_protocol_read_binary (protocol, &binary, + g_assert (thrift_compact_protocol_read_binary (protocol, &binary, &len, NULL) == -1); transport_read_error_at = -1; transport_read_error = 1; - assert (thrift_compact_protocol_read_bool (protocol, + g_assert (thrift_compact_protocol_read_bool (protocol, &value_boolean, NULL) == -1); - assert (thrift_compact_protocol_read_byte (protocol, + g_assert (thrift_compact_protocol_read_byte (protocol, &value_byte, NULL) == -1); - assert (thrift_compact_protocol_read_i16 (protocol, + g_assert (thrift_compact_protocol_read_i16 (protocol, &value_16, NULL) == -1); - assert (thrift_compact_protocol_read_i32 (protocol, &value_32, NULL) == -1); - assert (thrift_compact_protocol_read_i64 (protocol, &value_64, NULL) == -1); - assert (thrift_compact_protocol_read_i16 (protocol, + g_assert (thrift_compact_protocol_read_i32 (protocol, &value_32, NULL) == -1); + g_assert (thrift_compact_protocol_read_i64 (protocol, &value_64, NULL) == -1); + g_assert (thrift_compact_protocol_read_i16 (protocol, &value_n16, NULL) == -1); - assert (thrift_compact_protocol_read_i32 (protocol, &value_n32, NULL) == -1); - assert (thrift_compact_protocol_read_i64 (protocol, &value_n64, NULL) == -1); - assert (thrift_compact_protocol_read_double (protocol, + g_assert (thrift_compact_protocol_read_i32 (protocol, &value_n32, NULL) == -1); + g_assert (thrift_compact_protocol_read_i64 (protocol, &value_n64, NULL) == -1); + g_assert (thrift_compact_protocol_read_double (protocol, &value_double, NULL) == -1); transport_read_error = 0; @@ -802,7 +812,7 @@ thrift_server_complex_types (const int port) transport = THRIFT_SERVER_TRANSPORT (tsocket); thrift_server_transport_listen (transport, NULL); client = thrift_server_transport_accept (transport, NULL); - assert (client != NULL); + g_assert (client != NULL); tc = g_object_new (THRIFT_TYPE_COMPACT_PROTOCOL, "transport", client, NULL); @@ -816,40 +826,40 @@ thrift_server_complex_types (const int port) /* test field state w.r.t. deltas */ field_id = 0; - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) == 1); - assert (field_id == 1); + g_assert (field_id == 1); field_id = 0; - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) == 1); - assert (field_id == 16); + g_assert (field_id == 16); field_id = 0; - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) == 1); - assert (field_id == 17); + g_assert (field_id == 17); field_id = 0; - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) > 1); - assert (field_id == 15); + g_assert (field_id == 15); field_id = 0; - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) == 1); - assert (field_id == 30); + g_assert (field_id == 30); field_id = 0; - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) > 1); - assert (field_id == 46); + g_assert (field_id == 46); field_id = 0; - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) == 1); - assert (field_id == 47); + g_assert (field_id == 47); field_id = 0; /* test field operations */ @@ -860,62 +870,62 @@ thrift_server_complex_types (const int port) /* test field state w.r.t. structs */ - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) > 1); - assert (field_id == 1); + g_assert (field_id == 1); field_id = 0; thrift_compact_protocol_read_field_end (protocol, NULL); - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) == 1); - assert (field_id == 16); + g_assert (field_id == 16); field_id = 0; thrift_compact_protocol_read_field_end (protocol, NULL); - assert (thrift_compact_protocol_read_struct_begin (protocol, + g_assert (thrift_compact_protocol_read_struct_begin (protocol, &struct_name, NULL) == 0); - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) > 1); - assert (field_id == 17); + g_assert (field_id == 17); field_id = 0; thrift_compact_protocol_read_field_end (protocol, NULL); - assert (thrift_compact_protocol_read_struct_begin (protocol, + g_assert (thrift_compact_protocol_read_struct_begin (protocol, &struct_name, NULL) == 0); - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) > 1); - assert (field_id == 18); + g_assert (field_id == 18); field_id = 0; thrift_compact_protocol_read_field_end (protocol, NULL); - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) == 1); - assert (field_id == 19); + g_assert (field_id == 19); field_id = 0; thrift_compact_protocol_read_field_end (protocol, NULL); - assert (thrift_compact_protocol_read_struct_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_read_struct_end (protocol, NULL) == 0); - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) == 1); - assert (field_id == 18); + g_assert (field_id == 18); field_id = 0; thrift_compact_protocol_read_field_end (protocol, NULL); - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) == 1); - assert (field_id == 25); + g_assert (field_id == 25); field_id = 0; thrift_compact_protocol_read_field_end (protocol, NULL); - assert (thrift_compact_protocol_read_struct_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_read_struct_end (protocol, NULL) == 0); - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) == 1); - assert (field_id == 17); + g_assert (field_id == 17); field_id = 0; thrift_compact_protocol_read_field_end (protocol, NULL); @@ -923,83 +933,83 @@ thrift_server_complex_types (const int port) /* deltas */ /* non-bool field -> bool field -> non-bool field */ - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) == 1); thrift_compact_protocol_read_field_end (protocol, NULL); - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) == 1); - assert (field_type == T_BOOL); - assert (thrift_compact_protocol_read_bool (protocol, + g_assert (field_type == T_BOOL); + g_assert (thrift_compact_protocol_read_bool (protocol, &value_boolean, NULL) == 0); - assert (value_boolean == TEST_BOOL); + g_assert (value_boolean == TEST_BOOL); value_boolean = ! TEST_BOOL; thrift_compact_protocol_read_field_end (protocol, NULL); - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) == 1); thrift_compact_protocol_read_field_end (protocol, NULL); /* bool -> bool field -> bool */ - assert (thrift_compact_protocol_read_bool (protocol, + g_assert (thrift_compact_protocol_read_bool (protocol, &value_boolean, NULL) > 0); - assert (value_boolean == TEST_BOOL); + g_assert (value_boolean == TEST_BOOL); value_boolean = ! TEST_BOOL; - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) == 1); - assert (field_type == T_BOOL); - assert (thrift_compact_protocol_read_bool (protocol, + g_assert (field_type == T_BOOL); + g_assert (thrift_compact_protocol_read_bool (protocol, &value_boolean, NULL) == 0); - assert (value_boolean == TEST_BOOL); + g_assert (value_boolean == TEST_BOOL); value_boolean = ! TEST_BOOL; thrift_compact_protocol_read_field_end (protocol, NULL); - assert (thrift_compact_protocol_read_bool (protocol, + g_assert (thrift_compact_protocol_read_bool (protocol, &value_boolean, NULL) > 0); - assert (value_boolean == TEST_BOOL); + g_assert (value_boolean == TEST_BOOL); value_boolean = ! TEST_BOOL; /* no deltas */ /* non-bool field -> bool field -> non-bool field */ - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) > 1); thrift_compact_protocol_read_field_end (protocol, NULL); - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) > 1); - assert (field_type == T_BOOL); - assert (thrift_compact_protocol_read_bool (protocol, + g_assert (field_type == T_BOOL); + g_assert (thrift_compact_protocol_read_bool (protocol, &value_boolean, NULL) == 0); - assert (value_boolean == TEST_BOOL); + g_assert (value_boolean == TEST_BOOL); value_boolean = ! TEST_BOOL; thrift_compact_protocol_read_field_end (protocol, NULL); - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) > 1); thrift_compact_protocol_read_field_end (protocol, NULL); /* bool -> bool field -> bool */ - assert (thrift_compact_protocol_read_bool (protocol, + g_assert (thrift_compact_protocol_read_bool (protocol, &value_boolean, NULL) > 0); - assert (value_boolean == TEST_BOOL); + g_assert (value_boolean == TEST_BOOL); value_boolean = ! TEST_BOOL; - assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) > 1); - assert (field_type == T_BOOL); - assert (thrift_compact_protocol_read_bool (protocol, + g_assert (field_type == T_BOOL); + g_assert (thrift_compact_protocol_read_bool (protocol, &value_boolean, NULL) == 0); - assert (value_boolean == TEST_BOOL); + g_assert (value_boolean == TEST_BOOL); value_boolean = ! TEST_BOOL; thrift_compact_protocol_read_field_end (protocol, NULL); - assert (thrift_compact_protocol_read_bool (protocol, + g_assert (thrift_compact_protocol_read_bool (protocol, &value_boolean, NULL) > 0); - assert (value_boolean == TEST_BOOL); + g_assert (value_boolean == TEST_BOOL); value_boolean = ! TEST_BOOL; /* test first read error on a field */ transport_read_error = 1; - assert (thrift_compact_protocol_read_field_begin (protocol, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) == -1); transport_read_error = 0; @@ -1010,7 +1020,7 @@ thrift_server_complex_types (const int port) /* test 2nd read failure on a field */ transport_read_count = 0; transport_read_error_at = 1; - assert (thrift_compact_protocol_read_field_begin (protocol, + g_assert (thrift_compact_protocol_read_field_begin (protocol, &field_name, &field_type, &field_id, NULL) == -1); transport_read_error_at = -1; @@ -1028,7 +1038,7 @@ thrift_server_complex_types (const int port) /* test 1st read failure on a map */ transport_read_count = 0; transport_read_error_at = 0; - assert (thrift_compact_protocol_read_map_begin (protocol, + g_assert (thrift_compact_protocol_read_map_begin (protocol, &key_type, &value_type, &size, NULL) == -1); transport_read_error_at = -1; @@ -1036,7 +1046,7 @@ thrift_server_complex_types (const int port) /* test 2nd read failure on a map */ transport_read_count = 0; transport_read_error_at = 1; - assert (thrift_compact_protocol_read_map_begin (protocol, + g_assert (thrift_compact_protocol_read_map_begin (protocol, &key_type, &value_type, &size, NULL) == -1); transport_read_error_at = -1; @@ -1047,7 +1057,7 @@ thrift_server_complex_types (const int port) thrift_compact_protocol_read_byte (protocol, &value, NULL); /* test negative map size */ - assert (thrift_compact_protocol_read_map_begin (protocol, + g_assert (thrift_compact_protocol_read_map_begin (protocol, &key_type, &value_type, &size, NULL) == -1); @@ -1058,13 +1068,13 @@ thrift_server_complex_types (const int port) /* test small list 1st read failure */ transport_read_error = 1; - assert (thrift_compact_protocol_read_list_begin (protocol, &element_type, + g_assert (thrift_compact_protocol_read_list_begin (protocol, &element_type, &size, NULL) == -1); transport_read_error = 0; /* test big list 1st read failure */ transport_read_error = 1; - assert (thrift_compact_protocol_read_list_begin (protocol, &element_type, + g_assert (thrift_compact_protocol_read_list_begin (protocol, &element_type, &size, NULL) == -1); transport_read_error = 0; @@ -1092,23 +1102,23 @@ thrift_server_complex_types (const int port) /* broken read */ transport_read_error = 1; - assert (thrift_compact_protocol_read_message_begin (protocol, &message_name, + g_assert (thrift_compact_protocol_read_message_begin (protocol, &message_name, &message_type, &seqid, NULL) == -1); transport_read_error = 0; /* invalid protocol */ - assert (thrift_compact_protocol_read_message_begin (protocol, &message_name, + g_assert (thrift_compact_protocol_read_message_begin (protocol, &message_name, &message_type, &seqid, NULL) == -1); /* invalid version */ - assert (thrift_compact_protocol_read_message_begin (protocol, &message_name, + g_assert (thrift_compact_protocol_read_message_begin (protocol, &message_name, &message_type, &seqid, NULL) == -1); /* read a valid message */ - assert (thrift_compact_protocol_read_message_begin (protocol, &message_name, + g_assert (thrift_compact_protocol_read_message_begin (protocol, &message_name, &message_type, &seqid, NULL) > 0); g_free (message_name); @@ -1116,7 +1126,7 @@ thrift_server_complex_types (const int port) /* broken 2nd read on a message */ transport_read_count = 0; transport_read_error_at = 1; - assert (thrift_compact_protocol_read_message_begin (protocol, &message_name, + g_assert (thrift_compact_protocol_read_message_begin (protocol, &message_name, &message_type, &seqid, NULL) == -1); transport_read_error_at = -1; @@ -1124,7 +1134,7 @@ thrift_server_complex_types (const int port) /* broken 3rd read on a message */ transport_read_count = 0; transport_read_error_at = 2; - assert (thrift_compact_protocol_read_message_begin (protocol, &message_name, + g_assert (thrift_compact_protocol_read_message_begin (protocol, &message_name, &message_type, &seqid, NULL) == -1); transport_read_error_at = -1; @@ -1132,18 +1142,18 @@ thrift_server_complex_types (const int port) /* broken 4th read on a message */ transport_read_count = 0; transport_read_error_at = 3; - assert (thrift_compact_protocol_read_message_begin (protocol, &message_name, + g_assert (thrift_compact_protocol_read_message_begin (protocol, &message_name, &message_type, &seqid, NULL) == -1); transport_read_error_at = -1; /* read a valid message */ - assert (thrift_compact_protocol_read_message_begin (protocol, &message_name, + g_assert (thrift_compact_protocol_read_message_begin (protocol, &message_name, &message_type, &seqid, NULL) > 0); g_free (message_name); - assert (thrift_compact_protocol_read_message_end (protocol, NULL) == 0); + g_assert (thrift_compact_protocol_read_message_end (protocol, NULL) == 0); /* handle 2nd write failure on a message */ thrift_compact_protocol_read_byte (protocol, &protocol_id, NULL); @@ -1181,6 +1191,7 @@ thrift_server_many_frames (const int port) gint64 value_n64 = 0; gdouble value_double = 0; gchar *string = NULL; + gchar *empty_string = NULL; gpointer binary = NULL; guint32 len = 0; void *comparator = (void *) TEST_STRING; @@ -1193,52 +1204,62 @@ thrift_server_many_frames (const int port) client = g_object_new (THRIFT_TYPE_FRAMED_TRANSPORT, "transport", thrift_server_transport_accept (transport, NULL), "r_buf_size", 1, NULL); - assert (client != NULL); + g_assert (client != NULL); tcp = g_object_new (THRIFT_TYPE_COMPACT_PROTOCOL, "transport", client, NULL); protocol = THRIFT_PROTOCOL (tcp); - assert (thrift_compact_protocol_read_bool (protocol, + g_assert (thrift_compact_protocol_read_bool (protocol, &value_boolean, NULL) > 0); - assert (thrift_compact_protocol_read_byte (protocol, &value_byte, NULL) > 0); - assert (thrift_compact_protocol_read_i16 (protocol, &value_16, NULL) > 0); - assert (thrift_compact_protocol_read_i32 (protocol, &value_32, NULL) > 0); - assert (thrift_compact_protocol_read_i64 (protocol, &value_64, NULL) > 0); - assert (thrift_compact_protocol_read_i16 (protocol, &value_n16, NULL) > 0); - assert (thrift_compact_protocol_read_i32 (protocol, &value_n32, NULL) > 0); - assert (thrift_compact_protocol_read_i64 (protocol, &value_n64, NULL) > 0); - assert (thrift_compact_protocol_read_byte (protocol, &zigzag_p16, NULL) > 0); - assert (thrift_compact_protocol_read_byte (protocol, &zigzag_p32, NULL) > 0); - assert (thrift_compact_protocol_read_byte (protocol, &zigzag_p64, NULL) > 0); - assert (thrift_compact_protocol_read_byte (protocol, &zigzag_n16, NULL) > 0); - assert (thrift_compact_protocol_read_byte (protocol, &zigzag_n32, NULL) > 0); - assert (thrift_compact_protocol_read_byte (protocol, &zigzag_n64, NULL) > 0); - assert (thrift_compact_protocol_read_double (protocol, + g_assert (thrift_compact_protocol_read_byte (protocol, &value_byte, NULL) > 0); + g_assert (thrift_compact_protocol_read_i16 (protocol, &value_16, NULL) > 0); + g_assert (thrift_compact_protocol_read_i32 (protocol, &value_32, NULL) > 0); + g_assert (thrift_compact_protocol_read_i64 (protocol, &value_64, NULL) > 0); + g_assert (thrift_compact_protocol_read_i16 (protocol, &value_n16, NULL) > 0); + g_assert (thrift_compact_protocol_read_i32 (protocol, &value_n32, NULL) > 0); + g_assert (thrift_compact_protocol_read_i64 (protocol, &value_n64, NULL) > 0); + g_assert (thrift_compact_protocol_read_byte (protocol, &zigzag_p16, NULL) > 0); + g_assert (thrift_compact_protocol_read_byte (protocol, &zigzag_p32, NULL) > 0); + g_assert (thrift_compact_protocol_read_byte (protocol, &zigzag_p64, NULL) > 0); + g_assert (thrift_compact_protocol_read_byte (protocol, &zigzag_n16, NULL) > 0); + g_assert (thrift_compact_protocol_read_byte (protocol, &zigzag_n32, NULL) > 0); + g_assert (thrift_compact_protocol_read_byte (protocol, &zigzag_n64, NULL) > 0); + g_assert (thrift_compact_protocol_read_double (protocol, &value_double, NULL) > 0); - assert (thrift_compact_protocol_read_string (protocol, &string, NULL) > 0); - assert (thrift_compact_protocol_read_binary (protocol, &binary, + g_assert (thrift_compact_protocol_read_string (protocol, &string, NULL) > 0); + g_assert (thrift_compact_protocol_read_string (protocol, &empty_string, + NULL) > 0); + g_assert (thrift_compact_protocol_read_binary (protocol, &binary, &len, NULL) > 0); - assert (value_boolean == TEST_BOOL); - assert (value_byte == TEST_BYTE); - assert (value_16 == TEST_I16); - assert (value_32 == TEST_I32); - assert (value_64 == TEST_I64); - assert (value_n16 == TEST_NI16); - assert (value_n32 == TEST_NI32); - assert (value_n64 == TEST_NI64); - assert (zigzag_p16 == 4); - assert (zigzag_p32 == 4); - assert (zigzag_p64 == 4); - assert (zigzag_n16 == 3); - assert (zigzag_n32 == 3); - assert (zigzag_n64 == 3); - assert (value_double == TEST_DOUBLE); - assert (strcmp (TEST_STRING, string) == 0); - assert (memcmp (comparator, binary, len) == 0); + g_assert (value_boolean == TEST_BOOL); + g_assert (value_byte == TEST_BYTE); + g_assert (value_16 == TEST_I16); + g_assert (value_32 == TEST_I32); + g_assert (value_64 == TEST_I64); + g_assert (value_n16 == TEST_NI16); + g_assert (value_n32 == TEST_NI32); + g_assert (value_n64 == TEST_NI64); + g_assert (zigzag_p16 == 4); + g_assert (zigzag_p32 == 4); + g_assert (zigzag_p64 == 4); + g_assert (zigzag_n16 == 3); + g_assert (zigzag_n32 == 3); + g_assert (zigzag_n64 == 3); + g_assert (value_double == TEST_DOUBLE); + g_assert (strcmp (TEST_STRING, string) == 0); + g_assert (strcmp ("", empty_string) == 0); + g_assert (memcmp (comparator, binary, len) == 0); g_free (string); + g_free (empty_string); + g_free (binary); + + g_assert (thrift_compact_protocol_read_binary (protocol, &binary, + &len, NULL) > 0); + g_assert (binary == NULL); + g_assert (len == 0); g_free (binary); thrift_transport_read_end (client, NULL); diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testcontainertest.c b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testcontainertest.c index 1cbc55c..5fc51d5 100644 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testcontainertest.c +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testcontainertest.c @@ -512,13 +512,12 @@ main(int argc, char *argv[]) THRIFT_SERVER_SOCKET_ERROR_ACCEPT)); /* Free our resources */ - g_object_unref (server); - g_object_unref (transport_factory); - g_object_unref (protocol_factory); - g_object_unref (server_transport); - - g_object_unref (processor); - g_object_unref (handler); + g_clear_object (&server); + g_clear_object (&protocol_factory); + g_clear_object (&transport_factory); + g_clear_object (&server_transport); + g_clear_object (&processor); + g_clear_object (&handler); /* Wait for the child process to complete and return its exit status */ g_assert (wait (&status) == pid); @@ -527,4 +526,4 @@ main(int argc, char *argv[]) return exit_status; } -} \ No newline at end of file +} diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testdebugproto.c b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testdebugproto.c index 47ac588..109a48b 100644 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testdebugproto.c +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testdebugproto.c @@ -17,7 +17,6 @@ * under the License. */ -#include #include #include #include @@ -838,11 +837,11 @@ test_services_inherited (void) NULL); /* TTestInheritedClient inherits from TTestSrvClient */ - assert (g_type_is_a (T_TEST_TYPE_INHERITED_CLIENT, + g_assert (g_type_is_a (T_TEST_TYPE_INHERITED_CLIENT, T_TEST_TYPE_SRV_CLIENT)); /* TTestInheritedClient implements TTestSrvClient's interface */ - assert (g_type_is_a (T_TEST_TYPE_INHERITED_CLIENT, + g_assert (g_type_is_a (T_TEST_TYPE_INHERITED_CLIENT, T_TEST_TYPE_SRV_IF)); /* TTestInheritedClient's inherited properties can be set and retrieved */ @@ -856,8 +855,8 @@ test_services_inherited (void) "output_protocol", &output_protocol, NULL); - assert (input_protocol == G_OBJECT(protocol)); - assert (output_protocol == G_OBJECT(protocol)); + g_assert (input_protocol == G_OBJECT(protocol)); + g_assert (output_protocol == G_OBJECT(protocol)); g_object_unref (output_protocol); g_object_unref (input_protocol); diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testfdtransport.c b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testfdtransport.c index 40c1acf..1ea89be 100755 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testfdtransport.c +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testfdtransport.c @@ -17,7 +17,6 @@ * under the License. */ -#include #include #include @@ -37,7 +36,7 @@ test_create_and_destroy (void) { GObject *object; object = g_object_new (THRIFT_TYPE_FD_TRANSPORT, "fd", -1, NULL); - assert (object != NULL); + g_assert (object != NULL); g_object_unref (object); } @@ -54,7 +53,7 @@ test_open_and_close (void) filename = NULL; fd = g_file_open_tmp (NULL, &filename, &error); - assert (fd >= 0); + g_assert (fd >= 0); transport = THRIFT_TRANSPORT (g_object_new (THRIFT_TYPE_FD_TRANSPORT, "fd", fd, @@ -62,20 +61,20 @@ test_open_and_close (void) klass = THRIFT_TRANSPORT_GET_CLASS (transport); /* open is no-op */ - assert (klass->is_open (transport)); - assert (klass->peek (transport, &error)); - assert (klass->open (transport, &error)); - assert (klass->is_open (transport)); - assert (klass->peek (transport, &error)); + g_assert (klass->is_open (transport)); + g_assert (klass->peek (transport, &error)); + g_assert (klass->open (transport, &error)); + g_assert (klass->is_open (transport)); + g_assert (klass->peek (transport, &error)); - assert (klass->close (transport, &error)); - assert (! klass->open (transport, &error)); - assert (! klass->is_open (transport)); - assert (! klass->peek (transport, &error)); + g_assert (klass->close (transport, &error)); + g_assert (! klass->open (transport, &error)); + g_assert (! klass->is_open (transport)); + g_assert (! klass->peek (transport, &error)); /* already closed */ - assert (close (fd) != 0); - assert (errno == EBADF); + g_assert (close (fd) != 0); + g_assert (errno == EBADF); g_object_unref (transport); @@ -88,13 +87,13 @@ test_open_and_close (void) NULL)); klass = THRIFT_TRANSPORT_GET_CLASS (transport); - assert (! klass->is_open (transport)); + g_assert (! klass->is_open (transport)); error = NULL; - assert (! klass->peek (transport, &error)); + g_assert (! klass->peek (transport, &error)); error = NULL; - assert (! klass->open (transport, &error)); + g_assert (! klass->open (transport, &error)); error = NULL; - assert (! klass->close (transport, &error)); + g_assert (! klass->close (transport, &error)); g_object_unref (transport); } @@ -115,22 +114,22 @@ test_read_and_write (void) filename = NULL; fd = g_file_open_tmp (NULL, &filename, &error); - assert (fd >= 0); + g_assert (fd >= 0); /* write */ transport = THRIFT_TRANSPORT (g_object_new (THRIFT_TYPE_FD_TRANSPORT, "fd", fd, NULL)); klass = THRIFT_TRANSPORT_GET_CLASS (transport); - assert (klass->is_open (transport)); - assert (klass->write (transport, (gpointer) TEST_DATA, 11, &error)); - assert (klass->flush (transport, &error)); - assert (klass->close (transport, &error)); + g_assert (klass->is_open (transport)); + g_assert (klass->write (transport, (gpointer) TEST_DATA, 11, &error)); + g_assert (klass->flush (transport, &error)); + g_assert (klass->close (transport, &error)); g_object_unref (transport); /* read */ fd = open(filename, O_RDONLY, S_IRUSR | S_IWUSR); - assert (fd >= 0); + g_assert (fd >= 0); transport = THRIFT_TRANSPORT (g_object_new (THRIFT_TYPE_FD_TRANSPORT, "fd", fd, @@ -142,24 +141,24 @@ test_read_and_write (void) want = 7; while (want > 0) { got = klass->read (transport, (gpointer) b, want, &error); - assert (got > 0 && got <= want); + g_assert (got > 0 && got <= want); b += got; want -= got; } - assert (memcmp (out_buf, TEST_DATA, 7) == 0); + g_assert (memcmp (out_buf, TEST_DATA, 7) == 0); memset(out_buf, 0, 8); b = out_buf; want = 4; while (want > 0) { got = klass->read (transport, (gpointer) b, want, &error); - assert (got > 0 && got <= want); + g_assert (got > 0 && got <= want); b += got; want -= got; } - assert (memcmp (out_buf, TEST_DATA + 7, 4) == 0); + g_assert (memcmp (out_buf, TEST_DATA + 7, 4) == 0); - assert (klass->close (transport, &error)); + g_assert (klass->close (transport, &error)); g_object_unref (transport); /* clean up */ diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testframedtransport.c b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testframedtransport.c index d50ff23..45397ce 100755 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testframedtransport.c +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testframedtransport.c @@ -17,7 +17,6 @@ * under the License. */ -#include #include #include @@ -31,6 +30,7 @@ #include "../src/thrift/c_glib/transport/thrift_framed_transport.c" static void thrift_server (const int port); +static void thrift_socket_server_open (const int port, int times); /* test object creation and destruction */ static void @@ -42,10 +42,10 @@ test_create_and_destroy(void) GObject *object = NULL; object = g_object_new (THRIFT_TYPE_FRAMED_TRANSPORT, NULL); - assert (object != NULL); + g_assert (object != NULL); g_object_get (G_OBJECT (object), "transport", &transport, - "r_buf_size", &r_buf_size, - "w_buf_size", &w_buf_size, NULL); + "r_buf_size", &r_buf_size, + "w_buf_size", &w_buf_size, NULL); g_object_unref (object); } @@ -55,35 +55,53 @@ test_open_and_close(void) ThriftSocket *tsocket = NULL; ThriftTransport *transport = NULL; GError *err = NULL; + pid_t pid; + int port = 51199; + int status; - /* create a ThriftSocket */ - tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", - "port", 51188, NULL); + pid = fork (); + g_assert ( pid >= 0 ); - /* create a BufferedTransport wrapper of the Socket */ - transport = g_object_new (THRIFT_TYPE_FRAMED_TRANSPORT, - "transport", THRIFT_TRANSPORT (tsocket), NULL); + if ( pid == 0 ) + { + /* child listens */ + thrift_socket_server_open (port,1); + exit (0); + } else { + /* parent connects, wait a bit for the socket to be created */ + sleep (1); + /* create a ThriftSocket */ + tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", + "port", port, NULL); - /* this shouldn't work */ - assert (thrift_framed_transport_open (transport, NULL) == FALSE); - assert (thrift_framed_transport_is_open (transport) == TRUE); - assert (thrift_framed_transport_close (transport, NULL) == TRUE); - g_object_unref (transport); - g_object_unref (tsocket); + /* create a BufferedTransport wrapper of the Socket */ + transport = g_object_new (THRIFT_TYPE_FRAMED_TRANSPORT, + "transport", THRIFT_TRANSPORT (tsocket), NULL); - /* try and underlying socket failure */ - tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost.broken", - NULL); + /* this shouldn't work */ + g_assert (thrift_framed_transport_open (transport, NULL) == TRUE); + g_assert (thrift_framed_transport_is_open (transport) == TRUE); + g_assert (thrift_framed_transport_close (transport, NULL) == TRUE); + g_object_unref (transport); + g_object_unref (tsocket); - /* create a BufferedTransport wrapper of the Socket */ - transport = g_object_new (THRIFT_TYPE_FRAMED_TRANSPORT, - "transport", THRIFT_TRANSPORT (tsocket), NULL); + /* try and underlying socket failure */ + tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost.broken", + NULL); - assert (thrift_framed_transport_open (transport, &err) == FALSE); - g_object_unref (transport); - g_object_unref (tsocket); - g_error_free (err); - err = NULL; + /* create a BufferedTransport wrapper of the Socket */ + transport = g_object_new (THRIFT_TYPE_FRAMED_TRANSPORT, + "transport", THRIFT_TRANSPORT (tsocket), NULL); + + g_assert (thrift_framed_transport_open (transport, &err) == FALSE); + g_object_unref (transport); + g_object_unref (tsocket); + g_error_free (err); + err = NULL; + + g_assert ( wait (&status) == pid ); + g_assert ( status == 0 ); + } } static void @@ -97,49 +115,49 @@ test_read_and_write(void) guchar buf[10] = TEST_DATA; /* a buffer */ pid = fork (); - assert ( pid >= 0 ); + g_assert ( pid >= 0 ); if ( pid == 0 ) - { - /* child listens */ - thrift_server (port); - exit (0); - } else { - /* parent connects, wait a bit for the socket to be created */ - sleep (1); + { + /* child listens */ + thrift_server (port); + exit (0); + } else { + /* parent connects, wait a bit for the socket to be created */ + sleep (1); - tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", - "port", port, NULL); - transport = g_object_new (THRIFT_TYPE_FRAMED_TRANSPORT, - "transport", THRIFT_TRANSPORT (tsocket), - "w_buf_size", 4, NULL); + tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", + "port", port, NULL); + transport = g_object_new (THRIFT_TYPE_FRAMED_TRANSPORT, + "transport", THRIFT_TRANSPORT (tsocket), + "w_buf_size", 4, NULL); - assert (thrift_framed_transport_open (transport, NULL) == TRUE); - assert (thrift_framed_transport_is_open (transport)); + g_assert (thrift_framed_transport_open (transport, NULL) == TRUE); + g_assert (thrift_framed_transport_is_open (transport)); - /* write 10 bytes */ - thrift_framed_transport_write (transport, buf, 10, NULL); - thrift_framed_transport_flush (transport, NULL); + /* write 10 bytes */ + thrift_framed_transport_write (transport, buf, 10, NULL); + thrift_framed_transport_flush (transport, NULL); - thrift_framed_transport_write (transport, buf, 1, NULL); - thrift_framed_transport_flush (transport, NULL); + thrift_framed_transport_write (transport, buf, 1, NULL); + thrift_framed_transport_flush (transport, NULL); - thrift_framed_transport_write (transport, buf, 10, NULL); - thrift_framed_transport_flush (transport, NULL); + thrift_framed_transport_write (transport, buf, 10, NULL); + thrift_framed_transport_flush (transport, NULL); - thrift_framed_transport_write (transport, buf, 10, NULL); - thrift_framed_transport_flush (transport, NULL); + thrift_framed_transport_write (transport, buf, 10, NULL); + thrift_framed_transport_flush (transport, NULL); - thrift_framed_transport_write_end (transport, NULL); - thrift_framed_transport_flush (transport, NULL); - thrift_framed_transport_close (transport, NULL); + thrift_framed_transport_write_end (transport, NULL); + thrift_framed_transport_flush (transport, NULL); + thrift_framed_transport_close (transport, NULL); - g_object_unref (transport); - g_object_unref (tsocket); + g_object_unref (transport); + g_object_unref (tsocket); - assert ( wait (&status) == pid ); - assert ( status == 0 ); - } + g_assert ( wait (&status) == pid ); + g_assert ( status == 0 ); + } } /* test reading from the transport after the peer has unexpectedly @@ -156,76 +174,100 @@ test_read_after_peer_close(void) g_assert (pid >= 0); if (pid == 0) - { - ThriftServerTransport *server_transport = NULL; - ThriftTransport *client_transport = NULL; + { + ThriftServerTransport *server_transport = NULL; + ThriftTransport *client_transport = NULL; - /* child listens */ - server_transport = g_object_new (THRIFT_TYPE_SERVER_SOCKET, - "port", port, - NULL); - g_assert (server_transport != NULL); + /* child listens */ + server_transport = g_object_new (THRIFT_TYPE_SERVER_SOCKET, + "port", port, + NULL); + g_assert (server_transport != NULL); - thrift_server_transport_listen (server_transport, &err); - g_assert (err == NULL); + thrift_server_transport_listen (server_transport, &err); + g_assert (err == NULL); - /* wrap the client transport in a ThriftFramedTransport */ - client_transport = g_object_new - (THRIFT_TYPE_FRAMED_TRANSPORT, - "transport", thrift_server_transport_accept (server_transport, &err), - "r_buf_size", 0, - NULL); - g_assert (err == NULL); - g_assert (client_transport != NULL); + /* wrap the client transport in a ThriftFramedTransport */ + client_transport = g_object_new + (THRIFT_TYPE_FRAMED_TRANSPORT, + "transport", thrift_server_transport_accept (server_transport, &err), + "r_buf_size", 0, + NULL); + g_assert (err == NULL); + g_assert (client_transport != NULL); - /* close the connection immediately after the client connects */ - thrift_transport_close (client_transport, NULL); + /* close the connection immediately after the client connects */ + thrift_transport_close (client_transport, NULL); - g_object_unref (client_transport); - g_object_unref (server_transport); + g_object_unref (client_transport); + g_object_unref (server_transport); - exit (0); - } else { - ThriftSocket *tsocket = NULL; - ThriftTransport *transport = NULL; - guchar buf[10]; /* a buffer */ + exit (0); + } else { + ThriftSocket *tsocket = NULL; + ThriftTransport *transport = NULL; + guchar buf[10]; /* a buffer */ - /* parent connects, wait a bit for the socket to be created */ - sleep (1); + /* parent connects, wait a bit for the socket to be created */ + sleep (1); - tsocket = g_object_new (THRIFT_TYPE_SOCKET, - "hostname", "localhost", - "port", port, - NULL); - transport = g_object_new (THRIFT_TYPE_FRAMED_TRANSPORT, - "transport", THRIFT_TRANSPORT (tsocket), - "w_buf_size", 0, - NULL); + tsocket = g_object_new (THRIFT_TYPE_SOCKET, + "hostname", "localhost", + "port", port, + NULL); + transport = g_object_new (THRIFT_TYPE_FRAMED_TRANSPORT, + "transport", THRIFT_TRANSPORT (tsocket), + "w_buf_size", 0, + NULL); - g_assert (thrift_transport_open (transport, NULL) == TRUE); - g_assert (thrift_transport_is_open (transport)); + g_assert (thrift_transport_open (transport, NULL) == TRUE); + g_assert (thrift_transport_is_open (transport)); - /* attempting to read from the transport after the peer has closed + /* attempting to read from the transport after the peer has closed the connection fails gracefully without generating a critical warning or segmentation fault */ - thrift_transport_read (transport, buf, 10, &err); - g_assert (err != NULL); + thrift_transport_read (transport, buf, 10, &err); + g_assert (err != NULL); - g_error_free (err); - err = NULL; + g_error_free (err); + err = NULL; - thrift_transport_read_end (transport, &err); - g_assert (err == NULL); + thrift_transport_read_end (transport, &err); + g_assert (err == NULL); - thrift_transport_close (transport, &err); - g_assert (err == NULL); + thrift_transport_close (transport, &err); + g_assert (err == NULL); - g_object_unref (transport); - g_object_unref (tsocket); + g_object_unref (transport); + g_object_unref (tsocket); - g_assert (wait (&status) == pid); - g_assert (status == 0); + g_assert (wait (&status) == pid); + g_assert (status == 0); + } +} + +static void +thrift_socket_server_open (const int port, int times) +{ + int bytes = 0; + ThriftServerTransport *transport = NULL; + ThriftTransport *client = NULL; + guchar buf[10]; /* a buffer */ + guchar match[10] = TEST_DATA; + int i; + + ThriftServerSocket *tsocket = g_object_new (THRIFT_TYPE_SERVER_SOCKET, + "port", port, NULL); + + transport = THRIFT_SERVER_TRANSPORT (tsocket); + thrift_server_transport_listen (transport, NULL); + for(i=0;i #include #include @@ -37,7 +36,7 @@ test_create_and_destroy (void) object = g_object_new (THRIFT_TYPE_MEMORY_BUFFER, "buf_size", 10, NULL); - assert (object != NULL); + g_assert (object != NULL); g_object_unref (object); } @@ -48,7 +47,7 @@ test_create_and_destroy_large (void) object = g_object_new (THRIFT_TYPE_MEMORY_BUFFER, "buf_size", 10 * 1024 * 1024, NULL); - assert (object != NULL); + g_assert (object != NULL); g_object_unref (object); } @@ -57,7 +56,7 @@ test_create_and_destroy_default (void) { GObject *object = NULL; object = g_object_new (THRIFT_TYPE_MEMORY_BUFFER, NULL); - assert (object != NULL); + g_assert (object != NULL); g_object_unref (object); } @@ -66,11 +65,11 @@ test_create_and_destroy_external (void) { GObject *object = NULL; GByteArray *buf = g_byte_array_new (); - assert (buf != NULL); + g_assert (buf != NULL); object = g_object_new (THRIFT_TYPE_MEMORY_BUFFER, "buf", buf, NULL); - assert (object != NULL); + g_assert (object != NULL); g_object_unref (object); } @@ -84,12 +83,12 @@ test_create_and_destroy_unowned (void) object = g_object_new (THRIFT_TYPE_MEMORY_BUFFER, "owner", FALSE, NULL); - assert (object != NULL); + g_assert (object != NULL); g_value_init (&val, G_TYPE_POINTER); g_object_get_property (object, "buf", &val); buf = (GByteArray*) g_value_get_pointer (&val); - assert (buf != NULL); + g_assert (buf != NULL); g_byte_array_unref (buf); g_value_unset (&val); @@ -105,9 +104,9 @@ test_open_and_close (void) tbuffer = g_object_new (THRIFT_TYPE_MEMORY_BUFFER, NULL); /* no-ops */ - assert (thrift_memory_buffer_open (THRIFT_TRANSPORT (tbuffer), NULL) == TRUE); - assert (thrift_memory_buffer_is_open (THRIFT_TRANSPORT (tbuffer)) == TRUE); - assert (thrift_memory_buffer_close (THRIFT_TRANSPORT (tbuffer), NULL) == TRUE); + g_assert (thrift_memory_buffer_open (THRIFT_TRANSPORT (tbuffer), NULL) == TRUE); + g_assert (thrift_memory_buffer_is_open (THRIFT_TRANSPORT (tbuffer)) == TRUE); + g_assert (thrift_memory_buffer_close (THRIFT_TRANSPORT (tbuffer), NULL) == TRUE); g_object_unref (tbuffer); } @@ -122,18 +121,18 @@ test_read_and_write (void) GError *error = NULL; tbuffer = g_object_new (THRIFT_TYPE_MEMORY_BUFFER, "buf_size", 5, NULL); - assert (thrift_memory_buffer_write (THRIFT_TRANSPORT (tbuffer), + g_assert (thrift_memory_buffer_write (THRIFT_TRANSPORT (tbuffer), (gpointer) TEST_DATA, 10, &error) == FALSE); - assert (error != NULL); + g_assert (error != NULL); g_error_free (error); error = NULL; g_object_unref (tbuffer); tbuffer = g_object_new (THRIFT_TYPE_MEMORY_BUFFER, "buf_size", 15, NULL); - assert (thrift_memory_buffer_write (THRIFT_TRANSPORT (tbuffer), + g_assert (thrift_memory_buffer_write (THRIFT_TRANSPORT (tbuffer), (gpointer) TEST_DATA, 10, &error) == TRUE); - assert (error == NULL); + g_assert (error == NULL); memset(read, 0, 10); b = read; @@ -141,12 +140,12 @@ test_read_and_write (void) while (want > 0) { got = thrift_memory_buffer_read (THRIFT_TRANSPORT (tbuffer), (gpointer) b, want, &error); - assert (got > 0 && got <= want); - assert (error == NULL); + g_assert (got > 0 && got <= want); + g_assert (error == NULL); b += got; want -= got; } - assert (memcmp (read, TEST_DATA, 10) == 0); + g_assert (memcmp (read, TEST_DATA, 10) == 0); g_object_unref (tbuffer); } @@ -161,9 +160,9 @@ test_read_and_write_default (void) tbuffer = g_object_new (THRIFT_TYPE_MEMORY_BUFFER, NULL); for (i = 0; i < 100; ++i) { - assert (thrift_memory_buffer_write (THRIFT_TRANSPORT (tbuffer), + g_assert (thrift_memory_buffer_write (THRIFT_TRANSPORT (tbuffer), (gpointer) TEST_DATA, 10, &error) == TRUE); - assert (error == NULL); + g_assert (error == NULL); } for (i = 0; i < 100; ++i) { @@ -173,12 +172,12 @@ test_read_and_write_default (void) while (want > 0) { got = thrift_memory_buffer_read (THRIFT_TRANSPORT (tbuffer), (gpointer) b, want, &error); - assert (got > 0 && got <= want); - assert (error == NULL); + g_assert (got > 0 && got <= want); + g_assert (error == NULL); b += got; want -= got; } - assert (memcmp (read, TEST_DATA, 10) == 0); + g_assert (memcmp (read, TEST_DATA, 10) == 0); } g_object_unref (tbuffer); } @@ -190,14 +189,14 @@ test_read_and_write_external (void) gchar *b; GError *error = NULL; GByteArray *buf = g_byte_array_new (); - assert (buf != NULL); + g_assert (buf != NULL); tbuffer = g_object_new (THRIFT_TYPE_MEMORY_BUFFER, "buf", buf, NULL); - assert (thrift_memory_buffer_write (THRIFT_TRANSPORT (tbuffer), + g_assert (thrift_memory_buffer_write (THRIFT_TRANSPORT (tbuffer), (gpointer) TEST_DATA, 10, &error) == TRUE); - assert (error == NULL); + g_assert (error == NULL); - assert (memcmp (buf->data, TEST_DATA, 10) == 0); + g_assert (memcmp (buf->data, TEST_DATA, 10) == 0); g_object_unref (tbuffer); } diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testoptionalrequired.c b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testoptionalrequired.c index 818343c..636c36d 100755 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testoptionalrequired.c +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testoptionalrequired.c @@ -17,7 +17,6 @@ * under the License. */ -#include #include #include @@ -76,18 +75,18 @@ test_simple (void) /* write-to-read with optional fields */ s1->im_optional = 10; - assert (s1->__isset_im_default == FALSE); - assert (s1->__isset_im_optional == FALSE); + g_assert (s1->__isset_im_default == FALSE); + g_assert (s1->__isset_im_optional == FALSE); write_to_read (THRIFT_STRUCT (s1), THRIFT_STRUCT (s2), NULL, NULL); - assert (s2->__isset_im_default == TRUE); - assert (s2->__isset_im_optional == FALSE); - assert (s2->im_optional == 0); + g_assert (s2->__isset_im_default == TRUE); + g_assert (s2->__isset_im_optional == FALSE); + g_assert (s2->im_optional == 0); s1->__isset_im_optional = TRUE; write_to_read (THRIFT_STRUCT (s1), THRIFT_STRUCT (s3), NULL, NULL); - assert (s3->__isset_im_default == TRUE); - assert (s3->__isset_im_optional == TRUE); - assert (s3->im_optional == 10); + g_assert (s3->__isset_im_default == TRUE); + g_assert (s3->__isset_im_optional == TRUE); + g_assert (s3->im_optional == 10); g_object_unref (s1); g_object_unref (s2); @@ -109,10 +108,10 @@ test_tricky1 (void) write_to_read (THRIFT_STRUCT (t2), THRIFT_STRUCT (t1), NULL, NULL); write_to_read (THRIFT_STRUCT (t1), THRIFT_STRUCT (t2), NULL, NULL); - assert (t1->__isset_im_default == FALSE); - assert (t2->__isset_im_optional == TRUE); - assert (t1->im_default == t2->im_optional); - assert (t1->im_default == 0); + g_assert (t1->__isset_im_default == FALSE); + g_assert (t2->__isset_im_optional == TRUE); + g_assert (t1->im_default == t2->im_optional); + g_assert (t1->im_default == 0); g_object_unref (t1); g_object_unref (t2); @@ -133,7 +132,7 @@ test_tricky2 (void) write_to_read (THRIFT_STRUCT (t1), THRIFT_STRUCT (t3), NULL, NULL); write_to_read (THRIFT_STRUCT (t3), THRIFT_STRUCT (t1), NULL, NULL); - assert (t1->__isset_im_default == TRUE); + g_assert (t1->__isset_im_default == TRUE); g_object_unref (t1); g_object_unref (t3); @@ -176,12 +175,12 @@ test_tricky4 (void) /* throws protocol exception */ write_to_read (THRIFT_STRUCT (t2), THRIFT_STRUCT (t3), NULL, &read_error); - assert (read_error != NULL); + g_assert (read_error != NULL); g_error_free (read_error); write_to_read (THRIFT_STRUCT (t3), THRIFT_STRUCT (t2), NULL, NULL); - assert (t2->__isset_im_optional); + g_assert (t2->__isset_im_optional); g_object_unref (t2); g_object_unref (t3); diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testsimpleserver.c b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testsimpleserver.c index 3af2eeb..3c6f2e8 100755 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testsimpleserver.c +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testsimpleserver.c @@ -17,7 +17,6 @@ * under the License. */ -#include #include #include #include @@ -89,7 +88,7 @@ test_server (void) /* run the server in a child process */ pid = fork (); - assert (pid >= 0); + g_assert (pid >= 0); if (pid == 0) { @@ -103,8 +102,8 @@ test_server (void) g_object_unref (ss); g_object_unref (tss); g_object_unref (p); - assert (wait (&status) == pid); - assert (status == SIGINT); + g_assert (wait (&status) == pid); + g_assert (status == SIGINT); } } diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/test/teststruct.c b/vendor/git.apache.org/thrift.git/lib/c_glib/test/teststruct.c index 5d4baf3..d120cbc 100755 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/test/teststruct.c +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/test/teststruct.c @@ -17,7 +17,6 @@ * under the License. */ -#include #include #include "../src/thrift/c_glib/thrift_struct.c" @@ -89,7 +88,7 @@ test_initialize_object (void) ThriftTestStruct *t = NULL; t = g_object_new (THRIFT_TYPE_TEST_STRUCT, NULL); - assert ( THRIFT_IS_STRUCT (t)); + g_assert ( THRIFT_IS_STRUCT (t)); thrift_struct_read (THRIFT_STRUCT (t), NULL, NULL); thrift_struct_write (THRIFT_STRUCT (t), NULL, NULL); thrift_test_struct_read (THRIFT_STRUCT (t), NULL, NULL); diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testthrifttest.c b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testthrifttest.c index 0211f53..23a934d 100755 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testthrifttest.c +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testthrifttest.c @@ -1,4 +1,3 @@ -#include #include #include @@ -87,14 +86,14 @@ test_thrift_handler (void) g_object_weak_ref (G_OBJECT (argument), set_indicator, (gpointer) &indicator); - assert (thrift_test_handler_test_insanity (NULL, &_return, argument, &error)); - assert (! indicator); + g_assert (thrift_test_handler_test_insanity (NULL, &_return, argument, &error)); + g_assert (! indicator); g_hash_table_unref (_return); - assert (! indicator); + g_assert (! indicator); g_object_unref (argument); - assert (indicator); + g_assert (indicator); } int diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testthrifttestclient.cpp b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testthrifttestclient.cpp index 7681cf5..5b06883 100755 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testthrifttestclient.cpp +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testthrifttestclient.cpp @@ -17,7 +17,7 @@ * under the License. */ -/* test a C client with a C++ server */ +/* test a C client with a C++ server (that makes sense...) */ #include #include @@ -25,23 +25,34 @@ #include #include #include +#include #include #include "ThriftTest.h" #include "ThriftTest_types.h" #include - -using namespace std; -using namespace boost; +#include +#include +#include +#include using namespace apache::thrift; using namespace apache::thrift::concurrency; using namespace apache::thrift::protocol; -using namespace apache::thrift::transport; using namespace apache::thrift::server; +using namespace apache::thrift::transport; using namespace thrift::test; +using std::cout; +using std::endl; +using std::fixed; +using std::make_pair; +using std::map; +using std::set; +using std::string; +using std::vector; + #define TEST_PORT 9980 // Extra functions required for ThriftTest_types to work @@ -347,7 +358,7 @@ test_thrift_client (void) gchar *string = NULL; gint8 byte = 0; gint16 i16 = 0; - gint32 i32 = 0, another_i32 = 56789; + gint32 i32 = 0, another_i32 = 56789; gint64 i64 = 0; double dbl = 0.0; TTestXtruct *xtruct_in, *xtruct_out; @@ -356,7 +367,7 @@ test_thrift_client (void) GHashTable *set_in = NULL, *set_out = NULL; GArray *list_in = NULL, *list_out = NULL; TTestNumberz enum_in, enum_out; - TTestUserId user_id_in, user_id_out; + TTestUserId user_id_in, user_id_out; GHashTable *insanity_in = NULL; TTestXtruct *xtruct1, *xtruct2; TTestInsanity *insanity_out = NULL; @@ -371,7 +382,7 @@ test_thrift_client (void) #endif // create a C client - tsocket = (ThriftSocket *) g_object_new (THRIFT_TYPE_SOCKET, + tsocket = (ThriftSocket *) g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", "port", TEST_PORT, NULL); protocol = (ThriftBinaryProtocol *) g_object_new (THRIFT_TYPE_BINARY_PROTOCOL, @@ -607,11 +618,11 @@ main (void) if (pid == 0) /* child */ { - boost::shared_ptr protocolFactory(new TBinaryProtocolFactory()); - boost::shared_ptr testHandler(new TestHandler()); - boost::shared_ptr testProcessor(new ThriftTestProcessor(testHandler)); - boost::shared_ptr serverSocket(new TServerSocket(TEST_PORT)); - boost::shared_ptr transportFactory(new TBufferedTransportFactory()); + stdcxx::shared_ptr protocolFactory(new TBinaryProtocolFactory()); + stdcxx::shared_ptr testHandler(new TestHandler()); + stdcxx::shared_ptr testProcessor(new ThriftTestProcessor(testHandler)); + stdcxx::shared_ptr serverSocket(new TServerSocket(TEST_PORT)); + stdcxx::shared_ptr transportFactory(new TBufferedTransportFactory()); TSimpleServer simpleServer(testProcessor, serverSocket, transportFactory, protocolFactory); signal (SIGALRM, bailout); alarm (60); diff --git a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testtransportsocket.c b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testtransportsocket.c index d91507f..fedbad6 100755 --- a/vendor/git.apache.org/thrift.git/lib/c_glib/test/testtransportsocket.c +++ b/vendor/git.apache.org/thrift.git/lib/c_glib/test/testtransportsocket.c @@ -17,7 +17,6 @@ * under the License. */ -#include #include #include @@ -34,9 +33,9 @@ int my_socket(int domain, int type, int protocol) { if (socket_error == 0) - { - return socket (domain, type, protocol); - } + { + return socket (domain, type, protocol); + } return -1; } @@ -45,9 +44,9 @@ ssize_t my_recv(int socket, void *buffer, size_t length, int flags) { if (recv_error == 0) - { - return recv (socket, buffer, length, flags); - } + { + return recv (socket, buffer, length, flags); + } return -1; } @@ -56,9 +55,9 @@ ssize_t my_send(int socket, const void *buffer, size_t length, int flags) { if (send_error == 0) - { - return send (socket, buffer, length, flags); - } + { + return send (socket, buffer, length, flags); + } return -1; } @@ -71,7 +70,7 @@ my_send(int socket, const void *buffer, size_t length, int flags) #undef send static void thrift_socket_server (const int port); - +static void thrift_socket_server_open (const int port, int times); /* test object creation and destruction */ static void test_create_and_destroy(void) @@ -81,7 +80,7 @@ test_create_and_destroy(void) GObject *object = NULL; object = g_object_new (THRIFT_TYPE_SOCKET, NULL); - assert (object != NULL); + g_assert (object != NULL); g_object_get (G_OBJECT(object), "hostname", &hostname, "port", &port, NULL); g_free (hostname); @@ -94,82 +93,100 @@ test_open_and_close(void) ThriftSocket *tsocket = NULL; ThriftTransport *transport = NULL; GError *err = NULL; + int port = 51199; + pid_t pid; + int status; - /* open a connection and close it */ - tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", - "port", 51188, NULL); - transport = THRIFT_TRANSPORT (tsocket); - thrift_socket_open (transport, NULL); - assert (thrift_socket_is_open (transport) == TRUE); - thrift_socket_close (transport, NULL); - assert (thrift_socket_is_open (transport) == FALSE); + pid = fork (); + g_assert ( pid >= 0 ); - /* test close failure */ - tsocket->sd = -1; - thrift_socket_close (transport, NULL); - g_object_unref (tsocket); + if ( pid == 0 ) + { + /* child listens */ + thrift_socket_server_open (port, 1); + exit (0); + } else { + /* parent connects, wait a bit for the socket to be created */ + sleep (1); - /* try a hostname lookup failure */ - tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost.broken", - NULL); - transport = THRIFT_TRANSPORT (tsocket); - assert (thrift_socket_open (transport, &err) == FALSE); - g_object_unref (tsocket); - g_error_free (err); - err = NULL; + /* open a connection and close it */ + tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", + "port", port, NULL); + transport = THRIFT_TRANSPORT (tsocket); + thrift_socket_open (transport, NULL); + g_assert (thrift_socket_is_open (transport) == TRUE); + thrift_socket_close (transport, NULL); + g_assert (thrift_socket_is_open (transport) == FALSE); - /* try an error call to socket() */ - tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", NULL); - transport = THRIFT_TRANSPORT (tsocket); - socket_error = 1; - assert (thrift_socket_open (transport, &err) == FALSE); - socket_error = 0; - g_object_unref (tsocket); - g_error_free (err); + /* test close failure */ + tsocket->sd = -1; + thrift_socket_close (transport, NULL); + g_object_unref (tsocket); + + /* try a hostname lookup failure */ + tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost.broken", + NULL); + transport = THRIFT_TRANSPORT (tsocket); + g_assert (thrift_socket_open (transport, &err) == FALSE); + g_object_unref (tsocket); + g_error_free (err); + err = NULL; + + /* try an error call to socket() */ + tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", NULL); + transport = THRIFT_TRANSPORT (tsocket); + socket_error = 1; + g_assert (thrift_socket_open (transport, &err) == FALSE); + socket_error = 0; + g_object_unref (tsocket); + g_error_free (err); + g_assert ( wait (&status) == pid ); + g_assert ( status == 0 ); + } } static void test_read_and_write(void) { - int status; - pid_t pid; ThriftSocket *tsocket = NULL; ThriftTransport *transport = NULL; + pid_t pid; int port = 51199; + int status; guchar buf[10] = TEST_DATA; /* a buffer */ pid = fork (); - assert ( pid >= 0 ); + g_assert ( pid >= 0 ); if ( pid == 0 ) - { - /* child listens */ - thrift_socket_server (port); - exit (0); - } else { - /* parent connects, wait a bit for the socket to be created */ - sleep (1); + { + /* child listens */ + thrift_socket_server (port); + exit (0); + } else { + /* parent connects, wait a bit for the socket to be created */ + sleep (1); - tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", - "port", port, NULL); - transport = THRIFT_TRANSPORT (tsocket); - assert (thrift_socket_open (transport, NULL) == TRUE); - assert (thrift_socket_is_open (transport)); - thrift_socket_write (transport, buf, 10, NULL); + tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", + "port", port, NULL); + transport = THRIFT_TRANSPORT (tsocket); + g_assert (thrift_socket_open (transport, NULL) == TRUE); + g_assert (thrift_socket_is_open (transport)); + thrift_socket_write (transport, buf, 10, NULL); - /* write fail */ - send_error = 1; - thrift_socket_write (transport, buf, 1, NULL); - send_error = 0; + /* write fail */ + send_error = 1; + thrift_socket_write (transport, buf, 1, NULL); + send_error = 0; - thrift_socket_write_end (transport, NULL); - thrift_socket_flush (transport, NULL); - thrift_socket_close (transport, NULL); - g_object_unref (tsocket); + thrift_socket_write_end (transport, NULL); + thrift_socket_flush (transport, NULL); + thrift_socket_close (transport, NULL); + g_object_unref (tsocket); - assert ( wait (&status) == pid ); - assert ( status == 0 ); - } + g_assert ( wait (&status) == pid ); + g_assert ( status == 0 ); + } } /* test ThriftSocket's peek() implementation */ @@ -184,9 +201,9 @@ test_peek(void) GError *error = NULL; client_transport = g_object_new (THRIFT_TYPE_SOCKET, - "hostname", "localhost", - "port", port, - NULL); + "hostname", "localhost", + "port", port, + NULL); /* thrift_transport_peek returns FALSE when the socket is closed */ g_assert (thrift_transport_is_open (client_transport) == FALSE); @@ -197,80 +214,104 @@ test_peek(void) g_assert (pid >= 0); if (pid == 0) - { - ThriftServerTransport *server_transport = NULL; + { + ThriftServerTransport *server_transport = NULL; - g_object_unref (client_transport); + g_object_unref (client_transport); - /* child listens */ - server_transport = g_object_new (THRIFT_TYPE_SERVER_SOCKET, - "port", port, - NULL); - g_assert (server_transport != NULL); + /* child listens */ + server_transport = g_object_new (THRIFT_TYPE_SERVER_SOCKET, + "port", port, + NULL); + g_assert (server_transport != NULL); - thrift_server_transport_listen (server_transport, &error); - g_assert (error == NULL); + thrift_server_transport_listen (server_transport, &error); + g_assert (error == NULL); - client_transport = g_object_new - (THRIFT_TYPE_BUFFERED_TRANSPORT, - "transport", thrift_server_transport_accept (server_transport, &error), - "r_buf_size", 0, - "w_buf_size", sizeof data, - NULL); - g_assert (error == NULL); - g_assert (client_transport != NULL); + client_transport = g_object_new + (THRIFT_TYPE_BUFFERED_TRANSPORT, + "transport", thrift_server_transport_accept (server_transport, &error), + "r_buf_size", 0, + "w_buf_size", sizeof data, + NULL); + g_assert (error == NULL); + g_assert (client_transport != NULL); - /* write exactly one character to the client */ - g_assert (thrift_transport_write (client_transport, - &data, - sizeof data, - &error) == TRUE); + /* write exactly one character to the client */ + g_assert (thrift_transport_write (client_transport, + &data, + sizeof data, + &error) == TRUE); - thrift_transport_flush (client_transport, &error); - thrift_transport_write_end (client_transport, &error); - thrift_transport_close (client_transport, &error); + thrift_transport_flush (client_transport, &error); + thrift_transport_write_end (client_transport, &error); + thrift_transport_close (client_transport, &error); - g_object_unref (client_transport); - g_object_unref (server_transport); + g_object_unref (client_transport); + g_object_unref (server_transport); - exit (0); - } + exit (0); + } else { - /* parent connects, wait a bit for the socket to be created */ - sleep (1); + /* parent connects, wait a bit for the socket to be created */ + sleep (1); - /* connect to the child */ - thrift_transport_open (client_transport, &error); - g_assert (error == NULL); - g_assert (thrift_transport_is_open (client_transport) == TRUE); + /* connect to the child */ + thrift_transport_open (client_transport, &error); + g_assert (error == NULL); + g_assert (thrift_transport_is_open (client_transport) == TRUE); - /* thrift_transport_peek returns TRUE when the socket is open and there is + /* thrift_transport_peek returns TRUE when the socket is open and there is data available to be read */ - g_assert (thrift_transport_peek (client_transport, &error) == TRUE); - g_assert (error == NULL); + g_assert (thrift_transport_peek (client_transport, &error) == TRUE); + g_assert (error == NULL); - /* read exactly one character from the server */ - g_assert_cmpint (thrift_transport_read (client_transport, - &data, - sizeof data, - &error), ==, sizeof data); + /* read exactly one character from the server */ + g_assert_cmpint (thrift_transport_read (client_transport, + &data, + sizeof data, + &error), ==, sizeof data); - /* thrift_transport_peek returns FALSE when the socket is open but there is + /* thrift_transport_peek returns FALSE when the socket is open but there is no (more) data available to be read */ - g_assert (thrift_transport_is_open (client_transport) == TRUE); - g_assert (thrift_transport_peek (client_transport, &error) == FALSE); - g_assert (error == NULL); + g_assert (thrift_transport_is_open (client_transport) == TRUE); + g_assert (thrift_transport_peek (client_transport, &error) == FALSE); + g_assert (error == NULL); - thrift_transport_read_end (client_transport, &error); - thrift_transport_close (client_transport, &error); + thrift_transport_read_end (client_transport, &error); + thrift_transport_close (client_transport, &error); - g_object_unref (client_transport); + g_object_unref (client_transport); - g_assert (wait (&status) == pid); - g_assert (status == 0); + g_assert (wait (&status) == pid); + g_assert (status == 0); } } +static void +thrift_socket_server_open (const int port, int times) +{ + int bytes = 0; + ThriftServerTransport *transport = NULL; + ThriftTransport *client = NULL; + guchar buf[10]; /* a buffer */ + guchar match[10] = TEST_DATA; + int i; + ThriftServerSocket *tsocket = g_object_new (THRIFT_TYPE_SERVER_SOCKET, + "port", port, NULL); + + transport = THRIFT_SERVER_TRANSPORT (tsocket); + thrift_server_transport_listen (transport, NULL); + for(i=0;i +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +/* #define TEST_DATA { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' } */ +#define TEST_DATA { "GET / HTTP/1.1\n\n" } + + +/* substituted functions to test failures of system and library calls */ +static int socket_error = 0; +int +my_socket(int domain, int type, int protocol) +{ + if (socket_error == 0) + { + return socket (domain, type, protocol); + } + return -1; +} + +static int recv_error = 0; +ssize_t +my_recv(int socket, void *buffer, size_t length, int flags) +{ + if (recv_error == 0) + { + return recv (socket, buffer, length, flags); + } + return -1; +} + +static int send_error = 0; +ssize_t +my_send(int socket, const void *buffer, size_t length, int flags) +{ + if (send_error == 0) + { + return send (socket, buffer, length, flags); + } + return -1; +} + +#define socket my_socket +#define recv my_recv +#define send my_send +#include "../src/thrift/c_glib/transport/thrift_ssl_socket.c" +#undef socket +#undef recv +#undef send + +static void thrift_socket_server (const int port); + +/* test object creation and destruction */ +static void +test_ssl_create_and_destroy(void) +{ + gchar *hostname = NULL; + guint port = 0; + + GObject *object = NULL; + object = g_object_new (THRIFT_TYPE_SSL_SOCKET, NULL); + g_assert (object != NULL); + g_object_get (G_OBJECT(object), "hostname", &hostname, "port", &port, NULL); + g_free (hostname); + g_object_unref (object); +} + +static void +test_ssl_create_and_set_properties(void) +{ + gchar *hostname = NULL; + guint port = 0; + SSL_CTX* ssl_ctx= NULL; + GError *error=NULL; + + GObject *object = NULL; + object = thrift_ssl_socket_new(SSLTLS, &error); + g_object_get (G_OBJECT(object), "hostname", &hostname, "port", &port, "ssl_context", &ssl_ctx, NULL); + g_assert (ssl_ctx!=NULL); + + g_free (hostname); + g_object_unref (object); +} + +static void +test_ssl_open_and_close_non_ssl_server(void) +{ + ThriftSSLSocket *tSSLSocket = NULL; + ThriftTransport *transport = NULL; + GError *error=NULL; + pid_t pid; + int non_ssl_port = 51198; + char errormsg[255]; + + + pid = fork (); + g_assert ( pid >= 0 ); + + if ( pid == 0 ) + { + /* child listens */ + /* This is a non SSL server */ + thrift_socket_server (non_ssl_port); + exit (0); + } else { + /* parent connects, wait a bit for the socket to be created */ + sleep (1); + + /* open a connection and close it */ + tSSLSocket = thrift_ssl_socket_new_with_host(SSLTLS, "localhost", non_ssl_port, &error); + + transport = THRIFT_TRANSPORT (tSSLSocket); + g_assert (thrift_ssl_socket_open (transport, &error) == FALSE); + g_assert_cmpstr(error->message, == ,"Error while connect/bind: 68 -> Connection reset by peer"); + g_clear_error (&error); + g_assert (thrift_ssl_socket_is_open (transport) == FALSE); + thrift_ssl_socket_close (transport, NULL); + g_assert (thrift_ssl_socket_is_open (transport) == FALSE); + + /* test close failure */ + THRIFT_SOCKET(tSSLSocket)->sd = -1; + thrift_ssl_socket_close (transport, NULL); + g_object_unref (tSSLSocket); + + /* try a hostname lookup failure */ + tSSLSocket = thrift_ssl_socket_new_with_host(SSLTLS, "localhost.broken", non_ssl_port, &error); + transport = THRIFT_TRANSPORT (tSSLSocket); + g_assert (thrift_ssl_socket_open (transport, &error) == FALSE); + snprintf(errormsg, 255, "host lookup failed for localhost.broken:%d - Unknown host", non_ssl_port); + g_assert_cmpstr(error->message, ==, errormsg); + g_clear_error (&error); + g_object_unref (tSSLSocket); + error = NULL; + + /* try an error call to socket() */ + /* + tSSLSocket = thrift_ssl_socket_new_with_host(SSLTLS, "localhost", port, &error); + transport = THRIFT_TRANSPORT (tSSLSocket); + socket_error = 1; + assert (thrift_ssl_socket_open (transport, &error) == FALSE); + socket_error = 0; + g_object_unref (tSSLSocket); + g_error_free (error); + */ + } +} + +static void +test_ssl_write_invalid_socket(void) +{ + ThriftSSLSocket *tSSLSocket = NULL; + ThriftTransport *transport = NULL; + GError *error=NULL; + char buffer[] = "this must not break"; + + /* open a connection and close it */ + tSSLSocket = thrift_ssl_socket_new_with_host(SSLTLS, "localhost", 51188+1, &error); + + transport = THRIFT_TRANSPORT (tSSLSocket); + g_assert (thrift_ssl_socket_open (transport, NULL) == FALSE); + g_assert (thrift_ssl_socket_is_open (transport) == FALSE); + + /* FIXME This must be tested but since the assertion inside thrift_ssl_socket_write breaks the test unit + it's disabled. They idea is to disable trap/coredump during this test + g_assert (thrift_ssl_socket_write(transport, buffer, sizeof(buffer), &error) == FALSE); + g_message ("write_failed_with_error: %s", + error != NULL ? error->message : "No"); + g_clear_error (&error); + */ + thrift_ssl_socket_close (transport, NULL); + g_assert (thrift_ssl_socket_is_open (transport) == FALSE); + + /* test close failure */ + THRIFT_SOCKET(tSSLSocket)->sd = -1; + thrift_ssl_socket_close (transport, NULL); + g_object_unref (tSSLSocket); +} + + + +/** + * Print the common name of certificate + */ +unsigned char * get_cn_name(X509_NAME* const name) +{ + int idx = -1; + unsigned char *utf8 = NULL; + + do + { + if(!name) break; /* failed */ + + idx = X509_NAME_get_index_by_NID(name, NID_commonName, -1); + if(!(idx > -1)) break; /* failed */ + + X509_NAME_ENTRY* entry = X509_NAME_get_entry(name, idx); + if(!entry) break; /* failed */ + + ASN1_STRING* data = X509_NAME_ENTRY_get_data(entry); + if(!data) break; /* failed */ + + int length = ASN1_STRING_to_UTF8(&utf8, data); + if(!utf8 || !(length > 0)) break; /* failed */ + + } while (0); + return utf8; +} + +/* + * Handle IPV4 and IPV6 addr + */ +void *get_in_addr(struct sockaddr *sa) +{ + if (sa->sa_family == AF_INET) + return &(((struct sockaddr_in*)sa)->sin_addr); + return &(((struct sockaddr_in6*)sa)->sin6_addr); +} + +int verify_ip(char * hostname, struct sockaddr_storage *addr) +{ + struct addrinfo *addr_info,*p; + struct addrinfo hints; + int res; + int retval = 0; + + + memset(&hints, 0, sizeof (struct addrinfo)); + hints.ai_family = AF_UNSPEC; /* use AF_INET6 to force IPv6 */ + hints.ai_socktype = SOCK_STREAM; + + + if ( (res = getaddrinfo(hostname, NULL, &hints, &addr_info) ) != 0) + { + /* get the host info */ + g_error("Cannot get the host address"); + return retval; + } + /* loop through all the results and connect to the first we can */ + char dnshost[INET6_ADDRSTRLEN]; /* bigger addr supported IPV6 */ + char socket_ip[INET6_ADDRSTRLEN]; + if(inet_ntop(addr->ss_family, get_in_addr(addr), socket_ip, INET6_ADDRSTRLEN)==socket_ip){ + g_debug("We are connected to host %s checking against certificate...", socket_ip); + int sizeip = socket_ip!=NULL ? strlen(socket_ip) : 0; + for(p = addr_info; p != NULL; p = p->ai_next) { + if(inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), dnshost, INET6_ADDRSTRLEN)==dnshost){ + if(dnshost!=NULL){ + g_info("DNS address [%i -> %s]", p->ai_addr, dnshost); + if(!strncmp(dnshost, socket_ip, sizeip)){ + retval=1; + break; /* if we get here, we must have connected successfully */ + } + } + } + } + } + + if(addr_info) + freeaddrinfo(addr_info); + + return retval; +} + +static void +read_from_file(char *buffer, long size, const char *file_name) +{ + char ch; + long index=0; + FILE *fp; + + fp = fopen(file_name,"r"); /* read mode */ + + if( fp == NULL ) + { + perror("Error while opening the file.\n"); + exit(EXIT_FAILURE); + } + + printf("The contents of %s file are :\n", file_name); + + while(index= len) { + g_warn(stderr, "buffer length shorter than serial number\n"); + BN_free(bn); + OPENSSL_free(tmp); + return EXIT_FAILURE; + } + */ + if(!strncmp(serial_number, tmp, strlen(serial_number))){ + retval=TRUE; + }else{ + g_warning("Serial number is not valid"); + } + + BN_free(bn); + OPENSSL_free(tmp); + return retval; +} + +gboolean my_access_manager(ThriftTransport * transport, X509 *cert, struct sockaddr_storage *addr, GError **error) +{ + ThriftSSLSocket *sslSocket = THRIFT_SSL_SOCKET (transport); + + g_info("Processing access to the server"); + X509_NAME* iname = cert ? X509_get_issuer_name(cert) : NULL; + X509_NAME* sname = cert ? X509_get_subject_name(cert) : NULL; + + /* Issuer is the authority we trust that warrants nothing useful */ + const unsigned char * issuer = get_cn_name(iname); + if(issuer){ + gboolean valid = TRUE; + g_info("Issuer (cn) %s", issuer); + + /* Issuer pinning */ + if(strncmp(ISSUER_CN_PINNING, issuer, strlen(ISSUER_CN_PINNING))){ + g_warning("The Issuer of the certificate is not valid"); + valid=FALSE; + } + OPENSSL_free(issuer); + if(!valid) + return valid; + } + + + /* Subject is who the certificate is issued to by the authority */ + const unsigned char * subject = get_cn_name(sname); + if(subject){ + g_info("Subject (cn) %s", subject); + gboolean valid = TRUE; + + /* Subject pinning */ + if(strncmp(SUBJECT_CN_PINNING, subject, strlen(SUBJECT_CN_PINNING))){ + g_warning("The subject of the certificate is not valid"); + valid=FALSE; + } + + if(!valid) + return valid; + + /* Host pinning */ + if(verify_ip(subject, addr)){ + g_info("Verified subject"); + }else{ + g_info("Cannot verify subject"); + valid=FALSE; + } + OPENSSL_free(subject); + + if(!valid) + return valid; + } + + if(!verify_certificate_sn(cert, CERT_SERIAL_NUMBER)){ + return FALSE; + }else{ + g_info("Verified serial number"); + } + + return TRUE; + +} + + + + +#ifdef BUILD_SERVER +static void +test_ssl_authorization_manager(void) +{ + int status=0; + pid_t pid; + ThriftSSLSocket *tSSLsocket = NULL; + ThriftTransport *transport = NULL; + /* int port = 51199; */ + int port = 443; + GError *error=NULL; + + guchar buf[17] = TEST_DATA; /* a buffer */ + +/* + pid = fork (); + g_assert ( pid >= 0 ); + + if ( pid == 0 ) + { + thrift_ssl_socket_server (port); + exit (0); + } else { + */ + /* parent connects, wait a bit for the socket to be created */ + sleep (1); + + /* Test against level2 owncloud certificate */ + tSSLsocket = thrift_ssl_socket_new_with_host(SSLTLS, "localhost", port, &error); + thrift_ssl_socket_set_manager(tSSLsocket, my_access_manager); /* Install pinning manager */ + /* thrift_ssl_load_cert_from_file(tSSLsocket, "./owncloud.level2crm.pem"); */ + unsigned char cert_buffer[65534]; + read_from_file(cert_buffer, 65534, "../../keys/client.pem"); + if(!thrift_ssl_load_cert_from_buffer(tSSLsocket, cert_buffer)){ + g_warning("Certificates cannot be loaded!"); + } + + transport = THRIFT_TRANSPORT (tSSLsocket); + g_assert (thrift_ssl_socket_open (transport, NULL) == TRUE); + g_assert (thrift_ssl_socket_is_open (transport)); + + thrift_ssl_socket_write (transport, buf, 17, NULL); + + /* write fail */ + send_error = 1; + /* + thrift_ssl_socket_write (transport, buf, 1, NULL); + send_error = 0; + thrift_ssl_socket_write_end (transport, NULL); + thrift_ssl_socket_flush (transport, NULL); + */ + thrift_ssl_socket_close (transport, NULL); + g_object_unref (tSSLsocket); + + /* g_assert ( wait (&status) == pid ); */ + g_assert ( status == 0 ); + /* } */ +} +#endif + + +static void +thrift_socket_server (const int port) +{ + int bytes = 0; + ThriftServerTransport *transport = NULL; + ThriftTransport *client = NULL; + guchar buf[10]; /* a buffer */ + guchar match[10] = TEST_DATA; + + ThriftServerSocket *tsocket = g_object_new (THRIFT_TYPE_SERVER_SOCKET, + "port", port, NULL); + + transport = THRIFT_SERVER_TRANSPORT (tsocket); + thrift_server_transport_listen (transport, NULL); + client = thrift_server_transport_accept (transport, NULL); + g_assert (client != NULL); + + /* read 10 bytes */ + bytes = thrift_ssl_socket_read (client, buf, 10, NULL); + g_assert (bytes == 10); /* make sure we've read 10 bytes */ + g_assert ( memcmp(buf, match, 10) == 0 ); /* make sure what we got matches */ + + /* failed read */ + recv_error = 1; + thrift_ssl_socket_read (client, buf, 1, NULL); + recv_error = 0; + + thrift_ssl_socket_read_end (client, NULL); + thrift_ssl_socket_close (client, NULL); + g_object_unref (tsocket); + g_object_unref (client); +} + +int +main(int argc, char *argv[]) +{ + int retval; +#if (!GLIB_CHECK_VERSION (2, 36, 0)) + g_type_init(); +#endif + + g_test_init (&argc, &argv, NULL); + + thrift_ssl_socket_initialize_openssl(); + + g_test_add_func ("/testtransportsslsocket/CreateAndDestroy", test_ssl_create_and_destroy); + g_test_add_func ("/testtransportsslsocket/CreateAndSetProperties", test_ssl_create_and_set_properties); + g_test_add_func ("/testtransportsslsocket/OpenAndCloseNonSSLServer", test_ssl_open_and_close_non_ssl_server); + g_test_add_func ("/testtransportsslsocket/OpenAndWriteInvalidSocket", test_ssl_write_invalid_socket); + + + + + retval = g_test_run (); + + thrift_ssl_socket_finalize_openssl(); + + return retval; +} + diff --git a/vendor/git.apache.org/thrift.git/build/docker/check_unmodified.sh b/vendor/git.apache.org/thrift.git/lib/cl/Makefile.am old mode 100755 new mode 100644 similarity index 55% rename from vendor/git.apache.org/thrift.git/build/docker/check_unmodified.sh rename to vendor/git.apache.org/thrift.git/lib/cl/Makefile.am index 9d5fa26..34b3886 --- a/vendor/git.apache.org/thrift.git/build/docker/check_unmodified.sh +++ b/vendor/git.apache.org/thrift.git/lib/cl/Makefile.am @@ -1,4 +1,3 @@ -#!/bin/bash # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file @@ -18,25 +17,24 @@ # under the License. # -# Download prebuilt docker image and compare Dockerfile hash values +THRIFT = $(top_builddir)/compiler/cpp/thrift -set -ex +all-local: + bash ensure-externals.sh -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -DISTRO=$1 -SRC_IMG=thrift/thrift-build:$DISTRO +run-tests: test/make-test-binary.lisp + $(SBCL) --script test/make-test-binary.lisp -function try_pull { - docker pull $SRC_IMG - cd ${SCRIPT_DIR}/$DISTRO - docker run $SRC_IMG bash -c 'cd .. && sha512sum Dockerfile' > .Dockerfile.sha512 - sha512sum -c .Dockerfile.sha512 -} +check-local: run-tests + ./run-tests -if try_pull; then - echo Dockerfile seems identical. No need to rebuild from scratch. - docker tag thrift/thrift-build:$DISTRO thrift-build:$DISTRO -else - echo Either Dockerfile has changed or pull failure. Need to build brand new one. - exit 1 -fi +clean-local: + $(RM) run-tests quicklisp.lisp backport-update.zip + $(RM) -rf lib externals quicklisp + +EXTRA_DIST = \ + README.md \ + READMES \ + load-locally.lisp \ + test \ + ensure-externals.sh diff --git a/vendor/git.apache.org/thrift.git/lib/cl/README.md b/vendor/git.apache.org/thrift.git/lib/cl/README.md new file mode 100644 index 0000000..1d6eafb --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/cl/README.md @@ -0,0 +1,253 @@ +Thrift Common Lisp Library + +License +======= + +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you 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. + + + +Using Thrift with Common Lisp +============================ + + Thrift is a protocol and library for language-independent communication between cooperating + processes. The communication takes the form of request and response messages, of which the forms + are specified in advance throufh a shared interface definition. A Thrift definition file is translated + into Lisp source files, which comprise several definitions: + + * Three packages, one for the namespace of the implementation operators, and one each for request and + response operators. + * Various type definitions as implementations for Thrift typedef and enum definitions. + * DEF-STRUCT and DEF-EXCEPTION forms for Thrift struct and exception definitions. + * DEF-SERVICE forms for thrift service definitions. + + Each service definition expands in a collection of generic function definitions. For each `op` + in the service definition, two functions are defined + + * `op`-request is defined for use by a client. It accepts an additional initial `protocol` argument, + to act as the client proxy for the operation and mediate the interaction with a remote process + through a Thrift-encoded transport stream. + * `op`-response is defined for use by a server. It accepts a single `protocol` argument. A server + uses it to decode the request message, invoke the base `op` function with the message arguments, + encode and send the the result as a response, and handles exceptions. + + The client interface is one operator + + * `with-client (variable location) . body` : creates a connection in a dynamic context and closes it + upon exit. The variable is bound to a client proxy stream/protocol instance, which wraps the + base i/o stream - socket, file, etc, with an operators which implement the Thrift protocol + and transport mechanisms. + + The server interface combines server and service objects + + * `serve (location service)` : accepts connections on the designated port and responds to + requests of the service's operations. + + +Building +-------- + +The Thrift Common Lisp library is packaged as the ASDF[[1]] system `thrift`. +It depends on the systems + +* puri[[2]] : for the thrift uri class +* closer-mop[[3]] : for class metadata +* trivial-utf-8[[4]] : for string codecs +* usocket[[5]] : for the socket transport +* ieee-floats[[6]] : for conversion between ints and floats +* trivial-gray-streams[[7]] : an abstraction layer for gray streams +* alexandria[[8]] : handy utilities + +The dependencies are bundled for local builds of tests and tutorial binaries - +it is possible to use those bundles to load the library, too. + +In order to build it, register those systems with ASDF and evaluate: + + (asdf:load-system :thrift) + +This will compile and load the Lisp compiler for Thrift definition files, the +transport and protocol implementations, and the client and server interface +functions. In order to use Thrift in an application, one must also author and/or +load the interface definitions for the remote service.[[9]] If one is implementing a service, +one must also define the actual functions to which Thrift is to act as the proxy +interface. The remainder of this document follows the Thrift tutorial to illustrate how +to perform the steps + + * implement the service + * translate the Thrift IDL + * load the Lisp service interfaces + * run a server for the service + * use a client to access the service remotely + +Note that, if one is to implement a new service, one will also need to author the +IDL files, as there is no facility to generate them from a service implementation. + + +Implement the Service +--------------------- + +The tutorial comprises serveral functions: `add`, `ping`, `zip`, and `calculate`. +Each translated IDL file generates three packages for every service. In the case of +the tutorial file, the relevant packages are: + + * tutorial.calculator + * tutorial.calculator-implementation + * tutorial.calculator-response + +This is to separate the request (generated), response (generated) and implementation +(meant to be implemented by the programmer) functions for defined Thrift methods. + +It is suggested to work in the `tutorial-implementation` package while implementing +the services - it imports the `common-lisp` package, while the service-specific ones +don't (to avoid conflicts between Thrift method names and function names in `common-lisp`). + + ;; define the base operations + + (in-package :tutorial-implementation) + + (defun tutorial.calculator-implementation:add (num1 num2) + (format t "~&Asked to add ~A and ~A." num1 num2) + (+ num1 num2)) + + (defun tutorial.calculator-implementation:ping () + (print :ping)) + + (defun tutorial.calculator-implementation:zip () + (print :zip)) + + (defun tutorial.calculator-implementation:calculate (logid task) + (calculate-op (work-op task) (work-num1 task) (work-num2 task))) + + (defgeneric calculate-op (op arg1 arg2) + (:method :around (op arg1 arg2) + (let ((result (call-next-method))) + (format t "~&Asked to calculate: ~d on ~A and ~A = ~d." op arg1 arg2 result) + result)) + + (:method ((op (eql operation.add)) arg1 arg2) + (+ arg1 arg2)) + (:method ((op (eql operation.subtract)) arg1 arg2) + (- arg1 arg2)) + (:method ((op (eql operation.multiply)) arg1 arg2) + (* arg1 arg2)) + (:method ((op (eql operation.divide)) arg1 arg2) + (/ arg1 arg2))) + + (defun zip () (print 'zip)) + + +Translate the Thrift IDL +------------------------ + +IDL files employ the file extension `thrift`. In this case, there are two files to translate + * `tutorial.thrift` + * `shared.thrift` +As the former includes the latter, one uses it to generate the interfaces: + + $THRIFT/bin/thrift -r --gen cl $THRIFT/tutorial/tutorial.thrift + +`-r` stands for recursion, while `--gen` lets one choose the language to translate to. + + +Load the Lisp translated service interfaces +------------------------------------------- + +The translator generates three files for each IDL file. For example `tutorial-types.lisp`, +`tutorial-vars.lisp` and an `.asd` file that can be used to load them both and pull in +other includes (like `shared` within the tutorial) as dependencies. + + +Run a Server for the Service +---------------------------- + +The actual service name, as specified in the `def-service` form in `tutorial.lisp`, is `calculator`. +Each service definition defines a global variable with the service name and binds it to a +service instance whch describes the operations. + +In order to start a service, specify a location and the service instance. + + (in-package :tutorial) + (serve #u"thrift://127.0.0.1:9091" calculator) + + +Use a Client to Access the Service Remotely +------------------------------------------- + + +[in some other process] run the client + + (in-package :cl-user) + + (macrolet ((show (form) + `(format *trace-output* "~%~s =>~{ ~s~}" + ',form + (multiple-value-list (ignore-errors ,form))))) + (with-client (protocol #u"thrift://127.0.0.1:9091") + (show (tutorial.calculator:ping protocol)) + (show (tutorial.calculator:add protocol 1 2)) + (show (tutorial.calculator:add protocol 1 4)) + + (let ((task (make-instance 'tutorial:work + :op operation.subtract :num1 15 :num2 10))) + (show (tutorial.calculator:calculate protocol 1 task)) + + (setf (tutorial:work-op task) operation.divide + (tutorial:work-num1 task) 1 + (tutorial:work-num2 task) 0) + (show (tutorial.calculator:calculate protocol 1 task))) + + (show (shared.shared-service:get-struct protocol 1)) + + (show (zip protocol)))) + +Issues +------ + +### optional fields + Where the IDL declares a field options, the def-struct form includes no + initform for the slot and the encoding operator skips an unbound slot. This leave some ambiguity + with bool fields. + +### instantiation protocol : + struct classes are standard classes and exception classes are + whatever the implementation prescribes. decoders apply make-struct to an initargs list. + particularly at the service end, there are advantages to resourcing structs and decoding + with direct side-effects on slot-values + +### maps: + Maps are now represented as hash tables. As data through the call/reply interface is all statically + typed, it is not necessary for the objects to themselves indicate the coding form. Association lists + would be sufficient. As the key type is arbitrary, property lists offer no additional convenience: + as `getf` operates with `eq` a new access interface would be necessary and they would not be + available for function application. + + + [1]: www.common-lisp.net/asdf + [2]: http://github.com/lisp/com.b9.puri.ppcre + [3]: www.common-lisp.net/closer-mop + [4]: trivial-utf-8 + [5]: https://github.com/usocket/usocket + [6]: https://github.com/marijnh/ieee-floats + [7]: https://github.com/trivial-gray-streams/trivial-gray-streams + [8]: https://gitlab.common-lisp.net/alexandria/alexandria + [9]: http://wiki.apache.org/thrift/ThriftGeneration + +* usocket[[5]] : for the socket transport +* ieee-floats[[6]] : for conversion between ints and floats +* trivial-gray-streams[[7]] : an abstraction layer for gray streams +* alexandria[[8]] : handy utilities diff --git a/vendor/git.apache.org/thrift.git/lib/cl/READMES/readme-cassandra.lisp b/vendor/git.apache.org/thrift.git/lib/cl/READMES/readme-cassandra.lisp new file mode 100644 index 0000000..72744ea --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/cl/READMES/readme-cassandra.lisp @@ -0,0 +1,64 @@ +(in-package :cl-user) + +#+(or ccl sbcl) /development/source/library/ +(load "build-init.lisp") + +;;; ! first, select the api version in the cassandra system definition +;;; as only one should be loaded at a time. +(asdf:load-system :de.setf.cassandra) + +(in-package :de.setf.cassandra) + +(defparameter *c-location* + ;; remote + ;; #u"thrift://ec2-174-129-66-148.compute-1.amazonaws.com:9160" + ;; local + #u"thrift://127.0.0.1:9160" + "A cassandra service location - either the local one or a remote service + - always a 'thrift' uri.") + +(defparameter *c* (thrift:client *c-location*)) + + +(cassandra:describe-keyspaces *c*) +;; => ("Keyspace1" "system") + +(cassandra:describe-cluster-name *c*) +;; =>"Test Cluster" + +(cassandra:describe-version *c*) +;; => "2.1.0" + +(loop for space in (cassandra:describe-keyspaces *c*) + collect (loop for key being each hash-key of (cassandra:describe-keyspace *c* space) + using (hash-value value) + collect (cons key + (loop for key being each hash-key of value + using (hash-value value) + collect (cons key value))))) + + +(close *c*) + +(defun describe-cassandra (location &optional (stream *standard-output*)) + "Print the first-order store metadata for a cassandra LOCATION." + + (thrift:with-client (cassandra location) + (let* ((keyspace-names (cassandra:describe-keyspaces cassandra)) + (cluster (cassandra:describe-cluster-name cassandra)) + (version (cassandra:describe-version cassandra)) + (keyspace-descriptions (loop for space in keyspace-names + collect (cons space + (loop for key being each hash-key + of (cassandra:describe-keyspace cassandra space) + using (hash-value value) + collect (cons key + (loop for key being each hash-key of value + using (hash-value value) + collect (cons key value)))))))) + (format stream "~&connection to : ~a" cassandra) + (format stream "~&version : ~a" version) + (format stream "~&cluster : ~a" cluster) + (format stream "~&keyspaces~{~{~%~%space: ~a~@{~% ~{~a :~@{~20t~:w~^~%~}~}~}~}~}" keyspace-descriptions)))) + +;;; (describe-cassandra *c-location*) diff --git a/vendor/git.apache.org/thrift.git/lib/cl/ensure-externals.sh b/vendor/git.apache.org/thrift.git/lib/cl/ensure-externals.sh new file mode 100755 index 0000000..0495f03 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/cl/ensure-externals.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +set -e + +if [[ ! -e quicklisp.lisp ]]; then curl -O https://beta.quicklisp.org/quicklisp.lisp; fi +sbcl --load quicklisp.lisp \ + --eval "(ignore-errors (quicklisp-quickstart:install :path \"quicklisp/\"))" \ + --eval "(load \"quicklisp/setup.lisp\")" \ + --eval "(quicklisp:bundle-systems '(#:puri #:usocket #:closer-mop #:trivial-utf-8 #:ieee-floats #:trivial-gray-streams #:alexandria #:bordeaux-threads #:cl-ppcre #:fiasco #:net.didierverna.clon) :to \"externals/\")" \ + --eval "(quit)" \ + --no-userinit +if [[ ! -e backport-update.zip ]]; then + curl -O -L https://github.com/TurtleWarePL/de.setf.thrift/archive/backport-update.zip; +fi +mkdir -p lib +unzip -u backport-update.zip -d lib diff --git a/vendor/git.apache.org/thrift.git/lib/cl/load-locally.lisp b/vendor/git.apache.org/thrift.git/lib/cl/load-locally.lisp new file mode 100644 index 0000000..d12c704 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/cl/load-locally.lisp @@ -0,0 +1,23 @@ +(in-package #:cl-user) + +;;;; 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. + +;;;; Just a script for loading the library itself, using bundled dependencies. +;;;; This is here for when we want to build the self-test and cross-test +;;;; binaries. + +(require "asdf") + +(load (merge-pathnames "externals/bundle.lisp" *load-truename*)) +(asdf:load-asd (merge-pathnames "lib/de.setf.thrift-backport-update/thrift.asd" *load-truename*)) +(asdf:load-system :thrift) diff --git a/vendor/git.apache.org/thrift.git/lib/cl/test/make-test-binary.lisp b/vendor/git.apache.org/thrift.git/lib/cl/test/make-test-binary.lisp new file mode 100644 index 0000000..4e7a58c --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/cl/test/make-test-binary.lisp @@ -0,0 +1,31 @@ +;;;; 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. + +;;;; This file is used to build the binary that runs all self-tests. The +;;;; binary is then meant to be hooked up to Thrift's `make check` facility, +;;;; but can easily be run on its own as well. + +(in-package #:cl-user) + +(require "asdf") +(load (merge-pathnames "../load-locally.lisp" *load-truename*)) +(asdf:load-asd (merge-pathnames "../lib/de.setf.thrift-backport-update/test/thrift-test.asd" *load-truename*)) +(asdf:load-system :thrift-test) +(asdf:load-system :net.didierverna.clon) + +(net.didierverna.clon:nickname-package) + +(defun main () + (let ((result (if (fiasco:run-tests 'thrift-test) 0 -1))) + (clon:exit result))) + +(clon:dump "run-tests" main) diff --git a/vendor/git.apache.org/thrift.git/lib/cocoa/src/Thrift.h b/vendor/git.apache.org/thrift.git/lib/cocoa/src/Thrift.h index 5c72a01..502ba17 100644 --- a/vendor/git.apache.org/thrift.git/lib/cocoa/src/Thrift.h +++ b/vendor/git.apache.org/thrift.git/lib/cocoa/src/Thrift.h @@ -17,4 +17,4 @@ * under the License. */ -#define ThriftVersion @"0.10.0" +#define ThriftVersion @"0.12.0" diff --git a/vendor/git.apache.org/thrift.git/lib/cocoa/src/protocol/TBase.h b/vendor/git.apache.org/thrift.git/lib/cocoa/src/protocol/TBase.h index b31061e..9935d50 100644 --- a/vendor/git.apache.org/thrift.git/lib/cocoa/src/protocol/TBase.h +++ b/vendor/git.apache.org/thrift.git/lib/cocoa/src/protocol/TBase.h @@ -26,14 +26,14 @@ /** * De-serialize object from the given input protocol * - * @param input protocol used for reading + * @param inProtocol protocol used for reading */ -(BOOL) read:(id )inProtocol error:(NSError **)error; /** * Serialize object to the given protocol * - * @param buf output protocol used for writing + * @param outProtocol output protocol used for writing */ -(BOOL) write:(id )outProtocol error:(NSError **)error; diff --git a/vendor/git.apache.org/thrift.git/lib/cocoa/src/server/TSocketServer.h b/vendor/git.apache.org/thrift.git/lib/cocoa/src/server/TSocketServer.h index fe657ea..95b0d3c 100644 --- a/vendor/git.apache.org/thrift.git/lib/cocoa/src/server/TSocketServer.h +++ b/vendor/git.apache.org/thrift.git/lib/cocoa/src/server/TSocketServer.h @@ -41,6 +41,10 @@ extern NSString *const TSockerServerTransportKey; protocolFactory:(id )protocolFactory processorFactory:(id )processorFactory; +- (instancetype) initWithPath: (NSString *) path + protocolFactory: (id ) protocolFactory + processorFactory: (id ) processorFactory; + @end diff --git a/vendor/git.apache.org/thrift.git/lib/cocoa/src/server/TSocketServer.m b/vendor/git.apache.org/thrift.git/lib/cocoa/src/server/TSocketServer.m index ccbbba1..09b603c 100644 --- a/vendor/git.apache.org/thrift.git/lib/cocoa/src/server/TSocketServer.m +++ b/vendor/git.apache.org/thrift.git/lib/cocoa/src/server/TSocketServer.m @@ -25,7 +25,7 @@ #import #include - +#include NSString *const TSocketServerClientConnectionFinished = @"TSocketServerClientConnectionFinished"; @@ -40,13 +40,14 @@ NSString *const TSockerServerTransportKey = @"TSockerServerTransport"; @property(strong, nonatomic) id processorFactory; @property(strong, nonatomic) NSFileHandle *socketFileHandle; @property(strong, nonatomic) dispatch_queue_t processingQueue; +@property(strong, nonatomic) NSString *domainSocketPath; @end @implementation TSocketServer --(instancetype) initWithPort:(int)port +-(instancetype) initWithSocket:(CFSocketRef)socket protocolFactory:(id )protocolFactory processorFactory:(id )processorFactory; { @@ -62,32 +63,7 @@ NSString *const TSockerServerTransportKey = @"TSockerServerTransport"; _processingQueue = dispatch_queue_create("TSocketServer.processing", processingQueueAttr); // create a socket. - int fd = -1; - CFSocketRef socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, 0, NULL, NULL); - if (socket) { - CFSocketSetSocketFlags(socket, CFSocketGetSocketFlags(socket) & ~kCFSocketCloseOnInvalidate); - fd = CFSocketGetNative(socket); - int yes = 1; - setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&yes, sizeof(yes)); - - struct sockaddr_in addr; - memset(&addr, 0, sizeof(addr)); - addr.sin_len = sizeof(addr); - addr.sin_family = AF_INET; - addr.sin_port = htons(port); - addr.sin_addr.s_addr = htonl(INADDR_ANY); - NSData *address = [NSData dataWithBytes:&addr length:sizeof(addr)]; - if (CFSocketSetAddress(socket, (__bridge CFDataRef)address) != kCFSocketSuccess) { - CFSocketInvalidate(socket); - CFRelease(socket); - NSLog(@"TSocketServer: Could not bind to address"); - return nil; - } - } - else { - NSLog(@"TSocketServer: No server socket"); - return nil; - } + int fd = CFSocketGetNative(socket); // wrap it in a file handle so we can get messages from it _socketFileHandle = [[NSFileHandle alloc] initWithFileDescriptor:fd @@ -106,15 +82,114 @@ NSString *const TSockerServerTransportKey = @"TSockerServerTransport"; // tell socket to listen [_socketFileHandle acceptConnectionInBackgroundAndNotify]; - NSLog(@"TSocketServer: Listening on TCP port %d", port); + return self; +} +- (id) initWithPort: (int) port + protocolFactory: (id ) protocolFactory + processorFactory: (id ) processorFactory +{ + CFSocketRef socket = [[self class] createSocketWithPort:port]; + if (socket == NULL) { + return nil; + } + + if (self = [self initWithSocket:socket protocolFactory:protocolFactory processorFactory:processorFactory]) { + NSLog(@"TSocketServer: Listening on TCP port %d", port); + } return self; } ++(CFSocketRef) createSocketWithPort:(int)port +{ + CFSocketRef socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, 0, NULL, NULL); + if (socket) { + CFSocketSetSocketFlags(socket, CFSocketGetSocketFlags(socket) & ~kCFSocketCloseOnInvalidate); + int fd = CFSocketGetNative(socket); + int yes = 1; + setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&yes, sizeof(yes)); + + struct sockaddr_in addr; + memset(&addr, 0, sizeof(addr)); + addr.sin_len = sizeof(addr); + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + addr.sin_addr.s_addr = htonl(INADDR_ANY); + NSData *address = [NSData dataWithBytes:&addr length:sizeof(addr)]; + if (CFSocketSetAddress(socket, (__bridge CFDataRef)address) != kCFSocketSuccess) { + CFSocketInvalidate(socket); + CFRelease(socket); + NSLog(@"TSocketServer: Could not bind to address"); + return NULL; + } + + return socket; + } + else { + NSLog(@"TSocketServer: No server socket"); + return NULL; + } +} + +- (id) initWithPath: (NSString *) path + protocolFactory: (id ) protocolFactory + processorFactory: (id ) processorFactory +{ + _domainSocketPath = path; + CFSocketRef socket = [[self class] createSocketWithPath:path]; + if (socket == NULL) { + return nil; + } + + if (self = [self initWithSocket:socket protocolFactory:protocolFactory processorFactory:processorFactory]) { + NSLog(@"TSocketServer: Listening on path %@", path); + } + return self; +} + ++ (CFSocketRef) createSocketWithPath: (NSString *) path +{ + CFSocketRef socket = CFSocketCreate(kCFAllocatorDefault, PF_LOCAL, SOCK_STREAM, IPPROTO_IP, 0, NULL, NULL); + if (socket) { + CFSocketSetSocketFlags(socket, CFSocketGetSocketFlags(socket) & ~kCFSocketCloseOnInvalidate); + int fd = CFSocketGetNative(socket); + int yes = 1; + setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&yes, sizeof(yes)); + + size_t nullTerminatedPathLength = path.length + 1; + struct sockaddr_un addr; + if (nullTerminatedPathLength> sizeof(addr.sun_path)) { + NSLog(@"TSocketServer: Unable to create socket at path %@. Path is too long.", path); + return NULL; + } + + addr.sun_family = AF_LOCAL; + memcpy(addr.sun_path, path.UTF8String, nullTerminatedPathLength); + addr.sun_len = SUN_LEN(&addr); + + NSData *address = [NSData dataWithBytes:&addr length:sizeof(addr)]; + if (CFSocketSetAddress(socket, (__bridge CFDataRef)address) != kCFSocketSuccess) { + CFSocketInvalidate(socket); + CFRelease(socket); + NSLog(@"TSocketServer: Could not bind to address"); + return NULL; + } + + return socket; + } else { + NSLog(@"TSocketServer: No server socket"); + return NULL; + } +} + -(void) dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; + + if (_domainSocketPath != nil) { + unlink(_domainSocketPath.UTF8String); + } } diff --git a/vendor/git.apache.org/thrift.git/lib/cocoa/src/transport/TNSStreamTransport.m b/vendor/git.apache.org/thrift.git/lib/cocoa/src/transport/TNSStreamTransport.m index c425043..18c41d3 100644 --- a/vendor/git.apache.org/thrift.git/lib/cocoa/src/transport/TNSStreamTransport.m +++ b/vendor/git.apache.org/thrift.git/lib/cocoa/src/transport/TNSStreamTransport.m @@ -94,7 +94,7 @@ -(BOOL) write:(const UInt8 *)data offset:(UInt32)offset length:(UInt32)length error:(NSError *__autoreleasing *)error { - int got = 0; + UInt32 got = 0; NSInteger total = 0; while (got < length) { diff --git a/vendor/git.apache.org/thrift.git/lib/cocoa/src/transport/TSocketTransport.h b/vendor/git.apache.org/thrift.git/lib/cocoa/src/transport/TSocketTransport.h index 4ea03cc..a7b91a2 100644 --- a/vendor/git.apache.org/thrift.git/lib/cocoa/src/transport/TSocketTransport.h +++ b/vendor/git.apache.org/thrift.git/lib/cocoa/src/transport/TSocketTransport.h @@ -28,6 +28,8 @@ NS_ASSUME_NONNULL_BEGIN -(id) initWithHostname:(NSString *)hostname port:(int)port; +-(id) initWithPath:(NSString *)path; + @end diff --git a/vendor/git.apache.org/thrift.git/lib/cocoa/src/transport/TSocketTransport.m b/vendor/git.apache.org/thrift.git/lib/cocoa/src/transport/TSocketTransport.m index 272baf6..9c58abb 100644 --- a/vendor/git.apache.org/thrift.git/lib/cocoa/src/transport/TSocketTransport.m +++ b/vendor/git.apache.org/thrift.git/lib/cocoa/src/transport/TSocketTransport.m @@ -24,21 +24,21 @@ #import #endif +#include +#include +#include + @interface TSocketTransport () @end @implementation TSocketTransport --(id) initWithHostname:(NSString *)hostname - port:(int)port +- (id) initWithReadStream: (CFReadStreamRef) readStream writeStream: (CFWriteStreamRef) writeStream { NSInputStream *inputStream = nil; NSOutputStream *outputStream = nil; - CFReadStreamRef readStream = NULL; - CFWriteStreamRef writeStream = NULL; - CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (__bridge CFStringRef)hostname, port, &readStream, &writeStream); if (readStream && writeStream) { CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue); @@ -70,4 +70,62 @@ return [super initWithInputStream:inputStream outputStream:outputStream]; } +- (id) initWithHostname: (NSString *) hostname + port: (int) port +{ + CFReadStreamRef readStream = NULL; + CFWriteStreamRef writeStream = NULL; + CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (__bridge CFStringRef)hostname, port, &readStream, &writeStream); + return [self initWithReadStream:readStream writeStream:writeStream]; +} + +- (id) initWithPath: (NSString *) path +{ + CFSocketNativeHandle sockfd = socket(AF_LOCAL, SOCK_STREAM, IPPROTO_IP); + int yes = 1; + if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) < 0) + { + NSLog(@"TSocketTransport: Unable to set REUSEADDR property of socket."); + return nil; + } + + NSData *serverAddress = [[self class] createAddressWithPath:path]; + + CFReadStreamRef readStream = NULL; + CFWriteStreamRef writeStream = NULL; + CFStreamCreatePairWithSocket(kCFAllocatorDefault, sockfd, &readStream, &writeStream); + if (!readStream || !writeStream) + { + NSLog(@"TSocketTransport: Unable to create read/write stream pair for socket."); + return nil; + } + + if (connect(sockfd, (struct sockaddr *)serverAddress.bytes, (socklen_t) serverAddress.length) < 0) + { + NSLog(@"TSocketTransport: Connect error: %s\n", strerror(errno)); + return nil; + } + + return [self initWithReadStream:readStream writeStream:writeStream]; +} + ++ (NSData *) createAddressWithPath: (NSString *)path +{ + struct sockaddr_un servaddr; + + size_t nullTerminatedPathLength = path.length + 1; + if (nullTerminatedPathLength> sizeof(servaddr.sun_path)) { + NSLog(@"TSocketTransport: Unable to create socket at path %@. Path is too long.", path); + return nil; + } + + bzero(&servaddr,sizeof(servaddr)); + servaddr.sun_family = AF_LOCAL; + memcpy(servaddr.sun_path, path.UTF8String, nullTerminatedPathLength); + servaddr.sun_len = SUN_LEN(&servaddr); + + return [NSData dataWithBytes:&servaddr length:sizeof(servaddr)]; +} + + @end diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/CMakeLists.txt b/vendor/git.apache.org/thrift.git/lib/cpp/CMakeLists.txt index d07b400..1ed0bfa 100755 --- a/vendor/git.apache.org/thrift.git/lib/cpp/CMakeLists.txt +++ b/vendor/git.apache.org/thrift.git/lib/cpp/CMakeLists.txt @@ -28,6 +28,7 @@ set( thriftcpp_SOURCES src/thrift/TApplicationException.cpp src/thrift/TOutput.cpp src/thrift/async/TAsyncChannel.cpp + src/thrift/async/TAsyncProtocolProcessor.cpp src/thrift/async/TConcurrentClientSyncInfo.h src/thrift/async/TConcurrentClientSyncInfo.cpp src/thrift/concurrency/ThreadManager.cpp @@ -57,7 +58,7 @@ set( thriftcpp_SOURCES src/thrift/server/TThreadedServer.cpp ) -# This files don't work on Windows CE as there is no pipe support +# These files don't work on Windows CE as there is no pipe support # TODO: These files won't work with UNICODE support on windows. If fixed this can be re-added. if (NOT WINCE) list(APPEND thriftcpp_SOURCES @@ -138,7 +139,8 @@ endif() # Thrift non blocking server set( thriftcppnb_SOURCES src/thrift/server/TNonblockingServer.cpp - src/thrift/async/TAsyncProtocolProcessor.cpp + src/thrift/transport/TNonblockingServerSocket.cpp + src/thrift/transport/TNonblockingSSLServerSocket.cpp src/thrift/async/TEvhttpServer.cpp src/thrift/async/TEvhttpClientChannel.cpp ) diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/Makefile.am b/vendor/git.apache.org/thrift.git/lib/cpp/Makefile.am index 2a1cca8..83ccd9b 100755 --- a/vendor/git.apache.org/thrift.git/lib/cpp/Makefile.am +++ b/vendor/git.apache.org/thrift.git/lib/cpp/Makefile.am @@ -62,7 +62,7 @@ pkgconfig_DATA += thrift-qt5.pc endif AM_CXXFLAGS = -Wall -Wextra -pedantic -AM_CPPFLAGS = $(BOOST_CPPFLAGS) $(OPENSSL_INCLUDES) -I$(srcdir)/src -D__STDC_LIMIT_MACROS +AM_CPPFLAGS = $(BOOST_CPPFLAGS) $(OPENSSL_INCLUDES) -I$(srcdir)/src -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS # Define the source files for the module @@ -70,6 +70,7 @@ libthrift_la_SOURCES = src/thrift/TApplicationException.cpp \ src/thrift/TOutput.cpp \ src/thrift/VirtualProfiling.cpp \ src/thrift/async/TAsyncChannel.cpp \ + src/thrift/async/TAsyncProtocolProcessor.cpp \ src/thrift/async/TConcurrentClientSyncInfo.cpp \ src/thrift/concurrency/ThreadManager.cpp \ src/thrift/concurrency/TimerManager.cpp \ @@ -94,6 +95,8 @@ libthrift_la_SOURCES = src/thrift/TApplicationException.cpp \ src/thrift/transport/TSocketPool.cpp \ src/thrift/transport/TServerSocket.cpp \ src/thrift/transport/TSSLServerSocket.cpp \ + src/thrift/transport/TNonblockingServerSocket.cpp \ + src/thrift/transport/TNonblockingSSLServerSocket.cpp \ src/thrift/transport/TTransportUtils.cpp \ src/thrift/transport/TBufferTransports.cpp \ src/thrift/server/TConnectedClient.cpp \ @@ -114,13 +117,12 @@ libthrift_la_SOURCES += src/thrift/concurrency/Mutex.cpp \ endif libthriftnb_la_SOURCES = src/thrift/server/TNonblockingServer.cpp \ - src/thrift/async/TAsyncProtocolProcessor.cpp \ src/thrift/async/TEvhttpServer.cpp \ src/thrift/async/TEvhttpClientChannel.cpp libthriftz_la_SOURCES = src/thrift/transport/TZlibTransport.cpp \ src/thrift/transport/THeaderTransport.cpp \ - src/thrift/protocol/THeaderProtocol.cpp + src/thrift/protocol/THeaderProtocol.cpp libthriftqt_la_MOC = src/thrift/qt/moc_TQTcpServer.cpp @@ -148,7 +150,7 @@ libthriftz_la_CXXFLAGS = $(AM_CXXFLAGS) libthriftqt_la_CXXFLAGS = $(AM_CXXFLAGS) libthriftqt5_la_CXXFLAGS = $(AM_CXXFLAGS) libthriftnb_la_LDFLAGS = -release $(VERSION) $(BOOST_LDFLAGS) -libthriftz_la_LDFLAGS = -release $(VERSION) $(BOOST_LDFLAGS) +libthriftz_la_LDFLAGS = -release $(VERSION) $(BOOST_LDFLAGS) $(ZLIB_LIBS) libthriftqt_la_LDFLAGS = -release $(VERSION) $(BOOST_LDFLAGS) $(QT_LIBS) libthriftqt5_la_LDFLAGS = -release $(VERSION) $(BOOST_LDFLAGS) $(QT5_LIBS) @@ -162,8 +164,8 @@ include_thrift_HEADERS = \ src/thrift/TProcessor.h \ src/thrift/TApplicationException.h \ src/thrift/TLogging.h \ - src/thrift/cxxfunctional.h \ src/thrift/TToString.h \ + src/thrift/stdcxx.h \ src/thrift/TBase.h include_concurrencydir = $(include_thriftdir)/concurrency @@ -212,6 +214,9 @@ include_transport_HEADERS = \ src/thrift/transport/TServerSocket.h \ src/thrift/transport/TSSLServerSocket.h \ src/thrift/transport/TServerTransport.h \ + src/thrift/transport/TNonblockingServerTransport.h \ + src/thrift/transport/TNonblockingServerSocket.h \ + src/thrift/transport/TNonblockingSSLServerSocket.h \ src/thrift/transport/THttpTransport.h \ src/thrift/transport/THttpClient.h \ src/thrift/transport/THttpServer.h \ @@ -260,8 +265,6 @@ include_qt_HEADERS = \ src/thrift/qt/TQIODeviceTransport.h \ src/thrift/qt/TQTcpServer.h -THRIFT = $(top_builddir)/compiler/cpp/thrift - WINDOWS_DIST = \ src/thrift/windows \ thrift.sln \ diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/README.md b/vendor/git.apache.org/thrift.git/lib/cpp/README.md index 2bee2ec..e744a6a 100755 --- a/vendor/git.apache.org/thrift.git/lib/cpp/README.md +++ b/vendor/git.apache.org/thrift.git/lib/cpp/README.md @@ -19,7 +19,6 @@ KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - # Using Thrift with C++ The Thrift C++ libraries are built using the GNU tools. Follow the instructions @@ -55,15 +54,22 @@ you are using libthriftnb you will also need libevent. ## Dependencies -boost shared pointers -http://www.boost.org/libs/smart_ptr/smart_ptr.htm +If your C++ environment implements C++11 or later, thrift will automatically use +std::shared_ptr. Otherwise you will need the boost library to provide a shared_ptr +implementation for C++ environments pre-C++11. If you are linking against code +that expects to be using boost::shared_ptr, you can define the preprocessor +variable FORCE_BOOST_SMART_PTR for your build of thrift to make it use boost instead +of std for a number of memory related classes. See thrift/stdcxx.h for more. libevent (for libthriftnb only) http://monkey.org/~provos/libevent/ # Using Thrift with C++ on Windows -You need to define an environment variables for 3rd party components separately: +Both the autoconf and cmake build systems are able to automatically detect many +system configurations without the need to specify library locations, however if +you run into problems or want to redirect thrift to build and link against your +own provided third party libraries: BOOST_ROOT : For boost, e.g. D:\boost_1_55_0 OPENSSL_ROOT_DIR : For OpenSSL, e.g. D:\OpenSSL-Win32 @@ -74,13 +80,7 @@ LIBEVENT_ROOT_DIR : For Libevent e.g. D:\libevent-2.0.21-stable See /3rdparty.user for more details. -Thrift is divided into two libraries. - -* libthrift - The core Thrift library contains all the core Thrift code. It requires - boost shared pointers, pthreads, and librt. - -* libthriftnb - This library contains the Thrift nonblocking server, which uses libevent. - To link this library you will also need to link libevent. +The same linking guidelines described above for libthriftnb apply to windows as well. ## Linking Against Thrift @@ -93,8 +93,7 @@ the config header: "windows/confg.h" ## Dependencies -boost shared pointers -http://www.boost.org/libs/smart_ptr/smart_ptr.htm +The same dependencies for shared_ptr as described above apply to windows as well. boost thread http://www.boost.org/doc/libs/release/doc/html/thread.html @@ -272,3 +271,26 @@ OpenSSL's RAND_poll() when OpenSSL library is first initialized. The PRNG seed is key to the application security. This method should be overridden if it's not strong enough for you. + +# Breaking Changes + +## 0.11.0 + +Older versions of thrift depended on the classes which +were used in thrift headers to define interfaces. Thrift now detects C++11 +at build time and will prefer to use classes from C++11 instead. +You can force the library to build with boost memory classes by defining the +preprocessor macro `FORCE_BOOST_SMART_PTR`. (THRIFT-2221) + +In the pthread mutex implementation, the contention profiling code was enabled +by default in all builds. This changed to be disabled by default. (THRIFT-4151) + +In older releases, if a TSSLSocketFactory's lifetime was not at least as long +as the TSSLSockets it created, we silently reverted openssl to unsafe multithread behavior +and so the results were undefined. Changes were made in 0.11.0 that cause either an +assertion or a core instead of undefined behavior. The lifetime of a TSSLSocketFactory +*must* be longer than any TSSLSocket that it creates, otherwise openssl will be cleaned +up too early. If the static boolean is set to disable openssl initialization and +cleanup and leave it up to the consuming application, this requirement is not needed. +(THRIFT-4164) + diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/libthrift.vcxproj b/vendor/git.apache.org/thrift.git/lib/cpp/libthrift.vcxproj index db0e5d9..d1097ec 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/libthrift.vcxproj +++ b/vendor/git.apache.org/thrift.git/lib/cpp/libthrift.vcxproj @@ -53,6 +53,9 @@ + + + diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/libthriftnb.vcxproj b/vendor/git.apache.org/thrift.git/lib/cpp/libthriftnb.vcxproj index 259bb20..9a6ffe6 100755 --- a/vendor/git.apache.org/thrift.git/lib/cpp/libthriftnb.vcxproj +++ b/vendor/git.apache.org/thrift.git/lib/cpp/libthriftnb.vcxproj @@ -35,16 +35,21 @@ - - - - + + + + + + + + + @@ -290,4 +295,4 @@ - + \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/libthriftnb.vcxproj.filters b/vendor/git.apache.org/thrift.git/lib/cpp/libthriftnb.vcxproj.filters index 5245544..85703dd 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/libthriftnb.vcxproj.filters +++ b/vendor/git.apache.org/thrift.git/lib/cpp/libthriftnb.vcxproj.filters @@ -10,6 +10,9 @@ {60fc9e5e-0866-4aba-8662-439bb4a461d3} + + {23fe2fde-a7c9-43ec-a409-7f53df5eee64} + @@ -27,6 +30,12 @@ windows + + transport + + + transport + @@ -53,5 +62,14 @@ windows + + transport + + + transport + + + transport + - \ No newline at end of file + diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/TDispatchProcessor.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/TDispatchProcessor.h index fd1dce7..dadc87b 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/TDispatchProcessor.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/TDispatchProcessor.h @@ -33,8 +33,8 @@ namespace thrift { template class TDispatchProcessorT : public TProcessor { public: - virtual bool process(boost::shared_ptr in, - boost::shared_ptr out, + virtual bool process(stdcxx::shared_ptr in, + stdcxx::shared_ptr out, void* connectionContext) { protocol::TProtocol* inRaw = in.get(); protocol::TProtocol* outRaw = out.get(); @@ -105,8 +105,8 @@ protected: */ class TDispatchProcessor : public TProcessor { public: - virtual bool process(boost::shared_ptr in, - boost::shared_ptr out, + virtual bool process(stdcxx::shared_ptr in, + stdcxx::shared_ptr out, void* connectionContext) { std::string fname; protocol::TMessageType mtype; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/TOutput.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/TOutput.cpp index 5739d0f..ae3a9e2 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/TOutput.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/TOutput.cpp @@ -18,9 +18,9 @@ */ #include +#include #include #include -#include #include #include @@ -94,13 +94,13 @@ void TOutput::errorTimeWrapper(const char* msg) { } void TOutput::perror(const char* message, int errno_copy) { - std::string out = message + strerror_s(errno_copy); + std::string out = message + std::string(": ") + strerror_s(errno_copy); f_(out.c_str()); } std::string TOutput::strerror_s(int errno_copy) { #ifndef HAVE_STRERROR_R - return "errno = " + boost::lexical_cast(errno_copy); + return "errno = " + to_string(errno_copy); #else // HAVE_STRERROR_R char b_errbuf[1024] = {'\0'}; @@ -112,7 +112,7 @@ std::string TOutput::strerror_s(int errno_copy) { if (rv == -1) { // strerror_r failed. omgwtfbbq. return "XSI-compliant strerror_r() failed with errno = " - + boost::lexical_cast(errno_copy); + + to_string(errno_copy); } #endif // Can anyone prove that explicit cast is probably not necessary diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/TProcessor.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/TProcessor.h index 4a0604e..27294d3 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/TProcessor.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/TProcessor.h @@ -22,7 +22,7 @@ #include #include -#include +#include namespace apache { namespace thrift { @@ -142,28 +142,28 @@ class TProcessor { public: virtual ~TProcessor() {} - virtual bool process(boost::shared_ptr in, - boost::shared_ptr out, + virtual bool process(stdcxx::shared_ptr in, + stdcxx::shared_ptr out, void* connectionContext) = 0; - bool process(boost::shared_ptr io, void* connectionContext) { + bool process(stdcxx::shared_ptr io, void* connectionContext) { return process(io, io, connectionContext); } - boost::shared_ptr getEventHandler() const { return eventHandler_; } + stdcxx::shared_ptr getEventHandler() const { return eventHandler_; } - void setEventHandler(boost::shared_ptr eventHandler) { + void setEventHandler(stdcxx::shared_ptr eventHandler) { eventHandler_ = eventHandler; } protected: TProcessor() {} - boost::shared_ptr eventHandler_; + stdcxx::shared_ptr eventHandler_; }; /** - * This is a helper class to allow boost::shared_ptr to be used with handler + * This is a helper class to allow stdcxx::shared_ptr to be used with handler * pointers returned by the generated handler factories. * * The handler factory classes generated by the thrift compiler return raw @@ -177,7 +177,7 @@ protected: template class ReleaseHandler { public: - ReleaseHandler(const boost::shared_ptr& handlerFactory) + ReleaseHandler(const stdcxx::shared_ptr& handlerFactory) : handlerFactory_(handlerFactory) {} void operator()(typename HandlerFactory_::Handler* handler) { @@ -187,18 +187,18 @@ public: } private: - boost::shared_ptr handlerFactory_; + stdcxx::shared_ptr handlerFactory_; }; struct TConnectionInfo { // The input and output protocols - boost::shared_ptr input; - boost::shared_ptr output; + stdcxx::shared_ptr input; + stdcxx::shared_ptr output; // The underlying transport used for the connection // This is the transport that was returned by TServerTransport::accept(), // and it may be different than the transport pointed to by the input and // output protocols. - boost::shared_ptr transport; + stdcxx::shared_ptr transport; }; class TProcessorFactory { @@ -212,17 +212,17 @@ public: * accepted on. This generally means that this call does not need to be * thread safe, as it will always be invoked from a single thread. */ - virtual boost::shared_ptr getProcessor(const TConnectionInfo& connInfo) = 0; + virtual stdcxx::shared_ptr getProcessor(const TConnectionInfo& connInfo) = 0; }; class TSingletonProcessorFactory : public TProcessorFactory { public: - TSingletonProcessorFactory(boost::shared_ptr processor) : processor_(processor) {} + TSingletonProcessorFactory(stdcxx::shared_ptr processor) : processor_(processor) {} - boost::shared_ptr getProcessor(const TConnectionInfo&) { return processor_; } + stdcxx::shared_ptr getProcessor(const TConnectionInfo&) { return processor_; } private: - boost::shared_ptr processor_; + stdcxx::shared_ptr processor_; }; } } // apache::thrift diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/TToString.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/TToString.h index 5023869..25780f9 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/TToString.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/TToString.h @@ -20,20 +20,45 @@ #ifndef _THRIFT_TOSTRING_H_ #define _THRIFT_TOSTRING_H_ 1 -#include - -#include +#include +#include #include #include -#include #include +#include +#include namespace apache { namespace thrift { template std::string to_string(const T& t) { - return boost::lexical_cast(t); + std::ostringstream o; + o << t; + return o.str(); +} + +// TODO: replace the computations below with std::numeric_limits::max_digits10 once C++11 +// is enabled. +inline std::string to_string(const float& t) { + std::ostringstream o; + o.precision(static_cast(std::ceil(static_cast(std::numeric_limits::digits * std::log10(2.0f) + 1)))); + o << t; + return o.str(); +} + +inline std::string to_string(const double& t) { + std::ostringstream o; + o.precision(static_cast(std::ceil(static_cast(std::numeric_limits::digits * std::log10(2.0f) + 1)))); + o << t; + return o.str(); +} + +inline std::string to_string(const long double& t) { + std::ostringstream o; + o.precision(static_cast(std::ceil(static_cast(std::numeric_limits::digits * std::log10(2.0f) + 1)))); + o << t; + return o.str(); } template diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncBufferProcessor.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncBufferProcessor.h index 3c957a6..0d56c78 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncBufferProcessor.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncBufferProcessor.h @@ -20,9 +20,7 @@ #ifndef _THRIFT_TASYNC_BUFFER_PROCESSOR_H_ #define _THRIFT_TASYNC_BUFFER_PROCESSOR_H_ 1 -#include -#include - +#include #include namespace apache { @@ -36,9 +34,9 @@ public: // forcefully close the connection (if applicable). // "in" and "out" should be TMemoryBuffer or similar, // not a wrapper around a socket. - virtual void process(apache::thrift::stdcxx::function _return, - boost::shared_ptr ibuf, - boost::shared_ptr obuf) = 0; + virtual void process(stdcxx::function _return, + stdcxx::shared_ptr ibuf, + stdcxx::shared_ptr obuf) = 0; virtual ~TAsyncBufferProcessor() {} }; } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncChannel.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncChannel.cpp index 4716af2..c87659f 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncChannel.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncChannel.cpp @@ -18,7 +18,7 @@ */ #include -#include +#include namespace apache { namespace thrift { diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncChannel.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncChannel.h index eb3ce2a..f8d2b03 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncChannel.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncChannel.h @@ -20,7 +20,7 @@ #ifndef _THRIFT_ASYNC_TASYNCCHANNEL_H_ #define _THRIFT_ASYNC_TASYNCCHANNEL_H_ 1 -#include +#include #include namespace apache { diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncDispatchProcessor.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncDispatchProcessor.h index e79c57d..a1450f0 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncDispatchProcessor.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncDispatchProcessor.h @@ -35,8 +35,8 @@ template class TAsyncDispatchProcessorT : public TAsyncProcessor { public: virtual void process(apache::thrift::stdcxx::function _return, - boost::shared_ptr in, - boost::shared_ptr out) { + stdcxx::shared_ptr in, + stdcxx::shared_ptr out) { protocol::TProtocol* inRaw = in.get(); protocol::TProtocol* outRaw = out.get(); @@ -107,8 +107,8 @@ public: class TAsyncDispatchProcessor : public TAsyncProcessor { public: virtual void process(apache::thrift::stdcxx::function _return, - boost::shared_ptr in, - boost::shared_ptr out) { + stdcxx::shared_ptr in, + stdcxx::shared_ptr out) { protocol::TProtocol* inRaw = in.get(); protocol::TProtocol* outRaw = out.get(); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncProcessor.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncProcessor.h index 01a34c4..afc4ffa 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncProcessor.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncProcessor.h @@ -20,9 +20,8 @@ #ifndef _THRIFT_TASYNCPROCESSOR_H_ #define _THRIFT_TASYNCPROCESSOR_H_ 1 -#include -#include #include +#include #include namespace apache { @@ -38,25 +37,25 @@ class TAsyncProcessor { public: virtual ~TAsyncProcessor() {} - virtual void process(apache::thrift::stdcxx::function _return, - boost::shared_ptr in, - boost::shared_ptr out) = 0; + virtual void process(stdcxx::function _return, + stdcxx::shared_ptr in, + stdcxx::shared_ptr out) = 0; - void process(apache::thrift::stdcxx::function _return, - boost::shared_ptr io) { + void process(stdcxx::function _return, + stdcxx::shared_ptr io) { return process(_return, io, io); } - boost::shared_ptr getEventHandler() const { return eventHandler_; } + stdcxx::shared_ptr getEventHandler() const { return eventHandler_; } - void setEventHandler(boost::shared_ptr eventHandler) { + void setEventHandler(stdcxx::shared_ptr eventHandler) { eventHandler_ = eventHandler; } protected: TAsyncProcessor() {} - boost::shared_ptr eventHandler_; + stdcxx::shared_ptr eventHandler_; }; class TAsyncProcessorFactory { @@ -70,16 +69,15 @@ public: * accepted on. This generally means that this call does not need to be * thread safe, as it will always be invoked from a single thread. */ - virtual boost::shared_ptr getProcessor(const TConnectionInfo& connInfo) = 0; + virtual stdcxx::shared_ptr getProcessor(const TConnectionInfo& connInfo) = 0; }; } } } // apache::thrift::async -// XXX I'm lazy for now namespace apache { namespace thrift { -using apache::thrift::async::TAsyncProcessor; + using apache::thrift::async::TAsyncProcessor; } } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncProtocolProcessor.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncProtocolProcessor.cpp index 5a4f347..b9ffb04 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncProtocolProcessor.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncProtocolProcessor.cpp @@ -27,10 +27,10 @@ namespace thrift { namespace async { void TAsyncProtocolProcessor::process(apache::thrift::stdcxx::function _return, - boost::shared_ptr ibuf, - boost::shared_ptr obuf) { - boost::shared_ptr iprot(pfact_->getProtocol(ibuf)); - boost::shared_ptr oprot(pfact_->getProtocol(obuf)); + stdcxx::shared_ptr ibuf, + stdcxx::shared_ptr obuf) { + stdcxx::shared_ptr iprot(pfact_->getProtocol(ibuf)); + stdcxx::shared_ptr oprot(pfact_->getProtocol(obuf)); return underlying_ ->process(apache::thrift::stdcxx::bind(&TAsyncProtocolProcessor::finish, _return, @@ -42,7 +42,7 @@ void TAsyncProtocolProcessor::process(apache::thrift::stdcxx::function _return, - boost::shared_ptr oprot, + stdcxx::shared_ptr oprot, bool healthy) { (void)oprot; // This is a stub function to hold a reference to oprot. diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncProtocolProcessor.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncProtocolProcessor.h index 3f2b394..ce3883c 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncProtocolProcessor.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TAsyncProtocolProcessor.h @@ -30,23 +30,23 @@ namespace async { class TAsyncProtocolProcessor : public TAsyncBufferProcessor { public: - TAsyncProtocolProcessor(boost::shared_ptr underlying, - boost::shared_ptr pfact) + TAsyncProtocolProcessor(stdcxx::shared_ptr underlying, + stdcxx::shared_ptr pfact) : underlying_(underlying), pfact_(pfact) {} virtual void process(apache::thrift::stdcxx::function _return, - boost::shared_ptr ibuf, - boost::shared_ptr obuf); + stdcxx::shared_ptr ibuf, + stdcxx::shared_ptr obuf); virtual ~TAsyncProtocolProcessor() {} private: static void finish(apache::thrift::stdcxx::function _return, - boost::shared_ptr oprot, + stdcxx::shared_ptr oprot, bool healthy); - boost::shared_ptr underlying_; - boost::shared_ptr pfact_; + stdcxx::shared_ptr underlying_; + stdcxx::shared_ptr pfact_; }; } } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TConcurrentClientSyncInfo.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TConcurrentClientSyncInfo.h index 7afcbc2..9ec77b9 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TConcurrentClientSyncInfo.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TConcurrentClientSyncInfo.h @@ -22,7 +22,7 @@ #include #include #include -#include +#include #include #include #include @@ -60,7 +60,7 @@ private: class TConcurrentClientSyncInfo { private: // typedefs - typedef boost::shared_ptr< ::apache::thrift::concurrency::Monitor> MonitorPtr; + typedef stdcxx::shared_ptr< ::apache::thrift::concurrency::Monitor> MonitorPtr; typedef std::map MonitorMap; public: diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TEvhttpClientChannel.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TEvhttpClientChannel.cpp index 74acfaa..6af8104 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TEvhttpClientChannel.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TEvhttpClientChannel.cpp @@ -38,13 +38,14 @@ TEvhttpClientChannel::TEvhttpClientChannel(const std::string& host, const std::string& path, const char* address, int port, - struct event_base* eb) + struct event_base* eb, + struct evdns_base* dnsbase) + : host_(host), path_(path), conn_(NULL) { - conn_ = evhttp_connection_new(address, port); + conn_ = evhttp_connection_base_new(eb, dnsbase, address, port); if (conn_ == NULL) { throw TException("evhttp_connection_new failed"); } - evhttp_connection_set_base(conn_, eb); } TEvhttpClientChannel::~TEvhttpClientChannel() { diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TEvhttpClientChannel.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TEvhttpClientChannel.h index 72eb32d..3515ca2 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TEvhttpClientChannel.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TEvhttpClientChannel.h @@ -23,10 +23,11 @@ #include #include #include -#include +#include #include struct event_base; +struct evdns_base; struct evhttp_connection; struct evhttp_request; @@ -50,7 +51,8 @@ public: const std::string& path, const char* address, int port, - struct event_base* eb); + struct event_base* eb, + struct evdns_base *dnsbase = 0); ~TEvhttpClientChannel(); virtual void sendAndRecvMessage(const VoidCallback& cob, diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TEvhttpServer.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TEvhttpServer.cpp index 57d0d61..d87e507 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TEvhttpServer.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TEvhttpServer.cpp @@ -20,10 +20,10 @@ #include #include #include +#include #include #include #include - #include #ifndef HTTP_INTERNAL // libevent < 2 @@ -31,6 +31,8 @@ #endif using apache::thrift::transport::TMemoryBuffer; +using apache::thrift::stdcxx::scoped_ptr; +using apache::thrift::stdcxx::shared_ptr; namespace apache { namespace thrift { @@ -38,17 +40,17 @@ namespace async { struct TEvhttpServer::RequestContext { struct evhttp_request* req; - boost::shared_ptr ibuf; - boost::shared_ptr obuf; + stdcxx::shared_ptr ibuf; + stdcxx::shared_ptr obuf; RequestContext(struct evhttp_request* req); }; -TEvhttpServer::TEvhttpServer(boost::shared_ptr processor) +TEvhttpServer::TEvhttpServer(stdcxx::shared_ptr processor) : processor_(processor), eb_(NULL), eh_(NULL) { } -TEvhttpServer::TEvhttpServer(boost::shared_ptr processor, int port) +TEvhttpServer::TEvhttpServer(stdcxx::shared_ptr processor, int port) : processor_(processor), eb_(NULL), eh_(NULL) { // Create event_base and evhttp. eb_ = event_base_new(); @@ -118,7 +120,7 @@ void TEvhttpServer::process(struct evhttp_request* req) { void TEvhttpServer::complete(RequestContext* ctx, bool success) { (void)success; - std::auto_ptr ptr(ctx); + scoped_ptr ptr(ctx); int code = success ? 200 : 400; const char* reason = success ? "OK" : "Bad Request"; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TEvhttpServer.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TEvhttpServer.h index 89bf337..afc679c 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TEvhttpServer.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/async/TEvhttpServer.h @@ -20,7 +20,7 @@ #ifndef _THRIFT_TEVHTTP_SERVER_H_ #define _THRIFT_TEVHTTP_SERVER_H_ 1 -#include +#include struct event_base; struct evhttp; @@ -41,14 +41,14 @@ public: * address of the server as the extra arg. * Do not call "serve" on this server. */ - TEvhttpServer(boost::shared_ptr processor); + TEvhttpServer(stdcxx::shared_ptr processor); /** * Create a TEvhttpServer with an embedded event_base and evhttp, * listening on port and responding on the endpoint "/". * Call "serve" on this server to serve forever. */ - TEvhttpServer(boost::shared_ptr processor, int port); + TEvhttpServer(stdcxx::shared_ptr processor, int port); ~TEvhttpServer(); @@ -63,7 +63,7 @@ private: void process(struct evhttp_request* req); void complete(RequestContext* ctx, bool success); - boost::shared_ptr processor_; + stdcxx::shared_ptr processor_; struct event_base* eb_; struct evhttp* eh_; }; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/BoostMonitor.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/BoostMonitor.cpp index 6c24d82..ebfa0b9 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/BoostMonitor.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/BoostMonitor.cpp @@ -23,9 +23,9 @@ #include #include #include -#include +#include -#include +#include #include #include @@ -155,7 +155,7 @@ public: private: void init(Mutex* mutex) { mutex_ = mutex; } - boost::scoped_ptr ownedMutex_; + stdcxx::scoped_ptr ownedMutex_; Mutex* mutex_; }; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/BoostMutex.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/BoostMutex.cpp index f7cadab..4e556df 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/BoostMutex.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/BoostMutex.cpp @@ -33,7 +33,9 @@ namespace thrift { namespace concurrency { /** - * Implementation of Mutex class using boost interprocess mutex + * Implementation of Mutex class using boost::timed_mutex + * + * Methods throw boost::lock_error on error. * * @version $Id:$ */ diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/BoostThreadFactory.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/BoostThreadFactory.cpp index a72d38b..d7d8d54 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/BoostThreadFactory.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/BoostThreadFactory.cpp @@ -23,18 +23,20 @@ #include #include - +#include #include -#include #include namespace apache { namespace thrift { -namespace concurrency { -using boost::shared_ptr; -using boost::weak_ptr; +using stdcxx::bind; +using stdcxx::scoped_ptr; +using stdcxx::shared_ptr; +using stdcxx::weak_ptr; + +namespace concurrency { /** * The boost thread class. @@ -48,7 +50,8 @@ public: static void* threadMain(void* arg); private: - std::auto_ptr thread_; + scoped_ptr thread_; + Monitor monitor_; STATE state_; weak_ptr self_; bool detached_; @@ -60,7 +63,7 @@ public: } ~BoostThread() { - if (!detached_) { + if (!detached_ && thread_->joinable()) { try { join(); } catch (...) { @@ -69,26 +72,46 @@ public: } } - void start() { - if (state_ != uninitialized) { - return; - } + STATE getState() const + { + Synchronized sync(monitor_); + return state_; + } + void setState(STATE newState) + { + Synchronized sync(monitor_); + state_ = newState; + + // unblock start() with the knowledge that the thread has actually + // started running, which avoids a race in detached threads. + if (newState == started) { + monitor_.notify(); + } + } + + void start() { // Create reference shared_ptr* selfRef = new shared_ptr(); *selfRef = self_.lock(); - state_ = starting; + setState(starting); - thread_ - = std::auto_ptr(new boost::thread(boost::bind(threadMain, (void*)selfRef))); + Synchronized sync(monitor_); + + thread_.reset(new boost::thread(bind(threadMain, (void*)selfRef))); if (detached_) thread_->detach(); + + // Wait for the thread to start and get far enough to grab everything + // that it needs from the calling context, thus absolving the caller + // from being required to hold on to runnable indefinitely. + monitor_.wait(); } void join() { - if (!detached_ && state_ != uninitialized) { + if (!detached_ && getState() != uninitialized) { thread_->join(); } } @@ -109,19 +132,11 @@ void* BoostThread::threadMain(void* arg) { shared_ptr thread = *(shared_ptr*)arg; delete reinterpret_cast*>(arg); - if (!thread) { - return (void*)0; - } - - if (thread->state_ != starting) { - return (void*)0; - } - - thread->state_ = started; + thread->setState(started); thread->runnable()->run(); - if (thread->state_ != stopping && thread->state_ != stopped) { - thread->state_ = stopping; + if (thread->getState() != stopping && thread->getState() != stopped) { + thread->setState(stopping); } return (void*)0; } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/BoostThreadFactory.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/BoostThreadFactory.h index 7973245..bf11a70 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/BoostThreadFactory.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/BoostThreadFactory.h @@ -20,9 +20,9 @@ #ifndef _THRIFT_CONCURRENCY_BOOSTTHREADFACTORY_H_ #define _THRIFT_CONCURRENCY_BOOSTTHREADFACTORY_H_ 1 +#include #include - -#include +#include namespace apache { namespace thrift { @@ -38,9 +38,8 @@ class BoostThreadFactory : public ThreadFactory { public: /** * Boost thread factory. All threads created by a factory are reference-counted - * via boost::shared_ptr and boost::weak_ptr. The factory guarantees that threads and - * the Runnable tasks they host will be properly cleaned up once the last strong reference - * to both is given up. + * via stdcxx::shared_ptr. The factory guarantees that threads and the Runnable tasks they + * host will be properly cleaned up once the last strong reference to both is given up. * * Threads are created with the specified boost policy, priority, stack-size. A detachable thread * is not joinable. @@ -51,7 +50,7 @@ public: BoostThreadFactory(bool detached = true); // From ThreadFactory; - boost::shared_ptr newThread(boost::shared_ptr runnable) const; + stdcxx::shared_ptr newThread(stdcxx::shared_ptr runnable) const; // From ThreadFactory; Thread::id_t getCurrentThreadId() const; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/FunctionRunner.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/FunctionRunner.h index 9c085c0..eabf019 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/FunctionRunner.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/FunctionRunner.h @@ -20,8 +20,8 @@ #ifndef _THRIFT_CONCURRENCY_FUNCTION_RUNNER_H #define _THRIFT_CONCURRENCY_FUNCTION_RUNNER_H 1 -#include #include +#include namespace apache { namespace thrift { @@ -53,20 +53,20 @@ public: // This is the type of callback 'pthread_create()' expects. typedef void* (*PthreadFuncPtr)(void* arg); // This a fully-generic void(void) callback for custom bindings. - typedef apache::thrift::stdcxx::function VoidFunc; + typedef stdcxx::function VoidFunc; - typedef apache::thrift::stdcxx::function BoolFunc; + typedef stdcxx::function BoolFunc; /** * Syntactic sugar to make it easier to create new FunctionRunner * objects wrapped in shared_ptr. */ - static boost::shared_ptr create(const VoidFunc& cob) { - return boost::shared_ptr(new FunctionRunner(cob)); + static stdcxx::shared_ptr create(const VoidFunc& cob) { + return stdcxx::shared_ptr(new FunctionRunner(cob)); } - static boost::shared_ptr create(PthreadFuncPtr func, void* arg) { - return boost::shared_ptr(new FunctionRunner(func, arg)); + static stdcxx::shared_ptr create(PthreadFuncPtr func, void* arg) { + return stdcxx::shared_ptr(new FunctionRunner(func, arg)); } private: @@ -81,7 +81,7 @@ public: * execute the given callback. Note that the 'void*' return value is ignored. */ FunctionRunner(PthreadFuncPtr func, void* arg) - : func_(apache::thrift::stdcxx::bind(pthread_func_wrapper, func, arg)), intervalMs_(-1) {} + : func_(stdcxx::bind(pthread_func_wrapper, func, arg)), intervalMs_(-1) {} /** * Given a generic callback, this FunctionRunner will execute it. diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/Monitor.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/Monitor.cpp index 5969e4a..af4fcd0 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/Monitor.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/Monitor.cpp @@ -23,8 +23,7 @@ #include #include #include - -#include +#include #include @@ -34,9 +33,11 @@ namespace apache { namespace thrift { -namespace concurrency { -using boost::scoped_ptr; +using stdcxx::scoped_ptr; +using stdcxx::shared_ptr; + +namespace concurrency { /** * Monitor implementation using the POSIX pthread library diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/Mutex.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/Mutex.cpp index e5e50f7..a526461 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/Mutex.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/Mutex.cpp @@ -17,25 +17,32 @@ * under the License. */ +// needed to test for pthread implementation capabilities: +#define __USE_GNU + #include #include +#include #include #include #include -#ifdef HAVE_PTHREAD_H +#include #include -#endif #include +#include -using boost::shared_ptr; +#include namespace apache { namespace thrift { namespace concurrency { -#ifndef THRIFT_NO_CONTENTION_PROFILING +// Enable this to turn on mutex contention profiling support +// #define THRIFT_PTHREAD_MUTEX_CONTENTION_PROFILING + +#ifdef THRIFT_PTHREAD_MUTEX_CONTENTION_PROFILING static int32_t mutexProfilingCounter = 0; static int32_t mutexProfilingSampleRate = 0; @@ -105,17 +112,25 @@ static inline int64_t maybeGetProfilingStartTime() { #define PROFILE_MUTEX_LOCKED() #define PROFILE_MUTEX_START_UNLOCK() #define PROFILE_MUTEX_UNLOCKED() -#endif // THRIFT_NO_CONTENTION_PROFILING +#endif // THRIFT_PTHREAD_MUTEX_CONTENTION_PROFILING + +#define EINTR_LOOP(_CALL) int ret; do { ret = _CALL; } while (ret == EINTR) +#define ABORT_ONFAIL(_CALL) { EINTR_LOOP(_CALL); if (ret) { abort(); } } +#define THROW_SRE(_CALLSTR, RET) { throw SystemResourceException(boost::str(boost::format("%1% returned %2% (%3%)") % _CALLSTR % RET % ::strerror(RET))); } +#define THROW_SRE_ONFAIL(_CALL) { EINTR_LOOP(_CALL); if (ret) { THROW_SRE(#_CALL, ret); } } +#define THROW_SRE_TRYFAIL(_CALL) { EINTR_LOOP(_CALL); if (ret == 0) { return true; } else if (ret == EBUSY) { return false; } THROW_SRE(#_CALL, ret); } /** * Implementation of Mutex class using POSIX mutex * + * Throws apache::thrift::concurrency::SystemResourceException on error. + * * @version $Id:$ */ class Mutex::impl { public: impl(Initializer init) : initialized_(false) { -#ifndef THRIFT_NO_CONTENTION_PROFILING +#ifdef THRIFT_PTHREAD_MUTEX_CONTENTION_PROFILING profileTime_ = 0; #endif init(&pthread_mutex_); @@ -125,19 +140,19 @@ public: ~impl() { if (initialized_) { initialized_ = false; - int ret = pthread_mutex_destroy(&pthread_mutex_); - THRIFT_UNUSED_VARIABLE(ret); - assert(ret == 0); + ABORT_ONFAIL(pthread_mutex_destroy(&pthread_mutex_)); } } void lock() const { PROFILE_MUTEX_START_LOCK(); - pthread_mutex_lock(&pthread_mutex_); + THROW_SRE_ONFAIL(pthread_mutex_lock(&pthread_mutex_)); PROFILE_MUTEX_LOCKED(); } - bool trylock() const { return (0 == pthread_mutex_trylock(&pthread_mutex_)); } + bool trylock() const { + THROW_SRE_TRYFAIL(pthread_mutex_trylock(&pthread_mutex_)); + } bool timedlock(int64_t milliseconds) const { #if defined(_POSIX_TIMEOUTS) && _POSIX_TIMEOUTS >= 200112L @@ -145,14 +160,16 @@ public: struct THRIFT_TIMESPEC ts; Util::toTimespec(ts, milliseconds + Util::currentTime()); - int ret = pthread_mutex_timedlock(&pthread_mutex_, &ts); + EINTR_LOOP(pthread_mutex_timedlock(&pthread_mutex_, &ts)); if (ret == 0) { PROFILE_MUTEX_LOCKED(); return true; + } else if (ret == ETIMEDOUT) { + PROFILE_MUTEX_NOT_LOCKED(); + return false; } - PROFILE_MUTEX_NOT_LOCKED(); - return false; + THROW_SRE("pthread_mutex_timedlock(&pthread_mutex_, &ts)", ret); #else /* Otherwise follow solution used by Mono for Android */ struct THRIFT_TIMESPEC sleepytime, now, to; @@ -177,7 +194,7 @@ public: void unlock() const { PROFILE_MUTEX_START_UNLOCK(); - pthread_mutex_unlock(&pthread_mutex_); + THROW_SRE_ONFAIL(pthread_mutex_unlock(&pthread_mutex_)); PROFILE_MUTEX_UNLOCKED(); } @@ -186,7 +203,7 @@ public: private: mutable pthread_mutex_t pthread_mutex_; mutable bool initialized_; -#ifndef THRIFT_NO_CONTENTION_PROFILING +#ifdef THRIFT_PTHREAD_MUTEX_CONTENTION_PROFILING mutable int64_t profileTime_; #endif }; @@ -216,28 +233,16 @@ void Mutex::unlock() const { void Mutex::DEFAULT_INITIALIZER(void* arg) { pthread_mutex_t* pthread_mutex = (pthread_mutex_t*)arg; - int ret = pthread_mutex_init(pthread_mutex, NULL); - THRIFT_UNUSED_VARIABLE(ret); - assert(ret == 0); + THROW_SRE_ONFAIL(pthread_mutex_init(pthread_mutex, NULL)); } -#if defined(PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP) \ - || defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP) +#if defined(PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP) || defined(PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP) || defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP) static void init_with_kind(pthread_mutex_t* mutex, int kind) { pthread_mutexattr_t mutexattr; - int ret = pthread_mutexattr_init(&mutexattr); - assert(ret == 0); - - // Apparently, this can fail. Should we really be aborting? - ret = pthread_mutexattr_settype(&mutexattr, kind); - assert(ret == 0); - - ret = pthread_mutex_init(mutex, &mutexattr); - assert(ret == 0); - - ret = pthread_mutexattr_destroy(&mutexattr); - assert(ret == 0); - THRIFT_UNUSED_VARIABLE(ret); + THROW_SRE_ONFAIL(pthread_mutexattr_init(&mutexattr)); + THROW_SRE_ONFAIL(pthread_mutexattr_settype(&mutexattr, kind)); + THROW_SRE_ONFAIL(pthread_mutex_init(mutex, &mutexattr)); + THROW_SRE_ONFAIL(pthread_mutexattr_destroy(&mutexattr)); } #endif @@ -255,6 +260,12 @@ void Mutex::ADAPTIVE_INITIALIZER(void* arg) { } #endif +#ifdef PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP +void Mutex::ERRORCHECK_INITIALIZER(void* arg) { + init_with_kind((pthread_mutex_t*)arg, PTHREAD_MUTEX_ERRORCHECK); +} +#endif + #ifdef PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP void Mutex::RECURSIVE_INITIALIZER(void* arg) { init_with_kind((pthread_mutex_t*)arg, PTHREAD_MUTEX_RECURSIVE_NP); @@ -269,50 +280,46 @@ void Mutex::RECURSIVE_INITIALIZER(void* arg) { class ReadWriteMutex::impl { public: impl() : initialized_(false) { -#ifndef THRIFT_NO_CONTENTION_PROFILING +#ifdef THRIFT_PTHREAD_MUTEX_CONTENTION_PROFILING profileTime_ = 0; #endif - int ret = pthread_rwlock_init(&rw_lock_, NULL); - THRIFT_UNUSED_VARIABLE(ret); - assert(ret == 0); + THROW_SRE_ONFAIL(pthread_rwlock_init(&rw_lock_, NULL)); initialized_ = true; } ~impl() { if (initialized_) { initialized_ = false; - int ret = pthread_rwlock_destroy(&rw_lock_); - THRIFT_UNUSED_VARIABLE(ret); - assert(ret == 0); + ABORT_ONFAIL(pthread_rwlock_destroy(&rw_lock_)); } } void acquireRead() const { PROFILE_MUTEX_START_LOCK(); - pthread_rwlock_rdlock(&rw_lock_); + THROW_SRE_ONFAIL(pthread_rwlock_rdlock(&rw_lock_)); PROFILE_MUTEX_NOT_LOCKED(); // not exclusive, so use not-locked path } void acquireWrite() const { PROFILE_MUTEX_START_LOCK(); - pthread_rwlock_wrlock(&rw_lock_); + THROW_SRE_ONFAIL(pthread_rwlock_wrlock(&rw_lock_)); PROFILE_MUTEX_LOCKED(); } - bool attemptRead() const { return !pthread_rwlock_tryrdlock(&rw_lock_); } + bool attemptRead() const { THROW_SRE_TRYFAIL(pthread_rwlock_tryrdlock(&rw_lock_)); } - bool attemptWrite() const { return !pthread_rwlock_trywrlock(&rw_lock_); } + bool attemptWrite() const { THROW_SRE_TRYFAIL(pthread_rwlock_trywrlock(&rw_lock_)); } void release() const { PROFILE_MUTEX_START_UNLOCK(); - pthread_rwlock_unlock(&rw_lock_); + THROW_SRE_ONFAIL(pthread_rwlock_unlock(&rw_lock_)); PROFILE_MUTEX_UNLOCKED(); } private: mutable pthread_rwlock_t rw_lock_; mutable bool initialized_; -#ifndef THRIFT_NO_CONTENTION_PROFILING +#ifdef THRIFT_PTHREAD_MUTEX_CONTENTION_PROFILING mutable int64_t profileTime_; #endif }; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/Mutex.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/Mutex.h index 6f892dc..09b938e 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/Mutex.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/Mutex.h @@ -20,7 +20,7 @@ #ifndef _THRIFT_CONCURRENCY_MUTEX_H_ #define _THRIFT_CONCURRENCY_MUTEX_H_ 1 -#include +#include #include #include @@ -53,6 +53,11 @@ void enableMutexProfiling(int32_t profilingSampleRate, MutexWaitCallback callbac #endif +/** + * NOTE: All mutex implementations throw an exception on failure. See each + * specific implementation to understand the exception type(s) used. + */ + /** * A simple mutex class * @@ -64,6 +69,7 @@ public: Mutex(Initializer init = DEFAULT_INITIALIZER); virtual ~Mutex() {} + virtual void lock() const; virtual bool trylock() const; virtual bool timedlock(int64_t milliseconds) const; @@ -71,13 +77,16 @@ public: void* getUnderlyingImpl() const; - static void DEFAULT_INITIALIZER(void*); + // If you attempt to use one of these and it fails to link, it means + // your version of pthreads does not support it - try another one. static void ADAPTIVE_INITIALIZER(void*); + static void DEFAULT_INITIALIZER(void*); + static void ERRORCHECK_INITIALIZER(void*); static void RECURSIVE_INITIALIZER(void*); private: class impl; - boost::shared_ptr impl_; + stdcxx::shared_ptr impl_; }; class ReadWriteMutex { @@ -98,7 +107,7 @@ public: private: class impl; - boost::shared_ptr impl_; + stdcxx::shared_ptr impl_; }; /** diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/PosixThreadFactory.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/PosixThreadFactory.cpp index 6a0b47c..2e35446 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/PosixThreadFactory.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/PosixThreadFactory.cpp @@ -19,8 +19,9 @@ #include -#include #include +#include +#include #if GOOGLE_PERFTOOLS_REGISTER_THREAD #include @@ -31,15 +32,12 @@ #include -#include +#include namespace apache { namespace thrift { namespace concurrency { -using boost::shared_ptr; -using boost::weak_ptr; - /** * The POSIX thread class. * @@ -55,11 +53,12 @@ public: private: pthread_t pthread_; - STATE state_; + Monitor monitor_; // guard to protect state_ and also notification + STATE state_; // to protect proper thread start behavior int policy_; int priority_; int stackSize_; - weak_ptr self_; + stdcxx::weak_ptr self_; bool detached_; public: @@ -67,13 +66,12 @@ public: int priority, int stackSize, bool detached, - shared_ptr runnable) + stdcxx::shared_ptr runnable) : #ifndef _WIN32 pthread_(0), #endif // _WIN32 - state_(uninitialized), policy_(policy), priority_(priority), @@ -96,8 +94,26 @@ public: } } + STATE getState() const + { + Synchronized sync(monitor_); + return state_; + } + + void setState(STATE newState) + { + Synchronized sync(monitor_); + state_ = newState; + + // unblock start() with the knowledge that the thread has actually + // started running, which avoids a race in detached threads. + if (newState == started) { + monitor_.notify(); + } + } + void start() { - if (state_ != uninitialized) { + if (getState() != uninitialized) { return; } @@ -139,18 +155,27 @@ public: } // Create reference - shared_ptr* selfRef = new shared_ptr(); + stdcxx::shared_ptr* selfRef = new stdcxx::shared_ptr(); *selfRef = self_.lock(); - state_ = starting; + setState(starting); + Synchronized sync(monitor_); + if (pthread_create(&pthread_, &thread_attr, threadMain, (void*)selfRef) != 0) { throw SystemResourceException("pthread_create failed"); } + + // The caller may not choose to guarantee the scope of the Runnable + // being used in the thread, so we must actually wait until the thread + // starts before we return. If we do not wait, it would be possible + // for the caller to start destructing the Runnable and the Thread, + // and we would end up in a race. This was identified with valgrind. + monitor_.wait(); } void join() { - if (!detached_ && state_ != uninitialized) { + if (!detached_ && getState() != uninitialized) { void* ignore; /* XXX If join fails it is most likely due to the fact @@ -164,8 +189,6 @@ public: if (res != 0) { GlobalOutput.printf("PthreadThread::join(): fail with code %d", res); } - } else { - GlobalOutput.printf("PthreadThread::join(): detached thread"); } } @@ -178,36 +201,31 @@ public: #endif // _WIN32 } - shared_ptr runnable() const { return Thread::runnable(); } + stdcxx::shared_ptr runnable() const { return Thread::runnable(); } - void runnable(shared_ptr value) { Thread::runnable(value); } + void runnable(stdcxx::shared_ptr value) { Thread::runnable(value); } - void weakRef(shared_ptr self) { + void weakRef(stdcxx::shared_ptr self) { assert(self.get() == this); - self_ = weak_ptr(self); + self_ = stdcxx::weak_ptr(self); } }; void* PthreadThread::threadMain(void* arg) { - shared_ptr thread = *(shared_ptr*)arg; - delete reinterpret_cast*>(arg); - - if (thread == NULL) { - return (void*)0; - } - - if (thread->state_ != starting) { - return (void*)0; - } + stdcxx::shared_ptr thread = *(stdcxx::shared_ptr*)arg; + delete reinterpret_cast*>(arg); #if GOOGLE_PERFTOOLS_REGISTER_THREAD ProfilerRegisterThread(); #endif - thread->state_ = started; + thread->setState(started); + thread->runnable()->run(); - if (thread->state_ != stopping && thread->state_ != stopped) { - thread->state_ = stopping; + + STATE _s = thread->getState(); + if (_s != stopping && _s != stopped) { + thread->setState(stopping); } return (void*)0; @@ -276,9 +294,9 @@ PosixThreadFactory::PosixThreadFactory(bool detached) stackSize_(1) { } -shared_ptr PosixThreadFactory::newThread(shared_ptr runnable) const { - shared_ptr result - = shared_ptr(new PthreadThread(toPthreadPolicy(policy_), +stdcxx::shared_ptr PosixThreadFactory::newThread(stdcxx::shared_ptr runnable) const { + stdcxx::shared_ptr result + = stdcxx::shared_ptr(new PthreadThread(toPthreadPolicy(policy_), toPthreadPriority(policy_, priority_), stackSize_, isDetached(), diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/PosixThreadFactory.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/PosixThreadFactory.h index c1bbe5c..5e04d01 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/PosixThreadFactory.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/PosixThreadFactory.h @@ -22,7 +22,7 @@ #include -#include +#include namespace apache { namespace thrift { @@ -63,9 +63,9 @@ public: /** * Posix thread (pthread) factory. All threads created by a factory are reference-counted - * via boost::shared_ptr and boost::weak_ptr. The factory guarantees that threads and - * the Runnable tasks they host will be properly cleaned up once the last strong reference - * to both is given up. + * via stdcxx::shared_ptr. The factory guarantees that threads and the Runnable tasks + * they host will be properly cleaned up once the last strong reference to both is + * given up. * * Threads are created with the specified policy, priority, stack-size and detachable-mode * detached means the thread is free-running and will release all system resources the @@ -88,7 +88,7 @@ public: PosixThreadFactory(bool detached); // From ThreadFactory; - boost::shared_ptr newThread(boost::shared_ptr runnable) const; + stdcxx::shared_ptr newThread(stdcxx::shared_ptr runnable) const; // From ThreadFactory; Thread::id_t getCurrentThreadId() const; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/StdMutex.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/StdMutex.cpp index 69678a2..e0f79fa 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/StdMutex.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/StdMutex.cpp @@ -33,11 +33,14 @@ namespace concurrency { /** * Implementation of Mutex class using C++11 std::timed_mutex * + * Methods throw std::system_error on error. + * * @version $Id:$ */ class Mutex::impl : public std::timed_mutex {}; Mutex::Mutex(Initializer init) : impl_(new Mutex::impl()) { + ((void)init); } void* Mutex::getUnderlyingImpl() const { @@ -61,6 +64,7 @@ void Mutex::unlock() const { } void Mutex::DEFAULT_INITIALIZER(void* arg) { + ((void)arg); } } } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/StdThreadFactory.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/StdThreadFactory.cpp index 66c7e75..da0c5e3 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/StdThreadFactory.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/StdThreadFactory.cpp @@ -21,13 +21,12 @@ #if USE_STD_THREAD -#include #include +#include +#include +#include #include - -#include -#include #include namespace apache { @@ -43,25 +42,26 @@ namespace concurrency { * * @version $Id:$ */ -class StdThread : public Thread, public boost::enable_shared_from_this { +class StdThread : public Thread, public stdcxx::enable_shared_from_this { public: enum STATE { uninitialized, starting, started, stopping, stopped }; - static void threadMain(boost::shared_ptr thread); + static void threadMain(stdcxx::shared_ptr thread); private: std::unique_ptr thread_; + Monitor monitor_; STATE state_; bool detached_; public: - StdThread(bool detached, boost::shared_ptr runnable) + StdThread(bool detached, stdcxx::shared_ptr runnable) : state_(uninitialized), detached_(detached) { this->Thread::runnable(runnable); } ~StdThread() { - if (!detached_) { + if (!detached_ && thread_->joinable()) { try { join(); } catch (...) { @@ -70,18 +70,42 @@ public: } } + STATE getState() const + { + Synchronized sync(monitor_); + return state_; + } + + void setState(STATE newState) + { + Synchronized sync(monitor_); + state_ = newState; + + // unblock start() with the knowledge that the thread has actually + // started running, which avoids a race in detached threads. + if (newState == started) { + monitor_.notify(); + } + } + void start() { - if (state_ != uninitialized) { + if (getState() != uninitialized) { return; } - boost::shared_ptr selfRef = shared_from_this(); - state_ = starting; + stdcxx::shared_ptr selfRef = shared_from_this(); + setState(starting); + Synchronized sync(monitor_); thread_ = std::unique_ptr(new std::thread(threadMain, selfRef)); if (detached_) thread_->detach(); + + // Wait for the thread to start and get far enough to grab everything + // that it needs from the calling context, thus absolving the caller + // from being required to hold on to runnable indefinitely. + monitor_.wait(); } void join() { @@ -92,35 +116,29 @@ public: Thread::id_t getId() { return thread_.get() ? thread_->get_id() : std::thread::id(); } - boost::shared_ptr runnable() const { return Thread::runnable(); } + stdcxx::shared_ptr runnable() const { return Thread::runnable(); } - void runnable(boost::shared_ptr value) { Thread::runnable(value); } + void runnable(stdcxx::shared_ptr value) { Thread::runnable(value); } }; -void StdThread::threadMain(boost::shared_ptr thread) { - if (thread == NULL) { - return; - } +void StdThread::threadMain(stdcxx::shared_ptr thread) { +#if GOOGLE_PERFTOOLS_REGISTER_THREAD + ProfilerRegisterThread(); +#endif - if (thread->state_ != starting) { - return; - } - - thread->state_ = started; + thread->setState(started); thread->runnable()->run(); - if (thread->state_ != stopping && thread->state_ != stopped) { - thread->state_ = stopping; + if (thread->getState() != stopping && thread->getState() != stopped) { + thread->setState(stopping); } - - return; } StdThreadFactory::StdThreadFactory(bool detached) : ThreadFactory(detached) { } -boost::shared_ptr StdThreadFactory::newThread(boost::shared_ptr runnable) const { - boost::shared_ptr result = boost::shared_ptr(new StdThread(isDetached(), runnable)); +stdcxx::shared_ptr StdThreadFactory::newThread(stdcxx::shared_ptr runnable) const { + stdcxx::shared_ptr result = stdcxx::shared_ptr(new StdThread(isDetached(), runnable)); runnable->thread(result); return result; } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/StdThreadFactory.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/StdThreadFactory.h index 88f00be..8e116b6 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/StdThreadFactory.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/StdThreadFactory.h @@ -22,7 +22,7 @@ #include -#include +#include namespace apache { namespace thrift { @@ -38,8 +38,8 @@ class StdThreadFactory : public ThreadFactory { public: /** * Std thread factory. All threads created by a factory are reference-counted - * via boost::shared_ptr and boost::weak_ptr. The factory guarantees that threads and - * the Runnable tasks they host will be properly cleaned up once the last strong reference + * via stdcxx::shared_ptr. The factory guarantees that threads and the Runnable tasks + * they host will be properly cleaned up once the last strong reference * to both is given up. * * By default threads are not joinable. @@ -48,7 +48,7 @@ public: StdThreadFactory(bool detached = true); // From ThreadFactory; - boost::shared_ptr newThread(boost::shared_ptr runnable) const; + stdcxx::shared_ptr newThread(stdcxx::shared_ptr runnable) const; // From ThreadFactory; Thread::id_t getCurrentThreadId() const; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/Thread.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/Thread.h index 2e15489..788623b 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/Thread.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/Thread.h @@ -21,8 +21,7 @@ #define _THRIFT_CONCURRENCY_THREAD_H_ 1 #include -#include -#include +#include #include @@ -57,16 +56,16 @@ public: * Gets the thread object that is hosting this runnable object - can return * an empty boost::shared pointer if no references remain on that thread object */ - virtual boost::shared_ptr thread() { return thread_.lock(); } + virtual stdcxx::shared_ptr thread() { return thread_.lock(); } /** * Sets the thread that is executing this object. This is only meant for * use by concrete implementations of Thread. */ - virtual void thread(boost::shared_ptr value) { thread_ = value; } + virtual void thread(stdcxx::shared_ptr value) { thread_ = value; } private: - boost::weak_ptr thread_; + stdcxx::weak_ptr thread_; }; /** @@ -122,13 +121,13 @@ public: /** * Gets the runnable object this thread is hosting */ - virtual boost::shared_ptr runnable() const { return _runnable; } + virtual stdcxx::shared_ptr runnable() const { return _runnable; } protected: - virtual void runnable(boost::shared_ptr value) { _runnable = value; } + virtual void runnable(stdcxx::shared_ptr value) { _runnable = value; } private: - boost::shared_ptr _runnable; + stdcxx::shared_ptr _runnable; }; /** @@ -155,7 +154,7 @@ public: /** * Create a new thread. */ - virtual boost::shared_ptr newThread(boost::shared_ptr runnable) const = 0; + virtual stdcxx::shared_ptr newThread(stdcxx::shared_ptr runnable) const = 0; /** * Gets the current thread id or unknown_thread_id if the current thread is not a thrift thread diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/ThreadManager.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/ThreadManager.cpp index c4726dd..2e27b7f 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/ThreadManager.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/ThreadManager.cpp @@ -24,22 +24,18 @@ #include #include -#include +#include #include #include #include -#if defined(DEBUG) -#include -#endif // defined(DEBUG) - namespace apache { namespace thrift { namespace concurrency { -using boost::shared_ptr; -using boost::dynamic_pointer_cast; +using stdcxx::shared_ptr; +using stdcxx::dynamic_pointer_cast; /** * ThreadManager class @@ -508,7 +504,7 @@ void ThreadManager::Impl::remove(shared_ptr task) { } } -boost::shared_ptr ThreadManager::Impl::removeNextPending() { +stdcxx::shared_ptr ThreadManager::Impl::removeNextPending() { Guard g(mutex_); if (state_ != ThreadManager::STARTED) { throw IllegalStateException( @@ -517,7 +513,7 @@ boost::shared_ptr ThreadManager::Impl::removeNextPending() { } if (tasks_.empty()) { - return boost::shared_ptr(); + return stdcxx::shared_ptr(); } shared_ptr task = tasks_.front(); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/ThreadManager.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/ThreadManager.h index d8bf71b..b3b7542 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/ThreadManager.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/ThreadManager.h @@ -20,10 +20,9 @@ #ifndef _THRIFT_CONCURRENCY_THREADMANAGER_H_ #define _THRIFT_CONCURRENCY_THREADMANAGER_H_ 1 -#include -#include #include #include +#include namespace apache { namespace thrift { @@ -59,7 +58,7 @@ protected: ThreadManager() {} public: - typedef apache::thrift::stdcxx::function)> ExpireCallback; + typedef apache::thrift::stdcxx::function)> ExpireCallback; virtual ~ThreadManager() {} @@ -88,14 +87,14 @@ public: /** * \returns the current thread factory */ - virtual boost::shared_ptr threadFactory() const = 0; + virtual stdcxx::shared_ptr threadFactory() const = 0; /** * Set the thread factory. * \throws InvalidArgumentException if the new thread factory has a different * detached disposition than the one replacing it */ - virtual void threadFactory(boost::shared_ptr value) = 0; + virtual void threadFactory(stdcxx::shared_ptr value) = 0; /** * Adds worker thread(s). @@ -162,21 +161,21 @@ public: * * @throws TooManyPendingTasksException Pending task count exceeds max pending task count */ - virtual void add(boost::shared_ptr task, + virtual void add(stdcxx::shared_ptr task, int64_t timeout = 0LL, int64_t expiration = 0LL) = 0; /** * Removes a pending task */ - virtual void remove(boost::shared_ptr task) = 0; + virtual void remove(stdcxx::shared_ptr task) = 0; /** * Remove the next pending task which would be run. * * @return the task removed. */ - virtual boost::shared_ptr removeNextPending() = 0; + virtual stdcxx::shared_ptr removeNextPending() = 0; /** * Remove tasks from front of task queue that have expired. @@ -191,14 +190,14 @@ public: */ virtual void setExpireCallback(ExpireCallback expireCallback) = 0; - static boost::shared_ptr newThreadManager(); + static stdcxx::shared_ptr newThreadManager(); /** * Creates a simple thread manager the uses count number of worker threads and has * a pendingTaskCountMax maximum pending tasks. The default, 0, specified no limit * on pending tasks */ - static boost::shared_ptr newSimpleThreadManager(size_t count = 4, + static stdcxx::shared_ptr newSimpleThreadManager(size_t count = 4, size_t pendingTaskCountMax = 0); class Task; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/TimerManager.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/TimerManager.cpp index f95fcda..2017146 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/TimerManager.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/TimerManager.cpp @@ -29,7 +29,8 @@ namespace apache { namespace thrift { namespace concurrency { -using boost::shared_ptr; +using stdcxx::shared_ptr; +using stdcxx::weak_ptr; /** * TimerManager class @@ -52,6 +53,10 @@ public: } } + bool operator==(const shared_ptr & runnable) const { return runnable_ == runnable; } + + task_iterator it_; + private: shared_ptr runnable_; friend class TimerManager::Dispatcher; @@ -106,6 +111,7 @@ public: for (task_iterator ix = manager_->taskMap_.begin(); ix != expiredTaskEnd; ix++) { shared_ptr task = ix->second; expiredTasks.insert(task); + task->it_ = manager_->taskMap_.end(); if (task->state_ == TimerManager::Task::WAITING) { task->state_ = TimerManager::Task::EXECUTING; } @@ -233,7 +239,7 @@ size_t TimerManager::taskCount() const { return taskCount_; } -void TimerManager::add(shared_ptr task, int64_t timeout) { +TimerManager::Timer TimerManager::add(shared_ptr task, int64_t timeout) { int64_t now = Util::currentTime(); timeout += now; @@ -248,9 +254,9 @@ void TimerManager::add(shared_ptr task, int64_t timeout) { // because the new task might insert at the front. bool notifyRequired = (taskCount_ == 0) ? true : timeout < taskMap_.begin()->first; + shared_ptr timer(new Task(task)); taskCount_++; - taskMap_.insert( - std::pair >(timeout, shared_ptr(new Task(task)))); + timer->it_ = taskMap_.insert(std::pair >(timeout, timer)); // If the task map was empty, or if we have an expiration that is earlier // than any previously seen, kick the dispatcher so it can update its @@ -258,10 +264,13 @@ void TimerManager::add(shared_ptr task, int64_t timeout) { if (notifyRequired) { monitor_.notify(); } + + return timer; } } -void TimerManager::add(shared_ptr task, const struct THRIFT_TIMESPEC& value) { +TimerManager::Timer TimerManager::add(shared_ptr task, + const struct THRIFT_TIMESPEC& value) { int64_t expiration; Util::toMilliseconds(expiration, value); @@ -272,10 +281,11 @@ void TimerManager::add(shared_ptr task, const struct THRIFT_TIMESPEC& throw InvalidArgumentException(); } - add(task, expiration - now); + return add(task, expiration - now); } -void TimerManager::add(shared_ptr task, const struct timeval& value) { +TimerManager::Timer TimerManager::add(shared_ptr task, + const struct timeval& value) { int64_t expiration; Util::toMilliseconds(expiration, value); @@ -286,15 +296,47 @@ void TimerManager::add(shared_ptr task, const struct timeval& value) { throw InvalidArgumentException(); } - add(task, expiration - now); + return add(task, expiration - now); } void TimerManager::remove(shared_ptr task) { - (void)task; Synchronized s(monitor_); if (state_ != TimerManager::STARTED) { throw IllegalStateException(); } + bool found = false; + for (task_iterator ix = taskMap_.begin(); ix != taskMap_.end();) { + if (*ix->second == task) { + found = true; + taskCount_--; + taskMap_.erase(ix++); + } else { + ++ix; + } + } + if (!found) { + throw NoSuchTaskException(); + } +} + +void TimerManager::remove(Timer handle) { + Synchronized s(monitor_); + if (state_ != TimerManager::STARTED) { + throw IllegalStateException(); + } + + shared_ptr task = handle.lock(); + if (!task) { + throw NoSuchTaskException(); + } + + if (task->it_ == taskMap_.end()) { + // Task is being executed + throw UncancellableTaskException(); + } + + taskMap_.erase(task->it_); + taskCount_--; } TimerManager::STATE TimerManager::state() const { diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/TimerManager.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/TimerManager.h index 3946827..2bfc6a7 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/TimerManager.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/concurrency/TimerManager.h @@ -24,7 +24,7 @@ #include #include -#include +#include #include #include @@ -42,13 +42,16 @@ namespace concurrency { class TimerManager { public: + class Task; + typedef stdcxx::weak_ptr Timer; + TimerManager(); virtual ~TimerManager(); - virtual boost::shared_ptr threadFactory() const; + virtual stdcxx::shared_ptr threadFactory() const; - virtual void threadFactory(boost::shared_ptr value); + virtual void threadFactory(stdcxx::shared_ptr value); /** * Starts the timer manager service @@ -69,28 +72,33 @@ public: * * @param task The task to execute * @param timeout Time in milliseconds to delay before executing task + * @return Handle of the timer, which can be used to remove the timer. */ - virtual void add(boost::shared_ptr task, int64_t timeout); + virtual Timer add(stdcxx::shared_ptr task, int64_t timeout); /** * Adds a task to be executed at some time in the future by a worker thread. * * @param task The task to execute * @param timeout Absolute time in the future to execute task. + * @return Handle of the timer, which can be used to remove the timer. */ - virtual void add(boost::shared_ptr task, const struct THRIFT_TIMESPEC& timeout); + virtual Timer add(stdcxx::shared_ptr task, const struct THRIFT_TIMESPEC& timeout); /** * Adds a task to be executed at some time in the future by a worker thread. * * @param task The task to execute * @param timeout Absolute time in the future to execute task. + * @return Handle of the timer, which can be used to remove the timer. */ - virtual void add(boost::shared_ptr task, const struct timeval& timeout); + virtual Timer add(stdcxx::shared_ptr task, const struct timeval& timeout); /** * Removes a pending task * + * @param task The task to remove. All timers which execute this task will + * be removed. * @throws NoSuchTaskException Specified task doesn't exist. It was either * processed already or this call was made for a * task that was never added to this timer @@ -98,25 +106,38 @@ public: * @throws UncancellableTaskException Specified task is already being * executed or has completed execution. */ - virtual void remove(boost::shared_ptr task); + virtual void remove(stdcxx::shared_ptr task); + + /** + * Removes a single pending task + * + * @param timer The timer to remove. The timer is returned when calling the + * add() method. + * @throws NoSuchTaskException Specified task doesn't exist. It was either + * processed already or this call was made for a + * task that was never added to this timer + * + * @throws UncancellableTaskException Specified task is already being + * executed or has completed execution. + */ + virtual void remove(Timer timer); enum STATE { UNINITIALIZED, STARTING, STARTED, STOPPING, STOPPED }; virtual STATE state() const; private: - boost::shared_ptr threadFactory_; - class Task; + stdcxx::shared_ptr threadFactory_; friend class Task; - std::multimap > taskMap_; + std::multimap > taskMap_; size_t taskCount_; Monitor monitor_; STATE state_; class Dispatcher; friend class Dispatcher; - boost::shared_ptr dispatcher_; - boost::shared_ptr dispatcherThread_; - typedef std::multimap >::iterator task_iterator; + stdcxx::shared_ptr dispatcher_; + stdcxx::shared_ptr dispatcherThread_; + typedef std::multimap >::iterator task_iterator; typedef std::pair task_range; }; } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/cxxfunctional.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/cxxfunctional.h deleted file mode 100644 index 32933a4..0000000 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/cxxfunctional.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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. - */ - -#ifndef _THRIFT_CXXFUNCTIONAL_H_ -#define _THRIFT_CXXFUNCTIONAL_H_ 1 - -// clang-format off - -/** - * Loads from the 'right' location, depending - * on compiler and whether or not it's using C++03 with TR1 - * or C++11. - */ - -/* - * MSVC 10 and 11 have the stuff at . - * In MSVC 10 all of the implementations live in std::tr1. - * In MSVC 11 all of the implementations live in std, with aliases - * in std::tr1 to point to the ones in std. - */ -#if defined(_WIN32) && !defined(__MINGW32__) - #define _THRIFT_USING_MICROSOFT_STDLIB 1 -#endif - -#ifdef __clang__ - /* Clang has two options, depending on standard library: - * - no -stdlib or -stdlib=libstdc++ set; uses GNU libstdc++. - * - * - -stdlib=libc++; uses LLVM libc++. - * , no 'std::tr1'. - * - * The compiler itself doesn't define anything differently - * depending on the value of -stdlib, but the library headers - * will set different preprocessor options. In order to check, - * though, we have to pull in some library header. - */ - #include - - /* With LLVM libc++, utility pulls in __config, which sets - _LIBCPP_VERSION. */ - #if defined(_LIBCPP_VERSION) - #define _THRIFT_USING_CLANG_LIBCXX 1 - - /* With GNU libstdc++, utility pulls in bits/c++config.h, - which sets __GLIBCXX__. */ - #elif defined(__GLIBCXX__) - #define _THRIFT_USING_GNU_LIBSTDCXX 1 - - /* No idea. */ - #else - #error Unable to detect which C++ standard library is in use. - #endif -#elif __GNUC__ - #define _THRIFT_USING_GNU_LIBSTDCXX 1 -#endif - -#if _THRIFT_USING_MICROSOFT_STDLIB - #include - - namespace apache { namespace thrift { namespace stdcxx { - using ::std::tr1::function; - using ::std::tr1::bind; - - namespace placeholders { - using ::std::tr1::placeholders::_1; - using ::std::tr1::placeholders::_2; - using ::std::tr1::placeholders::_3; - using ::std::tr1::placeholders::_4; - using ::std::tr1::placeholders::_5; - using ::std::tr1::placeholders::_6; - } // apache::thrift::stdcxx::placeholders - }}} // apache::thrift::stdcxx - -#elif _THRIFT_USING_CLANG_LIBCXX - #include - - namespace apache { namespace thrift { namespace stdcxx { - using ::std::function; - using ::std::bind; - - namespace placeholders { - using ::std::placeholders::_1; - using ::std::placeholders::_2; - using ::std::placeholders::_3; - using ::std::placeholders::_4; - using ::std::placeholders::_5; - using ::std::placeholders::_6; - } // apache::thrift::stdcxx::placeholders - }}} // apache::thrift::stdcxx - -#elif _THRIFT_USING_GNU_LIBSTDCXX - #ifdef USE_BOOST_THREAD - #include - #else - #include - #endif - - namespace apache { namespace thrift { namespace stdcxx { - using ::std::tr1::function; - using ::std::tr1::bind; - - namespace placeholders { - using ::std::tr1::placeholders::_1; - using ::std::tr1::placeholders::_2; - using ::std::tr1::placeholders::_3; - using ::std::tr1::placeholders::_4; - using ::std::tr1::placeholders::_5; - using ::std::tr1::placeholders::_6; - } // apache::thrift::stdcxx::placeholders - }}} // apache::thrift::stdcxx -#endif - - // Alias for thrift c++ compatibility namespace - namespace tcxx = apache::thrift::stdcxx; - -#endif // #ifndef _THRIFT_CXXFUNCTIONAL_H_ diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/processor/PeekProcessor.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/processor/PeekProcessor.cpp index 8c9a463..fa11a72 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/processor/PeekProcessor.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/processor/PeekProcessor.cpp @@ -34,26 +34,26 @@ PeekProcessor::PeekProcessor() { PeekProcessor::~PeekProcessor() { } -void PeekProcessor::initialize(boost::shared_ptr actualProcessor, - boost::shared_ptr protocolFactory, - boost::shared_ptr transportFactory) { +void PeekProcessor::initialize(stdcxx::shared_ptr actualProcessor, + stdcxx::shared_ptr protocolFactory, + stdcxx::shared_ptr transportFactory) { actualProcessor_ = actualProcessor; pipedProtocol_ = protocolFactory->getProtocol(targetTransport_); transportFactory_ = transportFactory; transportFactory_->initializeTargetTransport(targetTransport_); } -boost::shared_ptr PeekProcessor::getPipedTransport(boost::shared_ptr in) { +stdcxx::shared_ptr PeekProcessor::getPipedTransport(stdcxx::shared_ptr in) { return transportFactory_->getTransport(in); } -void PeekProcessor::setTargetTransport(boost::shared_ptr targetTransport) { +void PeekProcessor::setTargetTransport(stdcxx::shared_ptr targetTransport) { targetTransport_ = targetTransport; - if (boost::dynamic_pointer_cast(targetTransport_)) { - memoryBuffer_ = boost::dynamic_pointer_cast(targetTransport); - } else if (boost::dynamic_pointer_cast(targetTransport_)) { - memoryBuffer_ = boost::dynamic_pointer_cast( - boost::dynamic_pointer_cast(targetTransport_)->getTargetTransport()); + if (stdcxx::dynamic_pointer_cast(targetTransport_)) { + memoryBuffer_ = stdcxx::dynamic_pointer_cast(targetTransport); + } else if (stdcxx::dynamic_pointer_cast(targetTransport_)) { + memoryBuffer_ = stdcxx::dynamic_pointer_cast( + stdcxx::dynamic_pointer_cast(targetTransport_)->getTargetTransport()); } if (!memoryBuffer_) { @@ -62,8 +62,8 @@ void PeekProcessor::setTargetTransport(boost::shared_ptr targetTrans } } -bool PeekProcessor::process(boost::shared_ptr in, - boost::shared_ptr out, +bool PeekProcessor::process(stdcxx::shared_ptr in, + stdcxx::shared_ptr out, void* connectionContext) { std::string fname; @@ -120,7 +120,7 @@ void PeekProcessor::peekBuffer(uint8_t* buffer, uint32_t size) { (void)size; } -void PeekProcessor::peek(boost::shared_ptr in, TType ftype, int16_t fid) { +void PeekProcessor::peek(stdcxx::shared_ptr in, TType ftype, int16_t fid) { (void)fid; in->skip(ftype); } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/processor/PeekProcessor.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/processor/PeekProcessor.h index 21c5999..f5c10da 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/processor/PeekProcessor.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/processor/PeekProcessor.h @@ -25,7 +25,7 @@ #include #include #include -#include +#include namespace apache { namespace thrift { @@ -47,34 +47,34 @@ public: // transportFactory - this TPipedTransportFactory is used to wrap the source transport // via a call to getPipedTransport void initialize( - boost::shared_ptr actualProcessor, - boost::shared_ptr protocolFactory, - boost::shared_ptr transportFactory); + stdcxx::shared_ptr actualProcessor, + stdcxx::shared_ptr protocolFactory, + stdcxx::shared_ptr transportFactory); - boost::shared_ptr getPipedTransport( - boost::shared_ptr in); + stdcxx::shared_ptr getPipedTransport( + stdcxx::shared_ptr in); - void setTargetTransport(boost::shared_ptr targetTransport); + void setTargetTransport(stdcxx::shared_ptr targetTransport); - virtual bool process(boost::shared_ptr in, - boost::shared_ptr out, + virtual bool process(stdcxx::shared_ptr in, + stdcxx::shared_ptr out, void* connectionContext); // The following three functions can be overloaded by child classes to // achieve desired peeking behavior virtual void peekName(const std::string& fname); virtual void peekBuffer(uint8_t* buffer, uint32_t size); - virtual void peek(boost::shared_ptr in, + virtual void peek(stdcxx::shared_ptr in, apache::thrift::protocol::TType ftype, int16_t fid); virtual void peekEnd(); private: - boost::shared_ptr actualProcessor_; - boost::shared_ptr pipedProtocol_; - boost::shared_ptr transportFactory_; - boost::shared_ptr memoryBuffer_; - boost::shared_ptr targetTransport_; + stdcxx::shared_ptr actualProcessor_; + stdcxx::shared_ptr pipedProtocol_; + stdcxx::shared_ptr transportFactory_; + stdcxx::shared_ptr memoryBuffer_; + stdcxx::shared_ptr targetTransport_; }; } } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/processor/StatsProcessor.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/processor/StatsProcessor.h index e8ca067..8f6725f 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/processor/StatsProcessor.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/processor/StatsProcessor.h @@ -20,7 +20,7 @@ #ifndef STATSPROCESSOR_H #define STATSPROCESSOR_H -#include +#include #include #include #include @@ -38,8 +38,8 @@ public: StatsProcessor(bool print, bool frequency) : print_(print), frequency_(frequency) {} virtual ~StatsProcessor(){}; - virtual bool process(boost::shared_ptr piprot, - boost::shared_ptr poprot, + virtual bool process(stdcxx::shared_ptr piprot, + stdcxx::shared_ptr poprot, void* serverContext) { piprot_ = piprot; @@ -229,7 +229,7 @@ protected: } } - boost::shared_ptr piprot_; + stdcxx::shared_ptr piprot_; std::map frequency_map_; bool print_; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/processor/TMultiplexedProcessor.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/processor/TMultiplexedProcessor.h index 0ef7261..aa3d49f 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/processor/TMultiplexedProcessor.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/processor/TMultiplexedProcessor.h @@ -27,8 +27,6 @@ namespace apache { namespace thrift { -using boost::shared_ptr; - namespace protocol { /** @@ -38,7 +36,7 @@ namespace protocol { */ class StoredMessageProtocol : public TProtocolDecorator { public: - StoredMessageProtocol(shared_ptr _protocol, + StoredMessageProtocol(stdcxx::shared_ptr _protocol, const std::string& _name, const TMessageType _type, const int32_t _seqid) @@ -67,19 +65,19 @@ public: * processors with it, as shown in the following example:

* *
- * shared_ptr processor(new TMultiplexedProcessor()); + * stdcxx::shared_ptr processor(new TMultiplexedProcessor()); * * processor->registerProcessor( * "Calculator", - * shared_ptr( new CalculatorProcessor( - * shared_ptr( new CalculatorHandler())))); + * stdcxx::shared_ptr( new CalculatorProcessor( + * stdcxx::shared_ptr( new CalculatorHandler())))); * * processor->registerProcessor( * "WeatherReport", - * shared_ptr( new WeatherReportProcessor( - * shared_ptr( new WeatherReportHandler())))); + * stdcxx::shared_ptr( new WeatherReportProcessor( + * stdcxx::shared_ptr( new WeatherReportHandler())))); * - * shared_ptr transport(new TServerSocket(9090)); + * stdcxx::shared_ptr transport(new TServerSocket(9090)); * TSimpleServer server(processor, transport); * * server.serve(); @@ -87,7 +85,7 @@ public: */ class TMultiplexedProcessor : public TProcessor { public: - typedef std::map > services_t; + typedef std::map > services_t; /** * 'Register' a service with this TMultiplexedProcessor. This @@ -100,10 +98,40 @@ public: * as "handlers", e.g. WeatherReportHandler, * implementing WeatherReportIf interface. */ - void registerProcessor(const std::string& serviceName, shared_ptr processor) { + void registerProcessor(const std::string& serviceName, stdcxx::shared_ptr processor) { services[serviceName] = processor; } + /** + * Register a service to be called to process queries without service name + * \param [in] processor Implementation of a service. + */ + void registerDefault(const stdcxx::shared_ptr& processor) { + defaultProcessor = processor; + } + + /** + * Chew up invalid input and return an exception to throw. + */ + TException protocol_error(stdcxx::shared_ptr in, + stdcxx::shared_ptr out, + const std::string& name, + int32_t seqid, + const std::string& msg) const { + in->skip(::apache::thrift::protocol::T_STRUCT); + in->readMessageEnd(); + in->getTransport()->readEnd(); + ::apache::thrift::TApplicationException + x(::apache::thrift::TApplicationException::PROTOCOL_ERROR, + "TMultiplexedProcessor: " + msg); + out->writeMessageBegin(name, ::apache::thrift::protocol::T_EXCEPTION, seqid); + x.write(out.get()); + out->writeMessageEnd(); + out->getTransport()->writeEnd(); + out->getTransport()->flush(); + return TException(msg); +} + /** * This implementation of process performs the following steps: * @@ -119,8 +147,8 @@ public: * the service name was not found in the message, or if the service * name was not found in the service map. */ - bool process(shared_ptr in, - shared_ptr out, + bool process(stdcxx::shared_ptr in, + stdcxx::shared_ptr out, void* connectionContext) { std::string name; protocol::TMessageType type; @@ -133,22 +161,10 @@ public: if (type != protocol::T_CALL && type != protocol::T_ONEWAY) { // Unexpected message type. - in->skip(::apache::thrift::protocol::T_STRUCT); - in->readMessageEnd(); - in->getTransport()->readEnd(); - const std::string msg("TMultiplexedProcessor: Unexpected message type"); - ::apache::thrift::TApplicationException - x(::apache::thrift::TApplicationException::PROTOCOL_ERROR, msg); - out->writeMessageBegin(name, ::apache::thrift::protocol::T_EXCEPTION, seqid); - x.write(out.get()); - out->writeMessageEnd(); - out->getTransport()->writeEnd(); - out->getTransport()->flush(); - throw TException(msg); + throw protocol_error(in, out, name, seqid, "Unexpected message type"); } // Extract the service name - boost::tokenizer > tok(name, boost::char_separator(":")); std::vector tokens; @@ -161,39 +177,46 @@ public: services_t::iterator it = services.find(tokens[0]); if (it != services.end()) { - shared_ptr processor = it->second; + stdcxx::shared_ptr processor = it->second; // Let the processor registered for this service name // process the message. return processor - ->process(shared_ptr( + ->process(stdcxx::shared_ptr( new protocol::StoredMessageProtocol(in, tokens[1], type, seqid)), out, connectionContext); } else { // Unknown service. - in->skip(::apache::thrift::protocol::T_STRUCT); - in->readMessageEnd(); - in->getTransport()->readEnd(); - - std::string msg("TMultiplexedProcessor: Unknown service: "); - msg += tokens[0]; - ::apache::thrift::TApplicationException - x(::apache::thrift::TApplicationException::PROTOCOL_ERROR, msg); - out->writeMessageBegin(name, ::apache::thrift::protocol::T_EXCEPTION, seqid); - x.write(out.get()); - out->writeMessageEnd(); - out->getTransport()->writeEnd(); - out->getTransport()->flush(); - msg += ". Did you forget to call registerProcessor()?"; - throw TException(msg); + throw protocol_error(in, out, name, seqid, + "Unknown service: " + tokens[0] + + ". Did you forget to call registerProcessor()?"); } + } else if (tokens.size() == 1) { + if (defaultProcessor) { + // non-multiplexed client forwards to default processor + return defaultProcessor + ->process(stdcxx::shared_ptr( + new protocol::StoredMessageProtocol(in, tokens[0], type, seqid)), + out, + connectionContext); + } else { + throw protocol_error(in, out, name, seqid, + "Non-multiplexed client request dropped. " + "Did you forget to call defaultProcessor()?"); + } + } else { + throw protocol_error(in, out, name, seqid, + "Wrong number of tokens."); } - return false; } private: /** Map of service processor objects, indexed by service names. */ services_t services; + + //! If a non-multi client requests something, it goes to the + //! default processor (if one is defined) for backwards compatibility. + stdcxx::shared_ptr defaultProcessor; }; } } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TBinaryProtocol.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TBinaryProtocol.h index 87c53f7..f28d278 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TBinaryProtocol.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TBinaryProtocol.h @@ -23,7 +23,7 @@ #include #include -#include +#include namespace apache { namespace thrift { @@ -41,7 +41,7 @@ public: static const int32_t VERSION_1 = ((int32_t)0x80010000); // VERSION_2 (0x80020000) was taken by TDenseProtocol (which has since been removed) - TBinaryProtocolT(boost::shared_ptr trans) + TBinaryProtocolT(stdcxx::shared_ptr trans) : TVirtualProtocol >(trans), trans_(trans.get()), string_limit_(0), @@ -49,7 +49,7 @@ public: strict_read_(false), strict_write_(true) {} - TBinaryProtocolT(boost::shared_ptr trans, + TBinaryProtocolT(stdcxx::shared_ptr trans, int32_t string_limit, int32_t container_limit, bool strict_read, @@ -212,8 +212,8 @@ public: strict_write_ = strict_write; } - boost::shared_ptr getProtocol(boost::shared_ptr trans) { - boost::shared_ptr specific_trans = boost::dynamic_pointer_cast(trans); + stdcxx::shared_ptr getProtocol(stdcxx::shared_ptr trans) { + stdcxx::shared_ptr specific_trans = stdcxx::dynamic_pointer_cast(trans); TProtocol* prot; if (specific_trans) { prot = new TBinaryProtocolT(specific_trans, @@ -229,7 +229,7 @@ public: strict_write_); } - return boost::shared_ptr(prot); + return stdcxx::shared_ptr(prot); } private: diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TCompactProtocol.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TCompactProtocol.h index d970be2..e6024a9 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TCompactProtocol.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TCompactProtocol.h @@ -23,7 +23,7 @@ #include #include -#include +#include namespace apache { namespace thrift { @@ -74,7 +74,7 @@ protected: int16_t lastFieldId_; public: - TCompactProtocolT(boost::shared_ptr trans) + TCompactProtocolT(stdcxx::shared_ptr trans) : TVirtualProtocol >(trans), trans_(trans.get()), lastFieldId_(0), @@ -86,7 +86,7 @@ public: boolValue_.hasBoolValue = false; } - TCompactProtocolT(boost::shared_ptr trans, + TCompactProtocolT(stdcxx::shared_ptr trans, int32_t string_limit, int32_t container_limit) : TVirtualProtocol >(trans), @@ -239,8 +239,8 @@ public: void setContainerSizeLimit(int32_t container_limit) { container_limit_ = container_limit; } - boost::shared_ptr getProtocol(boost::shared_ptr trans) { - boost::shared_ptr specific_trans = boost::dynamic_pointer_cast(trans); + stdcxx::shared_ptr getProtocol(stdcxx::shared_ptr trans) { + stdcxx::shared_ptr specific_trans = stdcxx::dynamic_pointer_cast(trans); TProtocol* prot; if (specific_trans) { prot = new TCompactProtocolT(specific_trans, string_limit_, container_limit_); @@ -248,7 +248,7 @@ public: prot = new TCompactProtocol(trans, string_limit_, container_limit_); } - return boost::shared_ptr(prot); + return stdcxx::shared_ptr(prot); } private: diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TCompactProtocol.tcc b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TCompactProtocol.tcc index 6bbf9ef..d40c331 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TCompactProtocol.tcc +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TCompactProtocol.tcc @@ -387,7 +387,7 @@ uint32_t TCompactProtocolT::writeVarint64(uint64_t n) { */ template uint64_t TCompactProtocolT::i64ToZigzag(const int64_t l) { - return (l << 1) ^ (l >> 63); + return (static_cast(l) << 1) ^ (l >> 63); } /** @@ -396,7 +396,7 @@ uint64_t TCompactProtocolT::i64ToZigzag(const int64_t l) { */ template uint32_t TCompactProtocolT::i32ToZigzag(const int32_t n) { - return (n << 1) ^ (n >> 31); + return (static_cast(n) << 1) ^ (n >> 31); } /** diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TDebugProtocol.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TDebugProtocol.cpp index 09b978c..d3c6beb 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TDebugProtocol.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TDebugProtocol.cpp @@ -19,12 +19,12 @@ #include +#include #include #include #include #include #include -#include using std::string; @@ -129,7 +129,7 @@ uint32_t TDebugProtocol::startItem() { case MAP_VALUE: return writePlain(" -> "); case LIST: - size = writeIndented("[" + boost::lexical_cast(list_idx_.back()) + "] = "); + size = writeIndented("[" + to_string(list_idx_.back()) + "] = "); list_idx_.back()++; return size; default: @@ -223,7 +223,7 @@ uint32_t TDebugProtocol::writeFieldBegin(const char* name, const TType fieldType, const int16_t fieldId) { // sprintf(id_str, "%02d", fieldId); - string id_str = boost::lexical_cast(fieldId); + string id_str = to_string(fieldId); if (id_str.length() == 1) id_str = '0' + id_str; @@ -248,7 +248,7 @@ uint32_t TDebugProtocol::writeMapBegin(const TType keyType, bsize += startItem(); bsize += writePlain( "map<" + fieldTypeName(keyType) + "," + fieldTypeName(valType) + ">" - "[" + boost::lexical_cast(size) + "] {\n"); + "[" + to_string(size) + "] {\n"); indentUp(); write_state_.push_back(MAP_KEY); return bsize; @@ -269,7 +269,7 @@ uint32_t TDebugProtocol::writeListBegin(const TType elemType, const uint32_t siz bsize += startItem(); bsize += writePlain( "list<" + fieldTypeName(elemType) + ">" - "[" + boost::lexical_cast(size) + "] {\n"); + "[" + to_string(size) + "] {\n"); indentUp(); write_state_.push_back(LIST); list_idx_.push_back(0); @@ -292,7 +292,7 @@ uint32_t TDebugProtocol::writeSetBegin(const TType elemType, const uint32_t size bsize += startItem(); bsize += writePlain( "set<" + fieldTypeName(elemType) + ">" - "[" + boost::lexical_cast(size) + "] {\n"); + "[" + to_string(size) + "] {\n"); indentUp(); write_state_.push_back(SET); return bsize; @@ -316,19 +316,19 @@ uint32_t TDebugProtocol::writeByte(const int8_t byte) { } uint32_t TDebugProtocol::writeI16(const int16_t i16) { - return writeItem(boost::lexical_cast(i16)); + return writeItem(to_string(i16)); } uint32_t TDebugProtocol::writeI32(const int32_t i32) { - return writeItem(boost::lexical_cast(i32)); + return writeItem(to_string(i32)); } uint32_t TDebugProtocol::writeI64(const int64_t i64) { - return writeItem(boost::lexical_cast(i64)); + return writeItem(to_string(i64)); } uint32_t TDebugProtocol::writeDouble(const double dub) { - return writeItem(boost::lexical_cast(dub)); + return writeItem(to_string(dub)); } uint32_t TDebugProtocol::writeString(const string& str) { @@ -337,7 +337,7 @@ uint32_t TDebugProtocol::writeString(const string& str) { string to_show = str; if (to_show.length() > (string::size_type)string_limit_) { to_show = str.substr(0, string_prefix_size_); - to_show += "[...](" + boost::lexical_cast(str.length()) + ")"; + to_show += "[...](" + to_string(str.length()) + ")"; } string output = "\""; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TDebugProtocol.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TDebugProtocol.h index cc93230..301d05a 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TDebugProtocol.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TDebugProtocol.h @@ -22,7 +22,7 @@ #include -#include +#include namespace apache { namespace thrift { @@ -51,7 +51,7 @@ private: enum write_state_t { UNINIT, STRUCT, LIST, SET, MAP_KEY, MAP_VALUE }; public: - TDebugProtocol(boost::shared_ptr trans) + TDebugProtocol(stdcxx::shared_ptr trans) : TVirtualProtocol(trans), trans_(trans.get()), string_limit_(DEFAULT_STRING_LIMIT), @@ -141,8 +141,8 @@ public: TDebugProtocolFactory() {} virtual ~TDebugProtocolFactory() {} - boost::shared_ptr getProtocol(boost::shared_ptr trans) { - return boost::shared_ptr(new TDebugProtocol(trans)); + stdcxx::shared_ptr getProtocol(stdcxx::shared_ptr trans) { + return stdcxx::shared_ptr(new TDebugProtocol(trans)); } }; } @@ -160,7 +160,7 @@ std::string ThriftDebugString(const ThriftStruct& ts) { using namespace apache::thrift::transport; using namespace apache::thrift::protocol; TMemoryBuffer* buffer = new TMemoryBuffer; - boost::shared_ptr trans(buffer); + stdcxx::shared_ptr trans(buffer); TDebugProtocol protocol(trans); ts.write(&protocol); @@ -178,7 +178,7 @@ std::string DebugString(const std::vector& vec) { using namespace apache::thrift::transport; using namespace apache::thrift::protocol; TMemoryBuffer* buffer = new TMemoryBuffer; - boost::shared_ptr trans(buffer); + stdcxx::shared_ptr trans(buffer); TDebugProtocol protocol(trans); // I am gross! diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/THeaderProtocol.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/THeaderProtocol.cpp index 02dc736..2667617 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/THeaderProtocol.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/THeaderProtocol.cpp @@ -27,7 +27,7 @@ #include #include -#include +#include namespace apache { namespace thrift { @@ -42,11 +42,11 @@ void THeaderProtocol::resetProtocol() { switch (protoId_) { case T_BINARY_PROTOCOL: - proto_ = boost::make_shared >(trans_); + proto_ = stdcxx::make_shared >(trans_); break; case T_COMPACT_PROTOCOL: - proto_ = boost::make_shared >(trans_); + proto_ = stdcxx::make_shared >(trans_); break; default: diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/THeaderProtocol.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/THeaderProtocol.h index e7d4bd6..8cd5017 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/THeaderProtocol.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/THeaderProtocol.h @@ -25,7 +25,7 @@ #include #include -#include +#include using apache::thrift::transport::THeaderTransport; @@ -43,21 +43,21 @@ protected: public: void resetProtocol(); - explicit THeaderProtocol(const boost::shared_ptr& trans, + explicit THeaderProtocol(const stdcxx::shared_ptr& trans, uint16_t protoId = T_COMPACT_PROTOCOL) - : TVirtualProtocol(boost::shared_ptr(new THeaderTransport(trans))), - trans_(boost::dynamic_pointer_cast(this->getTransport())), + : TVirtualProtocol(stdcxx::shared_ptr(new THeaderTransport(trans))), + trans_(stdcxx::dynamic_pointer_cast(getTransport())), protoId_(protoId) { trans_->setProtocolId(protoId); resetProtocol(); } - THeaderProtocol(const boost::shared_ptr& inTrans, - const boost::shared_ptr& outTrans, + THeaderProtocol(const stdcxx::shared_ptr& inTrans, + const stdcxx::shared_ptr& outTrans, uint16_t protoId = T_COMPACT_PROTOCOL) : TVirtualProtocol( - boost::shared_ptr(new THeaderTransport(inTrans, outTrans))), - trans_(boost::dynamic_pointer_cast(this->getTransport())), + stdcxx::shared_ptr(new THeaderTransport(inTrans, outTrans))), + trans_(stdcxx::dynamic_pointer_cast(getTransport())), protoId_(protoId) { trans_->setProtocolId(protoId); resetProtocol(); @@ -182,25 +182,25 @@ public: uint32_t readBinary(std::string& binary); protected: - boost::shared_ptr trans_; + stdcxx::shared_ptr trans_; - boost::shared_ptr proto_; + stdcxx::shared_ptr proto_; uint32_t protoId_; }; class THeaderProtocolFactory : public TProtocolFactory { public: - virtual boost::shared_ptr getProtocol(boost::shared_ptr trans) { + virtual stdcxx::shared_ptr getProtocol(stdcxx::shared_ptr trans) { THeaderProtocol* headerProtocol - = new THeaderProtocol(trans, boost::shared_ptr(), T_BINARY_PROTOCOL); - return boost::shared_ptr(headerProtocol); + = new THeaderProtocol(trans, trans, T_BINARY_PROTOCOL); + return stdcxx::shared_ptr(headerProtocol); } - virtual boost::shared_ptr getProtocol( - boost::shared_ptr inTrans, - boost::shared_ptr outTrans) { + virtual stdcxx::shared_ptr getProtocol( + stdcxx::shared_ptr inTrans, + stdcxx::shared_ptr outTrans) { THeaderProtocol* headerProtocol = new THeaderProtocol(inTrans, outTrans, T_BINARY_PROTOCOL); - return boost::shared_ptr(headerProtocol); + return stdcxx::shared_ptr(headerProtocol); } }; } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TJSONProtocol.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TJSONProtocol.cpp index d3ec722..80def7f 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TJSONProtocol.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TJSONProtocol.cpp @@ -19,9 +19,9 @@ #include -#include #include #include +#include #include #include @@ -31,6 +31,7 @@ #include #include +#include using namespace apache::thrift::transport; @@ -397,7 +398,7 @@ private: bool first_; }; -TJSONProtocol::TJSONProtocol(boost::shared_ptr ptrans) +TJSONProtocol::TJSONProtocol(stdcxx::shared_ptr ptrans) : TVirtualProtocol(ptrans), trans_(ptrans.get()), context_(new TJSONContext()), @@ -407,7 +408,7 @@ TJSONProtocol::TJSONProtocol(boost::shared_ptr ptrans) TJSONProtocol::~TJSONProtocol() { } -void TJSONProtocol::pushContext(boost::shared_ptr c) { +void TJSONProtocol::pushContext(stdcxx::shared_ptr c) { contexts_.push(context_); context_ = c; } @@ -503,7 +504,7 @@ uint32_t TJSONProtocol::writeJSONBase64(const std::string& str) { template uint32_t TJSONProtocol::writeJSONInteger(NumberType num) { uint32_t result = context_->write(*trans_); - std::string val(boost::lexical_cast(num)); + std::string val(to_string(num)); bool escapeNum = context_->escapeNum(); if (escapeNum) { trans_->write(&kJSONStringDelimiter, 1); @@ -524,7 +525,7 @@ namespace { std::string doubleToString(double d) { std::ostringstream str; str.imbue(std::locale::classic()); - const int max_digits10 = 2 + std::numeric_limits::digits10; + const std::streamsize max_digits10 = 2 + std::numeric_limits::digits10; str.precision(max_digits10); str << d; return str.str(); @@ -575,7 +576,7 @@ uint32_t TJSONProtocol::writeJSONDouble(double num) { uint32_t TJSONProtocol::writeJSONObjectStart() { uint32_t result = context_->write(*trans_); trans_->write(&kJSONObjectStart, 1); - pushContext(boost::shared_ptr(new JSONPairContext())); + pushContext(stdcxx::shared_ptr(new JSONPairContext())); return result + 1; } @@ -588,7 +589,7 @@ uint32_t TJSONProtocol::writeJSONObjectEnd() { uint32_t TJSONProtocol::writeJSONArrayStart() { uint32_t result = context_->write(*trans_); trans_->write(&kJSONArrayStart, 1); - pushContext(boost::shared_ptr(new JSONListContext())); + pushContext(stdcxx::shared_ptr(new JSONListContext())); return result + 1; } @@ -684,7 +685,7 @@ uint32_t TJSONProtocol::writeBool(const bool value) { } uint32_t TJSONProtocol::writeByte(const int8_t byte) { - // writeByte() must be handled specially because boost::lexical cast sees + // writeByte() must be handled specially because to_string sees // int8_t as a text type instead of an integer type return writeJSONInteger((int16_t)byte); } @@ -772,7 +773,7 @@ uint32_t TJSONProtocol::readJSONString(std::string& str, bool skipContext) { continue; } else { size_t pos = kEscapeChars.find(ch); - if (pos == std::string::npos) { + if (pos == kEscapeChars.npos) { throw TProtocolException(TProtocolException::INVALID_DATA, "Expected control char, got '" + std::string((const char*)&ch, 1) + "'."); @@ -842,6 +843,19 @@ uint32_t TJSONProtocol::readJSONNumericChars(std::string& str) { return result; } +namespace { +template +T fromString(const std::string& s) { + T t; + std::istringstream str(s); + str.imbue(std::locale::classic()); + str >> t; + if (str.bad() || !str.eof()) + throw std::runtime_error(s); + return t; +} +} + // Reads a sequence of characters and assembles them into a number, // returning them via num template @@ -853,10 +867,10 @@ uint32_t TJSONProtocol::readJSONInteger(NumberType& num) { std::string str; result += readJSONNumericChars(str); try { - num = boost::lexical_cast(str); - } catch (boost::bad_lexical_cast e) { + num = fromString(str); + } catch (const std::runtime_error&) { throw TProtocolException(TProtocolException::INVALID_DATA, - "Expected numeric value; got \"" + str + "\""); + "Expected numeric value; got \"" + str + "\""); } if (context_->escapeNum()) { result += readJSONSyntaxChar(kJSONStringDelimiter); @@ -864,18 +878,6 @@ uint32_t TJSONProtocol::readJSONInteger(NumberType& num) { return result; } -namespace { -double stringToDouble(const std::string& s) { - double d; - std::istringstream str(s); - str.imbue(std::locale::classic()); - str >> d; - if (str.bad() || !str.eof()) - throw std::runtime_error(s); - return d; -} -} - // Reads a JSON number or string and interprets it as a double. uint32_t TJSONProtocol::readJSONDouble(double& num) { uint32_t result = context_->read(reader_); @@ -896,8 +898,8 @@ uint32_t TJSONProtocol::readJSONDouble(double& num) { "Numeric data unexpectedly quoted"); } try { - num = stringToDouble(str); - } catch (std::runtime_error e) { + num = fromString(str); + } catch (std::runtime_error& e) { throw TProtocolException(TProtocolException::INVALID_DATA, "Expected numeric value; got \"" + str + "\""); } @@ -909,8 +911,8 @@ uint32_t TJSONProtocol::readJSONDouble(double& num) { } result += readJSONNumericChars(str); try { - num = stringToDouble(str); - } catch (std::runtime_error e) { + num = fromString(str); + } catch (std::runtime_error& e) { throw TProtocolException(TProtocolException::INVALID_DATA, "Expected numeric value; got \"" + str + "\""); } @@ -921,7 +923,7 @@ uint32_t TJSONProtocol::readJSONDouble(double& num) { uint32_t TJSONProtocol::readJSONObjectStart() { uint32_t result = context_->read(reader_); result += readJSONSyntaxChar(kJSONObjectStart); - pushContext(boost::shared_ptr(new JSONPairContext())); + pushContext(stdcxx::shared_ptr(new JSONPairContext())); return result; } @@ -934,7 +936,7 @@ uint32_t TJSONProtocol::readJSONObjectEnd() { uint32_t TJSONProtocol::readJSONArrayStart() { uint32_t result = context_->read(reader_); result += readJSONSyntaxChar(kJSONArrayStart); - pushContext(boost::shared_ptr(new JSONListContext())); + pushContext(stdcxx::shared_ptr(new JSONListContext())); return result; } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TJSONProtocol.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TJSONProtocol.h index 5834eff..16dff56 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TJSONProtocol.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TJSONProtocol.h @@ -87,20 +87,21 @@ class TJSONContext; * the current implementation is to match as closely as possible the behavior * of Java's Double.toString(), which has no precision loss. Implementors in * other languages should strive to achieve that where possible. I have not - * yet verified whether boost:lexical_cast, which is doing that work for me in - * C++, loses any precision, but I am leaving this as a future improvement. I - * may try to provide a C component for this, so that other languages could - * bind to the same underlying implementation for maximum consistency. + * yet verified whether std::istringstream::operator>>, which is doing that + * work for me in C++, loses any precision, but I am leaving this as a future + * improvement. I may try to provide a C component for this, so that other + * languages could bind to the same underlying implementation for maximum + * consistency. * */ class TJSONProtocol : public TVirtualProtocol { public: - TJSONProtocol(boost::shared_ptr ptrans); + TJSONProtocol(stdcxx::shared_ptr ptrans); ~TJSONProtocol(); private: - void pushContext(boost::shared_ptr c); + void pushContext(stdcxx::shared_ptr c); void popContext(); @@ -275,8 +276,8 @@ public: private: TTransport* trans_; - std::stack > contexts_; - boost::shared_ptr context_; + std::stack > contexts_; + stdcxx::shared_ptr context_; LookaheadReader reader_; }; @@ -289,8 +290,8 @@ public: virtual ~TJSONProtocolFactory() {} - boost::shared_ptr getProtocol(boost::shared_ptr trans) { - return boost::shared_ptr(new TJSONProtocol(trans)); + stdcxx::shared_ptr getProtocol(stdcxx::shared_ptr trans) { + return stdcxx::shared_ptr(new TJSONProtocol(trans)); } }; } @@ -308,7 +309,7 @@ std::string ThriftJSONString(const ThriftStruct& ts) { using namespace apache::thrift::transport; using namespace apache::thrift::protocol; TMemoryBuffer* buffer = new TMemoryBuffer; - boost::shared_ptr trans(buffer); + stdcxx::shared_ptr trans(buffer); TJSONProtocol protocol(trans); ts.write(&protocol); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TMultiplexedProtocol.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TMultiplexedProtocol.h index 0244fbe..dd7e88f 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TMultiplexedProtocol.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TMultiplexedProtocol.h @@ -25,7 +25,7 @@ namespace apache { namespace thrift { namespace protocol { -using boost::shared_ptr; +using stdcxx::shared_ptr; /** * TMultiplexedProtocol is a protocol-independent concrete decorator diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TProtocol.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TProtocol.h index 448c4fe..aa5beea 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TProtocol.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TProtocol.h @@ -28,7 +28,7 @@ #include #include -#include +#include #include #ifdef HAVE_NETINET_IN_H @@ -550,12 +550,12 @@ public: } virtual uint32_t skip_virt(TType type); - inline boost::shared_ptr getTransport() { return ptrans_; } + inline stdcxx::shared_ptr getTransport() { return ptrans_; } // TODO: remove these two calls, they are for backwards // compatibility - inline boost::shared_ptr getInputTransport() { return ptrans_; } - inline boost::shared_ptr getOutputTransport() { return ptrans_; } + inline stdcxx::shared_ptr getInputTransport() { return ptrans_; } + inline stdcxx::shared_ptr getOutputTransport() { return ptrans_; } // input and output recursion depth are kept separate so that one protocol // can be used concurrently for both input and output. @@ -577,11 +577,11 @@ public: void setRecurisionLimit(uint32_t depth) {recursion_limit_ = depth;} protected: - TProtocol(boost::shared_ptr ptrans) + TProtocol(stdcxx::shared_ptr ptrans) : ptrans_(ptrans), input_recursion_depth_(0), output_recursion_depth_(0), recursion_limit_(DEFAULT_RECURSION_LIMIT) {} - boost::shared_ptr ptrans_; + stdcxx::shared_ptr ptrans_; private: TProtocol() {} @@ -599,9 +599,9 @@ public: virtual ~TProtocolFactory(); - virtual boost::shared_ptr getProtocol(boost::shared_ptr trans) = 0; - virtual boost::shared_ptr getProtocol(boost::shared_ptr inTrans, - boost::shared_ptr outTrans) { + virtual stdcxx::shared_ptr getProtocol(stdcxx::shared_ptr trans) = 0; + virtual stdcxx::shared_ptr getProtocol(stdcxx::shared_ptr inTrans, + stdcxx::shared_ptr outTrans) { (void)outTrans; return getProtocol(inTrans); } @@ -672,7 +672,7 @@ uint32_t skip(Protocol_& prot, TType type) { return prot.readBool(boolv); } case T_BYTE: { - int8_t bytev; + int8_t bytev = 0; return prot.readByte(bytev); } case T_I16: { @@ -753,6 +753,8 @@ uint32_t skip(Protocol_& prot, TType type) { case T_UTF8: case T_UTF16: break; + default: + throw TProtocolException(TProtocolException::INVALID_DATA); } return 0; } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TProtocolDecorator.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TProtocolDecorator.h index 446a81f..a353b79 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TProtocolDecorator.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TProtocolDecorator.h @@ -21,12 +21,12 @@ #define THRIFT_TPROTOCOLDECORATOR_H_ 1 #include -#include +#include namespace apache { namespace thrift { namespace protocol { -using boost::shared_ptr; +using stdcxx::shared_ptr; /** * TProtocolDecorator forwards all requests to an enclosed diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TProtocolTap.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TProtocolTap.h index 3e56393..176d4fd 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TProtocolTap.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TProtocolTap.h @@ -36,7 +36,7 @@ using apache::thrift::transport::TTransport; */ class TProtocolTap : public TVirtualProtocol { public: - TProtocolTap(boost::shared_ptr source, boost::shared_ptr sink) + TProtocolTap(stdcxx::shared_ptr source, stdcxx::shared_ptr sink) : TVirtualProtocol(source->getTransport()), source_(source), sink_(sink) {} uint32_t readMessageBegin(std::string& name, TMessageType& messageType, int32_t& seqid) { @@ -167,8 +167,8 @@ public: } private: - boost::shared_ptr source_; - boost::shared_ptr sink_; + stdcxx::shared_ptr source_; + stdcxx::shared_ptr sink_; }; } } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TVirtualProtocol.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TVirtualProtocol.h index 831c3a2..628b494 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TVirtualProtocol.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/protocol/TVirtualProtocol.h @@ -301,7 +301,7 @@ public: uint32_t skip(TType type) { return ::apache::thrift::protocol::skip(*this, type); } protected: - TProtocolDefaults(boost::shared_ptr ptrans) : TProtocol(ptrans) {} + TProtocolDefaults(stdcxx::shared_ptr ptrans) : TProtocol(ptrans) {} }; /** @@ -504,7 +504,7 @@ public: using Super_::readBool; // so we don't hide readBool(bool&) protected: - TVirtualProtocol(boost::shared_ptr ptrans) : Super_(ptrans) {} + TVirtualProtocol(stdcxx::shared_ptr ptrans) : Super_(ptrans) {} }; } } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/qt/TQIODeviceTransport.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/qt/TQIODeviceTransport.cpp index 686f242..0e46f11 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/qt/TQIODeviceTransport.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/qt/TQIODeviceTransport.cpp @@ -23,11 +23,13 @@ #include #include - -using boost::shared_ptr; +#include namespace apache { namespace thrift { + +using stdcxx::shared_ptr; + namespace transport { TQIODeviceTransport::TQIODeviceTransport(shared_ptr dev) : dev_(dev) { @@ -89,7 +91,7 @@ uint32_t TQIODeviceTransport::read(uint8_t* buf, uint32_t len) { "read(): underlying QIODevice is not open"); } - actualSize = (uint32_t)std::min((qint64)len, dev_->bytesAvailable()); + actualSize = (uint32_t)(std::min)((qint64)len, dev_->bytesAvailable()); readSize = dev_->read(reinterpret_cast(buf), actualSize); if (readSize < 0) { diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/qt/TQIODeviceTransport.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/qt/TQIODeviceTransport.h index 8091d32..9087f2c 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/qt/TQIODeviceTransport.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/qt/TQIODeviceTransport.h @@ -20,7 +20,7 @@ #ifndef _THRIFT_ASYNC_TQIODEVICE_TRANSPORT_H_ #define _THRIFT_ASYNC_TQIODEVICE_TRANSPORT_H_ 1 -#include +#include #include @@ -36,7 +36,7 @@ namespace transport { class TQIODeviceTransport : public apache::thrift::transport::TVirtualTransport { public: - explicit TQIODeviceTransport(boost::shared_ptr dev); + explicit TQIODeviceTransport(stdcxx::shared_ptr dev); virtual ~TQIODeviceTransport(); void open(); @@ -59,7 +59,7 @@ private: TQIODeviceTransport(const TQIODeviceTransport&); TQIODeviceTransport& operator=(const TQIODeviceTransport&); - boost::shared_ptr dev_; + stdcxx::shared_ptr dev_; }; } } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/qt/TQTcpServer.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/qt/TQTcpServer.cpp index 350198c..c4669d7 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/qt/TQTcpServer.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/qt/TQTcpServer.cpp @@ -23,19 +23,20 @@ #include #include -#include +#include #include #include -using boost::shared_ptr; using apache::thrift::protocol::TProtocol; using apache::thrift::protocol::TProtocolFactory; using apache::thrift::transport::TTransport; using apache::thrift::transport::TTransportException; using apache::thrift::transport::TQIODeviceTransport; -using apache::thrift::stdcxx::function; using apache::thrift::stdcxx::bind; +using apache::thrift::stdcxx::function; +using apache::thrift::stdcxx::placeholders::_1; +using apache::thrift::stdcxx::shared_ptr; QT_USE_NAMESPACE @@ -110,7 +111,7 @@ void TQTcpServer::beginDecode() { try { processor_ - ->process(bind(&TQTcpServer::finish, this, ctx, apache::thrift::stdcxx::placeholders::_1), + ->process(bind(&TQTcpServer::finish, this, ctx, _1), ctx->iprot_, ctx->oprot_); } catch (const TTransportException& ex) { diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/qt/TQTcpServer.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/qt/TQTcpServer.h index 081d84a..0d32afa 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/qt/TQTcpServer.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/qt/TQTcpServer.h @@ -23,7 +23,7 @@ #include #include -#include +#include namespace apache { namespace thrift { @@ -47,9 +47,9 @@ class TAsyncProcessor; class TQTcpServer : public QObject { Q_OBJECT public: - TQTcpServer(boost::shared_ptr server, - boost::shared_ptr processor, - boost::shared_ptr protocolFactory, + TQTcpServer(stdcxx::shared_ptr server, + stdcxx::shared_ptr processor, + stdcxx::shared_ptr protocolFactory, QObject* parent = NULL); virtual ~TQTcpServer(); @@ -65,13 +65,13 @@ private: struct ConnectionContext; void scheduleDeleteConnectionContext(QTcpSocket* connection); - void finish(boost::shared_ptr ctx, bool healthy); + void finish(stdcxx::shared_ptr ctx, bool healthy); - boost::shared_ptr server_; - boost::shared_ptr processor_; - boost::shared_ptr pfact_; + stdcxx::shared_ptr server_; + stdcxx::shared_ptr processor_; + stdcxx::shared_ptr pfact_; - typedef std::map > ConnectionContextMap; + typedef std::map > ConnectionContextMap; ConnectionContextMap ctxMap_; }; } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TConnectedClient.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TConnectedClient.cpp index 889c885..33ec3a9 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TConnectedClient.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TConnectedClient.cpp @@ -28,7 +28,7 @@ using apache::thrift::protocol::TProtocol; using apache::thrift::server::TServerEventHandler; using apache::thrift::transport::TTransport; using apache::thrift::transport::TTransportException; -using boost::shared_ptr; +using stdcxx::shared_ptr; using std::string; TConnectedClient::TConnectedClient(const shared_ptr& processor, diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TConnectedClient.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TConnectedClient.h index 3ea065e..2f9d4c9 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TConnectedClient.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TConnectedClient.h @@ -20,7 +20,7 @@ #ifndef _THRIFT_SERVER_TCONNECTEDCLIENT_H_ #define _THRIFT_SERVER_TCONNECTEDCLIENT_H_ 1 -#include +#include #include #include #include @@ -49,11 +49,11 @@ public: * @param[in] client the TTransport representing the client */ TConnectedClient( - const boost::shared_ptr& processor, - const boost::shared_ptr& inputProtocol, - const boost::shared_ptr& outputProtocol, - const boost::shared_ptr& eventHandler, - const boost::shared_ptr& client); + const stdcxx::shared_ptr& processor, + const stdcxx::shared_ptr& inputProtocol, + const stdcxx::shared_ptr& outputProtocol, + const stdcxx::shared_ptr& eventHandler, + const stdcxx::shared_ptr& client); /** * Destructor. @@ -92,11 +92,11 @@ protected: virtual void cleanup(); private: - boost::shared_ptr processor_; - boost::shared_ptr inputProtocol_; - boost::shared_ptr outputProtocol_; - boost::shared_ptr eventHandler_; - boost::shared_ptr client_; + stdcxx::shared_ptr processor_; + stdcxx::shared_ptr inputProtocol_; + stdcxx::shared_ptr outputProtocol_; + stdcxx::shared_ptr eventHandler_; + stdcxx::shared_ptr client_; /** * Context acquired from the eventHandler_ if one exists. diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TNonblockingServer.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TNonblockingServer.cpp index ccc37a2..194d59f 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TNonblockingServer.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TNonblockingServer.cpp @@ -17,8 +17,6 @@ * under the License. */ -#define __STDC_FORMAT_MACROS - #include #include @@ -27,9 +25,14 @@ #include #include +#include #include -#ifdef HAVE_SYS_SELECT_H +#ifdef HAVE_POLL_H +#include +#elif HAVE_SYS_POLL_H +#include +#elif HAVE_SYS_SELECT_H #include #endif @@ -64,13 +67,12 @@ #define AF_LOCAL AF_UNIX #endif -#if !defined(PRIu32) -#define PRIu32 "I32u" -#define PRIu64 "I64u" +#ifdef HAVE_INTTYPES_H +#include #endif -#if defined(_WIN32) && (_WIN32_WINNT < 0x0600) - #define AI_ADDRCONFIG 0x0400 +#ifdef HAVE_STDINT_H +#include #endif namespace apache { @@ -80,10 +82,9 @@ namespace server { using namespace apache::thrift::protocol; using namespace apache::thrift::transport; using namespace apache::thrift::concurrency; -using namespace std; using apache::thrift::transport::TSocket; using apache::thrift::transport::TTransportException; -using boost::shared_ptr; +using stdcxx::shared_ptr; /// Three states for sockets: recv frame size, recv data, and send mode enum TSocketState { SOCKET_RECV_FRAMING, SOCKET_RECV, SOCKET_SEND }; @@ -118,10 +119,10 @@ private: TNonblockingServer* server_; /// TProcessor - boost::shared_ptr processor_; + stdcxx::shared_ptr processor_; /// Object wrapping network socket - boost::shared_ptr tSocket_; + stdcxx::shared_ptr tSocket_; /// Libevent object struct event event_; @@ -163,23 +164,23 @@ private: int32_t callsForResize_; /// Transport to read from - boost::shared_ptr inputTransport_; + stdcxx::shared_ptr inputTransport_; /// Transport that processor writes to - boost::shared_ptr outputTransport_; + stdcxx::shared_ptr outputTransport_; /// extra transport generated by transport factory (e.g. BufferedRouterTransport) - boost::shared_ptr factoryInputTransport_; - boost::shared_ptr factoryOutputTransport_; + stdcxx::shared_ptr factoryInputTransport_; + stdcxx::shared_ptr factoryOutputTransport_; /// Protocol decoder - boost::shared_ptr inputProtocol_; + stdcxx::shared_ptr inputProtocol_; /// Protocol encoder - boost::shared_ptr outputProtocol_; + stdcxx::shared_ptr outputProtocol_; /// Server event handler, if any - boost::shared_ptr serverEventHandler_; + stdcxx::shared_ptr serverEventHandler_; /// Thrift call context, if any void* connectionContext_; @@ -212,10 +213,8 @@ public: class Task; /// Constructor - TConnection(THRIFT_SOCKET socket, - TNonblockingIOThread* ioThread, - const sockaddr* addr, - socklen_t addrLen) { + TConnection(stdcxx::shared_ptr socket, + TNonblockingIOThread* ioThread) { readBuffer_ = NULL; readBufferSize_ = 0; @@ -227,8 +226,10 @@ public: inputTransport_.reset(new TMemoryBuffer(readBuffer_, readBufferSize_)); outputTransport_.reset( new TMemoryBuffer(static_cast(server_->getWriteBufferDefaultSize()))); - tSocket_.reset(new TSocket()); - init(socket, ioThread, addr, addrLen); + + tSocket_ = socket; + + init(ioThread); } ~TConnection() { std::free(readBuffer_); } @@ -245,10 +246,10 @@ public: void checkIdleBufferMemLimit(size_t readLimit, size_t writeLimit); /// Initialize - void init(THRIFT_SOCKET socket, - TNonblockingIOThread* ioThread, - const sockaddr* addr, - socklen_t addrLen); + void init(TNonblockingIOThread* ioThread); + + /// set socket for connection + void setSocket(stdcxx::shared_ptr socket); /** * This is called when the application transitions from one state into @@ -291,6 +292,7 @@ public: void forceClose() { appState_ = APP_CLOSE_CONNECTION; if (!notifyIOThread()) { + server_->decrementActiveProcessors(); close(); throw TException("TConnection::forceClose: failed write on notify pipe"); } @@ -303,10 +305,10 @@ public: TAppState getState() const { return appState_; } /// return the TSocket transport wrapping this network connection - boost::shared_ptr getTSocket() const { return tSocket_; } + stdcxx::shared_ptr getTSocket() const { return tSocket_; } /// return the server event handler if any - boost::shared_ptr getServerEventHandler() { return serverEventHandler_; } + stdcxx::shared_ptr getServerEventHandler() { return serverEventHandler_; } /// return the Thrift connection context if any void* getConnectionContext() { return connectionContext_; } @@ -314,9 +316,9 @@ public: class TNonblockingServer::TConnection::Task : public Runnable { public: - Task(boost::shared_ptr processor, - boost::shared_ptr input, - boost::shared_ptr output, + Task(stdcxx::shared_ptr processor, + stdcxx::shared_ptr input, + stdcxx::shared_ptr output, TConnection* connection) : processor_(processor), input_(input), @@ -338,7 +340,7 @@ public: } } catch (const TTransportException& ttx) { GlobalOutput.printf("TNonblockingServer: client died: %s", ttx.what()); - } catch (const bad_alloc&) { + } catch (const std::bad_alloc&) { GlobalOutput("TNonblockingServer: caught bad_alloc exception."); exit(1); } catch (const std::exception& x) { @@ -352,6 +354,7 @@ public: // Signal completion back to the libevent thread via a pipe if (!connection_->notifyIOThread()) { GlobalOutput.printf("TNonblockingServer: failed to notifyIOThread, closing."); + connection_->server_->decrementActiveProcessors(); connection_->close(); throw TException("TNonblockingServer::Task::run: failed write on notify pipe"); } @@ -360,21 +363,15 @@ public: TConnection* getTConnection() { return connection_; } private: - boost::shared_ptr processor_; - boost::shared_ptr input_; - boost::shared_ptr output_; + stdcxx::shared_ptr processor_; + stdcxx::shared_ptr input_; + stdcxx::shared_ptr output_; TConnection* connection_; - boost::shared_ptr serverEventHandler_; + stdcxx::shared_ptr serverEventHandler_; void* connectionContext_; }; -void TNonblockingServer::TConnection::init(THRIFT_SOCKET socket, - TNonblockingIOThread* ioThread, - const sockaddr* addr, - socklen_t addrLen) { - tSocket_->setSocketFD(socket); - tSocket_->setCachedAddress(addr, addrLen); - +void TNonblockingServer::TConnection::init(TNonblockingIOThread* ioThread) { ioThread_ = ioThread; server_ = ioThread->getServer(); appState_ = APP_INIT; @@ -417,6 +414,10 @@ void TNonblockingServer::TConnection::init(THRIFT_SOCKET socket, processor_ = server_->getProcessor(inputProtocol_, outputProtocol_, tSocket_); } +void TNonblockingServer::TConnection::setSocket(stdcxx::shared_ptr socket) { + tSocket_ = socket; +} + void TNonblockingServer::TConnection::workSocket() { int got = 0, left = 0, sent = 0; uint32_t fetch = 0; @@ -442,10 +443,14 @@ void TNonblockingServer::TConnection::workSocket() { } readBufferPos_ += fetch; } catch (TTransportException& te) { - GlobalOutput.printf("TConnection::workSocket(): %s", te.what()); - close(); + //In Nonblocking SSLSocket some operations need to be retried again. + //Current approach is parsing exception message, but a better solution needs to be investigated. + if(!strstr(te.what(), "retry")) { + GlobalOutput.printf("TConnection::workSocket(): %s", te.what()); + close(); - return; + return; + } } if (readBufferPos_ < sizeof(framing.size)) { @@ -471,6 +476,18 @@ void TNonblockingServer::TConnection::workSocket() { } // size known; now get the rest of the frame transition(); + + // If the socket has more data than the frame header, continue to work on it. This is not strictly necessary for + // regular sockets, because if there is more data, libevent will fire the event handler registered for read + // readiness, which will in turn call workSocket(). However, some socket types (such as TSSLSocket) may have the + // data sitting in their internal buffers and from libevent's perspective, there is no further data available. In + // that case, not having this workSocket() call here would result in a hang as we will never get to work the socket, + // despite having more data. + if (tSocket_->hasPendingDataToRead()) + { + workSocket(); + } + return; case SOCKET_RECV: @@ -482,8 +499,12 @@ void TNonblockingServer::TConnection::workSocket() { fetch = readWant_ - readBufferPos_; got = tSocket_->read(readBuffer_ + readBufferPos_, fetch); } catch (TTransportException& te) { - GlobalOutput.printf("TConnection::workSocket(): %s", te.what()); - close(); + //In Nonblocking SSLSocket some operations need to be retried again. + //Current approach is parsing exception message, but a better solution needs to be investigated. + if(!strstr(te.what(), "retry")) { + GlobalOutput.printf("TConnection::workSocket(): %s", te.what()); + close(); + } return; } @@ -513,7 +534,7 @@ void TNonblockingServer::TConnection::workSocket() { // If there is no data to send, then let us move on if (writeBufferPos_ == writeBufferSize_) { - GlobalOutput("WARNING: Send state with no data to send\n"); + GlobalOutput("WARNING: Send state with no data to send"); transition(); return; } @@ -589,26 +610,29 @@ void TNonblockingServer::TConnection::transition() { // We are setting up a Task to do this work and we will wait on it // Create task and dispatch to the thread manager - boost::shared_ptr task = boost::shared_ptr( + stdcxx::shared_ptr task = stdcxx::shared_ptr( new Task(processor_, inputProtocol_, outputProtocol_, this)); // The application is now waiting on the task to finish appState_ = APP_WAIT_TASK; + // Set this connection idle so that libevent doesn't process more + // data on it while we're still waiting for the threadmanager to + // finish this task + setIdle(); + try { server_->addTask(task); } catch (IllegalStateException& ise) { // The ThreadManager is not ready to handle any more tasks (it's probably shutting down). GlobalOutput.printf("IllegalStateException: Server::process() %s", ise.what()); + server_->decrementActiveProcessors(); close(); } catch (TimedOutException& to) { GlobalOutput.printf("[ERROR] TimedOutException: Server::process() %s", to.what()); + server_->decrementActiveProcessors(); close(); } - // Set this connection idle so that libevent doesn't process more - // data on it while we're still waiting for the threadmanager to - // finish this task - setIdle(); return; } else { try { @@ -639,6 +663,7 @@ void TNonblockingServer::TConnection::transition() { return; } } + // fallthrough // Intentionally fall through here, the call to process has written into // the writeBuffer_ @@ -669,9 +694,6 @@ void TNonblockingServer::TConnection::transition() { appState_ = APP_SEND_RESULT; setWrite(); - // Try to work the socket immediately - // workSocket(); - return; } @@ -690,6 +712,7 @@ void TNonblockingServer::TConnection::transition() { server_->getIdleWriteBufferLimit()); callsForResize_ = 0; } + // fallthrough // N.B.: We also intentionally fall through here into the INIT state! @@ -710,9 +733,6 @@ void TNonblockingServer::TConnection::transition() { // Register read event setRead(); - // Try to work the socket right away - // workSocket(); - return; case APP_READ_FRAME_SIZE: @@ -745,9 +765,6 @@ void TNonblockingServer::TConnection::transition() { socketState_ = SOCKET_RECV; appState_ = APP_READ_REQUEST; - // Work the socket right away - // workSocket(); - return; case APP_CLOSE_CONNECTION: @@ -768,11 +785,9 @@ void TNonblockingServer::TConnection::setFlags(short eventFlags) { } // Delete a previously existing event - if (eventFlags_ != 0) { - if (event_del(&event_) == -1) { - GlobalOutput("TConnection::setFlags event_del"); - return; - } + if (eventFlags_ && event_del(&event_) == -1) { + GlobalOutput.perror("TConnection::setFlags() event_del", THRIFT_GET_SOCKET_ERROR); + return; } // Update in memory structure @@ -815,7 +830,7 @@ void TNonblockingServer::TConnection::setFlags(short eventFlags) { // Add the event if (event_add(&event_, 0) == -1) { - GlobalOutput("TConnection::setFlags(): could not event_add"); + GlobalOutput.perror("TConnection::setFlags(): could not event_add", THRIFT_GET_SOCKET_ERROR); } } @@ -823,10 +838,7 @@ void TNonblockingServer::TConnection::setFlags(short eventFlags) { * Closes a connection */ void TNonblockingServer::TConnection::close() { - // Delete the registered libevent - if (event_del(&event_) == -1) { - GlobalOutput.perror("TConnection::close() event_del", THRIFT_GET_SOCKET_ERROR); - } + setIdle(); if (serverEventHandler_) { serverEventHandler_->deleteContext(connectionContext_, inputProtocol_, outputProtocol_); @@ -876,9 +888,9 @@ TNonblockingServer::~TNonblockingServer() { // objects and the Thread objects have shared_ptrs to the TNonblockingIOThread // objects (as runnable) so these objects will never deallocate without help. while (!ioThreads_.empty()) { - boost::shared_ptr iot = ioThreads_.back(); + stdcxx::shared_ptr iot = ioThreads_.back(); ioThreads_.pop_back(); - iot->setThread(boost::shared_ptr()); + iot->setThread(stdcxx::shared_ptr()); } } @@ -886,9 +898,7 @@ TNonblockingServer::~TNonblockingServer() { * Creates a new connection either by reusing an object off the stack or * by allocating a new one entirely */ -TNonblockingServer::TConnection* TNonblockingServer::createConnection(THRIFT_SOCKET socket, - const sockaddr* addr, - socklen_t addrLen) { +TNonblockingServer::TConnection* TNonblockingServer::createConnection(stdcxx::shared_ptr socket) { // Check the stack Guard g(connMutex_); @@ -902,12 +912,13 @@ TNonblockingServer::TConnection* TNonblockingServer::createConnection(THRIFT_SOC // Check the connection stack to see if we can re-use TConnection* result = NULL; if (connectionStack_.empty()) { - result = new TConnection(socket, ioThread, addr, addrLen); + result = new TConnection(socket, ioThread); ++numTConnections_; } else { result = connectionStack_.top(); connectionStack_.pop(); - result->init(socket, ioThread, addr, addrLen); + result->setSocket(socket); + result->init(ioThread); } activeConnections_.push_back(result); return result; @@ -942,53 +953,35 @@ void TNonblockingServer::handleEvent(THRIFT_SOCKET fd, short which) { // Make sure that libevent didn't mess up the socket handles assert(fd == serverSocket_); - // Server socket accepted a new connection - socklen_t addrLen; - sockaddr_storage addrStorage; - sockaddr* addrp = (sockaddr*)&addrStorage; - addrLen = sizeof(addrStorage); - // Going to accept a new client socket - THRIFT_SOCKET clientSocket; + stdcxx::shared_ptr clientSocket; - // Accept as many new clients as possible, even though libevent signaled only - // one, this helps us to avoid having to go back into the libevent engine so - // many times - while ((clientSocket = ::accept(fd, addrp, &addrLen)) != -1) { + clientSocket = serverTransport_->accept(); + if (clientSocket) { // If we're overloaded, take action here if (overloadAction_ != T_OVERLOAD_NO_ACTION && serverOverloaded()) { Guard g(connMutex_); nConnectionsDropped_++; nTotalConnectionsDropped_++; if (overloadAction_ == T_OVERLOAD_CLOSE_ON_ACCEPT) { - ::THRIFT_CLOSESOCKET(clientSocket); + clientSocket->close(); return; } else if (overloadAction_ == T_OVERLOAD_DRAIN_TASK_QUEUE) { if (!drainPendingTask()) { // Nothing left to discard, so we drop connection instead. - ::THRIFT_CLOSESOCKET(clientSocket); + clientSocket->close(); return; } } } - // Explicitly set this socket to NONBLOCK mode - int flags; - if ((flags = THRIFT_FCNTL(clientSocket, THRIFT_F_GETFL, 0)) < 0 - || THRIFT_FCNTL(clientSocket, THRIFT_F_SETFL, flags | THRIFT_O_NONBLOCK) < 0) { - GlobalOutput.perror("thriftServerEventHandler: set THRIFT_O_NONBLOCK (THRIFT_FCNTL) ", - THRIFT_GET_SOCKET_ERROR); - ::THRIFT_CLOSESOCKET(clientSocket); - return; - } - // Create a new TConnection for this client socket. - TConnection* clientConnection = createConnection(clientSocket, addrp, addrLen); + TConnection* clientConnection = createConnection(clientSocket); // Fail fast if we could not create a TConnection object if (clientConnection == NULL) { GlobalOutput.printf("thriftServerEventHandler: failed TConnection factory"); - ::THRIFT_CLOSESOCKET(clientSocket); + clientSocket->close(); return; } @@ -1009,18 +1002,9 @@ void TNonblockingServer::handleEvent(THRIFT_SOCKET fd, short which) { } else { if (!clientConnection->notifyIOThread()) { GlobalOutput.perror("[ERROR] notifyIOThread failed on fresh connection, closing", errno); - returnConnection(clientConnection); + clientConnection->close(); } } - - // addrLen is written by the accept() call, so needs to be set before the next call. - addrLen = sizeof(addrStorage); - } - - // Done looping accept, now we have to make sure the error is due to - // blocking. Any other error is a problem - if (THRIFT_GET_SOCKET_ERROR != THRIFT_EAGAIN && THRIFT_GET_SOCKET_ERROR != THRIFT_EWOULDBLOCK) { - GlobalOutput.perror("thriftServerEventHandler: accept() ", THRIFT_GET_SOCKET_ERROR); } } @@ -1028,132 +1012,12 @@ void TNonblockingServer::handleEvent(THRIFT_SOCKET fd, short which) { * Creates a socket to listen on and binds it to the local port. */ void TNonblockingServer::createAndListenOnSocket() { -#ifdef _WIN32 - TWinsockSingleton::create(); -#endif // _WIN32 - - THRIFT_SOCKET s; - - struct addrinfo hints, *res, *res0; - int error; - - char port[sizeof("65536") + 1]; - memset(&hints, 0, sizeof(hints)); - hints.ai_family = PF_UNSPEC; - hints.ai_socktype = SOCK_STREAM; - hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG; - sprintf(port, "%d", port_); - - // Wildcard address - error = getaddrinfo(NULL, port, &hints, &res0); - if (error) { - throw TException("TNonblockingServer::serve() getaddrinfo " - + string(THRIFT_GAI_STRERROR(error))); - } - - // Pick the ipv6 address first since ipv4 addresses can be mapped - // into ipv6 space. - for (res = res0; res; res = res->ai_next) { - if (res->ai_family == AF_INET6 || res->ai_next == NULL) - break; - } - - // Create the server socket - s = socket(res->ai_family, res->ai_socktype, res->ai_protocol); - if (s == -1) { - freeaddrinfo(res0); - throw TException("TNonblockingServer::serve() socket() -1"); - } - -#ifdef IPV6_V6ONLY - if (res->ai_family == AF_INET6) { - int zero = 0; - if (-1 == setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, const_cast_sockopt(&zero), sizeof(zero))) { - GlobalOutput("TServerSocket::listen() IPV6_V6ONLY"); - } - } -#endif // #ifdef IPV6_V6ONLY - - int one = 1; - - // Set THRIFT_NO_SOCKET_CACHING to avoid 2MSL delay on server restart - setsockopt(s, SOL_SOCKET, THRIFT_NO_SOCKET_CACHING, const_cast_sockopt(&one), sizeof(one)); - - if (::bind(s, res->ai_addr, static_cast(res->ai_addrlen)) == -1) { - ::THRIFT_CLOSESOCKET(s); - freeaddrinfo(res0); - throw TTransportException(TTransportException::NOT_OPEN, - "TNonblockingServer::serve() bind", - THRIFT_GET_SOCKET_ERROR); - } - - // Done with the addr info - freeaddrinfo(res0); - - // Set up this file descriptor for listening - listenSocket(s); + serverTransport_->listen(); + serverSocket_ = serverTransport_->getSocketFD(); } -/** - * Takes a socket created by listenSocket() and sets various options on it - * to prepare for use in the server. - */ -void TNonblockingServer::listenSocket(THRIFT_SOCKET s) { - // Set socket to nonblocking mode - int flags; - if ((flags = THRIFT_FCNTL(s, THRIFT_F_GETFL, 0)) < 0 - || THRIFT_FCNTL(s, THRIFT_F_SETFL, flags | THRIFT_O_NONBLOCK) < 0) { - ::THRIFT_CLOSESOCKET(s); - throw TException("TNonblockingServer::serve() THRIFT_O_NONBLOCK"); - } - int one = 1; - struct linger ling = {0, 0}; - - // Keepalive to ensure full result flushing - setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, const_cast_sockopt(&one), sizeof(one)); - - // Turn linger off to avoid hung sockets - setsockopt(s, SOL_SOCKET, SO_LINGER, const_cast_sockopt(&ling), sizeof(ling)); - -// Set TCP nodelay if available, MAC OS X Hack -// See http://lists.danga.com/pipermail/memcached/2005-March/001240.html -#ifndef TCP_NOPUSH - setsockopt(s, IPPROTO_TCP, TCP_NODELAY, const_cast_sockopt(&one), sizeof(one)); -#endif - -#ifdef TCP_LOW_MIN_RTO - if (TSocket::getUseLowMinRto()) { - setsockopt(s, IPPROTO_TCP, TCP_LOW_MIN_RTO, const_cast_sockopt(&one), sizeof(one)); - } -#endif - - if (listen(s, LISTEN_BACKLOG) == -1) { - ::THRIFT_CLOSESOCKET(s); - throw TTransportException(TTransportException::NOT_OPEN, "TNonblockingServer::serve() listen"); - } - - // Cool, this socket is good to go, set it as the serverSocket_ - serverSocket_ = s; - - if (!port_) { - struct sockaddr_storage addr; - socklen_t size = sizeof(addr); - if (!getsockname(serverSocket_, reinterpret_cast(&addr), &size)) { - if (addr.ss_family == AF_INET6) { - const struct sockaddr_in6* sin = reinterpret_cast(&addr); - listenPort_ = ntohs(sin->sin6_port); - } else { - const struct sockaddr_in* sin = reinterpret_cast(&addr); - listenPort_ = ntohs(sin->sin_port); - } - } else { - GlobalOutput.perror("TNonblocking: failed to get listen port: ", THRIFT_GET_SOCKET_ERROR); - } - } -} - -void TNonblockingServer::setThreadManager(boost::shared_ptr threadManager) { +void TNonblockingServer::setThreadManager(stdcxx::shared_ptr threadManager) { threadManager_ = threadManager; if (threadManager) { threadManager->setExpireCallback( @@ -1191,7 +1055,7 @@ bool TNonblockingServer::serverOverloaded() { bool TNonblockingServer::drainPendingTask() { if (threadManager_) { - boost::shared_ptr task = threadManager_->removeNextPending(); + stdcxx::shared_ptr task = threadManager_->removeNextPending(); if (task) { TConnection* connection = static_cast(task.get())->getTConnection(); assert(connection && connection->getServer() && connection->getState() == APP_WAIT_TASK); @@ -1202,16 +1066,13 @@ bool TNonblockingServer::drainPendingTask() { return false; } -void TNonblockingServer::expireClose(boost::shared_ptr task) { +void TNonblockingServer::expireClose(stdcxx::shared_ptr task) { TConnection* connection = static_cast(task.get())->getTConnection(); assert(connection && connection->getServer() && connection->getState() == APP_WAIT_TASK); connection->forceClose(); } void TNonblockingServer::stop() { - if (!port_) { - listenPort_ = 0; - } // Breaks the event loop in all threads so that they end ASAP. for (uint32_t i = 0; i < ioThreads_.size(); ++i) { ioThreads_[i]->stop(); @@ -1252,8 +1113,7 @@ void TNonblockingServer::registerEvents(event_base* user_event_base) { assert(ioThreads_.size() == numIOThreads_); assert(ioThreads_.size() > 0); - GlobalOutput.printf("TNonblockingServer: Serving on port %d, %d io threads.", - listenPort_, + GlobalOutput.printf("TNonblockingServer: Serving with %d io threads.", ioThreads_.size()); // Launch all the secondary IO threads in separate threads @@ -1324,7 +1184,7 @@ TNonblockingIOThread::~TNonblockingIOThread() { ownEventBase_ = false; } - if (listenSocket_ >= 0) { + if (listenSocket_ != THRIFT_INVALID_SOCKET) { if (0 != ::THRIFT_CLOSESOCKET(listenSocket_)) { GlobalOutput.perror("TNonblockingIOThread listenSocket_ close(): ", THRIFT_GET_SOCKET_ERROR); } @@ -1390,7 +1250,7 @@ void TNonblockingIOThread::registerEvents() { event_base_get_method(eventBase_)); } - if (listenSocket_ >= 0) { + if (listenSocket_ != THRIFT_INVALID_SOCKET) { // Register the server event event_set(&serverEvent_, listenSocket_, @@ -1435,10 +1295,44 @@ bool TNonblockingIOThread::notify(TNonblockingServer::TConnection* conn) { return false; } - fd_set wfds, efds; - long ret = -1; + int ret = -1; long kSize = sizeof(conn); - const char* pos = reinterpret_cast(&conn); + const char * pos = (const char *)const_cast_sockopt(&conn); + +#if defined(HAVE_POLL_H) || defined(HAVE_SYS_POLL_H) + struct pollfd pfd = {fd, POLLOUT, 0}; + + while (kSize > 0) { + pfd.revents = 0; + ret = poll(&pfd, 1, -1); + if (ret < 0) { + return false; + } else if (ret == 0) { + continue; + } + + if (pfd.revents & POLLHUP || pfd.revents & POLLERR) { + ::THRIFT_CLOSESOCKET(fd); + return false; + } + + if (pfd.revents & POLLOUT) { + ret = send(fd, pos, kSize, 0); + if (ret < 0) { + if (errno == EAGAIN) { + continue; + } + + ::THRIFT_CLOSESOCKET(fd); + return false; + } + + kSize -= ret; + pos += ret; + } + } +#else + fd_set wfds, efds; while (kSize > 0) { FD_ZERO(&wfds); @@ -1472,6 +1366,7 @@ bool TNonblockingIOThread::notify(TNonblockingServer::TConnection* conn) { pos += ret; } } +#endif return true; } @@ -1489,6 +1384,7 @@ void TNonblockingIOThread::notifyHandler(evutil_socket_t fd, short which, void* if (nBytes == kSize) { if (connection == NULL) { // this is the command to stop our thread, exit the handler! + ioThread->breakLoop(false); return; } connection->transition(); @@ -1499,6 +1395,7 @@ void TNonblockingIOThread::notifyHandler(evutil_socket_t fd, short which, void* return; } else if (nBytes == 0) { GlobalOutput.printf("notifyHandler: Notify socket closed!"); + ioThread->breakLoop(false); // exit the loop break; } else { // nBytes < 0 @@ -1523,19 +1420,15 @@ void TNonblockingIOThread::breakLoop(bool error) { ::abort(); } - // sets a flag so that the loop exits on the next event - event_base_loopbreak(eventBase_); - - // event_base_loopbreak() only causes the loop to exit the next time - // it wakes up. We need to force it to wake up, in case there are - // no real events it needs to process. - // // If we're running in the same thread, we can't use the notify(0) // mechanism to stop the thread, but happily if we're running in the // same thread, this means the thread can't be blocking in the event // loop either. if (!Thread::is_current(threadId_)) { notify(NULL); + } else { + // cause the loop to stop ASAP - even if it has things to do in it + event_base_loopbreak(eventBase_); } } @@ -1569,31 +1462,33 @@ void TNonblockingIOThread::setCurrentThreadHighPriority(bool value) { } void TNonblockingIOThread::run() { - if (eventBase_ == NULL) + if (eventBase_ == NULL) { registerEvents(); - - GlobalOutput.printf("TNonblockingServer: IO thread #%d entering loop...", number_); - + } if (useHighPriority_) { setCurrentThreadHighPriority(true); } - // Run libevent engine, never returns, invokes calls to eventHandler - event_base_loop(eventBase_, 0); + if (eventBase_ != NULL) + { + GlobalOutput.printf("TNonblockingServer: IO thread #%d entering loop...", number_); + // Run libevent engine, never returns, invokes calls to eventHandler + event_base_loop(eventBase_, 0); - if (useHighPriority_) { - setCurrentThreadHighPriority(false); + if (useHighPriority_) { + setCurrentThreadHighPriority(false); + } + + // cleans up our registered events + cleanupEvents(); } - // cleans up our registered events - cleanupEvents(); - GlobalOutput.printf("TNonblockingServer: IO thread #%d run() done!", number_); } void TNonblockingIOThread::cleanupEvents() { // stop the listen socket, if any - if (listenSocket_ >= 0) { + if (listenSocket_ != THRIFT_INVALID_SOCKET) { if (event_del(&serverEvent_) == -1) { GlobalOutput.perror("TNonblockingIOThread::stop() event_del: ", THRIFT_GET_SOCKET_ERROR); } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TNonblockingServer.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TNonblockingServer.h index 82d40e9..f95a729 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TNonblockingServer.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TNonblockingServer.h @@ -21,10 +21,12 @@ #define _THRIFT_SERVER_TNONBLOCKINGSERVER_H_ 1 #include +#include #include #include #include #include +#include #include #include #include @@ -47,6 +49,7 @@ namespace server { using apache::thrift::transport::TMemoryBuffer; using apache::thrift::transport::TSocket; +using apache::thrift::transport::TNonblockingServerTransport; using apache::thrift::protocol::TProtocol; using apache::thrift::concurrency::Runnable; using apache::thrift::concurrency::ThreadManager; @@ -96,10 +99,6 @@ inline SOCKOPT_CAST_T* cast_sockopt(T* v) { * operates a set of IO threads (by default only one). It assumes that * all incoming requests are framed with a 4 byte length indicator and * writes out responses using the same framing. - * - * It does not use the TServerTransport framework, but rather has socket - * operations hardcoded for use with select. - * */ /// Overload condition actions. @@ -157,26 +156,20 @@ private: /// Server socket file descriptor THRIFT_SOCKET serverSocket_; - /// Port server runs on. Zero when letting OS decide actual port - int port_; - - /// Port server actually runs on - int listenPort_; - /// The optional user-provided event-base (for single-thread servers) event_base* userEventBase_; /// For processing via thread pool, may be NULL - boost::shared_ptr threadManager_; + stdcxx::shared_ptr threadManager_; /// Is thread pool processing? bool threadPoolProcessing_; // Factory to create the IO threads - boost::shared_ptr ioThreadFactory_; + stdcxx::shared_ptr ioThreadFactory_; // Vector of IOThread objects that will handle our IO - std::vector > ioThreads_; + std::vector > ioThreads_; // Index of next IO Thread to be used (for round-robin) uint32_t nextIOThread_; @@ -269,23 +262,24 @@ private: */ std::vector activeConnections_; + /* + */ + stdcxx::shared_ptr serverTransport_; + /** * Called when server socket had something happen. We accept all waiting * client connections on listen socket fd and assign TConnection objects * to handle those requests. * - * @param fd the listen socket. * @param which the event flag that triggered the handler. */ void handleEvent(THRIFT_SOCKET fd, short which); - void init(int port) { + void init() { serverSocket_ = THRIFT_INVALID_SOCKET; numIOThreads_ = DEFAULT_IO_THREADS; nextIOThread_ = 0; useHighPriorityIOThreads_ = false; - port_ = port; - listenPort_ = port; userEventBase_ = NULL; threadPoolProcessing_ = false; numTConnections_ = 0; @@ -307,55 +301,55 @@ private: } public: - TNonblockingServer(const boost::shared_ptr& processorFactory, int port) - : TServer(processorFactory) { - init(port); + TNonblockingServer(const stdcxx::shared_ptr& processorFactory, + const stdcxx::shared_ptr& serverTransport) + : TServer(processorFactory), serverTransport_(serverTransport) { + init(); } - TNonblockingServer(const boost::shared_ptr& processor, int port) - : TServer(processor) { - init(port); + TNonblockingServer(const stdcxx::shared_ptr& processor, + const stdcxx::shared_ptr& serverTransport) + : TServer(processor), serverTransport_(serverTransport) { + init(); } - TNonblockingServer(const boost::shared_ptr& processorFactory, - const boost::shared_ptr& protocolFactory, - int port, - const boost::shared_ptr& threadManager - = boost::shared_ptr()) - : TServer(processorFactory) { - init(port); + TNonblockingServer(const stdcxx::shared_ptr& processorFactory, + const stdcxx::shared_ptr& protocolFactory, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& threadManager + = stdcxx::shared_ptr()) + : TServer(processorFactory), serverTransport_(serverTransport) { + init(); setInputProtocolFactory(protocolFactory); setOutputProtocolFactory(protocolFactory); setThreadManager(threadManager); } - TNonblockingServer(const boost::shared_ptr& processor, - const boost::shared_ptr& protocolFactory, - int port, - const boost::shared_ptr& threadManager - = boost::shared_ptr()) - : TServer(processor) { - - init(port); + TNonblockingServer(const stdcxx::shared_ptr& processor, + const stdcxx::shared_ptr& protocolFactory, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& threadManager + = stdcxx::shared_ptr()) + : TServer(processor), serverTransport_(serverTransport) { + init(); setInputProtocolFactory(protocolFactory); setOutputProtocolFactory(protocolFactory); setThreadManager(threadManager); } - TNonblockingServer(const boost::shared_ptr& processorFactory, - const boost::shared_ptr& inputTransportFactory, - const boost::shared_ptr& outputTransportFactory, - const boost::shared_ptr& inputProtocolFactory, - const boost::shared_ptr& outputProtocolFactory, - int port, - const boost::shared_ptr& threadManager - = boost::shared_ptr()) - : TServer(processorFactory) { - - init(port); + TNonblockingServer(const stdcxx::shared_ptr& processorFactory, + const stdcxx::shared_ptr& inputTransportFactory, + const stdcxx::shared_ptr& outputTransportFactory, + const stdcxx::shared_ptr& inputProtocolFactory, + const stdcxx::shared_ptr& outputProtocolFactory, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& threadManager + = stdcxx::shared_ptr()) + : TServer(processorFactory), serverTransport_(serverTransport) { + init(); setInputTransportFactory(inputTransportFactory); setOutputTransportFactory(outputTransportFactory); @@ -364,17 +358,16 @@ public: setThreadManager(threadManager); } - TNonblockingServer(const boost::shared_ptr& processor, - const boost::shared_ptr& inputTransportFactory, - const boost::shared_ptr& outputTransportFactory, - const boost::shared_ptr& inputProtocolFactory, - const boost::shared_ptr& outputProtocolFactory, - int port, - const boost::shared_ptr& threadManager - = boost::shared_ptr()) - : TServer(processor) { - - init(port); + TNonblockingServer(const stdcxx::shared_ptr& processor, + const stdcxx::shared_ptr& inputTransportFactory, + const stdcxx::shared_ptr& outputTransportFactory, + const stdcxx::shared_ptr& inputProtocolFactory, + const stdcxx::shared_ptr& outputProtocolFactory, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& threadManager + = stdcxx::shared_ptr()) + : TServer(processor), serverTransport_(serverTransport) { + init(); setInputTransportFactory(inputTransportFactory); setOutputTransportFactory(outputTransportFactory); @@ -385,11 +378,11 @@ public: ~TNonblockingServer(); - void setThreadManager(boost::shared_ptr threadManager); + void setThreadManager(stdcxx::shared_ptr threadManager); - int getListenPort() { return listenPort_; } + int getListenPort() { return serverTransport_->getListenPort(); } - boost::shared_ptr getThreadManager() { return threadManager_; } + stdcxx::shared_ptr getThreadManager() { return threadManager_; } /** * Sets the number of IO threads used by this server. Can only be used before @@ -428,7 +421,7 @@ public: bool isThreadPoolProcessing() const { return threadPoolProcessing_; } - void addTask(boost::shared_ptr task) { + void addTask(stdcxx::shared_ptr task) { threadManager_->add(task, 0LL, taskExpireTime_); } @@ -688,14 +681,6 @@ public: /// Creates a socket to listen on and binds it to the local port. void createAndListenOnSocket(); - /** - * Takes a socket created by createAndListenOnSocket() and sets various - * options on it to prepare for use in the server. - * - * @param fd descriptor of socket to be initialized/ - */ - void listenSocket(THRIFT_SOCKET fd); - /** * Register the optional user-provided event-base (for single-thread servers) * @@ -724,7 +709,7 @@ private: * * @param task the runnable associated with the expired task. */ - void expireClose(boost::shared_ptr task); + void expireClose(stdcxx::shared_ptr task); /** * Return an initialized connection object. Creates or recovers from @@ -736,7 +721,7 @@ private: * @param addrLen the length of addr * @return pointer to initialized TConnection object. */ - TConnection* createConnection(THRIFT_SOCKET socket, const sockaddr* addr, socklen_t addrLen); + TConnection* createConnection(stdcxx::shared_ptr socket); /** * Returns a connection to pool or deletion. If the connection pool @@ -780,10 +765,10 @@ public: evutil_socket_t getNotificationRecvFD() const { return notificationPipeFDs_[0]; } // Returns the actual thread object associated with this IO thread. - boost::shared_ptr getThread() const { return thread_; } + stdcxx::shared_ptr getThread() const { return thread_; } // Sets the actual thread object associated with this IO thread. - void setThread(const boost::shared_ptr& t) { thread_ = t; } + void setThread(const stdcxx::shared_ptr& t) { thread_ = t; } // Used by TConnection objects to indicate processing has finished. bool notify(TNonblockingServer::TConnection* conn); @@ -868,7 +853,7 @@ private: evutil_socket_t notificationPipeFDs_[2]; /// Actual IO Thread - boost::shared_ptr thread_; + stdcxx::shared_ptr thread_; }; } } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TServer.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TServer.h index 47e0d40..f4cd7bc 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TServer.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TServer.h @@ -25,7 +25,7 @@ #include #include -#include +#include namespace apache { namespace thrift { @@ -58,8 +58,8 @@ public: /** * Called when a new client has connected and is about to being processing. */ - virtual void* createContext(boost::shared_ptr input, - boost::shared_ptr output) { + virtual void* createContext(stdcxx::shared_ptr input, + stdcxx::shared_ptr output) { (void)input; (void)output; return NULL; @@ -70,8 +70,8 @@ public: * context. */ virtual void deleteContext(void* serverContext, - boost::shared_ptr input, - boost::shared_ptr output) { + stdcxx::shared_ptr input, + stdcxx::shared_ptr output) { (void)serverContext; (void)input; (void)output; @@ -80,7 +80,7 @@ public: /** * Called when a client is about to call the processor. */ - virtual void processContext(void* serverContext, boost::shared_ptr transport) { + virtual void processContext(void* serverContext, stdcxx::shared_ptr transport) { (void)serverContext; (void)transport; } @@ -107,62 +107,62 @@ public: // Allows running the server as a Runnable thread virtual void run() { serve(); } - boost::shared_ptr getProcessorFactory() { return processorFactory_; } + stdcxx::shared_ptr getProcessorFactory() { return processorFactory_; } - boost::shared_ptr getServerTransport() { return serverTransport_; } + stdcxx::shared_ptr getServerTransport() { return serverTransport_; } - boost::shared_ptr getInputTransportFactory() { return inputTransportFactory_; } + stdcxx::shared_ptr getInputTransportFactory() { return inputTransportFactory_; } - boost::shared_ptr getOutputTransportFactory() { + stdcxx::shared_ptr getOutputTransportFactory() { return outputTransportFactory_; } - boost::shared_ptr getInputProtocolFactory() { return inputProtocolFactory_; } + stdcxx::shared_ptr getInputProtocolFactory() { return inputProtocolFactory_; } - boost::shared_ptr getOutputProtocolFactory() { return outputProtocolFactory_; } + stdcxx::shared_ptr getOutputProtocolFactory() { return outputProtocolFactory_; } - boost::shared_ptr getEventHandler() { return eventHandler_; } + stdcxx::shared_ptr getEventHandler() { return eventHandler_; } protected: - TServer(const boost::shared_ptr& processorFactory) + TServer(const stdcxx::shared_ptr& processorFactory) : processorFactory_(processorFactory) { - setInputTransportFactory(boost::shared_ptr(new TTransportFactory())); - setOutputTransportFactory(boost::shared_ptr(new TTransportFactory())); - setInputProtocolFactory(boost::shared_ptr(new TBinaryProtocolFactory())); - setOutputProtocolFactory(boost::shared_ptr(new TBinaryProtocolFactory())); + setInputTransportFactory(stdcxx::shared_ptr(new TTransportFactory())); + setOutputTransportFactory(stdcxx::shared_ptr(new TTransportFactory())); + setInputProtocolFactory(stdcxx::shared_ptr(new TBinaryProtocolFactory())); + setOutputProtocolFactory(stdcxx::shared_ptr(new TBinaryProtocolFactory())); } - TServer(const boost::shared_ptr& processor) + TServer(const stdcxx::shared_ptr& processor) : processorFactory_(new TSingletonProcessorFactory(processor)) { - setInputTransportFactory(boost::shared_ptr(new TTransportFactory())); - setOutputTransportFactory(boost::shared_ptr(new TTransportFactory())); - setInputProtocolFactory(boost::shared_ptr(new TBinaryProtocolFactory())); - setOutputProtocolFactory(boost::shared_ptr(new TBinaryProtocolFactory())); + setInputTransportFactory(stdcxx::shared_ptr(new TTransportFactory())); + setOutputTransportFactory(stdcxx::shared_ptr(new TTransportFactory())); + setInputProtocolFactory(stdcxx::shared_ptr(new TBinaryProtocolFactory())); + setOutputProtocolFactory(stdcxx::shared_ptr(new TBinaryProtocolFactory())); } - TServer(const boost::shared_ptr& processorFactory, - const boost::shared_ptr& serverTransport) + TServer(const stdcxx::shared_ptr& processorFactory, + const stdcxx::shared_ptr& serverTransport) : processorFactory_(processorFactory), serverTransport_(serverTransport) { - setInputTransportFactory(boost::shared_ptr(new TTransportFactory())); - setOutputTransportFactory(boost::shared_ptr(new TTransportFactory())); - setInputProtocolFactory(boost::shared_ptr(new TBinaryProtocolFactory())); - setOutputProtocolFactory(boost::shared_ptr(new TBinaryProtocolFactory())); + setInputTransportFactory(stdcxx::shared_ptr(new TTransportFactory())); + setOutputTransportFactory(stdcxx::shared_ptr(new TTransportFactory())); + setInputProtocolFactory(stdcxx::shared_ptr(new TBinaryProtocolFactory())); + setOutputProtocolFactory(stdcxx::shared_ptr(new TBinaryProtocolFactory())); } - TServer(const boost::shared_ptr& processor, - const boost::shared_ptr& serverTransport) + TServer(const stdcxx::shared_ptr& processor, + const stdcxx::shared_ptr& serverTransport) : processorFactory_(new TSingletonProcessorFactory(processor)), serverTransport_(serverTransport) { - setInputTransportFactory(boost::shared_ptr(new TTransportFactory())); - setOutputTransportFactory(boost::shared_ptr(new TTransportFactory())); - setInputProtocolFactory(boost::shared_ptr(new TBinaryProtocolFactory())); - setOutputProtocolFactory(boost::shared_ptr(new TBinaryProtocolFactory())); + setInputTransportFactory(stdcxx::shared_ptr(new TTransportFactory())); + setOutputTransportFactory(stdcxx::shared_ptr(new TTransportFactory())); + setInputProtocolFactory(stdcxx::shared_ptr(new TBinaryProtocolFactory())); + setOutputProtocolFactory(stdcxx::shared_ptr(new TBinaryProtocolFactory())); } - TServer(const boost::shared_ptr& processorFactory, - const boost::shared_ptr& serverTransport, - const boost::shared_ptr& transportFactory, - const boost::shared_ptr& protocolFactory) + TServer(const stdcxx::shared_ptr& processorFactory, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& transportFactory, + const stdcxx::shared_ptr& protocolFactory) : processorFactory_(processorFactory), serverTransport_(serverTransport), inputTransportFactory_(transportFactory), @@ -170,10 +170,10 @@ protected: inputProtocolFactory_(protocolFactory), outputProtocolFactory_(protocolFactory) {} - TServer(const boost::shared_ptr& processor, - const boost::shared_ptr& serverTransport, - const boost::shared_ptr& transportFactory, - const boost::shared_ptr& protocolFactory) + TServer(const stdcxx::shared_ptr& processor, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& transportFactory, + const stdcxx::shared_ptr& protocolFactory) : processorFactory_(new TSingletonProcessorFactory(processor)), serverTransport_(serverTransport), inputTransportFactory_(transportFactory), @@ -181,12 +181,12 @@ protected: inputProtocolFactory_(protocolFactory), outputProtocolFactory_(protocolFactory) {} - TServer(const boost::shared_ptr& processorFactory, - const boost::shared_ptr& serverTransport, - const boost::shared_ptr& inputTransportFactory, - const boost::shared_ptr& outputTransportFactory, - const boost::shared_ptr& inputProtocolFactory, - const boost::shared_ptr& outputProtocolFactory) + TServer(const stdcxx::shared_ptr& processorFactory, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& inputTransportFactory, + const stdcxx::shared_ptr& outputTransportFactory, + const stdcxx::shared_ptr& inputProtocolFactory, + const stdcxx::shared_ptr& outputProtocolFactory) : processorFactory_(processorFactory), serverTransport_(serverTransport), inputTransportFactory_(inputTransportFactory), @@ -194,12 +194,12 @@ protected: inputProtocolFactory_(inputProtocolFactory), outputProtocolFactory_(outputProtocolFactory) {} - TServer(const boost::shared_ptr& processor, - const boost::shared_ptr& serverTransport, - const boost::shared_ptr& inputTransportFactory, - const boost::shared_ptr& outputTransportFactory, - const boost::shared_ptr& inputProtocolFactory, - const boost::shared_ptr& outputProtocolFactory) + TServer(const stdcxx::shared_ptr& processor, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& inputTransportFactory, + const stdcxx::shared_ptr& outputTransportFactory, + const stdcxx::shared_ptr& inputProtocolFactory, + const stdcxx::shared_ptr& outputProtocolFactory) : processorFactory_(new TSingletonProcessorFactory(processor)), serverTransport_(serverTransport), inputTransportFactory_(inputTransportFactory), @@ -214,9 +214,9 @@ protected: * call). This allows the TProcessorFactory to return a different processor * for each connection if it desires. */ - boost::shared_ptr getProcessor(boost::shared_ptr inputProtocol, - boost::shared_ptr outputProtocol, - boost::shared_ptr transport) { + stdcxx::shared_ptr getProcessor(stdcxx::shared_ptr inputProtocol, + stdcxx::shared_ptr outputProtocol, + stdcxx::shared_ptr transport) { TConnectionInfo connInfo; connInfo.input = inputProtocol; connInfo.output = outputProtocol; @@ -225,35 +225,35 @@ protected: } // Class variables - boost::shared_ptr processorFactory_; - boost::shared_ptr serverTransport_; + stdcxx::shared_ptr processorFactory_; + stdcxx::shared_ptr serverTransport_; - boost::shared_ptr inputTransportFactory_; - boost::shared_ptr outputTransportFactory_; + stdcxx::shared_ptr inputTransportFactory_; + stdcxx::shared_ptr outputTransportFactory_; - boost::shared_ptr inputProtocolFactory_; - boost::shared_ptr outputProtocolFactory_; + stdcxx::shared_ptr inputProtocolFactory_; + stdcxx::shared_ptr outputProtocolFactory_; - boost::shared_ptr eventHandler_; + stdcxx::shared_ptr eventHandler_; public: - void setInputTransportFactory(boost::shared_ptr inputTransportFactory) { + void setInputTransportFactory(stdcxx::shared_ptr inputTransportFactory) { inputTransportFactory_ = inputTransportFactory; } - void setOutputTransportFactory(boost::shared_ptr outputTransportFactory) { + void setOutputTransportFactory(stdcxx::shared_ptr outputTransportFactory) { outputTransportFactory_ = outputTransportFactory; } - void setInputProtocolFactory(boost::shared_ptr inputProtocolFactory) { + void setInputProtocolFactory(stdcxx::shared_ptr inputProtocolFactory) { inputProtocolFactory_ = inputProtocolFactory; } - void setOutputProtocolFactory(boost::shared_ptr outputProtocolFactory) { + void setOutputProtocolFactory(stdcxx::shared_ptr outputProtocolFactory) { outputProtocolFactory_ = outputProtocolFactory; } - void setServerEventHandler(boost::shared_ptr eventHandler) { + void setServerEventHandler(stdcxx::shared_ptr eventHandler) { eventHandler_ = eventHandler; } }; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TServerFramework.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TServerFramework.cpp index b62cf40..ae38336 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TServerFramework.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TServerFramework.cpp @@ -18,7 +18,6 @@ */ #include -#include #include #include #include @@ -28,14 +27,14 @@ namespace thrift { namespace server { using apache::thrift::concurrency::Synchronized; +using apache::thrift::protocol::TProtocol; +using apache::thrift::protocol::TProtocolFactory; +using apache::thrift::stdcxx::bind; +using apache::thrift::stdcxx::shared_ptr; using apache::thrift::transport::TServerTransport; using apache::thrift::transport::TTransport; using apache::thrift::transport::TTransportException; using apache::thrift::transport::TTransportFactory; -using apache::thrift::protocol::TProtocol; -using apache::thrift::protocol::TProtocolFactory; -using boost::bind; -using boost::shared_ptr; using std::string; TServerFramework::TServerFramework(const shared_ptr& processorFactory, @@ -162,7 +161,7 @@ void TServerFramework::serve() { outputProtocol, eventHandler_, client), - bind(&TServerFramework::disposeConnectedClient, this, _1))); + bind(&TServerFramework::disposeConnectedClient, this, stdcxx::placeholders::_1))); } catch (TTransportException& ttx) { releaseOneDescriptor("inputTransport", inputTransport); @@ -221,7 +220,7 @@ void TServerFramework::stop() { serverTransport_->interrupt(); } -void TServerFramework::newlyConnectedClient(const boost::shared_ptr& pClient) { +void TServerFramework::newlyConnectedClient(const shared_ptr& pClient) { { Synchronized sync(mon_); ++clients_; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TServerFramework.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TServerFramework.h index 53d9bfd..706fd49 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TServerFramework.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TServerFramework.h @@ -20,7 +20,7 @@ #ifndef _THRIFT_SERVER_TSERVERFRAMEWORK_H_ #define _THRIFT_SERVER_TSERVERFRAMEWORK_H_ 1 -#include +#include #include #include #include @@ -48,32 +48,32 @@ namespace server { class TServerFramework : public TServer { public: TServerFramework( - const boost::shared_ptr& processorFactory, - const boost::shared_ptr& serverTransport, - const boost::shared_ptr& transportFactory, - const boost::shared_ptr& protocolFactory); + const stdcxx::shared_ptr& processorFactory, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& transportFactory, + const stdcxx::shared_ptr& protocolFactory); TServerFramework( - const boost::shared_ptr& processor, - const boost::shared_ptr& serverTransport, - const boost::shared_ptr& transportFactory, - const boost::shared_ptr& protocolFactory); + const stdcxx::shared_ptr& processor, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& transportFactory, + const stdcxx::shared_ptr& protocolFactory); TServerFramework( - const boost::shared_ptr& processorFactory, - const boost::shared_ptr& serverTransport, - const boost::shared_ptr& inputTransportFactory, - const boost::shared_ptr& outputTransportFactory, - const boost::shared_ptr& inputProtocolFactory, - const boost::shared_ptr& outputProtocolFactory); + const stdcxx::shared_ptr& processorFactory, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& inputTransportFactory, + const stdcxx::shared_ptr& outputTransportFactory, + const stdcxx::shared_ptr& inputProtocolFactory, + const stdcxx::shared_ptr& outputProtocolFactory); TServerFramework( - const boost::shared_ptr& processor, - const boost::shared_ptr& serverTransport, - const boost::shared_ptr& inputTransportFactory, - const boost::shared_ptr& outputTransportFactory, - const boost::shared_ptr& inputProtocolFactory, - const boost::shared_ptr& outputProtocolFactory); + const stdcxx::shared_ptr& processor, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& inputTransportFactory, + const stdcxx::shared_ptr& outputTransportFactory, + const stdcxx::shared_ptr& inputProtocolFactory, + const stdcxx::shared_ptr& outputProtocolFactory); virtual ~TServerFramework(); @@ -130,7 +130,7 @@ protected: * * \param[in] pClient the newly connected client */ - virtual void onClientConnected(const boost::shared_ptr& pClient) = 0; + virtual void onClientConnected(const stdcxx::shared_ptr& pClient) = 0; /** * A client has disconnected. @@ -149,7 +149,7 @@ private: * client rate limiting after onClientConnected returns by blocking the * serve() thread if the limit has been reached. */ - void newlyConnectedClient(const boost::shared_ptr& pClient); + void newlyConnectedClient(const stdcxx::shared_ptr& pClient); /** * Smart pointer client deletion. diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TSimpleServer.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TSimpleServer.cpp index 2f69ff4..a0afbbe 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TSimpleServer.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TSimpleServer.cpp @@ -29,7 +29,7 @@ using apache::thrift::transport::TServerTransport; using apache::thrift::transport::TTransport; using apache::thrift::transport::TTransportException; using apache::thrift::transport::TTransportFactory; -using boost::shared_ptr; +using stdcxx::shared_ptr; using std::string; TSimpleServer::TSimpleServer(const shared_ptr& processorFactory, diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TSimpleServer.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TSimpleServer.h index 391fbec..ac4ed34 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TSimpleServer.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TSimpleServer.h @@ -34,37 +34,37 @@ namespace server { class TSimpleServer : public TServerFramework { public: TSimpleServer( - const boost::shared_ptr& processorFactory, - const boost::shared_ptr& serverTransport, - const boost::shared_ptr& transportFactory, - const boost::shared_ptr& protocolFactory); + const stdcxx::shared_ptr& processorFactory, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& transportFactory, + const stdcxx::shared_ptr& protocolFactory); TSimpleServer( - const boost::shared_ptr& processor, - const boost::shared_ptr& serverTransport, - const boost::shared_ptr& transportFactory, - const boost::shared_ptr& protocolFactory); + const stdcxx::shared_ptr& processor, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& transportFactory, + const stdcxx::shared_ptr& protocolFactory); TSimpleServer( - const boost::shared_ptr& processorFactory, - const boost::shared_ptr& serverTransport, - const boost::shared_ptr& inputTransportFactory, - const boost::shared_ptr& outputTransportFactory, - const boost::shared_ptr& inputProtocolFactory, - const boost::shared_ptr& outputProtocolFactory); + const stdcxx::shared_ptr& processorFactory, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& inputTransportFactory, + const stdcxx::shared_ptr& outputTransportFactory, + const stdcxx::shared_ptr& inputProtocolFactory, + const stdcxx::shared_ptr& outputProtocolFactory); TSimpleServer( - const boost::shared_ptr& processor, - const boost::shared_ptr& serverTransport, - const boost::shared_ptr& inputTransportFactory, - const boost::shared_ptr& outputTransportFactory, - const boost::shared_ptr& inputProtocolFactory, - const boost::shared_ptr& outputProtocolFactory); + const stdcxx::shared_ptr& processor, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& inputTransportFactory, + const stdcxx::shared_ptr& outputTransportFactory, + const stdcxx::shared_ptr& inputProtocolFactory, + const stdcxx::shared_ptr& outputProtocolFactory); virtual ~TSimpleServer(); protected: - virtual void onClientConnected(const boost::shared_ptr& pClient) /* override */; + virtual void onClientConnected(const stdcxx::shared_ptr& pClient) /* override */; virtual void onClientDisconnected(TConnectedClient* pClient) /* override */; private: diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TThreadPoolServer.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TThreadPoolServer.cpp index 63af85c..f07ff84 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TThreadPoolServer.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TThreadPoolServer.cpp @@ -30,7 +30,7 @@ using apache::thrift::transport::TServerTransport; using apache::thrift::transport::TTransport; using apache::thrift::transport::TTransportException; using apache::thrift::transport::TTransportFactory; -using boost::shared_ptr; +using stdcxx::shared_ptr; using std::string; TThreadPoolServer::TThreadPoolServer(const shared_ptr& processorFactory, @@ -115,7 +115,7 @@ void TThreadPoolServer::setTaskExpiration(int64_t value) { taskExpiration_ = value; } -boost::shared_ptr +stdcxx::shared_ptr TThreadPoolServer::getThreadManager() const { return threadManager_; } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TThreadPoolServer.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TThreadPoolServer.h index c750b8c..94088d5 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TThreadPoolServer.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TThreadPoolServer.h @@ -34,39 +34,39 @@ namespace server { class TThreadPoolServer : public TServerFramework { public: TThreadPoolServer( - const boost::shared_ptr& processorFactory, - const boost::shared_ptr& serverTransport, - const boost::shared_ptr& transportFactory, - const boost::shared_ptr& protocolFactory, - const boost::shared_ptr& threadManager + const stdcxx::shared_ptr& processorFactory, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& transportFactory, + const stdcxx::shared_ptr& protocolFactory, + const stdcxx::shared_ptr& threadManager = apache::thrift::concurrency::ThreadManager::newSimpleThreadManager()); TThreadPoolServer( - const boost::shared_ptr& processor, - const boost::shared_ptr& serverTransport, - const boost::shared_ptr& transportFactory, - const boost::shared_ptr& protocolFactory, - const boost::shared_ptr& threadManager + const stdcxx::shared_ptr& processor, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& transportFactory, + const stdcxx::shared_ptr& protocolFactory, + const stdcxx::shared_ptr& threadManager = apache::thrift::concurrency::ThreadManager::newSimpleThreadManager()); TThreadPoolServer( - const boost::shared_ptr& processorFactory, - const boost::shared_ptr& serverTransport, - const boost::shared_ptr& inputTransportFactory, - const boost::shared_ptr& outputTransportFactory, - const boost::shared_ptr& inputProtocolFactory, - const boost::shared_ptr& outputProtocolFactory, - const boost::shared_ptr& threadManager + const stdcxx::shared_ptr& processorFactory, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& inputTransportFactory, + const stdcxx::shared_ptr& outputTransportFactory, + const stdcxx::shared_ptr& inputProtocolFactory, + const stdcxx::shared_ptr& outputProtocolFactory, + const stdcxx::shared_ptr& threadManager = apache::thrift::concurrency::ThreadManager::newSimpleThreadManager()); TThreadPoolServer( - const boost::shared_ptr& processor, - const boost::shared_ptr& serverTransport, - const boost::shared_ptr& inputTransportFactory, - const boost::shared_ptr& outputTransportFactory, - const boost::shared_ptr& inputProtocolFactory, - const boost::shared_ptr& outputProtocolFactory, - const boost::shared_ptr& threadManager + const stdcxx::shared_ptr& processor, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& inputTransportFactory, + const stdcxx::shared_ptr& outputTransportFactory, + const stdcxx::shared_ptr& inputProtocolFactory, + const stdcxx::shared_ptr& outputProtocolFactory, + const stdcxx::shared_ptr& threadManager = apache::thrift::concurrency::ThreadManager::newSimpleThreadManager()); virtual ~TThreadPoolServer(); @@ -83,13 +83,13 @@ public: virtual int64_t getTaskExpiration() const; virtual void setTaskExpiration(int64_t value); - virtual boost::shared_ptr getThreadManager() const; + virtual stdcxx::shared_ptr getThreadManager() const; protected: - virtual void onClientConnected(const boost::shared_ptr& pClient) /* override */; + virtual void onClientConnected(const stdcxx::shared_ptr& pClient) /* override */; virtual void onClientDisconnected(TConnectedClient* pClient) /* override */; - boost::shared_ptr threadManager_; + stdcxx::shared_ptr threadManager_; boost::atomic timeout_; boost::atomic taskExpiration_; }; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TThreadedServer.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TThreadedServer.cpp index c413be1..3fe5aa6 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TThreadedServer.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TThreadedServer.cpp @@ -17,11 +17,8 @@ * under the License. */ -#include -#include -#include -#include #include +#include #include #include @@ -35,11 +32,12 @@ using apache::thrift::concurrency::Thread; using apache::thrift::concurrency::ThreadFactory; using apache::thrift::protocol::TProtocol; using apache::thrift::protocol::TProtocolFactory; +using apache::thrift::stdcxx::make_shared; +using apache::thrift::stdcxx::shared_ptr; using apache::thrift::transport::TServerTransport; using apache::thrift::transport::TTransport; using apache::thrift::transport::TTransportException; using apache::thrift::transport::TTransportFactory; -using boost::shared_ptr; TThreadedServer::TThreadedServer(const shared_ptr& processorFactory, const shared_ptr& serverTransport, @@ -117,8 +115,8 @@ void TThreadedServer::drainDeadClients() { void TThreadedServer::onClientConnected(const shared_ptr& pClient) { Synchronized sync(clientMonitor_); - boost::shared_ptr pRunnable = boost::make_shared(pClient); - boost::shared_ptr pThread = threadFactory_->newThread(pRunnable); + shared_ptr pRunnable = make_shared(pClient); + shared_ptr pThread = threadFactory_->newThread(pRunnable); pRunnable->thread(pThread); activeClientMap_.insert(ClientMap::value_type(pClient.get(), pThread)); pThread->start(); @@ -128,15 +126,17 @@ void TThreadedServer::onClientDisconnected(TConnectedClient* pClient) { Synchronized sync(clientMonitor_); drainDeadClients(); // use the outgoing thread to do some maintenance on our dead client backlog ClientMap::iterator it = activeClientMap_.find(pClient); - ClientMap::iterator end = it; - deadClientMap_.insert(it, ++end); - activeClientMap_.erase(it); + if (it != activeClientMap_.end()) { + ClientMap::iterator end = it; + deadClientMap_.insert(it, ++end); + activeClientMap_.erase(it); + } if (activeClientMap_.empty()) { clientMonitor_.notify(); } } -TThreadedServer::TConnectedClientRunner::TConnectedClientRunner(const boost::shared_ptr& pClient) +TThreadedServer::TConnectedClientRunner::TConnectedClientRunner(const shared_ptr& pClient) : pClient_(pClient) { } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TThreadedServer.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TThreadedServer.h index 56da901..1e0a824 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TThreadedServer.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/server/TThreadedServer.h @@ -38,43 +38,43 @@ namespace server { class TThreadedServer : public TServerFramework { public: TThreadedServer( - const boost::shared_ptr& processorFactory, - const boost::shared_ptr& serverTransport, - const boost::shared_ptr& transportFactory, - const boost::shared_ptr& protocolFactory, - const boost::shared_ptr& threadFactory - = boost::shared_ptr( + const stdcxx::shared_ptr& processorFactory, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& transportFactory, + const stdcxx::shared_ptr& protocolFactory, + const stdcxx::shared_ptr& threadFactory + = stdcxx::shared_ptr( new apache::thrift::concurrency::PlatformThreadFactory(false))); TThreadedServer( - const boost::shared_ptr& processor, - const boost::shared_ptr& serverTransport, - const boost::shared_ptr& transportFactory, - const boost::shared_ptr& protocolFactory, - const boost::shared_ptr& threadFactory - = boost::shared_ptr( + const stdcxx::shared_ptr& processor, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& transportFactory, + const stdcxx::shared_ptr& protocolFactory, + const stdcxx::shared_ptr& threadFactory + = stdcxx::shared_ptr( new apache::thrift::concurrency::PlatformThreadFactory(false))); TThreadedServer( - const boost::shared_ptr& processorFactory, - const boost::shared_ptr& serverTransport, - const boost::shared_ptr& inputTransportFactory, - const boost::shared_ptr& outputTransportFactory, - const boost::shared_ptr& inputProtocolFactory, - const boost::shared_ptr& outputProtocolFactory, - const boost::shared_ptr& threadFactory - = boost::shared_ptr( + const stdcxx::shared_ptr& processorFactory, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& inputTransportFactory, + const stdcxx::shared_ptr& outputTransportFactory, + const stdcxx::shared_ptr& inputProtocolFactory, + const stdcxx::shared_ptr& outputProtocolFactory, + const stdcxx::shared_ptr& threadFactory + = stdcxx::shared_ptr( new apache::thrift::concurrency::PlatformThreadFactory(false))); TThreadedServer( - const boost::shared_ptr& processor, - const boost::shared_ptr& serverTransport, - const boost::shared_ptr& inputTransportFactory, - const boost::shared_ptr& outputTransportFactory, - const boost::shared_ptr& inputProtocolFactory, - const boost::shared_ptr& outputProtocolFactory, - const boost::shared_ptr& threadFactory - = boost::shared_ptr( + const stdcxx::shared_ptr& processor, + const stdcxx::shared_ptr& serverTransport, + const stdcxx::shared_ptr& inputTransportFactory, + const stdcxx::shared_ptr& outputTransportFactory, + const stdcxx::shared_ptr& inputProtocolFactory, + const stdcxx::shared_ptr& outputProtocolFactory, + const stdcxx::shared_ptr& threadFactory + = stdcxx::shared_ptr( new apache::thrift::concurrency::PlatformThreadFactory(false))); virtual ~TThreadedServer(); @@ -95,14 +95,14 @@ protected: /** * Implementation of TServerFramework::onClientConnected */ - virtual void onClientConnected(const boost::shared_ptr& pClient) /* override */; + virtual void onClientConnected(const stdcxx::shared_ptr& pClient) /* override */; /** * Implementation of TServerFramework::onClientDisconnected */ virtual void onClientDisconnected(TConnectedClient *pClient) /* override */; - boost::shared_ptr threadFactory_; + stdcxx::shared_ptr threadFactory_; /** * A helper wrapper used to wrap the client in something we can use to maintain @@ -114,16 +114,16 @@ protected: class TConnectedClientRunner : public apache::thrift::concurrency::Runnable { public: - TConnectedClientRunner(const boost::shared_ptr& pClient); + TConnectedClientRunner(const stdcxx::shared_ptr& pClient); virtual ~TConnectedClientRunner(); void run() /* override */; private: - boost::shared_ptr pClient_; + stdcxx::shared_ptr pClient_; }; apache::thrift::concurrency::Monitor clientMonitor_; - typedef std::map > ClientMap; + typedef std::map > ClientMap; /** * A map of active clients diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/stdcxx.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/stdcxx.h new file mode 100644 index 0000000..c8cabf5 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/stdcxx.h @@ -0,0 +1,129 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +#ifndef _THRIFT_STDCXX_H_ +#define _THRIFT_STDCXX_H_ 1 + +#include +#include + +/////////////////////////////////////////////////////////////////// +// +// functional (function, bind) +// +/////////////////////////////////////////////////////////////////// + +#if defined(BOOST_NO_CXX11_HDR_FUNCTIONAL) || (defined(_MSC_VER) && _MSC_VER < 1800) || defined(FORCE_BOOST_FUNCTIONAL) +#if (BOOST_VERSION <= 106500) +#include +#else +#include +#endif +#define _THRIFT_FUNCTIONAL_TR1_ 1 +#endif + +#if _THRIFT_FUNCTIONAL_TR1_ + + namespace apache { namespace thrift { namespace stdcxx { + + using ::std::tr1::bind; + using ::std::tr1::function; + + namespace placeholders { + using ::std::tr1::placeholders::_1; + using ::std::tr1::placeholders::_2; + using ::std::tr1::placeholders::_3; + using ::std::tr1::placeholders::_4; + using ::std::tr1::placeholders::_5; + using ::std::tr1::placeholders::_6; + using ::std::tr1::placeholders::_7; + using ::std::tr1::placeholders::_8; + using ::std::tr1::placeholders::_9; + } // apache::thrift::stdcxx::placeholders + }}} // apache::thrift::stdcxx + +#else + + #include + + namespace apache { namespace thrift { namespace stdcxx { + using ::std::bind; + using ::std::function; + + namespace placeholders { + using ::std::placeholders::_1; + using ::std::placeholders::_2; + using ::std::placeholders::_3; + using ::std::placeholders::_4; + using ::std::placeholders::_5; + using ::std::placeholders::_6; + using ::std::placeholders::_7; + using ::std::placeholders::_8; + using ::std::placeholders::_9; + } // apache::thrift::stdcxx::placeholders + }}} // apache::thrift::stdcxx + +#endif + +/////////////////////////////////////////////////////////////////// +// +// Smart Pointers +// +/////////////////////////////////////////////////////////////////// + +// We can use std for memory functions only if the compiler supports template aliasing +// The macro BOOST_NO_CXX11_SMART_PTR is defined as 1 under Visual Studio 2010 and 2012 +// which do not support the feature, so we must continue to use C++98 and boost on them. +// We cannot use __cplusplus to detect this either, since Microsoft advertises an older one. + +#if defined(BOOST_NO_CXX11_SMART_PTR) || (defined(_MSC_VER) && _MSC_VER < 1800) || defined(FORCE_BOOST_SMART_PTR) +#include +#else +#include +#endif + +namespace apache { namespace thrift { namespace stdcxx { + +#if defined(BOOST_NO_CXX11_SMART_PTR) || (defined(_MSC_VER) && _MSC_VER < 1800) || defined(FORCE_BOOST_SMART_PTR) + + using ::boost::const_pointer_cast; + using ::boost::dynamic_pointer_cast; + using ::boost::enable_shared_from_this; + using ::boost::make_shared; + using ::boost::scoped_ptr; + using ::boost::shared_ptr; + using ::boost::static_pointer_cast; + using ::boost::weak_ptr; + +#else + + using ::std::const_pointer_cast; + using ::std::dynamic_pointer_cast; + using ::std::enable_shared_from_this; + using ::std::make_shared; + template using scoped_ptr = std::unique_ptr; // compiler must support template aliasing + using ::std::shared_ptr; + using ::std::static_pointer_cast; + using ::std::weak_ptr; + +#endif + +}}} // apache::thrift::stdcxx + +#endif // #ifndef _THRIFT_STDCXX_H_ diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/PlatformSocket.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/PlatformSocket.h index e7addd6..9591058 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/PlatformSocket.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/PlatformSocket.h @@ -23,6 +23,7 @@ # define _THRIFT_TRANSPORT_PLATFORM_SOCKET_H_ #ifdef _WIN32 +# include # define THRIFT_GET_SOCKET_ERROR ::WSAGetLastError() # define THRIFT_ERRNO (*_errno()) # define THRIFT_EINPROGRESS WSAEINPROGRESS @@ -50,6 +51,8 @@ # define THRIFT_LSEEK _lseek # define THRIFT_WRITE _write # define THRIFT_READ _read +# define THRIFT_IOCTL_SOCKET ioctlsocket +# define THRIFT_IOCTL_SOCKET_NUM_BYTES_TYPE u_long # define THRIFT_FSTAT _fstat # define THRIFT_STAT _stat # ifdef _WIN32_WCE @@ -78,6 +81,9 @@ # define THRIFT_POLLOUT POLLOUT # endif //WINVER # define THRIFT_SHUT_RDWR SD_BOTH +# if !defined(AI_ADDRCONFIG) +# define AI_ADDRCONFIG 0x00000400 +# endif #else //not _WIN32 # include # define THRIFT_GET_SOCKET_ERROR errno @@ -107,6 +113,8 @@ # define THRIFT_LSEEK lseek # define THRIFT_WRITE write # define THRIFT_READ read +# define THRIFT_IOCTL_SOCKET ioctl +# define THRIFT_IOCTL_SOCKET_NUM_BYTES_TYPE int # define THRIFT_STAT stat # define THRIFT_FSTAT fstat # define THRIFT_GAI_STRERROR gai_strerror diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TBufferTransports.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TBufferTransports.cpp index 700bdd5..9ac2f84 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TBufferTransports.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TBufferTransports.cpp @@ -361,10 +361,14 @@ void TMemoryBuffer::ensureCanWrite(uint32_t len) { } // Grow the buffer as necessary. - uint32_t new_size = bufferSize_; + uint64_t new_size = bufferSize_; while (len > avail) { new_size = new_size > 0 ? new_size * 2 : 1; - avail = available_write() + (new_size - bufferSize_); + if (new_size > maxBufferSize_) { + throw TTransportException(TTransportException::BAD_ARGS, + "Internal buffer size overflow"); + } + avail = available_write() + (static_cast(new_size) - bufferSize_); } // Allocate into a new pointer so we don't bork ours if it fails. @@ -378,7 +382,7 @@ void TMemoryBuffer::ensureCanWrite(uint32_t len) { wBase_ = new_buffer + (wBase_ - buffer_); wBound_ = new_buffer + new_size; buffer_ = new_buffer; - bufferSize_ = new_size; + bufferSize_ = static_cast(new_size); } void TMemoryBuffer::writeSlow(const uint8_t* buf, uint32_t len) { diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TBufferTransports.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TBufferTransports.h index e690d0c..79aace6 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TBufferTransports.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TBufferTransports.h @@ -186,7 +186,7 @@ public: static const int DEFAULT_BUFFER_SIZE = 512; /// Use default buffer sizes. - TBufferedTransport(boost::shared_ptr transport) + TBufferedTransport(stdcxx::shared_ptr transport) : transport_(transport), rBufSize_(DEFAULT_BUFFER_SIZE), wBufSize_(DEFAULT_BUFFER_SIZE), @@ -196,7 +196,7 @@ public: } /// Use specified buffer sizes. - TBufferedTransport(boost::shared_ptr transport, uint32_t sz) + TBufferedTransport(stdcxx::shared_ptr transport, uint32_t sz) : transport_(transport), rBufSize_(sz), wBufSize_(sz), @@ -206,7 +206,7 @@ public: } /// Use specified read and write buffer sizes. - TBufferedTransport(boost::shared_ptr transport, uint32_t rsz, uint32_t wsz) + TBufferedTransport(stdcxx::shared_ptr transport, uint32_t rsz, uint32_t wsz) : transport_(transport), rBufSize_(rsz), wBufSize_(wsz), @@ -255,7 +255,7 @@ public: */ virtual const uint8_t* borrowSlow(uint8_t* buf, uint32_t* len); - boost::shared_ptr getUnderlyingTransport() { return transport_; } + stdcxx::shared_ptr getUnderlyingTransport() { return transport_; } /* * TVirtualTransport provides a default implementation of readAll(). @@ -270,7 +270,7 @@ protected: // Write size never changes. } - boost::shared_ptr transport_; + stdcxx::shared_ptr transport_; uint32_t rBufSize_; uint32_t wBufSize_; @@ -291,8 +291,8 @@ public: /** * Wraps the transport into a buffered one. */ - virtual boost::shared_ptr getTransport(boost::shared_ptr trans) { - return boost::shared_ptr(new TBufferedTransport(trans)); + virtual stdcxx::shared_ptr getTransport(stdcxx::shared_ptr trans) { + return stdcxx::shared_ptr(new TBufferedTransport(trans)); } }; @@ -319,7 +319,7 @@ public: initPointers(); } - TFramedTransport(boost::shared_ptr transport) + TFramedTransport(stdcxx::shared_ptr transport) : transport_(transport), rBufSize_(0), wBufSize_(DEFAULT_BUFFER_SIZE), @@ -330,7 +330,7 @@ public: initPointers(); } - TFramedTransport(boost::shared_ptr transport, + TFramedTransport(stdcxx::shared_ptr transport, uint32_t sz, uint32_t bufReclaimThresh = (std::numeric_limits::max)()) : transport_(transport), @@ -366,7 +366,7 @@ public: const uint8_t* borrowSlow(uint8_t* buf, uint32_t* len); - boost::shared_ptr getUnderlyingTransport() { return transport_; } + stdcxx::shared_ptr getUnderlyingTransport() { return transport_; } /* * TVirtualTransport provides a default implementation of readAll(). @@ -407,7 +407,7 @@ protected: this->write((uint8_t*)&pad, sizeof(pad)); } - boost::shared_ptr transport_; + stdcxx::shared_ptr transport_; uint32_t rBufSize_; uint32_t wBufSize_; @@ -430,8 +430,8 @@ public: /** * Wraps the transport into a framed one. */ - virtual boost::shared_ptr getTransport(boost::shared_ptr trans) { - return boost::shared_ptr(new TFramedTransport(trans)); + virtual stdcxx::shared_ptr getTransport(stdcxx::shared_ptr trans) { + return stdcxx::shared_ptr(new TFramedTransport(trans)); } }; @@ -448,11 +448,14 @@ class TMemoryBuffer : public TVirtualTransport { private: // Common initialization done by all constructors. void initCommon(uint8_t* buf, uint32_t size, bool owner, uint32_t wPos) { + + maxBufferSize_ = (std::numeric_limits::max)(); + if (buf == NULL && size != 0) { assert(owner); buf = (uint8_t*)std::malloc(size); if (buf == NULL) { - throw std::bad_alloc(); + throw std::bad_alloc(); } } @@ -673,6 +676,29 @@ public: */ uint32_t readAll(uint8_t* buf, uint32_t len) { return TBufferBase::readAll(buf, len); } + //! \brief Get the current buffer size + //! \returns the current buffer size + uint32_t getBufferSize() const { + return bufferSize_; + } + + //! \brief Get the current maximum buffer size + //! \returns the current maximum buffer size + uint32_t getMaxBufferSize() const { + return maxBufferSize_; + } + + //! \brief Change the maximum buffer size + //! \param[in] maxSize the new maximum buffer size allowed to grow to + //! \throws TTransportException(BAD_ARGS) if maxSize is less than the current buffer size + void setMaxBufferSize(uint32_t maxSize) { + if (maxSize < bufferSize_) { + throw TTransportException(TTransportException::BAD_ARGS, + "Maximum buffer size would be less than current buffer size"); + } + maxBufferSize_ = maxSize; + } + protected: void swap(TMemoryBuffer& that) { using std::swap; @@ -705,6 +731,9 @@ protected: // Allocated buffer size uint32_t bufferSize_; + // Maximum allowed size + uint32_t maxBufferSize_; + // Is this object the owner of the buffer? bool owner_; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TFDTransport.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TFDTransport.cpp index 4bce3a8..93dd100 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TFDTransport.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TFDTransport.cpp @@ -31,7 +31,7 @@ #include #endif -using namespace std; +using std::string; namespace apache { namespace thrift { diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TFileTransport.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TFileTransport.cpp index 85e88b9..b08a5f1 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TFileTransport.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TFileTransport.cpp @@ -24,6 +24,15 @@ #include #include +#include +#if (BOOST_VERSION >= 105700) +#include +using boost::movelib::unique_ptr; +#else +#include +using boost::interprocess::unique_ptr; +#endif + #ifdef HAVE_SYS_TIME_H #include #else @@ -52,9 +61,11 @@ namespace apache { namespace thrift { namespace transport { -using boost::scoped_ptr; -using boost::shared_ptr; -using namespace std; +using stdcxx::shared_ptr; +using std::cerr; +using std::cout; +using std::endl; +using std::string; using namespace apache::thrift::protocol; using namespace apache::thrift::concurrency; @@ -192,6 +203,14 @@ void TFileTransport::write(const uint8_t* buf, uint32_t len) { enqueueEvent(buf, len); } +// this is needed until boost 1.57 as the older unique_ptr implementation +// has no default deleter in interprocess +template +struct uniqueDeleter +{ + void operator()(_T *ptr) const { delete ptr; } +}; + void TFileTransport::enqueueEvent(const uint8_t* buf, uint32_t eventLen) { // can't enqueue more events if file is going to close if (closing_) { @@ -209,7 +228,7 @@ void TFileTransport::enqueueEvent(const uint8_t* buf, uint32_t eventLen) { return; } - std::auto_ptr toEnqueue(new eventInfo()); + unique_ptr > toEnqueue(new eventInfo()); toEnqueue->eventBuff_ = new uint8_t[(sizeof(uint8_t) * eventLen) + 4]; // first 4 bytes is the event length @@ -363,7 +382,7 @@ void TFileTransport::writerThread() { while (hasIOError) { T_ERROR( - "TFileTransport: writer thread going to sleep for %d microseconds due to IO errors", + "TFileTransport: writer thread going to sleep for %u microseconds due to IO errors", writerThreadIOErrorSleepTime_); THRIFT_SLEEP_USEC(writerThreadIOErrorSleepTime_); if (closing_) { @@ -685,8 +704,8 @@ eventInfo* TFileTransport::readEvent() { readState_.event_->eventBuffPos_ = 0; } // take either the entire event or the remaining bytes in the buffer - int reclaimBuffer = min((uint32_t)(readState_.bufferLen_ - readState_.bufferPtr_), - readState_.event_->eventSize_ - readState_.event_->eventBuffPos_); + int reclaimBuffer = (std::min)((uint32_t)(readState_.bufferLen_ - readState_.bufferPtr_), + readState_.event_->eventSize_ - readState_.event_->eventBuffPos_); // copy data from read buffer into event buffer memcpy(readState_.event_->eventBuff_ + readState_.event_->eventBuffPos_, @@ -832,7 +851,7 @@ void TFileTransport::seekToChunk(int32_t chunk) { uint32_t oldReadTimeout = getReadTimeout(); setReadTimeout(NO_TAIL_READ_TIMEOUT); // keep on reading unti the last event at point of seekChunk call - boost::scoped_ptr event; + shared_ptr event; while ((offset_ + readState_.bufferPtr_) < minEndOffset) { event.reset(readEvent()); if (event.get() == NULL) { diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TFileTransport.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TFileTransport.h index c926c7c..d6da436 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TFileTransport.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TFileTransport.h @@ -28,8 +28,7 @@ #include #include -#include -#include +#include #include #include @@ -340,7 +339,7 @@ private: // writer thread apache::thrift::concurrency::PlatformThreadFactory threadFactory_; - boost::shared_ptr writerThread_; + stdcxx::shared_ptr writerThread_; // buffers to hold data before it is flushed. Each element of the buffer stores a msg that // needs to be written to the file. The buffers are swapped by the writer thread. @@ -349,7 +348,7 @@ private: // conditions used to block when the buffer is full or empty Monitor notFull_, notEmpty_; - bool closing_; + boost::atomic closing_; // To keep track of whether the buffer has been flushed Monitor flushed_; @@ -391,14 +390,14 @@ public: * @param protocolFactory protocol factory * @param inputTransport file transport */ - TFileProcessor(boost::shared_ptr processor, - boost::shared_ptr protocolFactory, - boost::shared_ptr inputTransport); + TFileProcessor(stdcxx::shared_ptr processor, + stdcxx::shared_ptr protocolFactory, + stdcxx::shared_ptr inputTransport); - TFileProcessor(boost::shared_ptr processor, - boost::shared_ptr inputProtocolFactory, - boost::shared_ptr outputProtocolFactory, - boost::shared_ptr inputTransport); + TFileProcessor(stdcxx::shared_ptr processor, + stdcxx::shared_ptr inputProtocolFactory, + stdcxx::shared_ptr outputProtocolFactory, + stdcxx::shared_ptr inputTransport); /** * Constructor @@ -408,10 +407,10 @@ public: * @param inputTransport input file transport * @param output output transport */ - TFileProcessor(boost::shared_ptr processor, - boost::shared_ptr protocolFactory, - boost::shared_ptr inputTransport, - boost::shared_ptr outputTransport); + TFileProcessor(stdcxx::shared_ptr processor, + stdcxx::shared_ptr protocolFactory, + stdcxx::shared_ptr inputTransport, + stdcxx::shared_ptr outputTransport); /** * processes events from the file @@ -428,11 +427,11 @@ public: void processChunk(); private: - boost::shared_ptr processor_; - boost::shared_ptr inputProtocolFactory_; - boost::shared_ptr outputProtocolFactory_; - boost::shared_ptr inputTransport_; - boost::shared_ptr outputTransport_; + stdcxx::shared_ptr processor_; + stdcxx::shared_ptr inputProtocolFactory_; + stdcxx::shared_ptr outputProtocolFactory_; + stdcxx::shared_ptr inputTransport_; + stdcxx::shared_ptr outputTransport_; }; } } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THeaderTransport.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THeaderTransport.cpp index b1fe923..ea16591 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THeaderTransport.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THeaderTransport.cpp @@ -22,20 +22,23 @@ #include #include #include +#include +#include #include -#include #include -#include #include +#include using std::map; -using boost::shared_ptr; using std::string; using std::vector; namespace apache { namespace thrift { + +using stdcxx::shared_ptr; + namespace transport { using namespace apache::thrift::protocol; @@ -172,7 +175,7 @@ bool THeaderTransport::readFrame() { * Reads a string from ptr, taking care not to reach headerBoundary * Advances ptr on success * - * @param str output string + * @param str output string * @throws CORRUPTED_DATA if size of string exceeds boundary */ void THeaderTransport::readString(uint8_t*& ptr, @@ -198,7 +201,10 @@ void THeaderTransport::readHeaderFormat(uint16_t headerSize, uint32_t sz) { uint8_t* ptr = reinterpret_cast(rBuf_.get() + 10); // Catch integer overflow, check for reasonable header size - assert(headerSize < 16384); + if (headerSize >= 16384) { + throw TTransportException(TTransportException::CORRUPTED_DATA, + "Header size is unreasonable"); + } headerSize *= 4; const uint8_t* const headerBoundary = ptr + headerSize; if (headerSize > sz) { @@ -252,7 +258,7 @@ void THeaderTransport::readHeaderFormat(uint16_t headerSize, uint32_t sz) { } // Untransform the data section. rBuf will contain result. - untransform(data, sz - (data - rBuf_.get())); // ignore header in size calc + untransform(data, safe_numeric_cast(static_cast(sz) - (data - rBuf_.get()))); } void THeaderTransport::untransform(uint8_t* ptr, uint32_t sz) { @@ -375,7 +381,7 @@ void THeaderTransport::resetProtocol() { } uint32_t THeaderTransport::getWriteBytes() { - return wBase_ - wBuf_.get(); + return safe_numeric_cast(wBase_ - wBuf_.get()); } /** @@ -384,7 +390,7 @@ uint32_t THeaderTransport::getWriteBytes() { * Automatically advances ptr to after the written portion */ void THeaderTransport::writeString(uint8_t*& ptr, const string& str) { - uint32_t strLen = str.length(); + int32_t strLen = safe_numeric_cast(str.length()); ptr += writeVarint32(strLen, ptr); memcpy(ptr, str.c_str(), strLen); // no need to write \0 ptr += strLen; @@ -394,7 +400,7 @@ void THeaderTransport::setHeader(const string& key, const string& value) { writeHeaders_[key] = value; } -size_t THeaderTransport::getMaxWriteHeadersSize() const { +uint32_t THeaderTransport::getMaxWriteHeadersSize() const { size_t maxWriteHeadersSize = 0; THeaderTransport::StringToStringMap::const_iterator it; for (it = writeHeaders_.begin(); it != writeHeaders_.end(); ++it) { @@ -402,7 +408,7 @@ size_t THeaderTransport::getMaxWriteHeadersSize() const { // 2 varints32 + the strings themselves maxWriteHeadersSize += 5 + 5 + (it->first).length() + (it->second).length(); } - return maxWriteHeadersSize; + return safe_numeric_cast(maxWriteHeadersSize); } void THeaderTransport::clearHeaders() { @@ -431,7 +437,7 @@ void THeaderTransport::flush() { if (clientType == THRIFT_HEADER_CLIENT_TYPE) { // header size will need to be updated at the end because of varints. // Make it big enough here for max varint size, plus 4 for padding. - int headerSize = (2 + getNumTransforms()) * THRIFT_MAX_VARINT32_BYTES + 4; + uint32_t headerSize = (2 + getNumTransforms()) * THRIFT_MAX_VARINT32_BYTES + 4; // add approximate size of info headers headerSize += getMaxWriteHeadersSize(); @@ -479,11 +485,11 @@ void THeaderTransport::flush() { // write info headers // for now only write kv-headers - uint16_t headerCount = writeHeaders_.size(); + int32_t headerCount = safe_numeric_cast(writeHeaders_.size()); if (headerCount > 0) { pkt += writeVarint32(infoIdType::KEYVALUE, pkt); // Write key-value headers count - pkt += writeVarint32(headerCount, pkt); + pkt += writeVarint32(static_cast(headerCount), pkt); // Write info headers map::const_iterator it; for (it = writeHeaders_.begin(); it != writeHeaders_.end(); ++it) { @@ -494,7 +500,7 @@ void THeaderTransport::flush() { } // Fixups after varint size calculations - headerSize = (pkt - headerStart); + headerSize = safe_numeric_cast(pkt - headerStart); uint8_t padding = 4 - (headerSize % 4); headerSize += padding; @@ -504,8 +510,13 @@ void THeaderTransport::flush() { } // Pkt size + ptrdiff_t szHbp = (headerStart - pktStart - 4); + if (static_cast(szHbp) > static_cast((std::numeric_limits().max)()) - (headerSize + haveBytes)) { + throw TTransportException(TTransportException::CORRUPTED_DATA, + "Header section size is unreasonable"); + } szHbo = headerSize + haveBytes // thrift header + payload - + (headerStart - pktStart - 4); // common header section + + static_cast(szHbp); // common header section headerSizeN = htons(headerSize / 4); memcpy(headerSizePtr, &headerSizeN, sizeof(headerSizeN)); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THeaderTransport.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THeaderTransport.h index bf82674..1a2c8e0 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THeaderTransport.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THeaderTransport.h @@ -21,13 +21,20 @@ #define THRIFT_TRANSPORT_THEADERTRANSPORT_H_ 1 #include +#include #include #include #include #include +#ifdef HAVE_STDINT_H +#include +#elif HAVE_INTTYPES_H +#include +#endif + #include -#include +#include #include #include @@ -68,7 +75,7 @@ public: static const int THRIFT_MAX_VARINT32_BYTES = 5; /// Use default buffer sizes. - explicit THeaderTransport(const boost::shared_ptr& transport) + explicit THeaderTransport(const stdcxx::shared_ptr& transport) : TVirtualTransport(transport), outTransport_(transport), protoId(T_COMPACT_PROTOCOL), @@ -81,8 +88,8 @@ public: initBuffers(); } - THeaderTransport(const boost::shared_ptr inTransport, - const boost::shared_ptr outTransport) + THeaderTransport(const stdcxx::shared_ptr inTransport, + const stdcxx::shared_ptr outTransport) : TVirtualTransport(inTransport), outTransport_(outTransport), protoId(T_COMPACT_PROTOCOL), @@ -135,8 +142,7 @@ public: void transform(uint8_t* ptr, uint32_t sz); uint16_t getNumTransforms() const { - int trans = writeTrans_.size(); - return trans; + return safe_numeric_cast(writeTrans_.size()); } void setTransform(uint16_t transId) { writeTrans_.push_back(transId); } @@ -180,7 +186,7 @@ protected: setWriteBuffer(wBuf_.get(), wBufSize_); } - boost::shared_ptr outTransport_; + stdcxx::shared_ptr outTransport_; // 0 and 16th bits must be 0 to differentiate from framed & unframed static const uint32_t HEADER_MAGIC = 0x0FFF0000; @@ -204,7 +210,7 @@ protected: /** * Returns the maximum number of bytes that write k/v headers can take */ - size_t getMaxWriteHeadersSize() const; + uint32_t getMaxWriteHeadersSize() const; struct infoIdType { enum idType { @@ -259,8 +265,8 @@ public: /** * Wraps the transport into a header one. */ - virtual boost::shared_ptr getTransport(boost::shared_ptr trans) { - return boost::shared_ptr(new THeaderTransport(trans)); + virtual stdcxx::shared_ptr getTransport(stdcxx::shared_ptr trans) { + return stdcxx::shared_ptr(new THeaderTransport(trans)); } }; } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpClient.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpClient.cpp index c610636..afd02a8 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpClient.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpClient.cpp @@ -22,23 +22,24 @@ #include #include +#include #include #include +using std::string; + namespace apache { namespace thrift { namespace transport { -using namespace std; - -THttpClient::THttpClient(boost::shared_ptr transport, +THttpClient::THttpClient(stdcxx::shared_ptr transport, std::string host, std::string path) : THttpTransport(transport), host_(host), path_(path) { } THttpClient::THttpClient(string host, int port, string path) - : THttpTransport(boost::shared_ptr(new TSocket(host, port))), + : THttpTransport(stdcxx::shared_ptr(new TSocket(host, port))), host_(host), path_(path) { } @@ -102,7 +103,7 @@ void THttpClient::flush() { std::ostringstream h; h << "POST " << path_ << " HTTP/1.1" << CRLF << "Host: " << host_ << CRLF << "Content-Type: application/x-thrift" << CRLF << "Content-Length: " << len << CRLF - << "Accept: application/x-thrift" << CRLF << "User-Agent: Thrift/" << VERSION + << "Accept: application/x-thrift" << CRLF << "User-Agent: Thrift/" << PACKAGE_VERSION << " (C++/THttpClient)" << CRLF << CRLF; string header = h.str(); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpClient.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpClient.h index 64e7332..96fd5b8 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpClient.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpClient.h @@ -28,7 +28,7 @@ namespace transport { class THttpClient : public THttpTransport { public: - THttpClient(boost::shared_ptr transport, std::string host, std::string path = ""); + THttpClient(stdcxx::shared_ptr transport, std::string host, std::string path = ""); THttpClient(std::string host, int port, std::string path = ""); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpServer.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpServer.cpp index c89ab94..2f48cf6 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpServer.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpServer.cpp @@ -21,28 +21,31 @@ #include #include +#include #include #include #if defined(_MSC_VER) || defined(__MINGW32__) #include #endif +using std::string; + namespace apache { namespace thrift { namespace transport { -using namespace std; - -THttpServer::THttpServer(boost::shared_ptr transport) : THttpTransport(transport) { +THttpServer::THttpServer(stdcxx::shared_ptr transport) : THttpTransport(transport) { } THttpServer::~THttpServer() { } #if defined(_MSC_VER) || defined(__MINGW32__) + #define THRIFT_GMTIME(TM, TIME) gmtime_s(&TM, &TIME) #define THRIFT_strncasecmp(str1, str2, len) _strnicmp(str1, str2, len) #define THRIFT_strcasestr(haystack, needle) StrStrIA(haystack, needle) #else + #define THRIFT_GMTIME(TM, TIME) gmtime_r(&TIME, &TM) #define THRIFT_strncasecmp(str1, str2, len) strncasecmp(str1, str2, len) #define THRIFT_strcasestr(haystack, needle) strcasestr(haystack, needle) #endif @@ -124,7 +127,7 @@ void THttpServer::flush() { // Construct the HTTP header std::ostringstream h; h << "HTTP/1.1 200 OK" << CRLF << "Date: " << getTimeRFC1123() << CRLF << "Server: Thrift/" - << VERSION << CRLF << "Access-Control-Allow-Origin: *" << CRLF + << PACKAGE_VERSION << CRLF << "Access-Control-Allow-Origin: *" << CRLF << "Content-Type: application/x-thrift" << CRLF << "Content-Length: " << len << CRLF << "Connection: Keep-Alive" << CRLF << CRLF; string header = h.str(); @@ -145,18 +148,20 @@ std::string THttpServer::getTimeRFC1123() { static const char* Months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; char buff[128]; + time_t t = time(NULL); - tm* broken_t = gmtime(&t); + struct tm tmb; + THRIFT_GMTIME(tmb, t); sprintf(buff, "%s, %d %s %d %d:%d:%d GMT", - Days[broken_t->tm_wday], - broken_t->tm_mday, - Months[broken_t->tm_mon], - broken_t->tm_year + 1900, - broken_t->tm_hour, - broken_t->tm_min, - broken_t->tm_sec); + Days[tmb.tm_wday], + tmb.tm_mday, + Months[tmb.tm_mon], + tmb.tm_year + 1900, + tmb.tm_hour, + tmb.tm_min, + tmb.tm_sec); return std::string(buff); } } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpServer.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpServer.h index a7ab944..086dd6f 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpServer.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpServer.h @@ -28,7 +28,7 @@ namespace transport { class THttpServer : public THttpTransport { public: - THttpServer(boost::shared_ptr transport); + THttpServer(stdcxx::shared_ptr transport); virtual ~THttpServer(); @@ -53,8 +53,8 @@ public: /** * Wraps the transport into a buffered one. */ - virtual boost::shared_ptr getTransport(boost::shared_ptr trans) { - return boost::shared_ptr(new THttpServer(trans)); + virtual stdcxx::shared_ptr getTransport(stdcxx::shared_ptr trans) { + return stdcxx::shared_ptr(new THttpServer(trans)); } }; } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpTransport.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpTransport.cpp index f93df23..4ccb4d3 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpTransport.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpTransport.cpp @@ -21,17 +21,17 @@ #include +using std::string; + namespace apache { namespace thrift { namespace transport { -using namespace std; - // Yeah, yeah, hacky to put these here, I know. const char* THttpTransport::CRLF = "\r\n"; const int THttpTransport::CRLF_LEN = 2; -THttpTransport::THttpTransport(boost::shared_ptr transport) +THttpTransport::THttpTransport(stdcxx::shared_ptr transport) : transport_(transport), origin_(""), readHeaders_(true), @@ -84,8 +84,10 @@ uint32_t THttpTransport::readEnd() { uint32_t THttpTransport::readMoreData() { uint32_t size; - // Get more data! - refill(); + if (httpPos_ == httpBufLen_) { + // Get more data! + refill(); + } if (readHeaders_) { readHeaders(); @@ -200,10 +202,11 @@ void THttpTransport::refill() { uint32_t avail = httpBufSize_ - httpBufLen_; if (avail <= (httpBufSize_ / 4)) { httpBufSize_ *= 2; - httpBuf_ = (char*)std::realloc(httpBuf_, httpBufSize_ + 1); - if (httpBuf_ == NULL) { + char* tmpBuf = (char*)std::realloc(httpBuf_, httpBufSize_ + 1); + if (tmpBuf == NULL) { throw std::bad_alloc(); } + httpBuf_ = tmpBuf; } // Read more data diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpTransport.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpTransport.h index a9f564c..3fa80f8 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpTransport.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/THttpTransport.h @@ -36,7 +36,7 @@ namespace transport { */ class THttpTransport : public TVirtualTransport { public: - THttpTransport(boost::shared_ptr transport); + THttpTransport(stdcxx::shared_ptr transport); virtual ~THttpTransport(); @@ -59,7 +59,7 @@ public: virtual const std::string getOrigin(); protected: - boost::shared_ptr transport_; + stdcxx::shared_ptr transport_; std::string origin_; TMemoryBuffer writeBuffer_; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TNonblockingSSLServerSocket.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TNonblockingSSLServerSocket.cpp new file mode 100644 index 0000000..da83bea --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TNonblockingSSLServerSocket.cpp @@ -0,0 +1,58 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +#include +#include + +namespace apache { +namespace thrift { +namespace transport { + +/** + * Nonblocking SSL server socket implementation. + */ +TNonblockingSSLServerSocket::TNonblockingSSLServerSocket(int port, stdcxx::shared_ptr factory) + : TNonblockingServerSocket(port), factory_(factory) { + factory_->server(true); +} + +TNonblockingSSLServerSocket::TNonblockingSSLServerSocket(const std::string& address, + int port, + stdcxx::shared_ptr factory) + : TNonblockingServerSocket(address, port), factory_(factory) { + factory_->server(true); +} + +TNonblockingSSLServerSocket::TNonblockingSSLServerSocket(int port, + int sendTimeout, + int recvTimeout, + stdcxx::shared_ptr factory) + : TNonblockingServerSocket(port, sendTimeout, recvTimeout), factory_(factory) { + factory_->server(true); +} + +stdcxx::shared_ptr TNonblockingSSLServerSocket::createSocket(THRIFT_SOCKET client) { + stdcxx::shared_ptr tSSLSocket; + tSSLSocket = factory_->createSocket(client); + tSSLSocket->setLibeventSafe(); + return tSSLSocket; +} +} +} +} diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TNonblockingSSLServerSocket.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TNonblockingSSLServerSocket.h new file mode 100644 index 0000000..7aaff53 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TNonblockingSSLServerSocket.h @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +#ifndef _THRIFT_TRANSPORT_TNONBLOCKINGSSLSERVERSOCKET_H_ +#define _THRIFT_TRANSPORT_TNONBLOCKINGSSLSERVERSOCKET_H_ 1 + +#include +#include + +namespace apache { +namespace thrift { +namespace transport { + +class TSSLSocketFactory; + +/** + * Nonblocking Server socket that accepts SSL connections. + */ +class TNonblockingSSLServerSocket : public TNonblockingServerSocket { +public: + /** + * Constructor. Binds to all interfaces. + * + * @param port Listening port + * @param factory SSL socket factory implementation + */ + TNonblockingSSLServerSocket(int port, stdcxx::shared_ptr factory); + + /** + * Constructor. Binds to the specified address. + * + * @param address Address to bind to + * @param port Listening port + * @param factory SSL socket factory implementation + */ + TNonblockingSSLServerSocket(const std::string& address, + int port, + stdcxx::shared_ptr factory); + + /** + * Constructor. Binds to all interfaces. + * + * @param port Listening port + * @param sendTimeout Socket send timeout + * @param recvTimeout Socket receive timeout + * @param factory SSL socket factory implementation + */ + TNonblockingSSLServerSocket(int port, + int sendTimeout, + int recvTimeout, + stdcxx::shared_ptr factory); + +protected: + stdcxx::shared_ptr createSocket(THRIFT_SOCKET socket); + stdcxx::shared_ptr factory_; +}; +} +} +} + +#endif diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TNonblockingServerSocket.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TNonblockingServerSocket.cpp new file mode 100644 index 0000000..cca52a4 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TNonblockingServerSocket.cpp @@ -0,0 +1,548 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +#include + +#include +#include +#include +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_SYS_UN_H +#include +#endif +#ifdef HAVE_SYS_POLL_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#include +#ifdef HAVE_UNISTD_H +#include +#endif + +#include +#include +#include + +#ifndef AF_LOCAL +#define AF_LOCAL AF_UNIX +#endif + +#ifndef SOCKOPT_CAST_T +#ifndef _WIN32 +#define SOCKOPT_CAST_T void +#else +#define SOCKOPT_CAST_T char +#endif // _WIN32 +#endif + +template +inline const SOCKOPT_CAST_T* const_cast_sockopt(const T* v) { + return reinterpret_cast(v); +} + +template +inline SOCKOPT_CAST_T* cast_sockopt(T* v) { + return reinterpret_cast(v); +} + +namespace apache { +namespace thrift { +namespace transport { + +using std::string; +using stdcxx::shared_ptr; + +TNonblockingServerSocket::TNonblockingServerSocket(int port) + : port_(port), + listenPort_(port), + serverSocket_(THRIFT_INVALID_SOCKET), + acceptBacklog_(DEFAULT_BACKLOG), + sendTimeout_(0), + recvTimeout_(0), + retryLimit_(0), + retryDelay_(0), + tcpSendBuffer_(0), + tcpRecvBuffer_(0), + keepAlive_(false), + listening_(false) { +} + +TNonblockingServerSocket::TNonblockingServerSocket(int port, int sendTimeout, int recvTimeout) + : port_(port), + listenPort_(port), + serverSocket_(THRIFT_INVALID_SOCKET), + acceptBacklog_(DEFAULT_BACKLOG), + sendTimeout_(sendTimeout), + recvTimeout_(recvTimeout), + retryLimit_(0), + retryDelay_(0), + tcpSendBuffer_(0), + tcpRecvBuffer_(0), + keepAlive_(false), + listening_(false) { +} + +TNonblockingServerSocket::TNonblockingServerSocket(const string& address, int port) + : port_(port), + listenPort_(port), + address_(address), + serverSocket_(THRIFT_INVALID_SOCKET), + acceptBacklog_(DEFAULT_BACKLOG), + sendTimeout_(0), + recvTimeout_(0), + retryLimit_(0), + retryDelay_(0), + tcpSendBuffer_(0), + tcpRecvBuffer_(0), + keepAlive_(false), + listening_(false) { +} + +TNonblockingServerSocket::TNonblockingServerSocket(const string& path) + : port_(0), + listenPort_(0), + path_(path), + serverSocket_(THRIFT_INVALID_SOCKET), + acceptBacklog_(DEFAULT_BACKLOG), + sendTimeout_(0), + recvTimeout_(0), + retryLimit_(0), + retryDelay_(0), + tcpSendBuffer_(0), + tcpRecvBuffer_(0), + keepAlive_(false), + listening_(false) { +} + +TNonblockingServerSocket::~TNonblockingServerSocket() { + close(); +} + +void TNonblockingServerSocket::setSendTimeout(int sendTimeout) { + sendTimeout_ = sendTimeout; +} + +void TNonblockingServerSocket::setRecvTimeout(int recvTimeout) { + recvTimeout_ = recvTimeout; +} + +void TNonblockingServerSocket::setAcceptBacklog(int accBacklog) { + acceptBacklog_ = accBacklog; +} + +void TNonblockingServerSocket::setRetryLimit(int retryLimit) { + retryLimit_ = retryLimit; +} + +void TNonblockingServerSocket::setRetryDelay(int retryDelay) { + retryDelay_ = retryDelay; +} + +void TNonblockingServerSocket::setTcpSendBuffer(int tcpSendBuffer) { + tcpSendBuffer_ = tcpSendBuffer; +} + +void TNonblockingServerSocket::setTcpRecvBuffer(int tcpRecvBuffer) { + tcpRecvBuffer_ = tcpRecvBuffer; +} + +void TNonblockingServerSocket::listen() { + listening_ = true; +#ifdef _WIN32 + TWinsockSingleton::create(); +#endif // _WIN32 + + // Validate port number + if (port_ < 0 || port_ > 0xFFFF) { + throw TTransportException(TTransportException::BAD_ARGS, "Specified port is invalid"); + } + + const struct addrinfo *res; + int error; + char port[sizeof("65535")]; + THRIFT_SNPRINTF(port, sizeof(port), "%d", port_); + + struct addrinfo hints; + std::memset(&hints, 0, sizeof(hints)); + hints.ai_family = PF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG; + + // If address is not specified use wildcard address (NULL) + TGetAddrInfoWrapper info(address_.empty() ? NULL : &address_[0], port, &hints); + + error = info.init(); + if (error) { + GlobalOutput.printf("getaddrinfo %d: %s", error, THRIFT_GAI_STRERROR(error)); + close(); + throw TTransportException(TTransportException::NOT_OPEN, + "Could not resolve host for server socket."); + } + + // Pick the ipv6 address first since ipv4 addresses can be mapped + // into ipv6 space. + for (res = info.res(); res; res = res->ai_next) { + if (res->ai_family == AF_INET6 || res->ai_next == NULL) + break; + } + + if (!path_.empty()) { + serverSocket_ = socket(PF_UNIX, SOCK_STREAM, IPPROTO_IP); + } else if (res != NULL) { + serverSocket_ = socket(res->ai_family, res->ai_socktype, res->ai_protocol); + } + + if (serverSocket_ == THRIFT_INVALID_SOCKET) { + int errno_copy = THRIFT_GET_SOCKET_ERROR; + GlobalOutput.perror("TNonblockingServerSocket::listen() socket() ", errno_copy); + close(); + throw TTransportException(TTransportException::NOT_OPEN, + "Could not create server socket.", + errno_copy); + } + + // Set THRIFT_NO_SOCKET_CACHING to prevent 2MSL delay on accept + int one = 1; + if (-1 == setsockopt(serverSocket_, + SOL_SOCKET, + THRIFT_NO_SOCKET_CACHING, + cast_sockopt(&one), + sizeof(one))) { +// ignore errors coming out of this setsockopt on Windows. This is because +// SO_EXCLUSIVEADDRUSE requires admin privileges on WinXP, but we don't +// want to force servers to be an admin. +#ifndef _WIN32 + int errno_copy = THRIFT_GET_SOCKET_ERROR; + GlobalOutput.perror("TNonblockingServerSocket::listen() setsockopt() THRIFT_NO_SOCKET_CACHING ", + errno_copy); + close(); + throw TTransportException(TTransportException::NOT_OPEN, + "Could not set THRIFT_NO_SOCKET_CACHING", + errno_copy); +#endif + } + + // Set TCP buffer sizes + if (tcpSendBuffer_ > 0) { + if (-1 == setsockopt(serverSocket_, + SOL_SOCKET, + SO_SNDBUF, + cast_sockopt(&tcpSendBuffer_), + sizeof(tcpSendBuffer_))) { + int errno_copy = THRIFT_GET_SOCKET_ERROR; + GlobalOutput.perror("TNonblockingServerSocket::listen() setsockopt() SO_SNDBUF ", errno_copy); + close(); + throw TTransportException(TTransportException::NOT_OPEN, + "Could not set SO_SNDBUF", + errno_copy); + } + } + + if (tcpRecvBuffer_ > 0) { + if (-1 == setsockopt(serverSocket_, + SOL_SOCKET, + SO_RCVBUF, + cast_sockopt(&tcpRecvBuffer_), + sizeof(tcpRecvBuffer_))) { + int errno_copy = THRIFT_GET_SOCKET_ERROR; + GlobalOutput.perror("TNonblockingServerSocket::listen() setsockopt() SO_RCVBUF ", errno_copy); + close(); + throw TTransportException(TTransportException::NOT_OPEN, + "Could not set SO_RCVBUF", + errno_copy); + } + } + +#ifdef IPV6_V6ONLY + if (res->ai_family == AF_INET6 && path_.empty()) { + int zero = 0; + if (-1 == setsockopt(serverSocket_, + IPPROTO_IPV6, + IPV6_V6ONLY, + cast_sockopt(&zero), + sizeof(zero))) { + GlobalOutput.perror("TNonblockingServerSocket::listen() IPV6_V6ONLY ", THRIFT_GET_SOCKET_ERROR); + } + } +#endif // #ifdef IPV6_V6ONLY + + // Turn linger off, don't want to block on calls to close + struct linger ling = {0, 0}; + if (-1 == setsockopt(serverSocket_, SOL_SOCKET, SO_LINGER, cast_sockopt(&ling), sizeof(ling))) { + int errno_copy = THRIFT_GET_SOCKET_ERROR; + GlobalOutput.perror("TNonblockingServerSocket::listen() setsockopt() SO_LINGER ", errno_copy); + close(); + throw TTransportException(TTransportException::NOT_OPEN, "Could not set SO_LINGER", errno_copy); + } + + // Keepalive to ensure full result flushing + if (-1 == setsockopt(serverSocket_, SOL_SOCKET, SO_KEEPALIVE, const_cast_sockopt(&one), sizeof(one))) { + int errno_copy = THRIFT_GET_SOCKET_ERROR; + GlobalOutput.perror("TNonblockingServerSocket::listen() setsockopt() SO_KEEPALIVE ", errno_copy); + close(); + throw TTransportException(TTransportException::NOT_OPEN, + "Could not set TCP_NODELAY", + errno_copy); + } + + // Set TCP nodelay if available, MAC OS X Hack + // See http://lists.danga.com/pipermail/memcached/2005-March/001240.html +#ifndef TCP_NOPUSH + // Unix Sockets do not need that + if (path_.empty()) { + // TCP Nodelay, speed over bandwidth + if (-1 + == setsockopt(serverSocket_, IPPROTO_TCP, TCP_NODELAY, cast_sockopt(&one), sizeof(one))) { + int errno_copy = THRIFT_GET_SOCKET_ERROR; + GlobalOutput.perror("TNonblockingServerSocket::listen() setsockopt() TCP_NODELAY ", errno_copy); + close(); + throw TTransportException(TTransportException::NOT_OPEN, + "Could not set TCP_NODELAY", + errno_copy); + } + } +#endif + + // Set NONBLOCK on the accept socket + int flags = THRIFT_FCNTL(serverSocket_, THRIFT_F_GETFL, 0); + if (flags == -1) { + int errno_copy = THRIFT_GET_SOCKET_ERROR; + GlobalOutput.perror("TNonblockingServerSocket::listen() THRIFT_FCNTL() THRIFT_F_GETFL ", errno_copy); + close(); + throw TTransportException(TTransportException::NOT_OPEN, + "THRIFT_FCNTL() THRIFT_F_GETFL failed", + errno_copy); + } + + if (-1 == THRIFT_FCNTL(serverSocket_, THRIFT_F_SETFL, flags | THRIFT_O_NONBLOCK)) { + int errno_copy = THRIFT_GET_SOCKET_ERROR; + GlobalOutput.perror("TNonblockingServerSocket::listen() THRIFT_FCNTL() THRIFT_O_NONBLOCK ", errno_copy); + close(); + throw TTransportException(TTransportException::NOT_OPEN, + "THRIFT_FCNTL() THRIFT_F_SETFL THRIFT_O_NONBLOCK failed", + errno_copy); + } + +#ifdef TCP_LOW_MIN_RTO + if (TSocket::getUseLowMinRto()) { + if (-1 == setsockopt(s, IPPROTO_TCP, TCP_LOW_MIN_RTO, const_cast_sockopt(&one), sizeof(one))) { + int errno_copy = THRIFT_GET_SOCKET_ERROR; + GlobalOutput.perror("TNonblockingServerSocket::listen() setsockopt() TCP_LOW_MIN_RTO ", errno_copy); + close(); + throw TTransportException(TTransportException::NOT_OPEN, + "Could not set TCP_NODELAY", + errno_copy); + } + } +#endif + + // prepare the port information + // we may want to try to bind more than once, since THRIFT_NO_SOCKET_CACHING doesn't + // always seem to work. The client can configure the retry variables. + int retries = 0; + int errno_copy = 0; + + if (!path_.empty()) { + +#ifndef _WIN32 + + // Unix Domain Socket + size_t len = path_.size() + 1; + if (len > sizeof(((sockaddr_un*)NULL)->sun_path)) { + errno_copy = THRIFT_GET_SOCKET_ERROR; + GlobalOutput.perror("TSocket::listen() Unix Domain socket path too long", errno_copy); + throw TTransportException(TTransportException::NOT_OPEN, + "Unix Domain socket path too long", + errno_copy); + } + + struct sockaddr_un address; + address.sun_family = AF_UNIX; + memcpy(address.sun_path, path_.c_str(), len); + + socklen_t structlen = static_cast(sizeof(address)); + + if (!address.sun_path[0]) { // abstract namespace socket +#ifdef __linux__ + // sun_path is not null-terminated in this case and structlen determines its length + structlen -= sizeof(address.sun_path) - len; +#else + GlobalOutput.perror("TSocket::open() Abstract Namespace Domain sockets only supported on linux: ", -99); + throw TTransportException(TTransportException::NOT_OPEN, + " Abstract Namespace Domain socket path not supported"); +#endif + } + + do { + if (0 == ::bind(serverSocket_, (struct sockaddr*)&address, structlen)) { + break; + } + errno_copy = THRIFT_GET_SOCKET_ERROR; + // use short circuit evaluation here to only sleep if we need to + } while ((retries++ < retryLimit_) && (THRIFT_SLEEP_SEC(retryDelay_) == 0)); +#else + GlobalOutput.perror("TSocket::open() Unix Domain socket path not supported on windows", -99); + throw TTransportException(TTransportException::NOT_OPEN, + " Unix Domain socket path not supported"); +#endif + } else { + do { + if (0 == ::bind(serverSocket_, res->ai_addr, static_cast(res->ai_addrlen))) { + break; + } + errno_copy = THRIFT_GET_SOCKET_ERROR; + // use short circuit evaluation here to only sleep if we need to + } while ((retries++ < retryLimit_) && (THRIFT_SLEEP_SEC(retryDelay_) == 0)); + + // retrieve bind info + if (port_ == 0 && retries <= retryLimit_) { + struct sockaddr_storage sa; + socklen_t len = sizeof(sa); + std::memset(&sa, 0, len); + if (::getsockname(serverSocket_, reinterpret_cast(&sa), &len) < 0) { + errno_copy = THRIFT_GET_SOCKET_ERROR; + GlobalOutput.perror("TNonblockingServerSocket::getPort() getsockname() ", errno_copy); + } else { + if (sa.ss_family == AF_INET6) { + const struct sockaddr_in6* sin = reinterpret_cast(&sa); + listenPort_ = ntohs(sin->sin6_port); + } else { + const struct sockaddr_in* sin = reinterpret_cast(&sa); + listenPort_ = ntohs(sin->sin_port); + } + } + } + } + + // throw an error if we failed to bind properly + if (retries > retryLimit_) { + char errbuf[1024]; + if (!path_.empty()) { + THRIFT_SNPRINTF(errbuf, sizeof(errbuf), "TNonblockingServerSocket::listen() PATH %s", path_.c_str()); + } else { + THRIFT_SNPRINTF(errbuf, sizeof(errbuf), "TNonblockingServerSocket::listen() BIND %d", port_); + } + GlobalOutput(errbuf); + close(); + throw TTransportException(TTransportException::NOT_OPEN, + "Could not bind", + errno_copy); + } + + if (listenCallback_) + listenCallback_(serverSocket_); + + // Call listen + if (-1 == ::listen(serverSocket_, acceptBacklog_)) { + errno_copy = THRIFT_GET_SOCKET_ERROR; + GlobalOutput.perror("TNonblockingServerSocket::listen() listen() ", errno_copy); + close(); + throw TTransportException(TTransportException::NOT_OPEN, "Could not listen", errno_copy); + } + + // The socket is now listening! +} + +int TNonblockingServerSocket::getPort() { + return port_; +} + +int TNonblockingServerSocket::getListenPort() { + return listenPort_; +} + +shared_ptr TNonblockingServerSocket::acceptImpl() { + if (serverSocket_ == THRIFT_INVALID_SOCKET) { + throw TTransportException(TTransportException::NOT_OPEN, "TNonblockingServerSocket not listening"); + } + + struct sockaddr_storage clientAddress; + int size = sizeof(clientAddress); + THRIFT_SOCKET clientSocket + = ::accept(serverSocket_, (struct sockaddr*)&clientAddress, (socklen_t*)&size); + + if (clientSocket == THRIFT_INVALID_SOCKET) { + int errno_copy = THRIFT_GET_SOCKET_ERROR; + GlobalOutput.perror("TNonblockingServerSocket::acceptImpl() ::accept() ", errno_copy); + throw TTransportException(TTransportException::UNKNOWN, "accept()", errno_copy); + } + + // Explicitly set this socket to NONBLOCK mode + int flags = THRIFT_FCNTL(clientSocket, THRIFT_F_GETFL, 0); + if (flags == -1) { + int errno_copy = THRIFT_GET_SOCKET_ERROR; + ::THRIFT_CLOSESOCKET(clientSocket); + GlobalOutput.perror("TNonblockingServerSocket::acceptImpl() THRIFT_FCNTL() THRIFT_F_GETFL ", errno_copy); + throw TTransportException(TTransportException::UNKNOWN, + "THRIFT_FCNTL(THRIFT_F_GETFL)", + errno_copy); + } + + if (-1 == THRIFT_FCNTL(clientSocket, THRIFT_F_SETFL, flags | THRIFT_O_NONBLOCK)) { + int errno_copy = THRIFT_GET_SOCKET_ERROR; + ::THRIFT_CLOSESOCKET(clientSocket); + GlobalOutput + .perror("TNonblockingServerSocket::acceptImpl() THRIFT_FCNTL() THRIFT_F_SETFL ~THRIFT_O_NONBLOCK ", + errno_copy); + throw TTransportException(TTransportException::UNKNOWN, + "THRIFT_FCNTL(THRIFT_F_SETFL)", + errno_copy); + } + + shared_ptr client = createSocket(clientSocket); + if (sendTimeout_ > 0) { + client->setSendTimeout(sendTimeout_); + } + if (recvTimeout_ > 0) { + client->setRecvTimeout(recvTimeout_); + } + if (keepAlive_) { + client->setKeepAlive(keepAlive_); + } + client->setCachedAddress((sockaddr*)&clientAddress, size); + + if (acceptCallback_) + acceptCallback_(clientSocket); + + return client; +} + +shared_ptr TNonblockingServerSocket::createSocket(THRIFT_SOCKET clientSocket) { + return shared_ptr(new TSocket(clientSocket)); +} + +void TNonblockingServerSocket::close() { + if (serverSocket_ != THRIFT_INVALID_SOCKET) { + shutdown(serverSocket_, THRIFT_SHUT_RDWR); + ::THRIFT_CLOSESOCKET(serverSocket_); + } + serverSocket_ = THRIFT_INVALID_SOCKET; + listening_ = false; +} +} +} +} // apache::thrift::transport diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TNonblockingServerSocket.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TNonblockingServerSocket.h new file mode 100644 index 0000000..1d33239 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TNonblockingServerSocket.h @@ -0,0 +1,137 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +#ifndef _THRIFT_TRANSPORT_TNONBLOCKINGSERVERSOCKET_H_ +#define _THRIFT_TRANSPORT_TNONBLOCKINGSERVERSOCKET_H_ 1 + +#include +#include +#include + +namespace apache { +namespace thrift { +namespace transport { + +class TSocket; + +/** + * Nonblocking Server socket implementation of TNonblockingServerTransport. Wrapper around a unix + * socket listen and accept calls. + * + */ +class TNonblockingServerSocket : public TNonblockingServerTransport { +public: + typedef apache::thrift::stdcxx::function socket_func_t; + + const static int DEFAULT_BACKLOG = 1024; + + /** + * Constructor. + * + * @param port Port number to bind to + */ + TNonblockingServerSocket(int port); + + /** + * Constructor. + * + * @param port Port number to bind to + * @param sendTimeout Socket send timeout + * @param recvTimeout Socket receive timeout + */ + TNonblockingServerSocket(int port, int sendTimeout, int recvTimeout); + + /** + * Constructor. + * + * @param address Address to bind to + * @param port Port number to bind to + */ + TNonblockingServerSocket(const std::string& address, int port); + + /** + * Constructor used for unix sockets. + * + * @param path Pathname for unix socket. + */ + TNonblockingServerSocket(const std::string& path); + + virtual ~TNonblockingServerSocket(); + + void setSendTimeout(int sendTimeout); + void setRecvTimeout(int recvTimeout); + + void setAcceptBacklog(int accBacklog); + + void setRetryLimit(int retryLimit); + void setRetryDelay(int retryDelay); + + void setKeepAlive(bool keepAlive) { keepAlive_ = keepAlive; } + + void setTcpSendBuffer(int tcpSendBuffer); + void setTcpRecvBuffer(int tcpRecvBuffer); + + // listenCallback gets called just before listen, and after all Thrift + // setsockopt calls have been made. If you have custom setsockopt + // things that need to happen on the listening socket, this is the place to do it. + void setListenCallback(const socket_func_t& listenCallback) { listenCallback_ = listenCallback; } + + // acceptCallback gets called after each accept call, on the newly created socket. + // It is called after all Thrift setsockopt calls have been made. If you have + // custom setsockopt things that need to happen on the accepted + // socket, this is the place to do it. + void setAcceptCallback(const socket_func_t& acceptCallback) { acceptCallback_ = acceptCallback; } + + THRIFT_SOCKET getSocketFD() { return serverSocket_; } + + int getPort(); + + int getListenPort(); + + void listen(); + void close(); + +protected: + apache::thrift::stdcxx::shared_ptr acceptImpl(); + virtual apache::thrift::stdcxx::shared_ptr createSocket(THRIFT_SOCKET client); + +private: + int port_; + int listenPort_; + std::string address_; + std::string path_; + THRIFT_SOCKET serverSocket_; + int acceptBacklog_; + int sendTimeout_; + int recvTimeout_; + int retryLimit_; + int retryDelay_; + int tcpSendBuffer_; + int tcpRecvBuffer_; + bool keepAlive_; + bool listening_; + + socket_func_t listenCallback_; + socket_func_t acceptCallback_; +}; +} +} +} // apache::thrift::transport + +#endif // #ifndef _THRIFT_TRANSPORT_TNONBLOCKINGSERVERSOCKET_H_ diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TNonblockingServerTransport.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TNonblockingServerTransport.h new file mode 100644 index 0000000..c32a051 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TNonblockingServerTransport.h @@ -0,0 +1,101 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +#ifndef _THRIFT_TRANSPORT_TNONBLOCKINGSERVERTRANSPORT_H_ +#define _THRIFT_TRANSPORT_TNONBLOCKINGSERVERTRANSPORT_H_ 1 + +#include +#include +#include + +namespace apache { +namespace thrift { +namespace transport { + +/** + * Server transport framework. A server needs to have some facility for + * creating base transports to read/write from. The server is expected + * to keep track of TTransport children that it creates for purposes of + * controlling their lifetime. + */ +class TNonblockingServerTransport { +public: + virtual ~TNonblockingServerTransport() {} + + /** + * Starts the server transport listening for new connections. Prior to this + * call most transports will not return anything when accept is called. + * + * @throws TTransportException if we were unable to listen + */ + virtual void listen() {} + + /** + * Gets a new dynamically allocated transport object and passes it to the + * caller. Note that it is the explicit duty of the caller to free the + * allocated object. The returned TTransport object must always be in the + * opened state. NULL should never be returned, instead an Exception should + * always be thrown. + * + * @return A new TTransport object + * @throws TTransportException if there is an error + */ + stdcxx::shared_ptr accept() { + stdcxx::shared_ptr result = acceptImpl(); + if (!result) { + throw TTransportException("accept() may not return NULL"); + } + return result; + } + + /** + * Utility method + * + * @return server socket file descriptor + * @throw TTransportException If an error occurs + */ + + virtual THRIFT_SOCKET getSocketFD() = 0; + + virtual int getPort() = 0; + + virtual int getListenPort() = 0; + + /** + * Closes this transport such that future calls to accept will do nothing. + */ + virtual void close() = 0; + +protected: + TNonblockingServerTransport() {} + + /** + * Subclasses should implement this function for accept. + * + * @return A newly allocated TTransport object + * @throw TTransportException If an error occurs + */ + virtual stdcxx::shared_ptr acceptImpl() = 0; + +}; +} +} +} // apache::thrift::transport + +#endif // #ifndef _THRIFT_TRANSPORT_TNONBLOCKINGSERVERTRANSPORT_H_ diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TPipe.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TPipe.cpp index 75ce5d2..8a84457 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TPipe.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TPipe.cpp @@ -28,8 +28,6 @@ namespace apache { namespace thrift { namespace transport { -using namespace std; - /** * TPipe implementation. */ @@ -160,7 +158,8 @@ uint32_t TWaitableNamedPipeImpl::read(uint8_t* buf, uint32_t len) { end_unread_idx_ = endAsyncRead(); } - uint32_t bytes_to_copy = (std::min)(len, end_unread_idx_ - begin_unread_idx_); + uint32_t __idxsize = end_unread_idx_ - begin_unread_idx_; + uint32_t bytes_to_copy = (len < __idxsize) ? len : __idxsize; memcpy(buf, &buffer_[begin_unread_idx_], bytes_to_copy); begin_unread_idx_ += bytes_to_copy; if (begin_unread_idx_ != end_unread_idx_) { @@ -341,12 +340,12 @@ void pipe_write(HANDLE pipe, const uint8_t* buf, uint32_t len) { // Accessors //--------------------------------------------------------- -string TPipe::getPipename() { +std::string TPipe::getPipename() { return pipename_; } void TPipe::setPipename(const std::string& pipename) { - if (pipename.find("\\\\") == -1) + if (pipename.find("\\\\") == std::string::npos) pipename_ = "\\\\.\\pipe\\" + pipename; else pipename_ = pipename; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TPipe.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TPipe.h index 5dd8f9a..dfc5f2c 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TPipe.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TPipe.h @@ -95,7 +95,7 @@ public: HANDLE getNativeWaitHandle(); private: - boost::shared_ptr impl_; + stdcxx::shared_ptr impl_; std::string pipename_; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TPipeServer.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TPipeServer.cpp index cf6b410..5923a62 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TPipeServer.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TPipeServer.cpp @@ -22,7 +22,7 @@ #include #include -#include +#include #include #ifdef _WIN32 @@ -37,15 +37,14 @@ namespace transport { #ifdef _WIN32 -using namespace std; -using boost::shared_ptr; +using stdcxx::shared_ptr; class TPipeServerImpl : boost::noncopyable { public: TPipeServerImpl() {} virtual ~TPipeServerImpl() {} virtual void interrupt() = 0; - virtual boost::shared_ptr acceptImpl() = 0; + virtual stdcxx::shared_ptr acceptImpl() = 0; virtual HANDLE getPipeHandle() = 0; virtual HANDLE getWrtPipeHandle() = 0; @@ -76,7 +75,7 @@ public: virtual void interrupt() {} // not currently implemented - virtual boost::shared_ptr acceptImpl(); + virtual stdcxx::shared_ptr acceptImpl(); virtual HANDLE getPipeHandle() { return PipeR_.h; } virtual HANDLE getWrtPipeHandle() { return PipeW_.h; } @@ -118,7 +117,7 @@ public: } } - virtual boost::shared_ptr acceptImpl(); + virtual stdcxx::shared_ptr acceptImpl(); virtual HANDLE getPipeHandle() { return Pipe_.h; } virtual HANDLE getWrtPipeHandle() { return INVALID_HANDLE_VALUE; } @@ -142,7 +141,7 @@ private: TCriticalSection pipe_protect_; // only read or write these variables underneath a locked pipe_protect_ - boost::shared_ptr cached_client_; + stdcxx::shared_ptr cached_client_; TAutoHandle Pipe_; }; @@ -297,6 +296,10 @@ shared_ptr TNamedPipeServer::acceptImpl() { // if we got here, then we are in an error / shutdown case DWORD gle = GetLastError(); // save error before doing cleanup GlobalOutput.perror("TPipeServer ConnectNamedPipe GLE=", gle); + if(gle == ERROR_OPERATION_ABORTED) { + TAutoCrit lock(pipe_protect_); // Needed to insure concurrent thread to be out of interrupt. + throw TTransportException(TTransportException::INTERRUPTED, "TPipeServer: server interupted"); + } throw TTransportException(TTransportException::NOT_OPEN, "TPipeServer: client connection failed"); } @@ -361,7 +364,7 @@ bool TNamedPipeServer::createNamedPipe(const TAutoCrit & /*lockProof*/) { GlobalOutput.perror("TPipeServer::TCreateNamedPipe() GLE=", lastError); throw TTransportException(TTransportException::NOT_OPEN, "TCreateNamedPipe() failed", - lastError); + lastError); return false; } @@ -404,12 +407,12 @@ bool TAnonPipeServer::createAnonPipe() { //--------------------------------------------------------- // Accessors //--------------------------------------------------------- -string TPipeServer::getPipename() { +std::string TPipeServer::getPipename() { return pipename_; } void TPipeServer::setPipename(const std::string& pipename) { - if (pipename.find("\\\\") == -1) + if (pipename.find("\\\\") == std::string::npos) pipename_ = "\\\\.\\pipe\\" + pipename; else pipename_ = pipename; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TPipeServer.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TPipeServer.h index 405793e..117773c 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TPipeServer.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TPipeServer.h @@ -21,7 +21,7 @@ #define _THRIFT_TRANSPORT_TSERVERWINPIPES_H_ 1 #include -#include +#include #ifndef _WIN32 #include #endif @@ -82,10 +82,10 @@ public: HANDLE getNativeWaitHandle(); protected: - virtual boost::shared_ptr acceptImpl(); + virtual stdcxx::shared_ptr acceptImpl(); private: - boost::shared_ptr impl_; + stdcxx::shared_ptr impl_; std::string pipename_; uint32_t bufsize_; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSSLServerSocket.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSSLServerSocket.cpp index 89423b4..8e81ad7 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSSLServerSocket.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSSLServerSocket.cpp @@ -27,14 +27,14 @@ namespace transport { /** * SSL server socket implementation. */ -TSSLServerSocket::TSSLServerSocket(int port, boost::shared_ptr factory) +TSSLServerSocket::TSSLServerSocket(int port, stdcxx::shared_ptr factory) : TServerSocket(port), factory_(factory) { factory_->server(true); } TSSLServerSocket::TSSLServerSocket(const std::string& address, int port, - boost::shared_ptr factory) + stdcxx::shared_ptr factory) : TServerSocket(address, port), factory_(factory) { factory_->server(true); } @@ -42,12 +42,12 @@ TSSLServerSocket::TSSLServerSocket(const std::string& address, TSSLServerSocket::TSSLServerSocket(int port, int sendTimeout, int recvTimeout, - boost::shared_ptr factory) + stdcxx::shared_ptr factory) : TServerSocket(port, sendTimeout, recvTimeout), factory_(factory) { factory_->server(true); } -boost::shared_ptr TSSLServerSocket::createSocket(THRIFT_SOCKET client) { +stdcxx::shared_ptr TSSLServerSocket::createSocket(THRIFT_SOCKET client) { if (interruptableChildren_) { return factory_->createSocket(client, pChildInterruptSockReader_); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSSLServerSocket.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSSLServerSocket.h index dfdbde8..dda9af4 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSSLServerSocket.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSSLServerSocket.h @@ -20,7 +20,7 @@ #ifndef _THRIFT_TRANSPORT_TSSLSERVERSOCKET_H_ #define _THRIFT_TRANSPORT_TSSLSERVERSOCKET_H_ 1 -#include +#include #include namespace apache { @@ -40,7 +40,7 @@ public: * @param port Listening port * @param factory SSL socket factory implementation */ - TSSLServerSocket(int port, boost::shared_ptr factory); + TSSLServerSocket(int port, stdcxx::shared_ptr factory); /** * Constructor. Binds to the specified address. @@ -51,7 +51,7 @@ public: */ TSSLServerSocket(const std::string& address, int port, - boost::shared_ptr factory); + stdcxx::shared_ptr factory); /** * Constructor. Binds to all interfaces. @@ -64,11 +64,11 @@ public: TSSLServerSocket(int port, int sendTimeout, int recvTimeout, - boost::shared_ptr factory); + stdcxx::shared_ptr factory); protected: - boost::shared_ptr createSocket(THRIFT_SOCKET socket); - boost::shared_ptr factory_; + stdcxx::shared_ptr createSocket(THRIFT_SOCKET socket); + stdcxx::shared_ptr factory_; }; } } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSSLSocket.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSSLSocket.cpp index 0af20cb..251ef2f 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSSLSocket.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSSLSocket.cpp @@ -21,6 +21,7 @@ #include #include +#include #ifdef HAVE_ARPA_INET_H #include #endif @@ -35,9 +36,14 @@ #include #endif +#define OPENSSL_VERSION_NO_THREAD_ID_BEFORE 0x10000000L +#define OPENSSL_ENGINE_CLEANUP_REQUIRED_BEFORE 0x10100000L -#include #include +#include +#if (OPENSSL_VERSION_NUMBER < OPENSSL_ENGINE_CLEANUP_REQUIRED_BEFORE) +#include +#endif #include #include #include @@ -45,11 +51,10 @@ #include #include #include +#include -#define OPENSSL_VERSION_NO_THREAD_ID 0x10000000L - -using namespace std; using namespace apache::thrift::concurrency; +using std::string; struct CRYPTO_dynlock_value { Mutex mutex; @@ -66,13 +71,16 @@ static boost::shared_array mutexes; static void callbackLocking(int mode, int n, const char*, int) { if (mode & CRYPTO_LOCK) { + // assertion of (px != 0) here typically means that a TSSLSocket's lifetime + // exceeded the lifetime of the TSSLSocketFactory that created it, and the + // TSSLSocketFactory already ran cleanupOpenSSL(), which deleted "mutexes". mutexes[n].lock(); } else { mutexes[n].unlock(); } } -#if (OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_NO_THREAD_ID) +#if (OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_NO_THREAD_ID_BEFORE) static unsigned long callbackThreadID() { #ifdef _WIN32 return (unsigned long)GetCurrentThreadId(); @@ -107,6 +115,8 @@ void initializeOpenSSL() { openSSLInitialized = true; SSL_library_init(); SSL_load_error_strings(); + ERR_load_crypto_strings(); + // static locking // newer versions of OpenSSL changed CRYPTO_num_locks - see THRIFT-3878 #ifdef CRYPTO_num_locks @@ -114,15 +124,13 @@ void initializeOpenSSL() { #else mutexes = boost::shared_array(new Mutex[ ::CRYPTO_num_locks()]); #endif - if (mutexes == NULL) { - throw TTransportException(TTransportException::INTERNAL_ERROR, - "initializeOpenSSL() failed, " - "out of memory while creating mutex array"); - } -#if (OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_NO_THREAD_ID) + +#if (OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_NO_THREAD_ID_BEFORE) CRYPTO_set_id_callback(callbackThreadID); #endif + CRYPTO_set_locking_callback(callbackLocking); + // dynamic locking CRYPTO_set_dynlock_create_callback(dyn_create); CRYPTO_set_dynlock_lock_callback(dyn_lock); @@ -134,21 +142,22 @@ void cleanupOpenSSL() { return; } openSSLInitialized = false; -#if (OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_NO_THREAD_ID) - CRYPTO_set_id_callback(NULL); + + // https://wiki.openssl.org/index.php/Library_Initialization#Cleanup + // we purposefully do NOT call FIPS_mode_set(0) and leave it up to the enclosing application to manage FIPS entirely +#if (OPENSSL_VERSION_NUMBER < OPENSSL_ENGINE_CLEANUP_REQUIRED_BEFORE) + ENGINE_cleanup(); // https://www.openssl.org/docs/man1.1.0/crypto/ENGINE_cleanup.html - cleanup call is needed before 1.1.0 #endif - CRYPTO_set_locking_callback(NULL); - CRYPTO_set_dynlock_create_callback(NULL); - CRYPTO_set_dynlock_lock_callback(NULL); - CRYPTO_set_dynlock_destroy_callback(NULL); - ERR_free_strings(); + CONF_modules_unload(1); EVP_cleanup(); CRYPTO_cleanup_all_ex_data(); ERR_remove_state(0); + ERR_free_strings(); + mutexes.reset(); } -static void buildErrors(string& message, int error = 0); +static void buildErrors(string& message, int errno_copy = 0, int sslerrno = 0); static bool matchName(const char* host, const char* pattern, int size); static char uppercase(char c); @@ -204,29 +213,35 @@ SSL* SSLContext::createSSL() { } // TSSLSocket implementation -TSSLSocket::TSSLSocket(boost::shared_ptr ctx) +TSSLSocket::TSSLSocket(stdcxx::shared_ptr ctx) : TSocket(), server_(false), ssl_(NULL), ctx_(ctx) { + init(); } -TSSLSocket::TSSLSocket(boost::shared_ptr ctx, boost::shared_ptr interruptListener) +TSSLSocket::TSSLSocket(stdcxx::shared_ptr ctx, stdcxx::shared_ptr interruptListener) : TSocket(), server_(false), ssl_(NULL), ctx_(ctx) { + init(); interruptListener_ = interruptListener; } -TSSLSocket::TSSLSocket(boost::shared_ptr ctx, THRIFT_SOCKET socket) +TSSLSocket::TSSLSocket(stdcxx::shared_ptr ctx, THRIFT_SOCKET socket) : TSocket(socket), server_(false), ssl_(NULL), ctx_(ctx) { + init(); } -TSSLSocket::TSSLSocket(boost::shared_ptr ctx, THRIFT_SOCKET socket, boost::shared_ptr interruptListener) +TSSLSocket::TSSLSocket(stdcxx::shared_ptr ctx, THRIFT_SOCKET socket, stdcxx::shared_ptr interruptListener) : TSocket(socket, interruptListener), server_(false), ssl_(NULL), ctx_(ctx) { + init(); } -TSSLSocket::TSSLSocket(boost::shared_ptr ctx, string host, int port) +TSSLSocket::TSSLSocket(stdcxx::shared_ptr ctx, string host, int port) : TSocket(host, port), server_(false), ssl_(NULL), ctx_(ctx) { + init(); } -TSSLSocket::TSSLSocket(boost::shared_ptr ctx, string host, int port, boost::shared_ptr interruptListener) +TSSLSocket::TSSLSocket(stdcxx::shared_ptr ctx, string host, int port, stdcxx::shared_ptr interruptListener) : TSocket(host, port), server_(false), ssl_(NULL), ctx_(ctx) { + init(); interruptListener_ = interruptListener; } @@ -234,6 +249,23 @@ TSSLSocket::~TSSLSocket() { close(); } +bool TSSLSocket::hasPendingDataToRead() { + if (!isOpen()) { + return false; + } + initializeHandshake(); + if (!checkHandshake()) + throw TSSLException("TSSLSocket::hasPendingDataToRead: Handshake is not completed"); + // data may be available in SSL buffers (note: SSL_pending does not have a failure mode) + return SSL_pending(ssl_) > 0 || TSocket::hasPendingDataToRead(); +} + +void TSSLSocket::init() { + handshakeCompleted_ = false; + readRetryCount_ = 0; + eventSafe_ = false; +} + bool TSSLSocket::isOpen() { if (ssl_ == NULL || !TSocket::isOpen()) { return false; @@ -248,11 +280,16 @@ bool TSSLSocket::isOpen() { return true; } +/* + * Note: This method is not libevent safe. +*/ bool TSSLSocket::peek() { if (!isOpen()) { return false; } - checkHandshake(); + initializeHandshake(); + if (!checkHandshake()) + throw TSSLException("SSL_peek: Handshake is not completed"); int rc; uint8_t byte; do { @@ -267,14 +304,16 @@ bool TSSLSocket::peek() { && (errno_copy != THRIFT_EAGAIN)) { break; } + // fallthrough case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: - waitForEvent(error == SSL_ERROR_WANT_READ); - continue; + // in the case of SSL_ERROR_SYSCALL we want to wait for an read event again + waitForEvent(error != SSL_ERROR_WANT_WRITE); + continue; default:;// do nothing } string errors; - buildErrors(errors, errno_copy); + buildErrors(errors, errno_copy, error); throw TSSLException("SSL_peek: " + errors); } else if (rc == 0) { ERR_clear_error(); @@ -291,24 +330,31 @@ void TSSLSocket::open() { TSocket::open(); } +/* + * Note: This method is not libevent safe. +*/ void TSSLSocket::close() { if (ssl_ != NULL) { try { int rc; + int errno_copy = 0; + int error = 0; do { rc = SSL_shutdown(ssl_); if (rc <= 0) { - int errno_copy = THRIFT_GET_SOCKET_ERROR; - int error = SSL_get_error(ssl_, rc); + errno_copy = THRIFT_GET_SOCKET_ERROR; + error = SSL_get_error(ssl_, rc); switch (error) { case SSL_ERROR_SYSCALL: if ((errno_copy != THRIFT_EINTR) && (errno_copy != THRIFT_EAGAIN)) { break; } + // fallthrough case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: + // in the case of SSL_ERROR_SYSCALL we want to wait for an write/read event again waitForEvent(error == SSL_ERROR_WANT_READ); rc = 2; default:;// do nothing @@ -317,9 +363,8 @@ void TSSLSocket::close() { } while (rc == 2); if (rc < 0) { - int errno_copy = THRIFT_GET_SOCKET_ERROR; string errors; - buildErrors(errors, errno_copy); + buildErrors(errors, errno_copy, error); GlobalOutput(("SSL_shutdown: " + errors).c_str()); } } catch (TTransportException& te) { @@ -331,55 +376,99 @@ void TSSLSocket::close() { } SSL_free(ssl_); ssl_ = NULL; + handshakeCompleted_ = false; ERR_remove_state(0); } TSocket::close(); } +/* + * Returns number of bytes read in SSL Socket. + * If eventSafe is set, and it may returns 0 bytes then read method + * needs to be called again until it is successfull or it throws + * exception incase of failure. +*/ uint32_t TSSLSocket::read(uint8_t* buf, uint32_t len) { - checkHandshake(); + initializeHandshake(); + if (!checkHandshake()) + throw TTransportException(TTransportException::UNKNOWN, "retry again"); int32_t bytes = 0; - for (int32_t retries = 0; retries < maxRecvRetries_; retries++) { - ERR_clear_error(); + while (readRetryCount_ < maxRecvRetries_) { bytes = SSL_read(ssl_, buf, len); - if (bytes >= 0) - break; int32_t errno_copy = THRIFT_GET_SOCKET_ERROR; int32_t error = SSL_get_error(ssl_, bytes); + readRetryCount_++; + if (error == SSL_ERROR_NONE) { + readRetryCount_ = 0; + break; + } + unsigned int waitEventReturn; + bool breakout = false; switch (error) { + case SSL_ERROR_ZERO_RETURN: + throw TTransportException(TTransportException::END_OF_FILE, "client disconnected"); + case SSL_ERROR_SYSCALL: + if (errno_copy == 0 && ERR_peek_error() == 0) { + breakout = true; + break; + } if ((errno_copy != THRIFT_EINTR) && (errno_copy != THRIFT_EAGAIN)) { break; } - if (retries++ >= maxRecvRetries_) { + if (readRetryCount_ >= maxRecvRetries_) { // THRIFT_EINTR needs to be handled manually and we can tolerate // a certain number break; } + // fallthrough + case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: - if (waitForEvent(error == SSL_ERROR_WANT_READ) == TSSL_EINTR ) { + if (isLibeventSafe()) { + if (readRetryCount_ < maxRecvRetries_) { + // THRIFT_EINTR needs to be handled manually and we can tolerate + // a certain number + throw TTransportException(TTransportException::UNKNOWN, "retry again"); + } + throw TTransportException(TTransportException::INTERNAL_ERROR, "too much recv retries"); + } + // in the case of SSL_ERROR_SYSCALL we want to wait for an read event again + else if ((waitEventReturn = waitForEvent(error != SSL_ERROR_WANT_WRITE)) == TSSL_EINTR ) { // repeat operation - if (retries++ < maxRecvRetries_) { + if (readRetryCount_ < maxRecvRetries_) { // THRIFT_EINTR needs to be handled manually and we can tolerate // a certain number continue; } throw TTransportException(TTransportException::INTERNAL_ERROR, "too much recv retries"); } - continue; + else if (waitEventReturn == TSSL_DATA) { + // in case of SSL and huge thrift packets, there may be a number of + // socket operations, before any data becomes available by SSL_read(). + // Therefore the number of retries should not be increased and + // the operation should be repeated. + readRetryCount_--; + continue; + } + throw TTransportException(TTransportException::INTERNAL_ERROR, "unkown waitForEvent return value"); default:;// do nothing } + if (breakout) { + break; + } string errors; - buildErrors(errors, errno_copy); + buildErrors(errors, errno_copy, error); throw TSSLException("SSL_read: " + errors); } return bytes; } void TSSLSocket::write(const uint8_t* buf, uint32_t len) { - checkHandshake(); + initializeHandshake(); + if (!checkHandshake()) + return; // loop in case SSL_MODE_ENABLE_PARTIAL_WRITE is set in SSL_CTX. uint32_t written = 0; while (written < len) { @@ -394,26 +483,81 @@ void TSSLSocket::write(const uint8_t* buf, uint32_t len) { && (errno_copy != THRIFT_EAGAIN)) { break; } + // fallthrough case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: - waitForEvent(error == SSL_ERROR_WANT_READ); - continue; + if (isLibeventSafe()) { + return; + } + else { + // in the case of SSL_ERROR_SYSCALL we want to wait for an write event again + waitForEvent(error == SSL_ERROR_WANT_READ); + continue; + } default:;// do nothing } string errors; - buildErrors(errors, errno_copy); + buildErrors(errors, errno_copy, error); throw TSSLException("SSL_write: " + errors); } written += bytes; } } +/* + * Returns number of bytes written in SSL Socket. + * If eventSafe is set, and it may returns 0 bytes then write method + * needs to be called again until it is successfull or it throws + * exception incase of failure. +*/ +uint32_t TSSLSocket::write_partial(const uint8_t* buf, uint32_t len) { + initializeHandshake(); + if (!checkHandshake()) + return 0; + // loop in case SSL_MODE_ENABLE_PARTIAL_WRITE is set in SSL_CTX. + uint32_t written = 0; + while (written < len) { + ERR_clear_error(); + int32_t bytes = SSL_write(ssl_, &buf[written], len - written); + if (bytes <= 0) { + int errno_copy = THRIFT_GET_SOCKET_ERROR; + int error = SSL_get_error(ssl_, bytes); + switch (error) { + case SSL_ERROR_SYSCALL: + if ((errno_copy != THRIFT_EINTR) + && (errno_copy != THRIFT_EAGAIN)) { + break; + } + // fallthrough + case SSL_ERROR_WANT_READ: + case SSL_ERROR_WANT_WRITE: + if (isLibeventSafe()) { + return 0; + } + else { + // in the case of SSL_ERROR_SYSCALL we want to wait for an write event again + waitForEvent(error == SSL_ERROR_WANT_READ); + continue; + } + default:;// do nothing + } + string errors; + buildErrors(errors, errno_copy, error); + throw TSSLException("SSL_write: " + errors); + } + written += bytes; + } + return written; +} + void TSSLSocket::flush() { // Don't throw exception if not open. Thrift servers close socket twice. if (ssl_ == NULL) { return; } - checkHandshake(); + initializeHandshake(); + if (!checkHandshake()) + throw TSSLException("BIO_flush: Handshake is not completed"); BIO* bio = SSL_get_wbio(ssl_); if (bio == NULL) { throw TSSLException("SSL_get_wbio returns NULL"); @@ -426,14 +570,7 @@ void TSSLSocket::flush() { } } -void TSSLSocket::checkHandshake() { - if (!TSocket::isOpen()) { - throw TTransportException(TTransportException::NOT_OPEN); - } - if (ssl_ != NULL) { - return; - } - +void TSSLSocket::initializeHandshakeParams() { // set underlying socket to non-blocking int flags; if ((flags = THRIFT_FCNTL(socket_, THRIFT_F_GETFL, 0)) < 0 @@ -443,77 +580,100 @@ void TSSLSocket::checkHandshake() { ::THRIFT_CLOSESOCKET(socket_); return; } - ssl_ = ctx_->createSSL(); - //set read and write bios to non-blocking - BIO* wbio = BIO_new(BIO_s_mem()); - if (wbio == NULL) { - throw TSSLException("SSL_get_wbio returns NULL"); - } - BIO_set_nbio(wbio, 1); - - BIO* rbio = BIO_new(BIO_s_mem()); - if (rbio == NULL) { - throw TSSLException("SSL_get_rbio returns NULL"); - } - BIO_set_nbio(rbio, 1); - - SSL_set_bio(ssl_, rbio, wbio); - SSL_set_fd(ssl_, static_cast(socket_)); +} + +bool TSSLSocket::checkHandshake() { + return handshakeCompleted_; +} + +void TSSLSocket::initializeHandshake() { + if (!TSocket::isOpen()) { + throw TTransportException(TTransportException::NOT_OPEN); + } + if (checkHandshake()) { + return; + } + + if (ssl_ == NULL) { + initializeHandshakeParams(); + } + int rc; + int errno_copy = 0; + int error = 0; if (server()) { do { rc = SSL_accept(ssl_); if (rc <= 0) { - int errno_copy = THRIFT_GET_SOCKET_ERROR; - int error = SSL_get_error(ssl_, rc); + errno_copy = THRIFT_GET_SOCKET_ERROR; + error = SSL_get_error(ssl_, rc); switch (error) { case SSL_ERROR_SYSCALL: if ((errno_copy != THRIFT_EINTR) && (errno_copy != THRIFT_EAGAIN)) { break; } + // fallthrough case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: - waitForEvent(error == SSL_ERROR_WANT_READ); - rc = 2; + if (isLibeventSafe()) { + return; + } + else { + // repeat operation + // in the case of SSL_ERROR_SYSCALL we want to wait for an write/read event again + waitForEvent(error == SSL_ERROR_WANT_READ); + rc = 2; + } default:;// do nothing } } } while (rc == 2); } else { - // set the SNI hostname - SSL_set_tlsext_host_name(ssl_, getHost().c_str()); + // OpenSSL < 0.9.8f does not have SSL_set_tlsext_host_name() + #if defined(SSL_set_tlsext_host_name) + // set the SNI hostname + SSL_set_tlsext_host_name(ssl_, getHost().c_str()); + #endif do { rc = SSL_connect(ssl_); if (rc <= 0) { - int errno_copy = THRIFT_GET_SOCKET_ERROR; - int error = SSL_get_error(ssl_, rc); + errno_copy = THRIFT_GET_SOCKET_ERROR; + error = SSL_get_error(ssl_, rc); switch (error) { case SSL_ERROR_SYSCALL: if ((errno_copy != THRIFT_EINTR) && (errno_copy != THRIFT_EAGAIN)) { break; } + // fallthrough case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: - waitForEvent(error == SSL_ERROR_WANT_READ); - rc = 2; + if (isLibeventSafe()) { + return; + } + else { + // repeat operation + // in the case of SSL_ERROR_SYSCALL we want to wait for an write/read event again + waitForEvent(error == SSL_ERROR_WANT_READ); + rc = 2; + } default:;// do nothing } } } while (rc == 2); } if (rc <= 0) { - int errno_copy = THRIFT_GET_SOCKET_ERROR; string fname(server() ? "SSL_accept" : "SSL_connect"); string errors; - buildErrors(errors, errno_copy); + buildErrors(errors, errno_copy, error); throw TSSLException(fname + ": " + errors); } authorize(); + handshakeCompleted_ = true; } void TSSLSocket::authorize() { @@ -622,6 +782,9 @@ void TSSLSocket::authorize() { } } +/* + * Note: This method is not libevent safe. +*/ unsigned int TSSLSocket::waitForEvent(bool wantRead) { int fdSocket; BIO* bio; @@ -641,9 +804,11 @@ unsigned int TSSLSocket::waitForEvent(bool wantRead) { } struct THRIFT_POLLFD fds[2]; - std::memset(fds, 0, sizeof(fds)); + memset(fds, 0, sizeof(fds)); fds[0].fd = fdSocket; - fds[0].events = wantRead ? THRIFT_POLLIN : THRIFT_POLLOUT; + // use POLLIN also on write operations too, this is needed for operations + // which requires read and write on the socket. + fds[0].events = wantRead ? THRIFT_POLLIN : THRIFT_POLLIN | THRIFT_POLLOUT; if (interruptListener_) { fds[1].fd = *(interruptListener_.get()); @@ -692,7 +857,7 @@ TSSLSocketFactory::TSSLSocketFactory(SSLProtocol protocol) : server_(false) { randomize(); } count_++; - ctx_ = boost::shared_ptr(new SSLContext(protocol)); + ctx_ = stdcxx::shared_ptr(new SSLContext(protocol)); } TSSLSocketFactory::~TSSLSocketFactory() { @@ -704,47 +869,47 @@ TSSLSocketFactory::~TSSLSocketFactory() { } } -boost::shared_ptr TSSLSocketFactory::createSocket() { - boost::shared_ptr ssl(new TSSLSocket(ctx_)); +stdcxx::shared_ptr TSSLSocketFactory::createSocket() { + stdcxx::shared_ptr ssl(new TSSLSocket(ctx_)); setup(ssl); return ssl; } -boost::shared_ptr TSSLSocketFactory::createSocket(boost::shared_ptr interruptListener) { - boost::shared_ptr ssl(new TSSLSocket(ctx_, interruptListener)); +stdcxx::shared_ptr TSSLSocketFactory::createSocket(stdcxx::shared_ptr interruptListener) { + stdcxx::shared_ptr ssl(new TSSLSocket(ctx_, interruptListener)); setup(ssl); return ssl; } -boost::shared_ptr TSSLSocketFactory::createSocket(THRIFT_SOCKET socket) { - boost::shared_ptr ssl(new TSSLSocket(ctx_, socket)); +stdcxx::shared_ptr TSSLSocketFactory::createSocket(THRIFT_SOCKET socket) { + stdcxx::shared_ptr ssl(new TSSLSocket(ctx_, socket)); setup(ssl); return ssl; } -boost::shared_ptr TSSLSocketFactory::createSocket(THRIFT_SOCKET socket, boost::shared_ptr interruptListener) { - boost::shared_ptr ssl(new TSSLSocket(ctx_, socket, interruptListener)); +stdcxx::shared_ptr TSSLSocketFactory::createSocket(THRIFT_SOCKET socket, stdcxx::shared_ptr interruptListener) { + stdcxx::shared_ptr ssl(new TSSLSocket(ctx_, socket, interruptListener)); setup(ssl); return ssl; } -boost::shared_ptr TSSLSocketFactory::createSocket(const string& host, int port) { - boost::shared_ptr ssl(new TSSLSocket(ctx_, host, port)); +stdcxx::shared_ptr TSSLSocketFactory::createSocket(const string& host, int port) { + stdcxx::shared_ptr ssl(new TSSLSocket(ctx_, host, port)); setup(ssl); return ssl; } -boost::shared_ptr TSSLSocketFactory::createSocket(const string& host, int port, boost::shared_ptr interruptListener) { - boost::shared_ptr ssl(new TSSLSocket(ctx_, host, port, interruptListener)); +stdcxx::shared_ptr TSSLSocketFactory::createSocket(const string& host, int port, stdcxx::shared_ptr interruptListener) { + stdcxx::shared_ptr ssl(new TSSLSocket(ctx_, host, port, interruptListener)); setup(ssl); return ssl; } -void TSSLSocketFactory::setup(boost::shared_ptr ssl) { +void TSSLSocketFactory::setup(stdcxx::shared_ptr ssl) { ssl->server(server()); if (access_ == NULL && !server()) { - access_ = boost::shared_ptr(new DefaultClientAccessManager); + access_ = stdcxx::shared_ptr(new DefaultClientAccessManager); } if (access_ != NULL) { ssl->access(access_); @@ -805,12 +970,12 @@ void TSSLSocketFactory::loadPrivateKey(const char* path, const char* format) { } } -void TSSLSocketFactory::loadTrustedCertificates(const char* path) { +void TSSLSocketFactory::loadTrustedCertificates(const char* path, const char* capath) { if (path == NULL) { throw TTransportException(TTransportException::BAD_ARGS, "loadTrustedCertificates: is NULL"); } - if (SSL_CTX_load_verify_locations(ctx_->get(), path, NULL) == 0) { + if (SSL_CTX_load_verify_locations(ctx_->get(), path, capath) == 0) { int errno_copy = THRIFT_GET_SOCKET_ERROR; string errors; buildErrors(errors, errno_copy); @@ -841,7 +1006,7 @@ int TSSLSocketFactory::passwordCallback(char* password, int size, int, void* dat } // extract error messages from error queue -void buildErrors(string& errors, int errno_copy) { +void buildErrors(string& errors, int errno_copy, int sslerrno) { unsigned long errorCode; char message[256]; @@ -863,7 +1028,18 @@ void buildErrors(string& errors, int errno_copy) { } } if (errors.empty()) { - errors = "error code: " + boost::lexical_cast(errno_copy); + errors = "error code: " + to_string(errno_copy); + } + if (sslerrno) { + errors += " (SSL_error_code = " + to_string(sslerrno) + ")"; + if (sslerrno == SSL_ERROR_SYSCALL) { + char buf[4096]; + int err; + while ((err = ERR_get_error()) != 0) { + errors += " "; + errors += ERR_error_string(err, buf); + } + } } } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSSLSocket.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSSLSocket.h index 03157d7..ec30cc1 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSSLSocket.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSSLSocket.h @@ -22,10 +22,11 @@ // Put this first to avoid WIN32 build failure #include -#include -#include + #include +#include #include +#include namespace apache { namespace thrift { @@ -77,8 +78,10 @@ public: bool peek(); void open(); void close(); + bool hasPendingDataToRead(); uint32_t read(uint8_t* buf, uint32_t len); void write(const uint8_t* buf, uint32_t len); + uint32_t write_partial(const uint8_t* buf, uint32_t len); void flush(); /** * Set whether to use client or server side SSL handshake protocol. @@ -95,43 +98,51 @@ public: * * @param manager Instance of AccessManager */ - virtual void access(boost::shared_ptr manager) { access_ = manager; } + virtual void access(stdcxx::shared_ptr manager) { access_ = manager; } + /** + * Set eventSafe flag if libevent is used. + */ + void setLibeventSafe() { eventSafe_ = true; } + /** + * Determines whether SSL Socket is libevent safe or not. + */ + bool isLibeventSafe() const { return eventSafe_; } protected: /** * Constructor. */ - TSSLSocket(boost::shared_ptr ctx); + TSSLSocket(stdcxx::shared_ptr ctx); /** * Constructor with an interrupt signal. */ - TSSLSocket(boost::shared_ptr ctx, boost::shared_ptr interruptListener); + TSSLSocket(stdcxx::shared_ptr ctx, stdcxx::shared_ptr interruptListener); /** * Constructor, create an instance of TSSLSocket given an existing socket. * * @param socket An existing socket */ - TSSLSocket(boost::shared_ptr ctx, THRIFT_SOCKET socket); + TSSLSocket(stdcxx::shared_ptr ctx, THRIFT_SOCKET socket); /** * Constructor, create an instance of TSSLSocket given an existing socket that can be interrupted. * * @param socket An existing socket */ - TSSLSocket(boost::shared_ptr ctx, THRIFT_SOCKET socket, boost::shared_ptr interruptListener); + TSSLSocket(stdcxx::shared_ptr ctx, THRIFT_SOCKET socket, stdcxx::shared_ptr interruptListener); /** * Constructor. * * @param host Remote host name * @param port Remote port number */ - TSSLSocket(boost::shared_ptr ctx, std::string host, int port); + TSSLSocket(stdcxx::shared_ptr ctx, std::string host, int port); /** - * Constructor with an interrupt signal. - * - * @param host Remote host name - * @param port Remote port number - */ - TSSLSocket(boost::shared_ptr ctx, std::string host, int port, boost::shared_ptr interruptListener); + * Constructor with an interrupt signal. + * + * @param host Remote host name + * @param port Remote port number + */ + TSSLSocket(stdcxx::shared_ptr ctx, std::string host, int port, stdcxx::shared_ptr interruptListener); /** * Authorize peer access after SSL handshake completes. */ @@ -139,7 +150,15 @@ protected: /** * Initiate SSL handshake if not already initiated. */ - void checkHandshake(); + void initializeHandshake(); + /** + * Initiate SSL handshake params. + */ + void initializeHandshakeParams(); + /** + * Check if SSL handshake is completed or not. + */ + bool checkHandshake(); /** * Waits for an socket or shutdown event. * @@ -152,13 +171,34 @@ protected: bool server_; SSL* ssl_; - boost::shared_ptr ctx_; - boost::shared_ptr access_; + stdcxx::shared_ptr ctx_; + stdcxx::shared_ptr access_; friend class TSSLSocketFactory; + +private: + bool handshakeCompleted_; + int readRetryCount_; + bool eventSafe_; + + void init(); }; /** * SSL socket factory. SSL sockets should be created via SSL factory. + * The factory will automatically initialize and cleanup openssl as long as + * there is a TSSLSocketFactory instantiated, and as long as the static + * boolean manualOpenSSLInitialization_ is set to false, the default. + * + * If you would like to initialize and cleanup openssl yourself, set + * manualOpenSSLInitialization_ to true and TSSLSocketFactory will no + * longer be responsible for openssl initialization and teardown. + * + * It is the responsibility of the code using TSSLSocketFactory to + * ensure that the factory lifetime exceeds the lifetime of any sockets + * it might create. If this is not guaranteed, a socket may call into + * openssl after the socket factory has cleaned up openssl! This + * guarantee is unnecessary if manualOpenSSLInitialization_ is true, + * however, since it would be up to the consuming application instead. */ class TSSLSocketFactory { public: @@ -172,37 +212,37 @@ public: /** * Create an instance of TSSLSocket with a fresh new socket. */ - virtual boost::shared_ptr createSocket(); + virtual stdcxx::shared_ptr createSocket(); /** * Create an instance of TSSLSocket with a fresh new socket, which is interruptable. */ - virtual boost::shared_ptr createSocket(boost::shared_ptr interruptListener); + virtual stdcxx::shared_ptr createSocket(stdcxx::shared_ptr interruptListener); /** * Create an instance of TSSLSocket with the given socket. * * @param socket An existing socket. */ - virtual boost::shared_ptr createSocket(THRIFT_SOCKET socket); + virtual stdcxx::shared_ptr createSocket(THRIFT_SOCKET socket); /** * Create an instance of TSSLSocket with the given socket which is interruptable. * * @param socket An existing socket. */ - virtual boost::shared_ptr createSocket(THRIFT_SOCKET socket, boost::shared_ptr interruptListener); + virtual stdcxx::shared_ptr createSocket(THRIFT_SOCKET socket, stdcxx::shared_ptr interruptListener); /** * Create an instance of TSSLSocket. * * @param host Remote host to be connected to * @param port Remote port to be connected to */ - virtual boost::shared_ptr createSocket(const std::string& host, int port); + virtual stdcxx::shared_ptr createSocket(const std::string& host, int port); /** * Create an instance of TSSLSocket. * * @param host Remote host to be connected to * @param port Remote port to be connected to */ - virtual boost::shared_ptr createSocket(const std::string& host, int port, boost::shared_ptr interruptListener); + virtual stdcxx::shared_ptr createSocket(const std::string& host, int port, stdcxx::shared_ptr interruptListener); /** * Set ciphers to be used in SSL handshake process. * @@ -234,7 +274,7 @@ public: * * @param path Path to trusted certificate file */ - virtual void loadTrustedCertificates(const char* path); + virtual void loadTrustedCertificates(const char* path, const char* capath = NULL); /** * Default randomize method. */ @@ -260,13 +300,13 @@ public: * * @param manager The AccessManager instance */ - virtual void access(boost::shared_ptr manager) { access_ = manager; } + virtual void access(stdcxx::shared_ptr manager) { access_ = manager; } static void setManualOpenSSLInitialization(bool manualOpenSSLInitialization) { manualOpenSSLInitialization_ = manualOpenSSLInitialization; } protected: - boost::shared_ptr ctx_; + stdcxx::shared_ptr ctx_; /** * Override this method for custom password callback. It may be called @@ -279,11 +319,11 @@ protected: private: bool server_; - boost::shared_ptr access_; + stdcxx::shared_ptr access_; static concurrency::Mutex mutex_; static uint64_t count_; static bool manualOpenSSLInitialization_; - void setup(boost::shared_ptr ssl); + void setup(stdcxx::shared_ptr ssl); static int passwordCallback(char* password, int size, int, void* data); }; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TServerSocket.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TServerSocket.cpp index 87b6383..3f11a59 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TServerSocket.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TServerSocket.cpp @@ -46,7 +46,7 @@ #include #include #include -#include +#include #ifndef AF_LOCAL #define AF_LOCAL AF_UNIX @@ -60,10 +60,6 @@ #endif // _WIN32 #endif -#if defined(_WIN32) && (_WIN32_WINNT < 0x0600) - #define AI_ADDRCONFIG 0x0400 -#endif - template inline const SOCKOPT_CAST_T* const_cast_sockopt(const T* v) { return reinterpret_cast(v); @@ -79,21 +75,13 @@ void destroyer_of_fine_sockets(THRIFT_SOCKET* ssock) { delete ssock; } -class TGetAddrInfoWrapper { -public: - TGetAddrInfoWrapper(const char* node, const char* service, const struct addrinfo* hints); +using std::string; - virtual ~TGetAddrInfoWrapper(); +namespace apache { +namespace thrift { +namespace transport { - int init(); - const struct addrinfo* res(); - -private: - const char* node_; - const char* service_; - const struct addrinfo* hints_; - struct addrinfo* res_; -}; +using stdcxx::shared_ptr; TGetAddrInfoWrapper::TGetAddrInfoWrapper(const char* node, const char* service, @@ -115,13 +103,6 @@ const struct addrinfo* TGetAddrInfoWrapper::res() { return this->res_; } -namespace apache { -namespace thrift { -namespace transport { - -using namespace std; -using boost::shared_ptr; - TServerSocket::TServerSocket(int port) : interruptableChildren_(true), port_(port), @@ -268,7 +249,7 @@ void TServerSocket::listen() { } else { childInterruptSockWriter_ = sv[1]; pChildInterruptSockReader_ - = boost::shared_ptr(new THRIFT_SOCKET(sv[0]), destroyer_of_fine_sockets); + = stdcxx::shared_ptr(new THRIFT_SOCKET(sv[0]), destroyer_of_fine_sockets); } // Validate port number @@ -307,7 +288,7 @@ void TServerSocket::listen() { if (!path_.empty()) { serverSocket_ = socket(PF_UNIX, SOCK_STREAM, IPPROTO_IP); - } else { + } else if (res != NULL) { serverSocket_ = socket(res->ai_family, res->ai_socktype, res->ai_protocol); } @@ -613,7 +594,7 @@ shared_ptr TServerSocket::acceptImpl() { THRIFT_SOCKET clientSocket = ::accept(serverSocket_, (struct sockaddr*)&clientAddress, (socklen_t*)&size); - if (clientSocket == -1) { + if (clientSocket == THRIFT_INVALID_SOCKET) { int errno_copy = THRIFT_GET_SOCKET_ERROR; GlobalOutput.perror("TServerSocket::acceptImpl() ::accept() ", errno_copy); throw TTransportException(TTransportException::UNKNOWN, "accept()", errno_copy); @@ -677,14 +658,21 @@ void TServerSocket::notify(THRIFT_SOCKET notifySocket) { } void TServerSocket::interrupt() { - notify(interruptSockWriter_); + concurrency::Guard g(rwMutex_); + if (interruptSockWriter_ != THRIFT_INVALID_SOCKET) { + notify(interruptSockWriter_); + } } void TServerSocket::interruptChildren() { - notify(childInterruptSockWriter_); + concurrency::Guard g(rwMutex_); + if (childInterruptSockWriter_ != THRIFT_INVALID_SOCKET) { + notify(childInterruptSockWriter_); + } } void TServerSocket::close() { + concurrency::Guard g(rwMutex_); if (serverSocket_ != THRIFT_INVALID_SOCKET) { shutdown(serverSocket_, THRIFT_SHUT_RDWR); ::THRIFT_CLOSESOCKET(serverSocket_); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TServerSocket.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TServerSocket.h index 20a37e7..1daaa82 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TServerSocket.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TServerSocket.h @@ -20,10 +20,18 @@ #ifndef _THRIFT_TRANSPORT_TSERVERSOCKET_H_ #define _THRIFT_TRANSPORT_TSERVERSOCKET_H_ 1 -#include +#include +#include #include -#include -#include +#include + +#include +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif namespace apache { namespace thrift { @@ -31,6 +39,22 @@ namespace transport { class TSocket; +class TGetAddrInfoWrapper { +public: + TGetAddrInfoWrapper(const char* node, const char* service, const struct addrinfo* hints); + + virtual ~TGetAddrInfoWrapper(); + + int init(); + const struct addrinfo* res(); + +private: + const char* node_; + const char* service_; + const struct addrinfo* hints_; + struct addrinfo* res_; +}; + /** * Server socket implementation of TServerTransport. Wrapper around a unix * socket listen and accept calls. @@ -113,6 +137,8 @@ public: // \throws std::logic_error if listen() has been called void setInterruptableChildren(bool enable); + THRIFT_SOCKET getSocketFD() { return serverSocket_; } + int getPort(); void listen(); @@ -121,10 +147,10 @@ public: void close(); protected: - boost::shared_ptr acceptImpl(); - virtual boost::shared_ptr createSocket(THRIFT_SOCKET client); + stdcxx::shared_ptr acceptImpl(); + virtual stdcxx::shared_ptr createSocket(THRIFT_SOCKET client); bool interruptableChildren_; - boost::shared_ptr pChildInterruptSockReader_; // if interruptableChildren_ this is shared with child TSockets + stdcxx::shared_ptr pChildInterruptSockReader_; // if interruptableChildren_ this is shared with child TSockets private: void notify(THRIFT_SOCKET notifySock); @@ -144,6 +170,7 @@ private: bool keepAlive_; bool listening_; + concurrency::Mutex rwMutex_; // thread-safe interrupt THRIFT_SOCKET interruptSockWriter_; // is notified on interrupt() THRIFT_SOCKET interruptSockReader_; // is used in select/poll with serverSocket_ for interruptability THRIFT_SOCKET childInterruptSockWriter_; // is notified on interruptChildren() diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TServerTransport.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TServerTransport.h index cd1d3da..9d5a3d5 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TServerTransport.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TServerTransport.h @@ -22,7 +22,7 @@ #include #include -#include +#include namespace apache { namespace thrift { @@ -56,8 +56,8 @@ public: * @return A new TTransport object * @throws TTransportException if there is an error */ - boost::shared_ptr accept() { - boost::shared_ptr result = acceptImpl(); + stdcxx::shared_ptr accept() { + stdcxx::shared_ptr result = acceptImpl(); if (!result) { throw TTransportException("accept() may not return NULL"); } @@ -82,6 +82,15 @@ public: */ virtual void interruptChildren() {} + /** + * Utility method + * + * @return server socket file descriptor + * @throw TTransportException If an error occurs + */ + + virtual THRIFT_SOCKET getSocketFD() { return -1; } + /** * Closes this transport such that future calls to accept will do nothing. */ @@ -96,7 +105,7 @@ protected: * @return A newly allocated TTransport object * @throw TTransportException If an error occurs */ - virtual boost::shared_ptr acceptImpl() = 0; + virtual stdcxx::shared_ptr acceptImpl() = 0; }; } } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TShortReadTransport.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TShortReadTransport.h index f2ecae1..550b6ba 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TShortReadTransport.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TShortReadTransport.h @@ -38,7 +38,7 @@ namespace test { */ class TShortReadTransport : public TVirtualTransport { public: - TShortReadTransport(boost::shared_ptr transport, double full_prob) + TShortReadTransport(stdcxx::shared_ptr transport, double full_prob) : transport_(transport), fullProb_(full_prob) {} bool isOpen() { return transport_->isOpen(); } @@ -68,10 +68,10 @@ public: void consume(uint32_t len) { return transport_->consume(len); } - boost::shared_ptr getUnderlyingTransport() { return transport_; } + stdcxx::shared_ptr getUnderlyingTransport() { return transport_; } protected: - boost::shared_ptr transport_; + stdcxx::shared_ptr transport_; double fullProb_; }; } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSocket.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSocket.cpp index e1c106a..18cadbc 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSocket.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSocket.cpp @@ -21,6 +21,9 @@ #include #include +#ifdef HAVE_SYS_IOCTL_H +#include +#endif #ifdef HAVE_SYS_SOCKET_H #include #endif @@ -53,10 +56,6 @@ #endif // _WIN32 #endif -#if defined(_WIN32) && (_WIN32_WINNT < 0x0600) - #define AI_ADDRCONFIG 0x0400 -#endif - template inline const SOCKOPT_CAST_T* const_cast_sockopt(const T* v) { return reinterpret_cast(v); @@ -67,12 +66,12 @@ inline SOCKOPT_CAST_T* cast_sockopt(T* v) { return reinterpret_cast(v); } +using std::string; + namespace apache { namespace thrift { namespace transport { -using namespace std; - /** * TSocket implementation. * @@ -145,7 +144,7 @@ TSocket::TSocket(THRIFT_SOCKET socket) #endif } -TSocket::TSocket(THRIFT_SOCKET socket, boost::shared_ptr interruptListener) +TSocket::TSocket(THRIFT_SOCKET socket, stdcxx::shared_ptr interruptListener) : port_(0), socket_(socket), peerPort_(0), @@ -171,6 +170,26 @@ TSocket::~TSocket() { close(); } +bool TSocket::hasPendingDataToRead() { + if (!isOpen()) { + return false; + } + + int32_t retries = 0; + THRIFT_IOCTL_SOCKET_NUM_BYTES_TYPE numBytesAvailable; +try_again: + int r = THRIFT_IOCTL_SOCKET(socket_, FIONREAD, &numBytesAvailable); + if (r == -1) { + int errno_copy = THRIFT_GET_SOCKET_ERROR; + if (errno_copy == THRIFT_EINTR && (retries++ < maxRecvRetries_)) { + goto try_again; + } + GlobalOutput.perror("TSocket::hasPendingDataToRead() THRIFT_IOCTL_SOCKET() " + getSocketInfo(), errno_copy); + throw TTransportException(TTransportException::UNKNOWN, "Unknown", errno_copy); + } + return numBytesAvailable > 0; +} + bool TSocket::isOpen() { return (socket_ != THRIFT_INVALID_SOCKET); } @@ -221,7 +240,6 @@ bool TSocket::peek() { * the other side */ if (errno_copy == THRIFT_ECONNRESET) { - close(); return false; } #endif @@ -390,7 +408,11 @@ void TSocket::openConnection(struct addrinfo* res) { done: // Set socket back to normal mode (blocking) - THRIFT_FCNTL(socket_, THRIFT_F_SETFL, flags); + if (-1 == THRIFT_FCNTL(socket_, THRIFT_F_SETFL, flags)) { + int errno_copy = THRIFT_GET_SOCKET_ERROR; + GlobalOutput.perror("TSocket::open() THRIFT_FCNTL " + getSocketInfo(), errno_copy); + throw TTransportException(TTransportException::NOT_OPEN, "THRIFT_FCNTL() failed", errno_copy); + } if (path_.empty()) { setCachedAddress(res->ai_addr, static_cast(res->ai_addrlen)); @@ -657,7 +679,6 @@ uint32_t TSocket::write_partial(const uint8_t* buf, uint32_t len) { if (errno_copy == THRIFT_EPIPE || errno_copy == THRIFT_ECONNRESET || errno_copy == THRIFT_ENOTCONN) { - close(); throw TTransportException(TTransportException::NOT_OPEN, "write() send()", errno_copy); } @@ -767,7 +788,7 @@ void TSocket::setSendTimeout(int ms) { void TSocket::setKeepAlive(bool keepAlive) { keepAlive_ = keepAlive; - if (socket_ == -1) { + if (socket_ == THRIFT_INVALID_SOCKET) { return; } @@ -788,11 +809,15 @@ void TSocket::setMaxRecvRetries(int maxRecvRetries) { string TSocket::getSocketInfo() { std::ostringstream oss; - if (host_.empty() || port_ == 0) { - oss << ""; + if (path_.empty()) { + if (host_.empty() || port_ == 0) { + oss << ""; + } else { + oss << ""; + } } else { - oss << ""; + oss << ""; } return oss.str(); } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSocket.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSocket.h index aa18c31..66d9e6c 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSocket.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSocket.h @@ -84,7 +84,9 @@ public: virtual bool isOpen(); /** - * Calls select on the socket to see if there is more data available. + * Checks whether there is more data available in the socket to read. + * + * This call blocks until at least one byte is available or the socket is closed. */ virtual bool peek(); @@ -100,6 +102,17 @@ public: */ virtual void close(); + /** + * Determines whether there is pending data to read or not. + * + * This call does not block. + * \throws TTransportException of types: + * NOT_OPEN means the socket has been closed + * UNKNOWN means something unexpected happened + * \returns true if there is pending data to read, false otherwise + */ + virtual bool hasPendingDataToRead(); + /** * Reads from the underlying socket. * \returns the number of bytes read or 0 indicates EOF @@ -120,7 +133,7 @@ public: /** * Writes to the underlying socket. Does single send() and returns result. */ - uint32_t write_partial(const uint8_t* buf, uint32_t len); + virtual uint32_t write_partial(const uint8_t* buf, uint32_t len); /** * Get the host that the socket is connected to @@ -257,7 +270,7 @@ public: * Constructor to create socket from file descriptor that * can be interrupted safely. */ - TSocket(THRIFT_SOCKET socket, boost::shared_ptr interruptListener); + TSocket(THRIFT_SOCKET socket, stdcxx::shared_ptr interruptListener); /** * Set a cache of the peer address (used when trivially available: e.g. @@ -294,7 +307,7 @@ protected: * A shared socket pointer that will interrupt a blocking read if data * becomes available on it */ - boost::shared_ptr interruptListener_; + stdcxx::shared_ptr interruptListener_; /** Connect timeout in ms */ int connTimeout_; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSocketPool.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSocketPool.cpp index ccab258..a34d135 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSocketPool.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSocketPool.cpp @@ -21,16 +21,21 @@ #include #include +#if __cplusplus >= 201703L +#include +#endif #include +using std::pair; +using std::string; +using std::vector; + namespace apache { namespace thrift { namespace transport { -using namespace std; - -using boost::shared_ptr; +using stdcxx::shared_ptr; /** * TSocketPoolServer implementation @@ -186,7 +191,13 @@ void TSocketPool::open() { } if (randomize_ && numServers > 1) { - random_shuffle(servers_.begin(), servers_.end()); +#if __cplusplus >= 201703L + std::random_device rng; + std::mt19937 urng(rng()); + std::shuffle(servers_.begin(), servers_.end(), urng); +#else + std::random_shuffle(servers_.begin(), servers_.end()); +#endif } for (size_t i = 0; i < numServers; ++i) { @@ -215,7 +226,7 @@ void TSocketPool::open() { for (int j = 0; j < numRetries_; ++j) { try { TSocket::open(); - } catch (TException e) { + } catch (const TException &e) { string errStr = "TSocketPool::open failed " + getSocketInfo() + ": " + e.what(); GlobalOutput(errStr.c_str()); socket_ = THRIFT_INVALID_SOCKET; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSocketPool.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSocketPool.h index 78f0ebf..bd49e55 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSocketPool.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TSocketPool.h @@ -92,7 +92,7 @@ public: * * @param servers list of TSocketPoolServers */ - TSocketPool(const std::vector >& servers); + TSocketPool(const std::vector >& servers); /** * Socket pool constructor @@ -115,17 +115,17 @@ public: /** * Add a server to the pool */ - void addServer(boost::shared_ptr& server); + void addServer(stdcxx::shared_ptr& server); /** * Set list of servers in this pool */ - void setServers(const std::vector >& servers); + void setServers(const std::vector >& servers); /** * Get list of servers in this pool */ - void getServers(std::vector >& servers); + void getServers(std::vector >& servers); /** * Sets how many times to keep retrying a host in the connect function. @@ -163,13 +163,13 @@ public: void close(); protected: - void setCurrentServer(const boost::shared_ptr& server); + void setCurrentServer(const stdcxx::shared_ptr& server); /** List of servers to connect to */ - std::vector > servers_; + std::vector > servers_; /** Current server */ - boost::shared_ptr currentServer_; + stdcxx::shared_ptr currentServer_; /** How many times to retry each host in connect */ int numRetries_; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TTransport.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TTransport.h index d06b0f8..de03290 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TTransport.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TTransport.h @@ -21,7 +21,7 @@ #define _THRIFT_TRANSPORT_TTRANSPORT_H_ 1 #include -#include +#include #include #include @@ -260,7 +260,7 @@ public: /** * Default implementation does nothing, just returns the transport given. */ - virtual boost::shared_ptr getTransport(boost::shared_ptr trans) { + virtual stdcxx::shared_ptr getTransport(stdcxx::shared_ptr trans) { return trans; } }; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TTransportException.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TTransportException.cpp index 612e7b7..9e15dbd 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TTransportException.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TTransportException.cpp @@ -18,13 +18,11 @@ */ #include -#include #include #include using std::string; -using boost::lexical_cast; namespace apache { namespace thrift { diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TTransportException.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TTransportException.h index 83e876a..dbbb971 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TTransportException.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TTransportException.h @@ -20,6 +20,7 @@ #ifndef _THRIFT_TRANSPORT_TTRANSPORTEXCEPTION_H_ #define _THRIFT_TRANSPORT_TTRANSPORTEXCEPTION_H_ 1 +#include #include #include @@ -83,6 +84,21 @@ protected: /** Error code */ TTransportExceptionType type_; }; + +/** + * Legacy code in transport implementations have overflow issues + * that need to be enforced. + */ +template To safe_numeric_cast(From i) { + try { + return boost::numeric_cast(i); + } + catch (const std::bad_cast& bc) { + throw TTransportException(TTransportException::CORRUPTED_DATA, + bc.what()); + } +} + } } } // apache::thrift::transport diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TTransportUtils.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TTransportUtils.cpp index 0f24c95..5a236dc 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TTransportUtils.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TTransportUtils.cpp @@ -41,7 +41,11 @@ uint32_t TPipedTransport::read(uint8_t* buf, uint32_t len) { // Double the size of the underlying buffer if it is full if (rLen_ == rBufSize_) { rBufSize_ *= 2; - rBuf_ = (uint8_t*)std::realloc(rBuf_, sizeof(uint8_t) * rBufSize_); + uint8_t *tmpBuf = (uint8_t*)std::realloc(rBuf_, sizeof(uint8_t) * rBufSize_); + if (tmpBuf == NULL) { + throw std::bad_alloc(); + } + rBuf_ = tmpBuf; } // try to fill up the buffer @@ -73,7 +77,12 @@ void TPipedTransport::write(const uint8_t* buf, uint32_t len) { while ((len + wLen_) >= newBufSize) { newBufSize *= 2; } - wBuf_ = (uint8_t*)std::realloc(wBuf_, sizeof(uint8_t) * newBufSize); + uint8_t *tmpBuf= (uint8_t*)std::realloc(wBuf_, sizeof(uint8_t) * newBufSize); + if (tmpBuf == NULL) { + throw std::bad_alloc(); + } + wBuf_ = tmpBuf; + wBufSize_ = newBufSize; } @@ -94,8 +103,8 @@ void TPipedTransport::flush() { } TPipedFileReaderTransport::TPipedFileReaderTransport( - boost::shared_ptr srcTrans, - boost::shared_ptr dstTrans) + stdcxx::shared_ptr srcTrans, + stdcxx::shared_ptr dstTrans) : TPipedTransport(srcTrans, dstTrans), srcTrans_(srcTrans) { } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TTransportUtils.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TTransportUtils.h index c221836..f3b4c5a 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TTransportUtils.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TTransportUtils.h @@ -63,7 +63,7 @@ public: */ class TPipedTransport : virtual public TTransport { public: - TPipedTransport(boost::shared_ptr srcTrans, boost::shared_ptr dstTrans) + TPipedTransport(stdcxx::shared_ptr srcTrans, stdcxx::shared_ptr dstTrans) : srcTrans_(srcTrans), dstTrans_(dstTrans), rBufSize_(512), @@ -86,8 +86,8 @@ public: } } - TPipedTransport(boost::shared_ptr srcTrans, - boost::shared_ptr dstTrans, + TPipedTransport(stdcxx::shared_ptr srcTrans, + stdcxx::shared_ptr dstTrans, uint32_t sz) : srcTrans_(srcTrans), dstTrans_(dstTrans), @@ -119,7 +119,11 @@ public: // Double the size of the underlying buffer if it is full if (rLen_ == rBufSize_) { rBufSize_ *= 2; - rBuf_ = (uint8_t*)std::realloc(rBuf_, sizeof(uint8_t) * rBufSize_); + uint8_t * tmpBuf = (uint8_t*)std::realloc(rBuf_, sizeof(uint8_t) * rBufSize_); + if (tmpBuf == NULL) { + throw std::bad_alloc(); + } + rBuf_ = tmpBuf; } // try to fill up the buffer @@ -170,7 +174,7 @@ public: void flush(); - boost::shared_ptr getTargetTransport() { return dstTrans_; } + stdcxx::shared_ptr getTargetTransport() { return dstTrans_; } /* * Override TTransport *_virt() functions to invoke our implementations. @@ -181,8 +185,8 @@ public: virtual void write_virt(const uint8_t* buf, uint32_t len) { this->write(buf, len); } protected: - boost::shared_ptr srcTrans_; - boost::shared_ptr dstTrans_; + stdcxx::shared_ptr srcTrans_; + stdcxx::shared_ptr dstTrans_; uint8_t* rBuf_; uint32_t rBufSize_; @@ -204,7 +208,7 @@ protected: class TPipedTransportFactory : public TTransportFactory { public: TPipedTransportFactory() {} - TPipedTransportFactory(boost::shared_ptr dstTrans) { + TPipedTransportFactory(stdcxx::shared_ptr dstTrans) { initializeTargetTransport(dstTrans); } virtual ~TPipedTransportFactory() {} @@ -212,11 +216,11 @@ public: /** * Wraps the base transport into a piped transport. */ - virtual boost::shared_ptr getTransport(boost::shared_ptr srcTrans) { - return boost::shared_ptr(new TPipedTransport(srcTrans, dstTrans_)); + virtual stdcxx::shared_ptr getTransport(stdcxx::shared_ptr srcTrans) { + return stdcxx::shared_ptr(new TPipedTransport(srcTrans, dstTrans_)); } - virtual void initializeTargetTransport(boost::shared_ptr dstTrans) { + virtual void initializeTargetTransport(stdcxx::shared_ptr dstTrans) { if (dstTrans_.get() == NULL) { dstTrans_ = dstTrans; } else { @@ -225,7 +229,7 @@ public: } protected: - boost::shared_ptr dstTrans_; + stdcxx::shared_ptr dstTrans_; }; /** @@ -236,8 +240,8 @@ protected: */ class TPipedFileReaderTransport : public TPipedTransport, public TFileReaderTransport { public: - TPipedFileReaderTransport(boost::shared_ptr srcTrans, - boost::shared_ptr dstTrans); + TPipedFileReaderTransport(stdcxx::shared_ptr srcTrans, + stdcxx::shared_ptr dstTrans); ~TPipedFileReaderTransport(); @@ -273,7 +277,7 @@ public: protected: // shouldn't be used TPipedFileReaderTransport(); - boost::shared_ptr srcTrans_; + stdcxx::shared_ptr srcTrans_; }; /** @@ -283,23 +287,23 @@ protected: class TPipedFileReaderTransportFactory : public TPipedTransportFactory { public: TPipedFileReaderTransportFactory() {} - TPipedFileReaderTransportFactory(boost::shared_ptr dstTrans) + TPipedFileReaderTransportFactory(stdcxx::shared_ptr dstTrans) : TPipedTransportFactory(dstTrans) {} virtual ~TPipedFileReaderTransportFactory() {} - boost::shared_ptr getTransport(boost::shared_ptr srcTrans) { - boost::shared_ptr pFileReaderTransport - = boost::dynamic_pointer_cast(srcTrans); + stdcxx::shared_ptr getTransport(stdcxx::shared_ptr srcTrans) { + stdcxx::shared_ptr pFileReaderTransport + = stdcxx::dynamic_pointer_cast(srcTrans); if (pFileReaderTransport.get() != NULL) { return getFileReaderTransport(pFileReaderTransport); } else { - return boost::shared_ptr(); + return stdcxx::shared_ptr(); } } - boost::shared_ptr getFileReaderTransport( - boost::shared_ptr srcTrans) { - return boost::shared_ptr( + stdcxx::shared_ptr getFileReaderTransport( + stdcxx::shared_ptr srcTrans) { + return stdcxx::shared_ptr( new TPipedFileReaderTransport(srcTrans, dstTrans_)); } }; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TZlibTransport.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TZlibTransport.cpp index fb5cc5d..e426dc3 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TZlibTransport.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TZlibTransport.cpp @@ -255,6 +255,15 @@ void TZlibTransport::flush() { throw TTransportException(TTransportException::BAD_ARGS, "flush() called after finish()"); } + flushToZlib(uwbuf_, uwpos_, Z_BLOCK); + uwpos_ = 0; + + if(wstream_->avail_out < 6){ + transport_->write(cwbuf_, cwbuf_size_ - wstream_->avail_out); + wstream_->next_out = cwbuf_; + wstream_->avail_out = cwbuf_size_; + } + flushToTransport(Z_FULL_FLUSH); } @@ -285,7 +294,7 @@ void TZlibTransport::flushToZlib(const uint8_t* buf, int len, int flush) { wstream_->avail_in = len; while (true) { - if (flush == Z_NO_FLUSH && wstream_->avail_in == 0) { + if ((flush == Z_NO_FLUSH || flush == Z_BLOCK) && wstream_->avail_in == 0) { break; } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TZlibTransport.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TZlibTransport.h index 1e7b5ec..a0fb464 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TZlibTransport.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/transport/TZlibTransport.h @@ -20,9 +20,9 @@ #ifndef _THRIFT_TRANSPORT_TZLIBTRANSPORT_H_ #define _THRIFT_TRANSPORT_TZLIBTRANSPORT_H_ 1 -#include #include #include +#include #include struct z_stream_s; @@ -51,7 +51,7 @@ public: rv += "(no message)"; } rv += " (status = "; - rv += boost::lexical_cast(status); + rv += to_string(status); rv += ")"; return rv; } @@ -78,7 +78,7 @@ public: * @param cwbuf_size Compressed buffer size for writing. * @param comp_level Compression level (0=none[fast], 6=default, 9=max[slow]). */ - TZlibTransport(boost::shared_ptr transport, + TZlibTransport(stdcxx::shared_ptr transport, int urbuf_size = DEFAULT_URBUF_SIZE, int crbuf_size = DEFAULT_CRBUF_SIZE, int uwbuf_size = DEFAULT_UWBUF_SIZE, @@ -105,7 +105,7 @@ public: int minimum = MIN_DIRECT_DEFLATE_SIZE; throw TTransportException(TTransportException::BAD_ARGS, "TZLibTransport: uncompressed write buffer must be at least" - + boost::lexical_cast(minimum) + "."); + + to_string(minimum) + "."); } try { @@ -180,6 +180,8 @@ public: static const int DEFAULT_UWBUF_SIZE = 128; static const int DEFAULT_CWBUF_SIZE = 1024; + stdcxx::shared_ptr getUnderlyingTransport() const { return transport_; } + protected: inline void checkZlibRv(int status, const char* msg); inline void checkZlibRvNothrow(int status, const char* msg); @@ -193,7 +195,7 @@ protected: // Larger (or equal) writes are dumped straight to zlib. static const uint32_t MIN_DIRECT_DEFLATE_SIZE = 32; - boost::shared_ptr transport_; + stdcxx::shared_ptr transport_; int urpos_; int uwpos_; @@ -229,8 +231,8 @@ public: virtual ~TZlibTransportFactory() {} - virtual boost::shared_ptr getTransport(boost::shared_ptr trans) { - return boost::shared_ptr(new TZlibTransport(trans)); + virtual stdcxx::shared_ptr getTransport(stdcxx::shared_ptr trans) { + return stdcxx::shared_ptr(new TZlibTransport(trans)); } }; } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/windows/OverlappedSubmissionThread.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/windows/OverlappedSubmissionThread.h index 56684bb..dd0c5c9 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/windows/OverlappedSubmissionThread.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/windows/OverlappedSubmissionThread.h @@ -63,7 +63,7 @@ namespace apache { namespace thrift { namespace transport { -DECLSPEC_ALIGN(MEMORY_ALLOCATION_ALIGNMENT) struct TOverlappedWorkItem : public SLIST_ENTRY { +struct DECLSPEC_ALIGN(MEMORY_ALLOCATION_ALIGNMENT) TOverlappedWorkItem : public SLIST_ENTRY { TOverlappedWorkItem(); enum action_t { diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/windows/TWinsockSingleton.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/windows/TWinsockSingleton.h index dc1b52f..0eab6d4 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/windows/TWinsockSingleton.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/windows/TWinsockSingleton.h @@ -32,7 +32,6 @@ // boost #include -#include #if USE_BOOST_THREAD #include @@ -42,6 +41,8 @@ #error For windows you must choose USE_BOOST_THREAD or USE_STD_THREAD #endif +#include + namespace apache { namespace thrift { namespace transport { @@ -53,7 +54,7 @@ namespace transport { class TWinsockSingleton : private boost::noncopyable { public: - typedef boost::scoped_ptr instance_ptr; + typedef stdcxx::shared_ptr instance_ptr; private: TWinsockSingleton(void); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/windows/config.h b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/windows/config.h index 049e249..bc4aa42 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/windows/config.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/src/thrift/windows/config.h @@ -28,16 +28,19 @@ #error "This is a Windows header only" #endif -// use std::thread in MSVC11 (2012) or newer -#if _MSC_VER >= 1700 +// use std::thread in MSVC11 (2012) or newer and in MinGW +#if (_MSC_VER >= 1700) || defined(__MINGW32__) #define USE_STD_THREAD 1 #else // otherwise use boost threads #define USE_BOOST_THREAD 1 #endif -// VS2010 or later has stdint.h -#if _MSC_VER >= 1600 +// Something that defines PRId64 is required to build +#define HAVE_INTTYPES_H 1 + +// VS2010 or later has stdint.h as does MinGW +#if (_MSC_VER >= 1600) || defined(__MINGW32__) #define HAVE_STDINT_H 1 #endif @@ -63,9 +66,10 @@ #define SIGNED_RIGHT_SHIFT_IS 1 #endif +#ifndef __MINGW32__ #pragma warning(disable : 4996) // Deprecated posix name. +#endif -#define VERSION "0.10.0" #define HAVE_GETTIMEOFDAY 1 #define HAVE_SYS_STAT_H 1 @@ -95,11 +99,14 @@ typedef boost::uint8_t uint8_t; // windows #include #include -#ifdef _WIN32_WCE -#pragma comment(lib, "Ws2.lib") -#else -#pragma comment(lib, "Ws2_32.lib") -#pragma comment(lib, "advapi32.lib") // For security APIs in TPipeServer -#pragma comment(lib, "Shlwapi.lib") // For StrStrIA in TPipeServer -#endif +#ifndef __MINGW32__ + #ifdef _WIN32_WCE + #pragma comment(lib, "Ws2.lib") + #else + #pragma comment(lib, "Ws2_32.lib") + #pragma comment(lib, "advapi32.lib") // For security APIs in TPipeServer + #pragma comment(lib, "Shlwapi.lib") // For StrStrIA in TPipeServer + #endif +#endif // __MINGW32__ + #endif // _THRIFT_WINDOWS_CONFIG_H_ diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/AllProtocolTests.tcc b/vendor/git.apache.org/thrift.git/lib/cpp/test/AllProtocolTests.tcc index 8c8eaa8..b6df656 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/AllProtocolTests.tcc +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/AllProtocolTests.tcc @@ -28,7 +28,7 @@ #include "GenericHelpers.h" -using boost::shared_ptr; +using apache::thrift::stdcxx::shared_ptr; using namespace apache::thrift; using namespace apache::thrift::protocol; using namespace apache::thrift::transport; @@ -190,14 +190,14 @@ void testProtocol(const char* protoname) { testNaked(0); for (int64_t i = 0; i < 62; i++) { - testNaked(1L << i); - testNaked(-(1L << i)); + testNaked(1LL << i); + testNaked(-(1LL << i)); } testField(0); for (int i = 0; i < 62; i++) { - testField(1L << i); - testField(-(1L << i)); + testField(1LL << i); + testField(-(1LL << i)); } testNaked(123.456); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/AnnotationTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/AnnotationTest.cpp new file mode 100644 index 0000000..2e18840 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/AnnotationTest.cpp @@ -0,0 +1,68 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ +#define BOOST_TEST_MODULE AnnotationTest +#include +#include "gen-cpp/AnnotationTest_types.h" +#include +#include + +// Normally thrift generates ostream operators, however +// with the annotation "cpp.customostream" one can tell the +// compiler they are going to provide their own, and not +// emit operator << or printTo(). + +std::ostream& operator<<(std::ostream& os, const ostr_custom& osc) +{ + os << "{ bar = " << osc.bar << "; }"; + return os; +} + +BOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE) + +BOOST_AUTO_TEST_CASE(test_cpp_compiler_generated_ostream_operator) +{ + ostr_default def; + def.__set_bar(10); + + std::stringstream ssd; + ssd << def; + BOOST_CHECK_EQUAL(ssd.str(), "ostr_default(bar=10)"); +} + +BOOST_AUTO_TEST_CASE(test_cpp_customostream_uses_consuming_application_definition) +{ + ostr_custom cus; + cus.__set_bar(10); + + std::stringstream csd; + csd << cus; + BOOST_CHECK_EQUAL(csd.str(), "{ bar = 10; }"); +} + +/** + * Disabled; see THRIFT-1567 - not sure what it is supposed to do +BOOST_AUTO_TEST_CASE(test_cpp_type) { + // Check that the "cpp.type" annotation changes "struct foo" to "DenseFoo" + // This won't compile if the annotation is mishandled + DenseFoo foo; + foo.__set_bar(5); +} + */ + +BOOST_AUTO_TEST_SUITE_END() diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/Base64Test.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/Base64Test.cpp index e9e86dd..7686e4e 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/Base64Test.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/Base64Test.cpp @@ -37,6 +37,10 @@ void setupTestData(int i, uint8_t* data, int& len) { } void checkEncoding(uint8_t* data, int len) { +#ifdef NDEBUG + ((void)data); +#endif + for (int i = 0; i < len; i++) { BOOST_ASSERT(isalnum(data[i]) || data[i] == '/' || data[i] == '+'); } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/Benchmark.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/Benchmark.cpp index 69e6414..afde7d4 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/Benchmark.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/Benchmark.cpp @@ -23,8 +23,9 @@ #include #define _USE_MATH_DEFINES #include -#include "thrift/transport/TBufferTransports.h" #include "thrift/protocol/TBinaryProtocol.h" +#include "thrift/stdcxx.h" +#include "thrift/transport/TBufferTransports.h" #include "gen-cpp/DebugProtoTest_types.h" #ifdef HAVE_SYS_TIME_H @@ -48,11 +49,11 @@ public: }; int main() { - using namespace std; using namespace thrift::test::debug; using namespace apache::thrift::transport; using namespace apache::thrift::protocol; - using namespace boost; + using std::cout; + using std::endl; OneOfEach ooe; ooe.im_true = true; @@ -67,7 +68,7 @@ int main() { ooe.base64 = "\1\2\3\255"; int num = 100000; - boost::shared_ptr buf(new TMemoryBuffer(num*1000)); + apache::thrift::stdcxx::shared_ptr buf(new TMemoryBuffer(num*1000)); uint8_t* data = NULL; uint32_t datasize = 0; @@ -88,7 +89,7 @@ int main() { buf->getBuffer(&data, &datasize); { - boost::shared_ptr buf2(new TMemoryBuffer(data, datasize)); + apache::thrift::stdcxx::shared_ptr buf2(new TMemoryBuffer(data, datasize)); TBinaryProtocolT prot(buf2); OneOfEach ooe2; double elapsed = 0.0; @@ -116,7 +117,7 @@ int main() { { OneOfEach ooe2; - boost::shared_ptr buf2(new TMemoryBuffer(data, datasize)); + apache::thrift::stdcxx::shared_ptr buf2(new TMemoryBuffer(data, datasize)); TBinaryProtocolT prot(buf2); double elapsed = 0.0; Timer timer; @@ -142,7 +143,7 @@ int main() { } { - boost::shared_ptr buf2(new TMemoryBuffer(data, datasize)); + apache::thrift::stdcxx::shared_ptr buf2(new TMemoryBuffer(data, datasize)); TBinaryProtocolT prot(buf2); OneOfEach ooe2; double elapsed = 0.0; @@ -181,7 +182,7 @@ int main() { buf->getBuffer(&data, &datasize); { - boost::shared_ptr buf2(new TMemoryBuffer(data, datasize)); + apache::thrift::stdcxx::shared_ptr buf2(new TMemoryBuffer(data, datasize)); TBinaryProtocolT prot(buf2); ListDoublePerf listDoublePerf2; double elapsed = 0.0; @@ -205,7 +206,7 @@ int main() { { ListDoublePerf listDoublePerf2; - boost::shared_ptr buf2(new TMemoryBuffer(data, datasize)); + apache::thrift::stdcxx::shared_ptr buf2(new TMemoryBuffer(data, datasize)); TBinaryProtocolT prot(buf2); double elapsed = 0.0; Timer timer; @@ -227,7 +228,7 @@ int main() { } { - boost::shared_ptr buf2(new TMemoryBuffer(data, datasize)); + apache::thrift::stdcxx::shared_ptr buf2(new TMemoryBuffer(data, datasize)); TBinaryProtocolT prot(buf2); ListDoublePerf listDoublePerf2; double elapsed = 0.0; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/CMakeLists.txt b/vendor/git.apache.org/thrift.git/lib/cpp/test/CMakeLists.txt index cbeff08..261382f 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/CMakeLists.txt +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/CMakeLists.txt @@ -19,11 +19,17 @@ include_directories(SYSTEM "${Boost_INCLUDE_DIRS}") -#Make sure gen-cpp files can be included +if (WITH_DYN_LINK_TEST) + add_definitions( -DBOOST_TEST_DYN_LINK ) +endif() + +# Make sure gen-cpp files can be included include_directories("${CMAKE_CURRENT_BINARY_DIR}") # Create the thrift C++ test library set(testgencpp_SOURCES + gen-cpp/AnnotationTest_types.cpp + gen-cpp/AnnotationTest_types.h gen-cpp/DebugProtoTest_types.cpp gen-cpp/DebugProtoTest_types.h gen-cpp/EnumTest_types.cpp @@ -34,6 +40,10 @@ set(testgencpp_SOURCES gen-cpp/Recursive_types.h gen-cpp/ThriftTest_types.cpp gen-cpp/ThriftTest_types.h + gen-cpp/OneWayTest_types.cpp + gen-cpp/OneWayTest_types.h + gen-cpp/OneWayService.cpp + gen-cpp/OneWayService.h gen-cpp/TypedefTest_types.cpp gen-cpp/TypedefTest_types.h ThriftTest_extras.cpp @@ -54,7 +64,6 @@ set(testgencpp_cob_SOURCES ) add_library(testgencpp_cob STATIC ${testgencpp_cob_SOURCES}) - add_executable(Benchmark Benchmark.cpp) target_link_libraries(Benchmark testgencpp) LINK_AGAINST_THRIFT_LIBRARY(Benchmark thrift) @@ -63,6 +72,7 @@ target_link_libraries(Benchmark testgencpp) set(UnitTest_SOURCES UnitTestMain.cpp + OneWayHTTPTest.cpp TMemoryBufferTest.cpp TBufferBaseTest.cpp Base64Test.cpp @@ -72,8 +82,9 @@ set(UnitTest_SOURCES TServerTransportTest.cpp ) -if(NOT WITH_BOOSTTHREADS AND NOT WITH_STDTHREADS AND NOT MSVC) - list(APPEND UnitTest_SOURCES RWMutexStarveTest.cpp) +if(NOT WITH_BOOSTTHREADS AND NOT WITH_STDTHREADS AND NOT MSVC AND NOT MINGW) + list(APPEND UnitTest_SOURCES concurrency/MutexTest.cpp) + list(APPEND UnitTest_SOURCES concurrency/RWMutexStarveTest.cpp) endif() add_executable(UnitTests ${UnitTest_SOURCES}) @@ -105,7 +116,7 @@ LINK_AGAINST_THRIFT_LIBRARY(TInterruptTest thrift) if (NOT MSVC AND NOT ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" AND NOT MINGW) target_link_libraries(TInterruptTest -lrt) endif () -add_test(NAME TInterruptTest COMMAND TInterruptTest "${CMAKE_CURRENT_SOURCE_DIR}/../../../test/keys") +add_test(NAME TInterruptTest COMMAND TInterruptTest -- "${CMAKE_CURRENT_SOURCE_DIR}/../../../test/keys") add_executable(TServerIntegrationTest TServerIntegrationTest.cpp) target_link_libraries(TServerIntegrationTest @@ -141,6 +152,13 @@ LINK_AGAINST_THRIFT_LIBRARY(ZlibTest thriftz) add_test(NAME ZlibTest COMMAND ZlibTest) endif(WITH_ZLIB) +add_executable(AnnotationTest AnnotationTest.cpp) +target_link_libraries(AnnotationTest + testgencpp + ${Boost_LIBRARIES} +) +LINK_AGAINST_THRIFT_LIBRARY(AnnotationTest thrift) +add_test(NAME AnnotationTest COMMAND AnnotationTest) add_executable(EnumTest EnumTest.cpp) target_link_libraries(EnumTest @@ -283,7 +301,21 @@ target_link_libraries(TNonblockingServerTest LINK_AGAINST_THRIFT_LIBRARY(TNonblockingServerTest thrift) LINK_AGAINST_THRIFT_LIBRARY(TNonblockingServerTest thriftnb) add_test(NAME TNonblockingServerTest COMMAND TNonblockingServerTest) -endif() + +if(OPENSSL_FOUND AND WITH_OPENSSL) + set(TNonblockingSSLServerTest_SOURCES TNonblockingSSLServerTest.cpp) + add_executable(TNonblockingSSLServerTest ${TNonblockingSSLServerTest_SOURCES}) + include_directories(${LIBEVENT_INCLUDE_DIRS}) + target_link_libraries(TNonblockingSSLServerTest + testgencpp_cob + ${LIBEVENT_LIBRARIES} + ${Boost_LIBRARIES} + ) + LINK_AGAINST_THRIFT_LIBRARY(TNonblockingSSLServerTest thrift) + LINK_AGAINST_THRIFT_LIBRARY(TNonblockingSSLServerTest thriftnb) + add_test(NAME TNonblockingSSLServerTest COMMAND TNonblockingSSLServerTest -- "${CMAKE_CURRENT_SOURCE_DIR}/../../../test/keys") +endif(OPENSSL_FOUND AND WITH_OPENSSL) +endif(WITH_LIBEVENT) if(OPENSSL_FOUND AND WITH_OPENSSL) add_executable(OpenSSLManualInitTest OpenSSLManualInitTest.cpp) @@ -303,7 +335,7 @@ LINK_AGAINST_THRIFT_LIBRARY(SecurityTest thrift) if (NOT MSVC AND NOT ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" AND NOT MINGW) target_link_libraries(SecurityTest -lrt) endif () -add_test(NAME SecurityTest COMMAND SecurityTest "${CMAKE_CURRENT_SOURCE_DIR}/../../../test/keys") +add_test(NAME SecurityTest COMMAND SecurityTest -- "${CMAKE_CURRENT_SOURCE_DIR}/../../../test/keys") endif() @@ -327,8 +359,16 @@ endif() # Common thrift code generation rules # +add_custom_command(OUTPUT gen-cpp/AnnotationTest_constants.cpp + gen-cpp/AnnotationTest_constants.h + gen-cpp/AnnotationTest_types.cpp + gen-cpp/AnnotationTest_types.h + gen-cpp/foo_service.cpp + gen-cpp/foo_service.h + COMMAND ${THRIFT_COMPILER} --gen cpp ${PROJECT_SOURCE_DIR}/test/AnnotationTest.thrift +) -add_custom_command(OUTPUT gen-cpp/DebugProtoTest_types.cpp gen-cpp/DebugProtoTest_types.h gen-cpp/EmptyService.cpp gen-cpp/EmptyService.h +add_custom_command(OUTPUT gen-cpp/DebugProtoTest_types.cpp gen-cpp/DebugProtoTest_types.h gen-cpp/EmptyService.cpp gen-cpp/EmptyService.h COMMAND ${THRIFT_COMPILER} --gen cpp ${PROJECT_SOURCE_DIR}/test/DebugProtoTest.thrift ) @@ -356,6 +396,10 @@ add_custom_command(OUTPUT gen-cpp/SecondService.cpp gen-cpp/ThriftTest_constants COMMAND ${THRIFT_COMPILER} --gen cpp ${PROJECT_SOURCE_DIR}/test/ThriftTest.thrift ) +add_custom_command(OUTPUT gen-cpp/OneWayService.cpp gen-cpp/OneWayTest_constants.cpp gen-cpp/OneWayTest_types.h gen-cpp/OneWayService.h gen-cpp/OneWayTest_constants.h gen-cpp/OneWayTest_types.cpp + COMMAND ${THRIFT_COMPILER} --gen cpp ${CMAKE_CURRENT_SOURCE_DIR}/OneWayTest.thrift +) + add_custom_command(OUTPUT gen-cpp/ChildService.cpp gen-cpp/ChildService.h gen-cpp/ParentService.cpp gen-cpp/ParentService.h gen-cpp/proc_types.cpp gen-cpp/proc_types.h COMMAND ${THRIFT_COMPILER} --gen cpp:templates,cob_style ${CMAKE_CURRENT_SOURCE_DIR}/processor/proc.thrift ) diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/DebugProtoTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/DebugProtoTest.cpp index 607744b..e04600a 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/DebugProtoTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/DebugProtoTest.cpp @@ -21,13 +21,14 @@ #include #include "gen-cpp/DebugProtoTest_types.h" #include +#include #define BOOST_TEST_MODULE DebugProtoTest #include using namespace thrift::test::debug; -static std::auto_ptr ooe; +static ::apache::thrift::stdcxx::shared_ptr ooe; void testCaseSetup_1() { ooe.reset(new OneOfEach); @@ -80,7 +81,7 @@ BOOST_AUTO_TEST_CASE(test_debug_proto_1) { "Expected:\n" << expected_result << "\nGotten:\n" << result); } -static std::auto_ptr n; +static ::apache::thrift::stdcxx::shared_ptr n; void testCaseSetup_2() { testCaseSetup_1(); @@ -148,7 +149,7 @@ BOOST_AUTO_TEST_CASE(test_debug_proto_2) { "Expected:\n" << expected_result << "\nGotten:\n" << result); } -static std::auto_ptr hm; +static ::apache::thrift::stdcxx::shared_ptr hm; void testCaseSetup_3() { testCaseSetup_2(); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/EnumTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/EnumTest.cpp index 0e34b16..c935bc4 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/EnumTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/EnumTest.cpp @@ -20,9 +20,15 @@ #include #include "gen-cpp/EnumTest_types.h" +std::ostream& operator <<(std::ostream& os, const MyEnumWithCustomOstream::type& val) +{ + os << "{" << (int)val << ":CUSTOM!" << "}"; + return os; +} + BOOST_AUTO_TEST_SUITE(EnumTest) -BOOST_AUTO_TEST_CASE(test_enum) { +BOOST_AUTO_TEST_CASE(test_enum_value) { // Check that all the enum values match what we expect BOOST_CHECK_EQUAL(MyEnum1::ME1_0, 0); BOOST_CHECK_EQUAL(MyEnum1::ME1_1, 1); @@ -47,9 +53,34 @@ BOOST_AUTO_TEST_CASE(test_enum) { BOOST_CHECK_EQUAL(MyEnum4::ME4_A, 0x7ffffffd); BOOST_CHECK_EQUAL(MyEnum4::ME4_B, 0x7ffffffe); BOOST_CHECK_EQUAL(MyEnum4::ME4_C, 0x7fffffff); + + BOOST_CHECK_EQUAL(MyEnum5::e1, 0); + BOOST_CHECK_EQUAL(MyEnum5::e2, 42); } -BOOST_AUTO_TEST_CASE(test_enum_constant) { +template +std::string EnumToString(_T e) +{ + std::stringstream ss; + ss << e; + return ss.str(); +} + + +BOOST_AUTO_TEST_CASE(test_enum_ostream) +{ + BOOST_CHECK_EQUAL(EnumToString(MyEnum1::ME1_0), "ME1_0"); + BOOST_CHECK_EQUAL(EnumToString(MyEnum5::e2), "e2"); + BOOST_CHECK_EQUAL(EnumToString(MyEnum3::ME3_N1), "ME3_N1"); + BOOST_CHECK_EQUAL(EnumToString(MyEnumWithCustomOstream::CustoM2), "{2:CUSTOM!}"); + + // some invalid or unknown value + MyEnum5::type uut = (MyEnum5::type)44; + BOOST_CHECK_EQUAL(EnumToString(uut), "44"); +} + +BOOST_AUTO_TEST_CASE(test_enum_constant) +{ MyStruct ms; BOOST_CHECK_EQUAL(ms.me2_2, 2); BOOST_CHECK_EQUAL(ms.me3_n2, -2); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/GenericHelpers.h b/vendor/git.apache.org/thrift.git/lib/cpp/test/GenericHelpers.h index c175561..e131c42 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/GenericHelpers.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/GenericHelpers.h @@ -20,13 +20,10 @@ #ifndef _THRIFT_TEST_GENERICHELPERS_H_ #define _THRIFT_TEST_GENERICHELPERS_H_ 1 -#include -#include +#include +#include #include -using boost::shared_ptr; -using namespace apache::thrift::protocol; - /* ClassName Helper for cleaner exceptions */ class ClassNames { public: @@ -66,43 +63,43 @@ class GenericIO { public: /* Write functions */ - static uint32_t write(shared_ptr proto, const int8_t& val) { + static uint32_t write(apache::thrift::stdcxx::shared_ptr proto, const int8_t& val) { return proto->writeByte(val); } - static uint32_t write(shared_ptr proto, const int16_t& val) { + static uint32_t write(apache::thrift::stdcxx::shared_ptr proto, const int16_t& val) { return proto->writeI16(val); } - static uint32_t write(shared_ptr proto, const int32_t& val) { + static uint32_t write(apache::thrift::stdcxx::shared_ptr proto, const int32_t& val) { return proto->writeI32(val); } - static uint32_t write(shared_ptr proto, const double& val) { + static uint32_t write(apache::thrift::stdcxx::shared_ptr proto, const double& val) { return proto->writeDouble(val); } - static uint32_t write(shared_ptr proto, const int64_t& val) { + static uint32_t write(apache::thrift::stdcxx::shared_ptr proto, const int64_t& val) { return proto->writeI64(val); } - static uint32_t write(shared_ptr proto, const std::string& val) { + static uint32_t write(apache::thrift::stdcxx::shared_ptr proto, const std::string& val) { return proto->writeString(val); } /* Read functions */ - static uint32_t read(shared_ptr proto, int8_t& val) { return proto->readByte(val); } + static uint32_t read(apache::thrift::stdcxx::shared_ptr proto, int8_t& val) { return proto->readByte(val); } - static uint32_t read(shared_ptr proto, int16_t& val) { return proto->readI16(val); } + static uint32_t read(apache::thrift::stdcxx::shared_ptr proto, int16_t& val) { return proto->readI16(val); } - static uint32_t read(shared_ptr proto, int32_t& val) { return proto->readI32(val); } + static uint32_t read(apache::thrift::stdcxx::shared_ptr proto, int32_t& val) { return proto->readI32(val); } - static uint32_t read(shared_ptr proto, int64_t& val) { return proto->readI64(val); } + static uint32_t read(apache::thrift::stdcxx::shared_ptr proto, int64_t& val) { return proto->readI64(val); } - static uint32_t read(shared_ptr proto, double& val) { return proto->readDouble(val); } + static uint32_t read(apache::thrift::stdcxx::shared_ptr proto, double& val) { return proto->readDouble(val); } - static uint32_t read(shared_ptr proto, std::string& val) { + static uint32_t read(apache::thrift::stdcxx::shared_ptr proto, std::string& val) { return proto->readString(val); } }; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/JSONProtoTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/JSONProtoTest.cpp index 301a064..77bc250 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/JSONProtoTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/JSONProtoTest.cpp @@ -21,18 +21,20 @@ #include #include #include -#include #include +#include +#include #include "gen-cpp/DebugProtoTest_types.h" #define BOOST_TEST_MODULE JSONProtoTest #include using namespace thrift::test::debug; +using namespace apache::thrift; using apache::thrift::transport::TMemoryBuffer; using apache::thrift::protocol::TJSONProtocol; -static std::auto_ptr ooe; +static stdcxx::shared_ptr ooe; void testCaseSetup_1() { ooe.reset(new OneOfEach); @@ -65,7 +67,7 @@ BOOST_AUTO_TEST_CASE(test_json_proto_1) { "Expected:\n" << expected_result << "\nGotten:\n" << result); } -static std::auto_ptr n; +static stdcxx::shared_ptr n; void testCaseSetup_2() { testCaseSetup_1(); @@ -105,7 +107,7 @@ BOOST_AUTO_TEST_CASE(test_json_proto_2) { "Expected:\n" << expected_result << "\nGotten:\n" << result); } -static std::auto_ptr hm; +static stdcxx::shared_ptr hm; void testCaseSetup_3() { testCaseSetup_2(); @@ -183,8 +185,8 @@ BOOST_AUTO_TEST_CASE(test_json_proto_3) { BOOST_AUTO_TEST_CASE(test_json_proto_4) { testCaseSetup_1(); - boost::shared_ptr buffer(new TMemoryBuffer()); - boost::shared_ptr proto(new TJSONProtocol(buffer)); + stdcxx::shared_ptr buffer(new TMemoryBuffer()); + stdcxx::shared_ptr proto(new TJSONProtocol(buffer)); ooe->write(proto.get()); OneOfEach ooe2; @@ -196,8 +198,8 @@ BOOST_AUTO_TEST_CASE(test_json_proto_4) { BOOST_AUTO_TEST_CASE(test_json_proto_5) { testCaseSetup_3(); - boost::shared_ptr buffer(new TMemoryBuffer()); - boost::shared_ptr proto(new TJSONProtocol(buffer)); + stdcxx::shared_ptr buffer(new TMemoryBuffer()); + stdcxx::shared_ptr proto(new TJSONProtocol(buffer)); hm->write(proto.get()); HolyMoley hm2; @@ -234,8 +236,8 @@ BOOST_AUTO_TEST_CASE(test_json_proto_6) { } BOOST_AUTO_TEST_CASE(test_json_proto_7) { - boost::shared_ptr buffer(new TMemoryBuffer()); - boost::shared_ptr proto(new TJSONProtocol(buffer)); + stdcxx::shared_ptr buffer(new TMemoryBuffer()); + stdcxx::shared_ptr proto(new TJSONProtocol(buffer)); Base64 base; base.a = 123; @@ -262,9 +264,10 @@ BOOST_AUTO_TEST_CASE(test_json_proto_8) { ":[\"i8\",3,1,2,3]},\"13\":{\"lst\":[\"i16\",3,1,2,3]},\"14\":{\"lst\":[\"i64" "\",3,1,2,3]}}"; - boost::shared_ptr buffer(new TMemoryBuffer( - (uint8_t*)(json_string), strlen(json_string)*sizeof(char))); - boost::shared_ptr proto(new TJSONProtocol(buffer)); + const std::size_t bufSiz = strlen(json_string) * sizeof(char); + stdcxx::shared_ptr buffer(new TMemoryBuffer( + (uint8_t*)(json_string), static_cast(bufSiz))); + stdcxx::shared_ptr proto(new TJSONProtocol(buffer)); OneOfEach ooe2; @@ -291,9 +294,9 @@ BOOST_AUTO_TEST_CASE(test_json_unicode_escaped) { "\",3,1,2,3]}}"; const char* expected_zomg_unicode = "\xe0\xb8\x81 \xf0\x9d\x94\xbe"; - boost::shared_ptr buffer(new TMemoryBuffer( + stdcxx::shared_ptr buffer(new TMemoryBuffer( (uint8_t*)(json_string), sizeof(json_string))); - boost::shared_ptr proto(new TJSONProtocol(buffer)); + stdcxx::shared_ptr proto(new TJSONProtocol(buffer)); OneOfEach ooe2; ooe2.read(proto.get()); @@ -312,9 +315,9 @@ BOOST_AUTO_TEST_CASE(test_json_unicode_escaped_missing_low_surrogate) { ":[\"i8\",3,1,2,3]},\"13\":{\"lst\":[\"i16\",3,1,2,3]},\"14\":{\"lst\":[\"i64" "\",3,1,2,3]}}"; - boost::shared_ptr buffer(new TMemoryBuffer( + stdcxx::shared_ptr buffer(new TMemoryBuffer( (uint8_t*)(json_string), sizeof(json_string))); - boost::shared_ptr proto(new TJSONProtocol(buffer)); + stdcxx::shared_ptr proto(new TJSONProtocol(buffer)); OneOfEach ooe2; BOOST_CHECK_THROW(ooe2.read(proto.get()), @@ -330,9 +333,9 @@ BOOST_AUTO_TEST_CASE(test_json_unicode_escaped_missing_hi_surrogate) { ":[\"i8\",3,1,2,3]},\"13\":{\"lst\":[\"i16\",3,1,2,3]},\"14\":{\"lst\":[\"i64" "\",3,1,2,3]}}"; - boost::shared_ptr buffer(new TMemoryBuffer( + stdcxx::shared_ptr buffer(new TMemoryBuffer( (uint8_t*)(json_string), sizeof(json_string))); - boost::shared_ptr proto(new TJSONProtocol(buffer)); + stdcxx::shared_ptr proto(new TJSONProtocol(buffer)); OneOfEach ooe2; BOOST_CHECK_THROW(ooe2.read(proto.get()), diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/Makefile.am b/vendor/git.apache.org/thrift.git/lib/cpp/test/Makefile.am index 6f46117..4b9f77d 100755 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/Makefile.am +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/Makefile.am @@ -18,7 +18,8 @@ # AUTOMAKE_OPTIONS = subdir-objects serial-tests -BUILT_SOURCES = gen-cpp/DebugProtoTest_types.h \ +BUILT_SOURCES = gen-cpp/AnnotationTest_types.h \ + gen-cpp/DebugProtoTest_types.h \ gen-cpp/EnumTest_types.h \ gen-cpp/OptionalRequiredTest_types.h \ gen-cpp/Recursive_types.h \ @@ -27,12 +28,19 @@ BUILT_SOURCES = gen-cpp/DebugProtoTest_types.h \ gen-cpp/ChildService.h \ gen-cpp/EmptyService.h \ gen-cpp/ParentService.h \ + gen-cpp/OneWayTest_types.h \ + gen-cpp/OneWayService.h \ + gen-cpp/OneWayTest_constants.h \ gen-cpp/proc_types.h noinst_LTLIBRARIES = libtestgencpp.la libprocessortest.la nodist_libtestgencpp_la_SOURCES = \ + gen-cpp/AnnotationTest_types.cpp \ + gen-cpp/AnnotationTest_types.h \ gen-cpp/DebugProtoTest_types.cpp \ gen-cpp/DebugProtoTest_types.h \ + gen-cpp/DoubleConstantsTest_constants.cpp \ + gen-cpp/DoubleConstantsTest_constants.h \ gen-cpp/EnumTest_types.cpp \ gen-cpp/EnumTest_types.h \ gen-cpp/OptionalRequiredTest_types.cpp \ @@ -45,6 +53,12 @@ nodist_libtestgencpp_la_SOURCES = \ gen-cpp/ThriftTest_constants.h \ gen-cpp/TypedefTest_types.cpp \ gen-cpp/TypedefTest_types.h \ + gen-cpp/OneWayService.cpp \ + gen-cpp/OneWayTest_constants.cpp \ + gen-cpp/OneWayTest_types.h \ + gen-cpp/OneWayService.h \ + gen-cpp/OneWayTest_constants.h \ + gen-cpp/OneWayTest_types.cpp \ ThriftTest_extras.cpp \ DebugProtoTest_extras.cpp @@ -89,13 +103,16 @@ check_PROGRAMS = \ TFileTransportTest \ link_test \ OpenSSLManualInitTest \ - EnumTest + EnumTest \ + RenderedDoubleConstantsTest \ + AnnotationTest if AMX_HAVE_LIBEVENT noinst_PROGRAMS += \ processor_test check_PROGRAMS += \ - TNonblockingServerTest + TNonblockingServerTest \ + TNonblockingSSLServerTest endif TESTS_ENVIRONMENT= \ @@ -108,6 +125,7 @@ TESTS = \ UnitTests_SOURCES = \ UnitTestMain.cpp \ + OneWayHTTPTest.cpp \ TMemoryBufferTest.cpp \ TBufferBaseTest.cpp \ Base64Test.cpp \ @@ -119,12 +137,15 @@ UnitTests_SOURCES = \ if !WITH_BOOSTTHREADS UnitTests_SOURCES += \ - RWMutexStarveTest.cpp + concurrency/MutexTest.cpp \ + concurrency/RWMutexStarveTest.cpp endif UnitTests_LDADD = \ libtestgencpp.la \ - $(BOOST_TEST_LDADD) + $(BOOST_TEST_LDADD) \ + $(BOOST_SYSTEM_LDADD) \ + $(BOOST_THREAD_LDADD) TInterruptTest_SOURCES = \ TSocketInterruptTest.cpp \ @@ -178,12 +199,23 @@ ZlibTest_LDADD = \ -lz EnumTest_SOURCES = \ - EnumTest.cpp + EnumTest.cpp EnumTest_LDADD = \ libtestgencpp.la \ $(BOOST_TEST_LDADD) +RenderedDoubleConstantsTest_SOURCES = RenderedDoubleConstantsTest.cpp + +RenderedDoubleConstantsTest_LDADD = libtestgencpp.la $(BOOST_TEST_LDADD) + +AnnotationTest_SOURCES = \ + AnnotationTest.cpp + +AnnotationTest_LDADD = \ + libtestgencpp.la \ + $(BOOST_TEST_LDADD) + TFileTransportTest_SOURCES = \ TFileTransportTest.cpp @@ -260,6 +292,21 @@ TNonblockingServerTest_LDADD = libprocessortest.la \ $(BOOST_TEST_LDADD) \ $(BOOST_LDFLAGS) \ $(LIBEVENT_LIBS) +# +# TNonblockingSSLServerTest +# +TNonblockingSSLServerTest_SOURCES = TNonblockingSSLServerTest.cpp + +TNonblockingSSLServerTest_LDADD = libprocessortest.la \ + $(top_builddir)/lib/cpp/libthrift.la \ + $(top_builddir)/lib/cpp/libthriftnb.la \ + $(BOOST_TEST_LDADD) \ + $(BOOST_LDFLAGS) \ + $(BOOST_FILESYSTEM_LDADD) \ + $(BOOST_CHRONO_LDADD) \ + $(BOOST_SYSTEM_LDADD) \ + $(BOOST_THREAD_LDADD) \ + $(LIBEVENT_LIBS) # # OptionalRequiredTest @@ -332,11 +379,17 @@ OpenSSLManualInitTest_LDADD = \ # # Common thrift code generation rules # -THRIFT = $(top_builddir)/compiler/cpp/thrift + +gen-cpp/AnnotationTest_constants.cpp gen-cpp/AnnotationTest_constants.h gen-cpp/AnnotationTest_types.cpp gen-cpp/AnnotationTest_types.h: $(top_srcdir)/test/AnnotationTest.thrift + $(THRIFT) --gen cpp $< gen-cpp/DebugProtoTest_types.cpp gen-cpp/DebugProtoTest_types.h gen-cpp/EmptyService.cpp gen-cpp/EmptyService.h: $(top_srcdir)/test/DebugProtoTest.thrift $(THRIFT) --gen cpp $< +gen-cpp/DoubleConstantsTest_constants.cpp gen-cpp/DoubleConstantsTest_constants.h: $(top_srcdir)/test/DoubleConstantsTest.thrift + $(THRIFT) --gen cpp $< + + gen-cpp/EnumTest_types.cpp gen-cpp/EnumTest_types.h: $(top_srcdir)/test/EnumTest.thrift $(THRIFT) --gen cpp $< @@ -355,10 +408,13 @@ gen-cpp/Service.cpp gen-cpp/StressTest_types.cpp: $(top_srcdir)/test/StressTest. gen-cpp/SecondService.cpp gen-cpp/ThriftTest_constants.cpp gen-cpp/ThriftTest.cpp gen-cpp/ThriftTest_types.cpp gen-cpp/ThriftTest_types.h: $(top_srcdir)/test/ThriftTest.thrift $(THRIFT) --gen cpp $< +gen-cpp/OneWayService.cpp gen-cpp/OneWayTest_constants.cpp gen-cpp/OneWayTest_types.h gen-cpp/OneWayService.h gen-cpp/OneWayTest_constants.h gen-cpp/OneWayTest_types.cpp: OneWayTest.thrift + $(THRIFT) --gen cpp $< + gen-cpp/ChildService.cpp gen-cpp/ChildService.h gen-cpp/ParentService.cpp gen-cpp/ParentService.h gen-cpp/proc_types.cpp gen-cpp/proc_types.h: processor/proc.thrift $(THRIFT) --gen cpp:templates,cob_style $< -AM_CPPFLAGS = $(BOOST_CPPFLAGS) -I$(top_srcdir)/lib/cpp/src -D__STDC_LIMIT_MACROS -I. +AM_CPPFLAGS = $(BOOST_CPPFLAGS) -I$(top_srcdir)/lib/cpp/src -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -I. AM_LDFLAGS = $(BOOST_LDFLAGS) AM_CXXFLAGS = -Wall -Wextra -pedantic @@ -371,4 +427,5 @@ EXTRA_DIST = \ qt \ CMakeLists.txt \ DebugProtoTest_extras.cpp \ - ThriftTest_extras.cpp + ThriftTest_extras.cpp \ + OneWayTest.thrift diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/OneWayHTTPTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/OneWayHTTPTest.cpp new file mode 100644 index 0000000..3fe63b6 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/OneWayHTTPTest.cpp @@ -0,0 +1,242 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "gen-cpp/OneWayService.h" + +BOOST_AUTO_TEST_SUITE(OneWayHTTPTest) + +using namespace apache::thrift; +using apache::thrift::protocol::TProtocol; +using apache::thrift::protocol::TBinaryProtocol; +using apache::thrift::protocol::TBinaryProtocolFactory; +using apache::thrift::protocol::TJSONProtocol; +using apache::thrift::protocol::TJSONProtocolFactory; +using apache::thrift::server::TThreadedServer; +using apache::thrift::server::TServerEventHandler; +using apache::thrift::transport::TTransport; +using apache::thrift::transport::THttpServer; +using apache::thrift::transport::THttpServerTransportFactory; +using apache::thrift::transport::THttpClient; +using apache::thrift::transport::TBufferedTransport; +using apache::thrift::transport::TBufferedTransportFactory; +using apache::thrift::transport::TMemoryBuffer; +using apache::thrift::transport::TServerSocket; +using apache::thrift::transport::TSocket; +using apache::thrift::transport::TTransportException; +using apache::thrift::stdcxx::shared_ptr; +using std::cout; +using std::cerr; +using std::endl; +using std::string; +namespace utf = boost::unit_test; + +// Define this env var to enable some logging (in case you need to debug) +#undef ENABLE_STDERR_LOGGING + +class OneWayServiceHandler : public onewaytest::OneWayServiceIf { +public: + OneWayServiceHandler() {} + + void roundTripRPC() override { +#ifdef ENABLE_STDERR_LOGGING + cerr << "roundTripRPC()" << endl; +#endif + } + void oneWayRPC() { +#ifdef ENABLE_STDERR_LOGGING + cerr << "oneWayRPC()" << std::endl ; +#endif + } +}; + +class OneWayServiceCloneFactory : virtual public onewaytest::OneWayServiceIfFactory { + public: + virtual ~OneWayServiceCloneFactory() {} + virtual onewaytest::OneWayServiceIf* getHandler(const ::apache::thrift::TConnectionInfo& connInfo) + { + (void)connInfo ; + return new OneWayServiceHandler; + } + virtual void releaseHandler( onewaytest::OneWayServiceIf* handler) { + delete handler; + } +}; + +class RPC0ThreadClass { +public: + RPC0ThreadClass(TThreadedServer& server) : server_(server) { } // Constructor +~RPC0ThreadClass() { } // Destructor + +void Run() { + server_.serve() ; +} + TThreadedServer& server_ ; +} ; + +using apache::thrift::concurrency::Monitor; +using apache::thrift::concurrency::Mutex; +using apache::thrift::concurrency::Synchronized; + +// copied from IntegrationTest +class TServerReadyEventHandler : public TServerEventHandler, public Monitor { +public: + TServerReadyEventHandler() : isListening_(false), accepted_(0) {} + virtual ~TServerReadyEventHandler() {} + virtual void preServe() { + Synchronized sync(*this); + isListening_ = true; + notify(); + } + virtual void* createContext(shared_ptr input, + shared_ptr output) { + Synchronized sync(*this); + ++accepted_; + notify(); + + (void)input; + (void)output; + return NULL; + } + bool isListening() const { return isListening_; } + uint64_t acceptedCount() const { return accepted_; } + +private: + bool isListening_; + uint64_t accepted_; +}; + +class TBlockableBufferedTransport : public TBufferedTransport { + public: + TBlockableBufferedTransport(stdcxx::shared_ptr transport) + : TBufferedTransport(transport, 10240), + blocked_(false) { + } + + uint32_t write_buffer_length() { + uint32_t have_bytes = static_cast(wBase_ - wBuf_.get()); + return have_bytes ; + } + + void block() { + blocked_ = true ; +#ifdef ENABLE_STDERR_LOGGING + cerr << "block flushing\n" ; +#endif + } + void unblock() { + blocked_ = false ; +#ifdef ENABLE_STDERR_LOGGING + cerr << "unblock flushing, buffer is\n<<" << std::string((char *)wBuf_.get(), write_buffer_length()) << ">>\n" ; +#endif + } + + void flush() override { + if (blocked_) { +#ifdef ENABLE_STDERR_LOGGING + cerr << "flush was blocked\n" ; +#endif + return ; + } + TBufferedTransport::flush() ; + } + + bool blocked_ ; +} ; + +BOOST_AUTO_TEST_CASE( JSON_BufferedHTTP ) +{ + stdcxx::shared_ptr ss = stdcxx::make_shared(0) ; + TThreadedServer server( + stdcxx::make_shared(stdcxx::make_shared()), + ss, //port + stdcxx::make_shared(), + stdcxx::make_shared()); + + stdcxx::shared_ptr pEventHandler(new TServerReadyEventHandler) ; + server.setServerEventHandler(pEventHandler); + +#ifdef ENABLE_STDERR_LOGGING + cerr << "Starting the server...\n"; +#endif + RPC0ThreadClass t(server) ; + boost::thread thread(&RPC0ThreadClass::Run, &t); + + { + Synchronized sync(*(pEventHandler.get())); + while (!pEventHandler->isListening()) { + pEventHandler->wait(); + } + } + + int port = ss->getPort() ; +#ifdef ENABLE_STDERR_LOGGING + cerr << "port " << port << endl ; +#endif + + { + stdcxx::shared_ptr socket(new TSocket("localhost", port)); + socket->setRecvTimeout(10000) ; // 1000msec should be enough + stdcxx::shared_ptr blockable_transport(new TBlockableBufferedTransport(socket)); + stdcxx::shared_ptr transport(new THttpClient(blockable_transport, "localhost", "/service")); + stdcxx::shared_ptr protocol(new TJSONProtocol(transport)); + onewaytest::OneWayServiceClient client(protocol); + + + transport->open(); + client.roundTripRPC(); + blockable_transport->block() ; + uint32_t size0 = blockable_transport->write_buffer_length() ; + client.send_oneWayRPC() ; + uint32_t size1 = blockable_transport->write_buffer_length() ; + client.send_oneWayRPC() ; + uint32_t size2 = blockable_transport->write_buffer_length() ; + BOOST_CHECK((size1 - size0) == (size2 - size1)) ; + blockable_transport->unblock() ; + client.send_roundTripRPC() ; + blockable_transport->flush() ; + try { + client.recv_roundTripRPC() ; + } catch (TTransportException e) { + BOOST_ERROR( "we should not get a transport exception -- this means we failed: " + std::string(e.what()) ) ; + } + transport->close(); + } + server.stop(); + thread.join() ; +#ifdef ENABLE_STDERR_LOGGING + cerr << "finished.\n"; +#endif +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/OneWayTest.thrift b/vendor/git.apache.org/thrift.git/lib/cpp/test/OneWayTest.thrift new file mode 100644 index 0000000..127e9ff --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/OneWayTest.thrift @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + * + * Contains some contributions under the Thrift Software License. + * Please see doc/old-thrift-license.txt in the Thrift distribution for + * details. + */ + +namespace c_glib OneWayTest +namespace java onewaytest +namespace cpp onewaytest +namespace rb Onewaytest +namespace perl OneWayTest +namespace csharp Onewaytest +namespace js OneWayTest +namespace st OneWayTest +namespace py OneWayTest +namespace py.twisted OneWayTest +namespace go onewaytest +namespace php OneWayTest +namespace delphi Onewaytest +namespace cocoa OneWayTest +namespace lua OneWayTest +namespace xsd test (uri = 'http://thrift.apache.org/ns/OneWayTest') +namespace netcore ThriftAsync.OneWayTest + +// a minimal Thrift service, for use in OneWayHTTPTtest.cpp +service OneWayService { + void roundTripRPC(), + oneway void oneWayRPC() +} diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/OpenSSLManualInitTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/OpenSSLManualInitTest.cpp index 5cd5e48..a30b303 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/OpenSSLManualInitTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/OpenSSLManualInitTest.cpp @@ -28,7 +28,6 @@ #include #include -using namespace std; using namespace apache::thrift::transport; void make_isolated_sslsocketfactory() { diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/OptionalRequiredTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/OptionalRequiredTest.cpp index b0e5ef7..55fe249 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/OptionalRequiredTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/OptionalRequiredTest.cpp @@ -40,7 +40,7 @@ template void trywrite(const Struct& s, bool should_work) { bool worked; try { - TBinaryProtocol protocol(boost::shared_ptr(new TMemoryBuffer)); + TBinaryProtocol protocol(stdcxx::shared_ptr(new TMemoryBuffer)); s.write(&protocol); worked = true; } catch (TProtocolException & ex) { @@ -52,7 +52,7 @@ void trywrite(const Struct& s, bool should_work) { template void write_to_read(const Struct1& w, Struct2& r) { - TBinaryProtocol protocol(boost::shared_ptr(new TMemoryBuffer)); + TBinaryProtocol protocol(stdcxx::shared_ptr(new TMemoryBuffer)); w.write(&protocol); r.read(&protocol); } @@ -303,7 +303,7 @@ BOOST_AUTO_TEST_CASE(test_optional_required_11) { o1.im_big.push_back(mymap); BOOST_CHECK(o1 == o2); - TBinaryProtocol protocol(boost::shared_ptr(new TMemoryBuffer)); + TBinaryProtocol protocol(stdcxx::shared_ptr(new TMemoryBuffer)); o1.write(&protocol); o1.im_big.push_back(mymap); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/RecursiveTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/RecursiveTest.cpp index e3e3f50..ce5569b 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/RecursiveTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/RecursiveTest.cpp @@ -22,20 +22,21 @@ */ #include "gen-cpp/Recursive_types.h" -#include #include +#include +#include #define BOOST_TEST_MODULE RecursiveTest #include using apache::thrift::transport::TMemoryBuffer; using apache::thrift::protocol::TBinaryProtocol; -using boost::shared_ptr; +using apache::thrift::stdcxx::shared_ptr; BOOST_AUTO_TEST_CASE(test_recursive_1) { shared_ptr buf(new TMemoryBuffer()); shared_ptr prot(new TBinaryProtocol(buf)); - + RecTree tree; RecTree child; tree.children.push_back(child); @@ -50,9 +51,9 @@ BOOST_AUTO_TEST_CASE(test_recursive_1) { BOOST_AUTO_TEST_CASE(test_recursive_2) { shared_ptr buf(new TMemoryBuffer()); shared_ptr prot(new TBinaryProtocol(buf)); - + RecList l; - boost::shared_ptr l2(new RecList); + shared_ptr l2(new RecList); l.nextitem = l2; l.write(prot.get()); @@ -68,7 +69,7 @@ BOOST_AUTO_TEST_CASE(test_recursive_3) { shared_ptr prot(new TBinaryProtocol(buf)); CoRec c; - boost::shared_ptr r(new CoRec2); + shared_ptr r(new CoRec2); c.other = r; c.write(prot.get()); @@ -82,7 +83,7 @@ BOOST_AUTO_TEST_CASE(test_recursive_4) { shared_ptr buf(new TMemoryBuffer()); shared_ptr prot(new TBinaryProtocol(buf)); - boost::shared_ptr depthLimit(new RecList); + shared_ptr depthLimit(new RecList); depthLimit->nextitem = depthLimit; BOOST_CHECK_THROW(depthLimit->write(prot.get()), apache::thrift::protocol::TProtocolException); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/RenderedDoubleConstantsTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/RenderedDoubleConstantsTest.cpp new file mode 100644 index 0000000..0ca042b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/RenderedDoubleConstantsTest.cpp @@ -0,0 +1,122 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ +#define EPSILON 0.0000001 +#include +#include +#include + +#include "gen-cpp/DoubleConstantsTest_constants.h" +using namespace thrift::test; + +#define BOOST_TEST_MODULE RenderedDoubleConstantsTest +#include + +BOOST_AUTO_TEST_SUITE(RenderedDoubleConstantsTest) + +BOOST_AUTO_TEST_CASE(test_rendered_double_constants) { + const double EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT = 1.0; + const double EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT = -100.0; + const double EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT = 9223372036854775807.0; + const double EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT = -9223372036854775807.0; + const double EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS = 3.14159265359; + const double EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE = 1000000.1; + const double EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE = -1000000.1; + const double EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE = 1.7e+308; + const double EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE = 9223372036854775816.43; + const double EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE = -1.7e+308; + const double EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE = -9223372036854775816.43; + BOOST_CHECK_CLOSE( + g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT, EPSILON); + BOOST_CHECK_CLOSE( + g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT, EPSILON); + BOOST_CHECK_CLOSE( + g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT, EPSILON); + BOOST_CHECK_CLOSE( + g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT, EPSILON); + BOOST_CHECK_CLOSE( + g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS, EPSILON); + BOOST_CHECK_CLOSE( + g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE, EPSILON); + BOOST_CHECK_CLOSE( + g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE, EPSILON); + BOOST_CHECK_CLOSE( + g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE, EPSILON); + BOOST_CHECK_CLOSE( + g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE, EPSILON); + BOOST_CHECK_CLOSE( + g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE, EPSILON); + BOOST_CHECK_CLOSE( + g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE, EPSILON); + BOOST_CHECK( + typeid(g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST).hash_code() == + typeid(EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT).hash_code()); + BOOST_CHECK( + typeid(g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST).hash_code() == + typeid(EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT).hash_code()); + BOOST_CHECK( + typeid(g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST).hash_code() == + typeid(EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT).hash_code()); + BOOST_CHECK( + typeid(g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST).hash_code() == + typeid(EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT).hash_code()); + BOOST_CHECK( + typeid(g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST).hash_code() == + typeid(EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS).hash_code()); + BOOST_CHECK( + typeid(g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST).hash_code() == + typeid(EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE).hash_code()); + BOOST_CHECK( + typeid(g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST).hash_code() == + typeid(EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE).hash_code()); + BOOST_CHECK( + typeid(g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST).hash_code() == + typeid(EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE).hash_code()); + BOOST_CHECK( + typeid(g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST).hash_code() == + typeid(EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE).hash_code()); + BOOST_CHECK( + typeid(g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST).hash_code() == + typeid(EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE).hash_code()); + BOOST_CHECK( + typeid(g_DoubleConstantsTest_constants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST) + .hash_code() == + typeid(EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE).hash_code()); +} + +BOOST_AUTO_TEST_CASE(test_rendered_double_list) { + const std::vector EXPECTED_DOUBLE_LIST{1.0,-100.0,100.0,9223372036854775807.0,-9223372036854775807.0, + 3.14159265359,1000000.1,-1000000.1,1.7e+308,-1.7e+308,9223372036854775816.43,-9223372036854775816.43}; + BOOST_CHECK_EQUAL(g_DoubleConstantsTest_constants.DOUBLE_LIST_TEST.size(), EXPECTED_DOUBLE_LIST.size()); + for (unsigned int i = 0; i < EXPECTED_DOUBLE_LIST.size(); ++i) { + BOOST_CHECK_CLOSE(g_DoubleConstantsTest_constants.DOUBLE_LIST_TEST[i], EXPECTED_DOUBLE_LIST[i], EPSILON); + } +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/SecurityTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/SecurityTest.cpp index 23650d6..51ee427 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/SecurityTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/SecurityTest.cpp @@ -19,13 +19,11 @@ #define BOOST_TEST_MODULE SecurityTest #include -#include #include #include #include -#include -#include #include +#include #include #include #include @@ -42,6 +40,9 @@ using apache::thrift::transport::TTransport; using apache::thrift::transport::TTransportException; using apache::thrift::transport::TTransportFactory; +using apache::thrift::stdcxx::bind; +using apache::thrift::stdcxx::shared_ptr; + boost::filesystem::path keyDir; boost::filesystem::path certFile(const std::string& filename) { @@ -54,36 +55,36 @@ struct GlobalFixture GlobalFixture() { using namespace boost::unit_test::framework; - for (int i = 0; i < master_test_suite().argc; ++i) - { - BOOST_TEST_MESSAGE(boost::format("argv[%1%] = \"%2%\"") % i % master_test_suite().argv[i]); - } + for (int i = 0; i < master_test_suite().argc; ++i) + { + BOOST_TEST_MESSAGE(boost::format("argv[%1%] = \"%2%\"") % i % master_test_suite().argv[i]); + } #ifdef __linux__ - // OpenSSL calls send() without MSG_NOSIGPIPE so writing to a socket that has - // disconnected can cause a SIGPIPE signal... - signal(SIGPIPE, SIG_IGN); + // OpenSSL calls send() without MSG_NOSIGPIPE so writing to a socket that has + // disconnected can cause a SIGPIPE signal... + signal(SIGPIPE, SIG_IGN); #endif - TSSLSocketFactory::setManualOpenSSLInitialization(true); - apache::thrift::transport::initializeOpenSSL(); + TSSLSocketFactory::setManualOpenSSLInitialization(true); + apache::thrift::transport::initializeOpenSSL(); - keyDir = boost::filesystem::current_path().parent_path().parent_path().parent_path() / "test" / "keys"; - if (!boost::filesystem::exists(certFile("server.crt"))) - { - keyDir = boost::filesystem::path(master_test_suite().argv[master_test_suite().argc - 1]); - if (!boost::filesystem::exists(certFile("server.crt"))) - { - throw std::invalid_argument("The last argument to this test must be the directory containing the test certificate(s)."); - } - } + keyDir = boost::filesystem::current_path().parent_path().parent_path().parent_path() / "test" / "keys"; + if (!boost::filesystem::exists(certFile("server.crt"))) + { + keyDir = boost::filesystem::path(master_test_suite().argv[master_test_suite().argc - 1]); + if (!boost::filesystem::exists(certFile("server.crt"))) + { + throw std::invalid_argument("The last argument to this test must be the directory containing the test certificate(s)."); + } + } } virtual ~GlobalFixture() { - apache::thrift::transport::cleanupOpenSSL(); + apache::thrift::transport::cleanupOpenSSL(); #ifdef __linux__ - signal(SIGPIPE, SIG_DFL); + signal(SIGPIPE, SIG_DFL); #endif } }; @@ -102,8 +103,8 @@ struct SecurityFixture { boost::mutex::scoped_lock lock(mMutex); - boost::shared_ptr pServerSocketFactory; - boost::shared_ptr pServerSocket; + shared_ptr pServerSocketFactory; + shared_ptr pServerSocket; pServerSocketFactory.reset(new TSSLSocketFactory(static_cast(protocol))); pServerSocketFactory->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); @@ -111,7 +112,7 @@ struct SecurityFixture pServerSocketFactory->loadPrivateKey(certFile("server.key").string().c_str()); pServerSocketFactory->server(true); pServerSocket.reset(new TSSLServerSocket("localhost", 0, pServerSocketFactory)); - boost::shared_ptr connectedClient; + shared_ptr connectedClient; try { @@ -153,8 +154,8 @@ struct SecurityFixture { try { - boost::shared_ptr pClientSocketFactory; - boost::shared_ptr pClientSocket; + shared_ptr pClientSocketFactory; + shared_ptr pClientSocket; try { @@ -254,11 +255,12 @@ BOOST_AUTO_TEST_CASE(ssl_security_matrix) % protocol2str(si) % protocol2str(ci)); mConnected = false; + // thread_group manages the thread lifetime - ignore the return value of create_thread boost::thread_group threads; - threads.create_thread(boost::bind(&SecurityFixture::server, this, static_cast(si))); + (void)threads.create_thread(bind(&SecurityFixture::server, this, static_cast(si))); mCVar.wait(lock); // wait for listen() to succeed lock.unlock(); - threads.create_thread(boost::bind(&SecurityFixture::client, this, static_cast(ci))); + (void)threads.create_thread(bind(&SecurityFixture::client, this, static_cast(ci))); threads.join_all(); BOOST_CHECK_MESSAGE(mConnected == matrix[ci][si], diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/SpecializationTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/SpecializationTest.cpp index e851bac..a060b4f 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/SpecializationTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/SpecializationTest.cpp @@ -82,8 +82,8 @@ BOOST_AUTO_TEST_CASE(test_specialization_1) { stage2.back().message = "nevermore"; hm.bonks["poe"] = stage2; - boost::shared_ptr buffer(new TMemoryBuffer()); - boost::shared_ptr proto(new MyProtocol(buffer)); + apache::thrift::stdcxx::shared_ptr buffer(new TMemoryBuffer()); + apache::thrift::stdcxx::shared_ptr proto(new MyProtocol(buffer)); ooe.write(proto.get()); OneOfEach ooe2; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/TBufferBaseTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/TBufferBaseTest.cpp index 5d0bf45..4201ddb 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/TBufferBaseTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/TBufferBaseTest.cpp @@ -21,13 +21,14 @@ #include #include #include +#include -using std::string; -using boost::shared_ptr; +using apache::thrift::stdcxx::shared_ptr; using apache::thrift::transport::TMemoryBuffer; using apache::thrift::transport::TBufferedTransport; using apache::thrift::transport::TFramedTransport; using apache::thrift::transport::test::TShortReadTransport; +using std::string; // Shamelessly copied from ZlibTransport. TODO: refactor. unsigned int dist[][5000] = { @@ -566,7 +567,7 @@ BOOST_AUTO_TEST_CASE( test_FramedTransport_Write_Read ) { for (int d1 = 0; d1 < 3; d1++) { shared_ptr buffer(new TMemoryBuffer(16)); TFramedTransport trans(buffer, size); - uint8_t data_out[1<<15]; + std::vector data_out(1<<17, 0); std::vector flush_sizes; int write_offset = 0; @@ -604,7 +605,7 @@ BOOST_AUTO_TEST_CASE( test_FramedTransport_Write_Read ) { } BOOST_CHECK_EQUAL((unsigned int)read_offset, sizeof(data)); - BOOST_CHECK(!memcmp(data, data_out, sizeof(data))); + BOOST_CHECK(!memcmp(data, &data_out[0], sizeof(data))); } } } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/TFileTransportTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/TFileTransportTest.cpp index 82e84e8..d0c26b3 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/TFileTransportTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/TFileTransportTest.cpp @@ -53,20 +53,6 @@ FsyncLog* fsync_log; * Helper code **************************************************************************/ -// Provide BOOST_WARN_LT() and BOOST_WARN_GT(), in case we're compiled -// with an older version of boost -#ifndef BOOST_WARN_LT -#define BOOST_WARN_CMP(a, b, op, check_fn) \ - check_fn((a)op(b), \ - "check " BOOST_STRINGIZE(a) " " BOOST_STRINGIZE(op) " " BOOST_STRINGIZE( \ - b) " failed: " BOOST_STRINGIZE(a) "=" \ - << (a) << " " BOOST_STRINGIZE(b) "=" << (b)) - -#define BOOST_WARN_LT(a, b) BOOST_WARN_CMP(a, b, <, BOOST_WARN_MESSAGE) -#define BOOST_WARN_GT(a, b) BOOST_WARN_CMP(a, b, >, BOOST_WARN_MESSAGE) -#define BOOST_WARN_LT(a, b) BOOST_WARN_CMP(a, b, <, BOOST_WARN_MESSAGE) -#endif // BOOST_WARN_LT - /** * Class to record calls to fsync */ @@ -83,7 +69,7 @@ public: void fsync(int fd) { (void)fd; FsyncCall call; - gettimeofday(&call.time, NULL); + THRIFT_GETTIMEOFDAY(&call.time, NULL); calls_.push_back(call); } @@ -100,6 +86,7 @@ class TempFile { public: TempFile(const char* directory, const char* prefix) { #ifdef __MINGW32__ + ((void)directory); size_t path_len = strlen(prefix) + 8; path_ = new char[path_len]; snprintf(path_, path_len, "%sXXXXXX", prefix); @@ -208,16 +195,16 @@ BOOST_AUTO_TEST_CASE(test_destructor) { struct timeval start; struct timeval end; - gettimeofday(&start, NULL); + THRIFT_GETTIMEOFDAY(&start, NULL); delete transport; - gettimeofday(&end, NULL); + THRIFT_GETTIMEOFDAY(&end, NULL); int delta = time_diff(&start, &end); // If any attempt takes more than 500ms, treat that as a failure. // Treat this as a fatal failure, so we'll return now instead of // looping over a very slow operation. - BOOST_WARN_LT(delta, 500000); + BOOST_WARN( delta < 500000 ); // Normally, it takes less than 100ms on my dev box. // However, if the box is heavily loaded, some of the test runs @@ -295,7 +282,7 @@ void test_flush_max_us_impl(uint32_t flush_us, uint32_t write_us, uint32_t test_ for (FsyncLog::CallList::const_iterator it = calls->begin(); it != calls->end(); ++it) { if (prev_time) { int delta = time_diff(prev_time, &it->time); - BOOST_WARN_LT(delta, max_allowed_delta); + BOOST_WARN( delta < max_allowed_delta ); } prev_time = &it->time; } @@ -331,13 +318,13 @@ BOOST_AUTO_TEST_CASE(test_noop_flush) { transport.write(buf, 1); struct timeval start; - gettimeofday(&start, NULL); + THRIFT_GETTIMEOFDAY(&start, NULL); for (unsigned int n = 0; n < 10; ++n) { transport.flush(); struct timeval now; - gettimeofday(&now, NULL); + THRIFT_GETTIMEOFDAY(&now, NULL); // Fail if at any point we've been running for longer than half a second. // (With the buggy code, TFileTransport used to take 3 seconds per flush()) @@ -345,7 +332,7 @@ BOOST_AUTO_TEST_CASE(test_noop_flush) { // Use a fatal fail so we break out early, rather than continuing to make // many more slow flush() calls. int delta = time_diff(&start, &now); - BOOST_WARN_LT(delta, 2000000); + BOOST_WARN( delta < 2000000 ); } } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/TMemoryBufferTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/TMemoryBufferTest.cpp index 84103e3..d81b1d8 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/TMemoryBufferTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/TMemoryBufferTest.cpp @@ -21,8 +21,9 @@ #include #include #include -#include #include +#include +#include #include "gen-cpp/ThriftTest_types.h" BOOST_AUTO_TEST_SUITE(TMemoryBufferTest) @@ -30,7 +31,7 @@ BOOST_AUTO_TEST_SUITE(TMemoryBufferTest) using apache::thrift::protocol::TBinaryProtocol; using apache::thrift::transport::TMemoryBuffer; using apache::thrift::transport::TTransportException; -using boost::shared_ptr; +using apache::thrift::stdcxx::shared_ptr; using std::cout; using std::endl; using std::string; @@ -79,19 +80,11 @@ BOOST_AUTO_TEST_CASE(test_roundtrip) { BOOST_CHECK(a == a2); } -BOOST_AUTO_TEST_CASE(test_copy) { +BOOST_AUTO_TEST_CASE(test_readAppendToString) { string* str1 = new string("abcd1234"); - const char* data1 = str1->data(); TMemoryBuffer buf((uint8_t*)str1->data(), static_cast(str1->length()), TMemoryBuffer::COPY); - delete str1; - string* str2 = new string("plsreuse"); - bool obj_reuse = (str1 == str2); - bool dat_reuse = (data1 == str2->data()); - BOOST_TEST_MESSAGE("Object reuse: " << obj_reuse << " Data reuse: " << dat_reuse - << ((obj_reuse && dat_reuse) ? " YAY!" : "")); - delete str2; string str3 = "wxyz", str4 = "6789"; buf.readAppendToString(str3, 4); @@ -116,4 +109,52 @@ BOOST_AUTO_TEST_CASE(test_exceptions) { BOOST_CHECK_NO_THROW(buf2.write((const uint8_t*)"bar", 3)); } +BOOST_AUTO_TEST_CASE(test_default_maximum_buffer_size) +{ + BOOST_CHECK_EQUAL((std::numeric_limits::max)(), TMemoryBuffer().getMaxBufferSize()); +} + +BOOST_AUTO_TEST_CASE(test_default_buffer_size) +{ + BOOST_CHECK_EQUAL(1024, TMemoryBuffer().getBufferSize()); +} + +BOOST_AUTO_TEST_CASE(test_error_set_max_buffer_size_too_small) +{ + TMemoryBuffer buf; + BOOST_CHECK_THROW(buf.setMaxBufferSize(buf.getBufferSize() - 1), TTransportException); +} + +BOOST_AUTO_TEST_CASE(test_maximum_buffer_size) +{ + TMemoryBuffer buf; + buf.setMaxBufferSize(8192); + std::vector small_buff(1); + + for (size_t i = 0; i < 8192; ++i) + { + buf.write(&small_buff[0], 1); + } + + BOOST_CHECK_THROW(buf.write(&small_buff[0], 1), TTransportException); +} + +BOOST_AUTO_TEST_CASE(test_memory_buffer_to_get_sizeof_objects) +{ + // This is a demonstration of how to use TMemoryBuffer to determine + // the serialized size of a thrift object in the Binary protocol. + // See THRIFT-3480 + + shared_ptr memBuffer(new TMemoryBuffer()); + shared_ptr binaryProtcol(new TBinaryProtocol(memBuffer)); + + thrift::test::Xtruct object; + object.i32_thing = 10; + object.i64_thing = 30; + object.string_thing = "who's your daddy?"; + + uint32_t size = object.write(binaryProtcol.get()); + BOOST_CHECK_EQUAL(47, size); +} + BOOST_AUTO_TEST_SUITE_END() diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/TNonblockingSSLServerTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/TNonblockingSSLServerTest.cpp new file mode 100644 index 0000000..3e9700f --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/TNonblockingSSLServerTest.cpp @@ -0,0 +1,293 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +#define BOOST_TEST_MODULE TNonblockingSSLServerTest +#include +#include +#include +#include +#include + +#include "thrift/server/TNonblockingServer.h" +#include "thrift/transport/TSSLSocket.h" +#include "thrift/transport/TNonblockingSSLServerSocket.h" + +#include "gen-cpp/ParentService.h" + +#include + +using namespace apache::thrift; +using apache::thrift::concurrency::Guard; +using apache::thrift::concurrency::Monitor; +using apache::thrift::concurrency::Mutex; +using apache::thrift::server::TServerEventHandler; +using apache::thrift::transport::TSSLSocketFactory; +using apache::thrift::transport::TSSLSocket; + +struct Handler : public test::ParentServiceIf { + void addString(const std::string& s) { strings_.push_back(s); } + void getStrings(std::vector& _return) { _return = strings_; } + std::vector strings_; + + // dummy overrides not used in this test + int32_t incrementGeneration() { return 0; } + int32_t getGeneration() { return 0; } + void getDataWait(std::string&, const int32_t) {} + void onewayWait() {} + void exceptionWait(const std::string&) {} + void unexpectedExceptionWait(const std::string&) {} +}; + +boost::filesystem::path keyDir; +boost::filesystem::path certFile(const std::string& filename) +{ + return keyDir / filename; +} + +struct GlobalFixtureSSL +{ + GlobalFixtureSSL() + { + using namespace boost::unit_test::framework; + for (int i = 0; i < master_test_suite().argc; ++i) + { + BOOST_TEST_MESSAGE(boost::format("argv[%1%] = \"%2%\"") % i % master_test_suite().argv[i]); + } + +#ifdef __linux__ + // OpenSSL calls send() without MSG_NOSIGPIPE so writing to a socket that has + // disconnected can cause a SIGPIPE signal... + signal(SIGPIPE, SIG_IGN); +#endif + + TSSLSocketFactory::setManualOpenSSLInitialization(true); + apache::thrift::transport::initializeOpenSSL(); + + keyDir = boost::filesystem::current_path().parent_path().parent_path().parent_path() / "test" / "keys"; + if (!boost::filesystem::exists(certFile("server.crt"))) + { + keyDir = boost::filesystem::path(master_test_suite().argv[master_test_suite().argc - 1]); + if (!boost::filesystem::exists(certFile("server.crt"))) + { + throw std::invalid_argument("The last argument to this test must be the directory containing the test certificate(s)."); + } + } + } + + virtual ~GlobalFixtureSSL() + { + apache::thrift::transport::cleanupOpenSSL(); +#ifdef __linux__ + signal(SIGPIPE, SIG_DFL); +#endif + } +}; + +#if (BOOST_VERSION >= 105900) +BOOST_GLOBAL_FIXTURE(GlobalFixtureSSL); +#else +BOOST_GLOBAL_FIXTURE(GlobalFixtureSSL) +#endif + +stdcxx::shared_ptr createServerSocketFactory() { + stdcxx::shared_ptr pServerSocketFactory; + + pServerSocketFactory.reset(new TSSLSocketFactory()); + pServerSocketFactory->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); + pServerSocketFactory->loadCertificate(certFile("server.crt").string().c_str()); + pServerSocketFactory->loadPrivateKey(certFile("server.key").string().c_str()); + pServerSocketFactory->server(true); + return pServerSocketFactory; +} + +stdcxx::shared_ptr createClientSocketFactory() { + stdcxx::shared_ptr pClientSocketFactory; + + pClientSocketFactory.reset(new TSSLSocketFactory()); + pClientSocketFactory->authenticate(true); + pClientSocketFactory->loadCertificate(certFile("client.crt").string().c_str()); + pClientSocketFactory->loadPrivateKey(certFile("client.key").string().c_str()); + pClientSocketFactory->loadTrustedCertificates(certFile("CA.pem").string().c_str()); + return pClientSocketFactory; +} + +class Fixture { +private: + struct ListenEventHandler : public TServerEventHandler { + public: + ListenEventHandler(Mutex* mutex) : listenMonitor_(mutex), ready_(false) {} + + void preServe() /* override */ { + Guard g(listenMonitor_.mutex()); + ready_ = true; + listenMonitor_.notify(); + } + + Monitor listenMonitor_; + bool ready_; + }; + + struct Runner : public apache::thrift::concurrency::Runnable { + int port; + stdcxx::shared_ptr userEventBase; + stdcxx::shared_ptr processor; + stdcxx::shared_ptr server; + stdcxx::shared_ptr listenHandler; + stdcxx::shared_ptr pServerSocketFactory; + stdcxx::shared_ptr socket; + Mutex mutex_; + + Runner() { + listenHandler.reset(new ListenEventHandler(&mutex_)); + } + + virtual void run() { + // When binding to explicit port, allow retrying to workaround bind failures on ports in use + int retryCount = port ? 10 : 0; + pServerSocketFactory = createServerSocketFactory(); + startServer(retryCount); + } + + void readyBarrier() { + // block until server is listening and ready to accept connections + Guard g(mutex_); + while (!listenHandler->ready_) { + listenHandler->listenMonitor_.wait(); + } + } + private: + void startServer(int retry_count) { + try { + socket.reset(new transport::TNonblockingSSLServerSocket(port, pServerSocketFactory)); + server.reset(new server::TNonblockingServer(processor, socket)); + server->setServerEventHandler(listenHandler); + server->setNumIOThreads(1); + if (userEventBase) { + server->registerEvents(userEventBase.get()); + } + server->serve(); + } catch (const transport::TTransportException&) { + if (retry_count > 0) { + ++port; + startServer(retry_count - 1); + } else { + throw; + } + } + } + }; + + struct EventDeleter { + void operator()(event_base* p) { event_base_free(p); } + }; + +protected: + Fixture() : processor(new test::ParentServiceProcessor(stdcxx::make_shared())) {} + + ~Fixture() { + if (server) { + server->stop(); + } + if (thread) { + thread->join(); + } + } + + void setEventBase(event_base* user_event_base) { + userEventBase_.reset(user_event_base, EventDeleter()); + } + + int startServer(int port) { + stdcxx::shared_ptr runner(new Runner); + runner->port = port; + runner->processor = processor; + runner->userEventBase = userEventBase_; + + apache::thrift::stdcxx::scoped_ptr threadFactory( + new apache::thrift::concurrency::PlatformThreadFactory( +#if !USE_BOOST_THREAD && !USE_STD_THREAD + concurrency::PlatformThreadFactory::OTHER, concurrency::PlatformThreadFactory::NORMAL, + 1, +#endif + false)); + thread = threadFactory->newThread(runner); + thread->start(); + runner->readyBarrier(); + + server = runner->server; + return runner->port; + } + + bool canCommunicate(int serverPort) { + stdcxx::shared_ptr pClientSocketFactory = createClientSocketFactory(); + stdcxx::shared_ptr socket = pClientSocketFactory->createSocket("localhost", serverPort); + socket->open(); + test::ParentServiceClient client(stdcxx::make_shared( + stdcxx::make_shared(socket))); + client.addString("foo"); + std::vector strings; + client.getStrings(strings); + return strings.size() == 1 && !(strings[0].compare("foo")); + } + +private: + stdcxx::shared_ptr userEventBase_; + stdcxx::shared_ptr processor; +protected: + stdcxx::shared_ptr server; +private: + stdcxx::shared_ptr thread; + +}; + +BOOST_AUTO_TEST_SUITE(TNonblockingSSLServerTest) + +BOOST_FIXTURE_TEST_CASE(get_specified_port, Fixture) { + int specified_port = startServer(12345); + BOOST_REQUIRE_GE(specified_port, 12345); + BOOST_REQUIRE_EQUAL(server->getListenPort(), specified_port); + BOOST_CHECK(canCommunicate(specified_port)); + + server->stop(); +} + +BOOST_FIXTURE_TEST_CASE(get_assigned_port, Fixture) { + int specified_port = startServer(0); + BOOST_REQUIRE_EQUAL(specified_port, 0); + int assigned_port = server->getListenPort(); + BOOST_REQUIRE_NE(assigned_port, 0); + BOOST_CHECK(canCommunicate(assigned_port)); + + server->stop(); +} + +BOOST_FIXTURE_TEST_CASE(provide_event_base, Fixture) { + event_base* eb = event_base_new(); + setEventBase(eb); + startServer(0); + + // assert that the server works + BOOST_CHECK(canCommunicate(server->getListenPort())); +#if LIBEVENT_VERSION_NUMBER > 0x02010400 + // also assert that the event_base is actually used when it's easy + BOOST_CHECK_GT(event_base_get_num_events(eb, EVENT_BASE_COUNT_ADDED), 0); +#endif +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/TNonblockingServerTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/TNonblockingServerTest.cpp index 48ea913..63d8a04 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/TNonblockingServerTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/TNonblockingServerTest.cpp @@ -19,15 +19,28 @@ #define BOOST_TEST_MODULE TNonblockingServerTest #include -#include +#include "thrift/concurrency/Monitor.h" #include "thrift/concurrency/Thread.h" #include "thrift/server/TNonblockingServer.h" +#include "thrift/transport/TNonblockingServerSocket.h" +#include "thrift/stdcxx.h" #include "gen-cpp/ParentService.h" #include +using apache::thrift::concurrency::Guard; +using apache::thrift::concurrency::Monitor; +using apache::thrift::concurrency::Mutex; +using apache::thrift::concurrency::PlatformThreadFactory; +using apache::thrift::concurrency::Runnable; +using apache::thrift::concurrency::Thread; +using apache::thrift::concurrency::ThreadFactory; +using apache::thrift::server::TServerEventHandler; +using apache::thrift::stdcxx::make_shared; +using apache::thrift::stdcxx::shared_ptr; + using namespace apache::thrift; struct Handler : public test::ParentServiceIf { @@ -46,11 +59,32 @@ struct Handler : public test::ParentServiceIf { class Fixture { private: - struct Runner : public apache::thrift::concurrency::Runnable { + struct ListenEventHandler : public TServerEventHandler { + public: + ListenEventHandler(Mutex* mutex) : listenMonitor_(mutex), ready_(false) {} + + void preServe() /* override */ { + Guard g(listenMonitor_.mutex()); + ready_ = true; + listenMonitor_.notify(); + } + + Monitor listenMonitor_; + bool ready_; + }; + + struct Runner : public Runnable { int port; - boost::shared_ptr userEventBase; - boost::shared_ptr processor; - boost::shared_ptr server; + shared_ptr userEventBase; + shared_ptr processor; + shared_ptr server; + shared_ptr listenHandler; + shared_ptr socket; + Mutex mutex_; + + Runner() { + listenHandler.reset(new ListenEventHandler(&mutex_)); + } virtual void run() { // When binding to explicit port, allow retrying to workaround bind failures on ports in use @@ -58,10 +92,19 @@ private: startServer(retryCount); } + void readyBarrier() { + // block until server is listening and ready to accept connections + Guard g(mutex_); + while (!listenHandler->ready_) { + listenHandler->listenMonitor_.wait(); + } + } private: void startServer(int retry_count) { try { - server.reset(new server::TNonblockingServer(processor, port)); + socket.reset(new transport::TNonblockingServerSocket(port)); + server.reset(new server::TNonblockingServer(processor, socket)); + server->setServerEventHandler(listenHandler); if (userEventBase) { server->registerEvents(userEventBase.get()); } @@ -82,7 +125,7 @@ private: }; protected: - Fixture() : processor(new test::ParentServiceProcessor(boost::make_shared())) {} + Fixture() : processor(new test::ParentServiceProcessor(make_shared())) {} ~Fixture() { if (server) { @@ -98,31 +141,31 @@ protected: } int startServer(int port) { - boost::shared_ptr runner(new Runner); + shared_ptr runner(new Runner); runner->port = port; runner->processor = processor; runner->userEventBase = userEventBase_; - boost::scoped_ptr threadFactory( - new apache::thrift::concurrency::PlatformThreadFactory( + shared_ptr threadFactory( + new PlatformThreadFactory( #if !USE_BOOST_THREAD && !USE_STD_THREAD - concurrency::PlatformThreadFactory::OTHER, concurrency::PlatformThreadFactory::NORMAL, + PlatformThreadFactory::OTHER, PlatformThreadFactory::NORMAL, 1, #endif false)); thread = threadFactory->newThread(runner); thread->start(); - // wait 100 ms for the server to begin listening - THRIFT_SLEEP_USEC(100000); + runner->readyBarrier(); + server = runner->server; return runner->port; } bool canCommunicate(int serverPort) { - boost::shared_ptr socket(new transport::TSocket("localhost", serverPort)); + shared_ptr socket(new transport::TSocket("localhost", serverPort)); socket->open(); - test::ParentServiceClient client(boost::make_shared( - boost::make_shared(socket))); + test::ParentServiceClient client(make_shared( + make_shared(socket))); client.addString("foo"); std::vector strings; client.getStrings(strings); @@ -130,12 +173,12 @@ protected: } private: - boost::shared_ptr userEventBase_; - boost::shared_ptr processor; + shared_ptr userEventBase_; + shared_ptr processor; protected: - boost::shared_ptr server; + shared_ptr server; private: - boost::shared_ptr thread; + shared_ptr thread; }; @@ -148,7 +191,6 @@ BOOST_FIXTURE_TEST_CASE(get_specified_port, Fixture) { BOOST_CHECK(canCommunicate(specified_port)); server->stop(); - BOOST_CHECK_EQUAL(server->getListenPort(), specified_port); } BOOST_FIXTURE_TEST_CASE(get_assigned_port, Fixture) { @@ -159,7 +201,6 @@ BOOST_FIXTURE_TEST_CASE(get_assigned_port, Fixture) { BOOST_CHECK(canCommunicate(assigned_port)); server->stop(); - BOOST_CHECK_EQUAL(server->getListenPort(), 0); } BOOST_FIXTURE_TEST_CASE(provide_event_base, Fixture) { diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/TPipeInterruptTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/TPipeInterruptTest.cpp index 80e4c1f..232e4bb 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/TPipeInterruptTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/TPipeInterruptTest.cpp @@ -22,17 +22,18 @@ #include #include -#include #include #include #include #include #include +#include using apache::thrift::transport::TPipeServer; using apache::thrift::transport::TPipe; using apache::thrift::transport::TTransport; using apache::thrift::transport::TTransportException; +using namespace apache::thrift; BOOST_AUTO_TEST_SUITE(TPipeInterruptTest) @@ -51,7 +52,7 @@ static void acceptWorker(TPipeServer *pipe) { { for (;;) { - boost::shared_ptr temp = pipe->accept(); + stdcxx::shared_ptr temp = pipe->accept(); } } catch (...) {/*just want to make sure nothing crashes*/ } @@ -69,8 +70,8 @@ BOOST_AUTO_TEST_CASE(stress_pipe_accept_interruption) { { TPipeServer pipeServer("TPipeInterruptTest"); pipeServer.listen(); - boost::thread acceptThread(boost::bind(acceptWorker, &pipeServer)); - boost::thread interruptThread(boost::bind(interruptWorker, &pipeServer)); + boost::thread acceptThread(stdcxx::bind(acceptWorker, &pipeServer)); + boost::thread interruptThread(stdcxx::bind(interruptWorker, &pipeServer)); try { for (;;) diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/TPipedTransportTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/TPipedTransportTest.cpp index 3221fb9..a3ce662 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/TPipedTransportTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/TPipedTransportTest.cpp @@ -18,6 +18,7 @@ */ #include +#include #include #include @@ -27,11 +28,12 @@ using apache::thrift::transport::TTransportException; using apache::thrift::transport::TPipedTransport; using apache::thrift::transport::TMemoryBuffer; +using namespace apache::thrift; BOOST_AUTO_TEST_CASE(test_read_write) { - boost::shared_ptr underlying(new TMemoryBuffer); - boost::shared_ptr pipe(new TMemoryBuffer); - boost::shared_ptr trans(new TPipedTransport(underlying, pipe)); + stdcxx::shared_ptr underlying(new TMemoryBuffer); + stdcxx::shared_ptr pipe(new TMemoryBuffer); + stdcxx::shared_ptr trans(new TPipedTransport(underlying, pipe)); uint8_t buffer[4]; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/TSSLSocketInterruptTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/TSSLSocketInterruptTest.cpp index ba43daf..85f6c39 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/TSSLSocketInterruptTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/TSSLSocketInterruptTest.cpp @@ -19,13 +19,12 @@ #include #include -#include #include #include #include #include #include -#include +#include #include #include #ifdef __linux__ @@ -38,6 +37,9 @@ using apache::thrift::transport::TTransport; using apache::thrift::transport::TTransportException; using apache::thrift::transport::TSSLSocketFactory; +using apache::thrift::stdcxx::static_pointer_cast; +using apache::thrift::stdcxx::shared_ptr; + BOOST_AUTO_TEST_SUITE(TSSLSocketInterruptTest) boost::filesystem::path keyDir; @@ -92,7 +94,7 @@ BOOST_GLOBAL_FIXTURE(GlobalFixtureSSL); BOOST_GLOBAL_FIXTURE(GlobalFixtureSSL) #endif -void readerWorker(boost::shared_ptr tt, uint32_t expectedResult) { +void readerWorker(shared_ptr tt, uint32_t expectedResult) { uint8_t buf[4]; try { tt->read(buf, 1); @@ -102,7 +104,7 @@ void readerWorker(boost::shared_ptr tt, uint32_t expectedResult) { } } -void readerWorkerMustThrow(boost::shared_ptr tt) { +void readerWorkerMustThrow(shared_ptr tt) { try { uint8_t buf[400]; tt->read(buf, 1); @@ -113,8 +115,8 @@ void readerWorkerMustThrow(boost::shared_ptr tt) { } } -boost::shared_ptr createServerSocketFactory() { - boost::shared_ptr pServerSocketFactory; +shared_ptr createServerSocketFactory() { + shared_ptr pServerSocketFactory; pServerSocketFactory.reset(new TSSLSocketFactory()); pServerSocketFactory->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); @@ -124,8 +126,8 @@ boost::shared_ptr createServerSocketFactory() { return pServerSocketFactory; } -boost::shared_ptr createClientSocketFactory() { - boost::shared_ptr pClientSocketFactory; +shared_ptr createClientSocketFactory() { + shared_ptr pClientSocketFactory; pClientSocketFactory.reset(new TSSLSocketFactory()); pClientSocketFactory->authenticate(true); @@ -136,15 +138,15 @@ boost::shared_ptr createClientSocketFactory() { } BOOST_AUTO_TEST_CASE(test_ssl_interruptable_child_read_while_handshaking) { - boost::shared_ptr pServerSocketFactory = createServerSocketFactory(); + shared_ptr pServerSocketFactory = createServerSocketFactory(); TSSLServerSocket sock1("localhost", 0, pServerSocketFactory); sock1.listen(); int port = sock1.getPort(); - boost::shared_ptr pClientSocketFactory = createClientSocketFactory(); - boost::shared_ptr clientSock = pClientSocketFactory->createSocket("localhost", port); + shared_ptr pClientSocketFactory = createClientSocketFactory(); + shared_ptr clientSock = pClientSocketFactory->createSocket("localhost", port); clientSock->open(); - boost::shared_ptr accepted = sock1.accept(); - boost::thread readThread(boost::bind(readerWorkerMustThrow, accepted)); + shared_ptr accepted = sock1.accept(); + boost::thread readThread(apache::thrift::stdcxx::bind(readerWorkerMustThrow, accepted)); boost::this_thread::sleep(boost::posix_time::milliseconds(50)); // readThread is practically guaranteed to be blocking now sock1.interruptChildren(); @@ -156,15 +158,15 @@ BOOST_AUTO_TEST_CASE(test_ssl_interruptable_child_read_while_handshaking) { } BOOST_AUTO_TEST_CASE(test_ssl_interruptable_child_read) { - boost::shared_ptr pServerSocketFactory = createServerSocketFactory(); + shared_ptr pServerSocketFactory = createServerSocketFactory(); TSSLServerSocket sock1("localhost", 0, pServerSocketFactory); sock1.listen(); int port = sock1.getPort(); - boost::shared_ptr pClientSocketFactory = createClientSocketFactory(); - boost::shared_ptr clientSock = pClientSocketFactory->createSocket("localhost", port); + shared_ptr pClientSocketFactory = createClientSocketFactory(); + shared_ptr clientSock = pClientSocketFactory->createSocket("localhost", port); clientSock->open(); - boost::shared_ptr accepted = sock1.accept(); - boost::thread readThread(boost::bind(readerWorkerMustThrow, accepted)); + shared_ptr accepted = sock1.accept(); + boost::thread readThread(apache::thrift::stdcxx::bind(readerWorkerMustThrow, accepted)); clientSock->write((const uint8_t*)"0", 1); boost::this_thread::sleep(boost::posix_time::milliseconds(50)); // readThread is practically guaranteed to be blocking now @@ -177,17 +179,17 @@ BOOST_AUTO_TEST_CASE(test_ssl_interruptable_child_read) { } BOOST_AUTO_TEST_CASE(test_ssl_non_interruptable_child_read) { - boost::shared_ptr pServerSocketFactory = createServerSocketFactory(); + shared_ptr pServerSocketFactory = createServerSocketFactory(); TSSLServerSocket sock1("localhost", 0, pServerSocketFactory); sock1.setInterruptableChildren(false); // returns to pre-THRIFT-2441 behavior sock1.listen(); int port = sock1.getPort(); - boost::shared_ptr pClientSocketFactory = createClientSocketFactory(); - boost::shared_ptr clientSock = pClientSocketFactory->createSocket("localhost", port); + shared_ptr pClientSocketFactory = createClientSocketFactory(); + shared_ptr clientSock = pClientSocketFactory->createSocket("localhost", port); clientSock->open(); - boost::shared_ptr accepted = sock1.accept(); - boost::static_pointer_cast(accepted)->setRecvTimeout(1000); - boost::thread readThread(boost::bind(readerWorker, accepted, 0)); + shared_ptr accepted = sock1.accept(); + static_pointer_cast(accepted)->setRecvTimeout(1000); + boost::thread readThread(apache::thrift::stdcxx::bind(readerWorker, accepted, 0)); clientSock->write((const uint8_t*)"0", 1); boost::this_thread::sleep(boost::posix_time::milliseconds(50)); // readThread is practically guaranteed to be blocking here @@ -203,24 +205,24 @@ BOOST_AUTO_TEST_CASE(test_ssl_non_interruptable_child_read) { } BOOST_AUTO_TEST_CASE(test_ssl_cannot_change_after_listen) { - boost::shared_ptr pServerSocketFactory = createServerSocketFactory(); + shared_ptr pServerSocketFactory = createServerSocketFactory(); TSSLServerSocket sock1("localhost", 0, pServerSocketFactory); sock1.listen(); BOOST_CHECK_THROW(sock1.setInterruptableChildren(false), std::logic_error); sock1.close(); } -void peekerWorker(boost::shared_ptr tt, bool expectedResult) { +void peekerWorker(shared_ptr tt, bool expectedResult) { uint8_t buf[400]; try { tt->read(buf, 1); - tt->peek(); + BOOST_CHECK_EQUAL(expectedResult, tt->peek()); } catch (const TTransportException& tx) { BOOST_CHECK_EQUAL(TTransportException::TIMED_OUT, tx.getType()); } } -void peekerWorkerInterrupt(boost::shared_ptr tt) { +void peekerWorkerInterrupt(shared_ptr tt) { uint8_t buf[400]; try { tt->read(buf, 1); @@ -231,15 +233,15 @@ void peekerWorkerInterrupt(boost::shared_ptr tt) { } BOOST_AUTO_TEST_CASE(test_ssl_interruptable_child_peek) { - boost::shared_ptr pServerSocketFactory = createServerSocketFactory(); + shared_ptr pServerSocketFactory = createServerSocketFactory(); TSSLServerSocket sock1("localhost", 0, pServerSocketFactory); sock1.listen(); int port = sock1.getPort(); - boost::shared_ptr pClientSocketFactory = createClientSocketFactory(); - boost::shared_ptr clientSock = pClientSocketFactory->createSocket("localhost", port); + shared_ptr pClientSocketFactory = createClientSocketFactory(); + shared_ptr clientSock = pClientSocketFactory->createSocket("localhost", port); clientSock->open(); - boost::shared_ptr accepted = sock1.accept(); - boost::thread peekThread(boost::bind(peekerWorkerInterrupt, accepted)); + shared_ptr accepted = sock1.accept(); + boost::thread peekThread(apache::thrift::stdcxx::bind(peekerWorkerInterrupt, accepted)); clientSock->write((const uint8_t*)"0", 1); boost::this_thread::sleep(boost::posix_time::milliseconds(50)); // peekThread is practically guaranteed to be blocking now @@ -252,17 +254,17 @@ BOOST_AUTO_TEST_CASE(test_ssl_interruptable_child_peek) { } BOOST_AUTO_TEST_CASE(test_ssl_non_interruptable_child_peek) { - boost::shared_ptr pServerSocketFactory = createServerSocketFactory(); + shared_ptr pServerSocketFactory = createServerSocketFactory(); TSSLServerSocket sock1("localhost", 0, pServerSocketFactory); sock1.setInterruptableChildren(false); // returns to pre-THRIFT-2441 behavior sock1.listen(); int port = sock1.getPort(); - boost::shared_ptr pClientSocketFactory = createClientSocketFactory(); - boost::shared_ptr clientSock = pClientSocketFactory->createSocket("localhost", port); + shared_ptr pClientSocketFactory = createClientSocketFactory(); + shared_ptr clientSock = pClientSocketFactory->createSocket("localhost", port); clientSock->open(); - boost::shared_ptr accepted = sock1.accept(); - boost::static_pointer_cast(accepted)->setRecvTimeout(1000); - boost::thread peekThread(boost::bind(peekerWorker, accepted, false)); + shared_ptr accepted = sock1.accept(); + static_pointer_cast(accepted)->setRecvTimeout(1000); + boost::thread peekThread(apache::thrift::stdcxx::bind(peekerWorker, accepted, false)); clientSock->write((const uint8_t*)"0", 1); boost::this_thread::sleep(boost::posix_time::milliseconds(50)); // peekThread is practically guaranteed to be blocking now diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/TServerIntegrationTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/TServerIntegrationTest.cpp index fd7bae2..5f7b2e8 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/TServerIntegrationTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/TServerIntegrationTest.cpp @@ -20,16 +20,14 @@ #define BOOST_TEST_MODULE TServerIntegrationTest #include #include -#include #include #include #include -#include -#include #include #include #include #include +#include #include #include #include @@ -57,6 +55,9 @@ using apache::thrift::server::TServerEventHandler; using apache::thrift::server::TSimpleServer; using apache::thrift::server::TThreadPoolServer; using apache::thrift::server::TThreadedServer; +using apache::thrift::stdcxx::dynamic_pointer_cast; +using apache::thrift::stdcxx::make_shared; +using apache::thrift::stdcxx::shared_ptr; using apache::thrift::test::ParentServiceClient; using apache::thrift::test::ParentServiceIf; using apache::thrift::test::ParentServiceIfFactory; @@ -79,8 +80,8 @@ public: isListening_ = true; notify(); } - virtual void* createContext(boost::shared_ptr input, - boost::shared_ptr output) { + virtual void* createContext(shared_ptr input, + shared_ptr output) { Synchronized sync(*this); ++accepted_; notify(); @@ -149,26 +150,26 @@ void autoSocketCloser(TSocket* pSock) { template class TServerIntegrationTestFixture { public: - TServerIntegrationTestFixture(const boost::shared_ptr& _processorFactory) + TServerIntegrationTestFixture(const shared_ptr& _processorFactory) : pServer(new TServerType(_processorFactory, - boost::shared_ptr( + shared_ptr( new TServerSocket("localhost", 0)), - boost::shared_ptr(new TTransportFactory), - boost::shared_ptr(new TBinaryProtocolFactory))), - pEventHandler(boost::shared_ptr(new TServerReadyEventHandler)), + shared_ptr(new TTransportFactory), + shared_ptr(new TBinaryProtocolFactory))), + pEventHandler(shared_ptr(new TServerReadyEventHandler)), bStressDone(false), bStressConnectionCount(0), bStressRequestCount(0) { pServer->setServerEventHandler(pEventHandler); } - TServerIntegrationTestFixture(const boost::shared_ptr& _processor) + TServerIntegrationTestFixture(const shared_ptr& _processor) : pServer( new TServerType(_processor, - boost::shared_ptr(new TServerSocket("localhost", 0)), - boost::shared_ptr(new TTransportFactory), - boost::shared_ptr(new TBinaryProtocolFactory))), - pEventHandler(boost::shared_ptr(new TServerReadyEventHandler)), + shared_ptr(new TServerSocket("localhost", 0)), + shared_ptr(new TTransportFactory), + shared_ptr(new TBinaryProtocolFactory))), + pEventHandler(shared_ptr(new TServerReadyEventHandler)), bStressDone(false), bStressConnectionCount(0), bStressRequestCount(0) { @@ -176,7 +177,7 @@ public: } void startServer() { - pServerThread.reset(new boost::thread(boost::bind(&TServerType::serve, pServer.get()))); + pServerThread.reset(new boost::thread(apache::thrift::stdcxx::bind(&TServerType::serve, pServer.get()))); // block until listen() completes so clients will be able to connect Synchronized sync(*(pEventHandler.get())); @@ -222,19 +223,19 @@ public: startServer(); - std::vector > holdSockets; - std::vector > holdThreads; + std::vector > holdSockets; + std::vector > holdThreads; for (int64_t i = 0; i < numToMake; ++i) { - boost::shared_ptr pClientSock(new TSocket("localhost", getServerPort()), + shared_ptr pClientSock(new TSocket("localhost", getServerPort()), autoSocketCloser); holdSockets.push_back(pClientSock); - boost::shared_ptr pClientProtocol(new TBinaryProtocol(pClientSock)); + shared_ptr pClientProtocol(new TBinaryProtocol(pClientSock)); ParentServiceClient client(pClientProtocol); pClientSock->open(); client.incrementGeneration(); - holdThreads.push_back(boost::shared_ptr( - new boost::thread(boost::bind(&TServerIntegrationTestFixture::delayClose, + holdThreads.push_back(shared_ptr( + new boost::thread(apache::thrift::stdcxx::bind(&TServerIntegrationTestFixture::delayClose, this, pClientSock, milliseconds(10 * numToMake))))); @@ -242,7 +243,7 @@ public: BOOST_CHECK_EQUAL(expectedHWM, pServer->getConcurrentClientCountHWM()); - BOOST_FOREACH (boost::shared_ptr pThread, holdThreads) { pThread->join(); } + BOOST_FOREACH (shared_ptr pThread, holdThreads) { pThread->join(); } holdThreads.clear(); holdSockets.clear(); @@ -254,7 +255,7 @@ public: * \param[in] toClose the connection to close * \param[in] after the delay to impose */ - void delayClose(boost::shared_ptr toClose, boost::posix_time::time_duration after) { + void delayClose(shared_ptr toClose, boost::posix_time::time_duration after) { boost::this_thread::sleep(after); toClose->close(); } @@ -264,6 +265,7 @@ public: */ int getServerPort() { TServerSocket* pSock = dynamic_cast(pServer->getServerTransport().get()); + if (!pSock) { throw std::logic_error("how come?"); } return pSock->getPort(); } @@ -279,10 +281,10 @@ public: startServer(); - std::vector > holdThreads; + std::vector > holdThreads; for (int64_t i = 0; i < numToMake; ++i) { - holdThreads.push_back(boost::shared_ptr( - new boost::thread(boost::bind(&TServerIntegrationTestFixture::stressor, this)))); + holdThreads.push_back(shared_ptr( + new boost::thread(apache::thrift::stdcxx::bind(&TServerIntegrationTestFixture::stressor, this)))); } boost::this_thread::sleep(duration); @@ -291,7 +293,7 @@ public: BOOST_TEST_MESSAGE(boost::format(" serviced %1% connections (HWM %2%) totaling %3% requests") % bStressConnectionCount % pServer->getConcurrentClientCountHWM() % bStressRequestCount); - BOOST_FOREACH (boost::shared_ptr pThread, holdThreads) { pThread->join(); } + BOOST_FOREACH (shared_ptr pThread, holdThreads) { pThread->join(); } holdThreads.clear(); BOOST_CHECK(bStressRequestCount > 0); @@ -304,8 +306,8 @@ public: */ void stressor() { while (!bStressDone) { - boost::shared_ptr pSocket(new TSocket("localhost", getServerPort()), autoSocketCloser); - boost::shared_ptr pProtocol(new TBinaryProtocol(pSocket)); + shared_ptr pSocket(new TSocket("localhost", getServerPort()), autoSocketCloser); + shared_ptr pProtocol(new TBinaryProtocol(pSocket)); ParentServiceClient client(pProtocol); pSocket->open(); bStressConnectionCount.fetch_add(1, boost::memory_order_relaxed); @@ -316,10 +318,10 @@ public: } } - boost::shared_ptr pServer; - boost::shared_ptr pEventHandler; - boost::shared_ptr pServerThread; - bool bStressDone; + shared_ptr pServer; + shared_ptr pEventHandler; + shared_ptr pServerThread; + boost::atomic bStressDone; boost::atomic_int64_t bStressConnectionCount; boost::atomic_int64_t bStressRequestCount; }; @@ -329,9 +331,9 @@ class TServerIntegrationProcessorFactoryTestFixture : public TServerIntegrationTestFixture { public: TServerIntegrationProcessorFactoryTestFixture() - : TServerIntegrationTestFixture(boost::make_shared( - boost::make_shared( - boost::make_shared()))) {} + : TServerIntegrationTestFixture(make_shared( + make_shared( + make_shared()))) {} }; template @@ -339,7 +341,7 @@ class TServerIntegrationProcessorTestFixture : public TServerIntegrationTestFixt public: TServerIntegrationProcessorTestFixture() : TServerIntegrationTestFixture( - boost::make_shared(boost::make_shared())) {} + make_shared(make_shared())) {} }; BOOST_AUTO_TEST_SUITE(constructors) @@ -376,7 +378,7 @@ BOOST_FIXTURE_TEST_CASE(test_threaded_stress, BOOST_FIXTURE_TEST_CASE(test_threadpool_factory, TServerIntegrationProcessorFactoryTestFixture) { pServer->getThreadManager()->threadFactory( - boost::shared_ptr( + shared_ptr( new apache::thrift::concurrency::PlatformThreadFactory)); pServer->getThreadManager()->start(); @@ -391,7 +393,7 @@ BOOST_FIXTURE_TEST_CASE(test_threadpool_factory, BOOST_FIXTURE_TEST_CASE(test_threadpool, TServerIntegrationProcessorTestFixture) { pServer->getThreadManager()->threadFactory( - boost::shared_ptr( + shared_ptr( new apache::thrift::concurrency::PlatformThreadFactory)); pServer->getThreadManager()->start(); @@ -406,7 +408,7 @@ BOOST_FIXTURE_TEST_CASE(test_threadpool, BOOST_FIXTURE_TEST_CASE(test_threadpool_bound, TServerIntegrationProcessorTestFixture) { pServer->getThreadManager()->threadFactory( - boost::shared_ptr( + shared_ptr( new apache::thrift::concurrency::PlatformThreadFactory)); pServer->getThreadManager()->start(); pServer->setConcurrentClientLimit(4); @@ -417,7 +419,7 @@ BOOST_FIXTURE_TEST_CASE(test_threadpool_bound, BOOST_FIXTURE_TEST_CASE(test_threadpool_stress, TServerIntegrationProcessorTestFixture) { pServer->getThreadManager()->threadFactory( - boost::shared_ptr( + shared_ptr( new apache::thrift::concurrency::PlatformThreadFactory)); pServer->getThreadManager()->start(); @@ -435,11 +437,11 @@ BOOST_AUTO_TEST_CASE(test_stop_with_interruptable_clients_connected) { startServer(); - boost::shared_ptr pClientSock1(new TSocket("localhost", getServerPort()), + shared_ptr pClientSock1(new TSocket("localhost", getServerPort()), autoSocketCloser); pClientSock1->open(); - boost::shared_ptr pClientSock2(new TSocket("localhost", getServerPort()), + shared_ptr pClientSock2(new TSocket("localhost", getServerPort()), autoSocketCloser); pClientSock2->open(); @@ -461,27 +463,27 @@ BOOST_AUTO_TEST_CASE(test_stop_with_uninterruptable_clients_connected) { // disconnect. BOOST_TEST_MESSAGE("Testing stop with uninterruptable clients"); - boost::dynamic_pointer_cast(pServer->getServerTransport()) + dynamic_pointer_cast(pServer->getServerTransport()) ->setInterruptableChildren(false); // returns to pre-THRIFT-2441 behavior startServer(); - boost::shared_ptr pClientSock1(new TSocket("localhost", getServerPort()), + shared_ptr pClientSock1(new TSocket("localhost", getServerPort()), autoSocketCloser); pClientSock1->open(); - boost::shared_ptr pClientSock2(new TSocket("localhost", getServerPort()), + shared_ptr pClientSock2(new TSocket("localhost", getServerPort()), autoSocketCloser); pClientSock2->open(); // Ensure they have been accepted blockUntilAccepted(2); - boost::thread t1(boost::bind(&TServerIntegrationTestFixture::delayClose, + boost::thread t1(apache::thrift::stdcxx::bind(&TServerIntegrationTestFixture::delayClose, this, pClientSock1, milliseconds(250))); - boost::thread t2(boost::bind(&TServerIntegrationTestFixture::delayClose, + boost::thread t2(apache::thrift::stdcxx::bind(&TServerIntegrationTestFixture::delayClose, this, pClientSock2, milliseconds(250))); @@ -502,24 +504,24 @@ BOOST_AUTO_TEST_CASE(test_concurrent_client_limit) { BOOST_CHECK_EQUAL(0, pServer->getConcurrentClientCount()); BOOST_CHECK_EQUAL(2, pServer->getConcurrentClientLimit()); - boost::shared_ptr pClientSock1(new TSocket("localhost", getServerPort()), + shared_ptr pClientSock1(new TSocket("localhost", getServerPort()), autoSocketCloser); pClientSock1->open(); blockUntilAccepted(1); BOOST_CHECK_EQUAL(1, pServer->getConcurrentClientCount()); - boost::shared_ptr pClientSock2(new TSocket("localhost", getServerPort()), + shared_ptr pClientSock2(new TSocket("localhost", getServerPort()), autoSocketCloser); pClientSock2->open(); blockUntilAccepted(2); BOOST_CHECK_EQUAL(2, pServer->getConcurrentClientCount()); // a third client cannot connect until one of the other two closes - boost::thread t2(boost::bind(&TServerIntegrationTestFixture::delayClose, + boost::thread t2(apache::thrift::stdcxx::bind(&TServerIntegrationTestFixture::delayClose, this, pClientSock2, milliseconds(250))); - boost::shared_ptr pClientSock3(new TSocket("localhost", getServerPort()), + shared_ptr pClientSock3(new TSocket("localhost", getServerPort()), autoSocketCloser); pClientSock2->open(); blockUntilAccepted(2); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/TServerSocketTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/TServerSocketTest.cpp index 1da5d36..a191147 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/TServerSocketTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/TServerSocketTest.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include "TTransportCheckThrow.h" #include @@ -27,6 +28,7 @@ using apache::thrift::transport::TServerSocket; using apache::thrift::transport::TSocket; using apache::thrift::transport::TTransport; using apache::thrift::transport::TTransportException; +using apache::thrift::stdcxx::shared_ptr; BOOST_AUTO_TEST_SUITE(TServerSocketTest) @@ -36,7 +38,7 @@ BOOST_AUTO_TEST_CASE(test_bind_to_address) { int port = sock1.getPort(); TSocket clientSock("localhost", port); clientSock.open(); - boost::shared_ptr accepted = sock1.accept(); + shared_ptr accepted = sock1.accept(); accepted->close(); sock1.close(); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/TServerTransportTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/TServerTransportTest.cpp index a554622..dc6aede 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/TServerTransportTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/TServerTransportTest.cpp @@ -20,10 +20,12 @@ #include #include #include +#include using apache::thrift::transport::TServerTransport; using apache::thrift::transport::TTransport; using apache::thrift::transport::TTransportException; +using apache::thrift::stdcxx::shared_ptr; BOOST_AUTO_TEST_SUITE(TServerTransportTest) @@ -36,9 +38,9 @@ public: bool valid_; protected: - boost::shared_ptr acceptImpl() { - return valid_ ? boost::shared_ptr(new TestTTransport) - : boost::shared_ptr(); + shared_ptr acceptImpl() { + return valid_ ? shared_ptr(new TestTTransport) + : shared_ptr(); } }; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/TSocketInterruptTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/TSocketInterruptTest.cpp index 27b89eb..3a189cc 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/TSocketInterruptTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/TSocketInterruptTest.cpp @@ -20,26 +20,27 @@ #define BOOST_TEST_MODULE TSocketInterruptTest #include -#include #include #include #include #include #include +#include using apache::thrift::transport::TServerSocket; using apache::thrift::transport::TSocket; using apache::thrift::transport::TTransport; using apache::thrift::transport::TTransportException; +using namespace apache::thrift; BOOST_AUTO_TEST_SUITE(TSocketInterruptTest) -void readerWorker(boost::shared_ptr tt, uint32_t expectedResult) { +void readerWorker(stdcxx::shared_ptr tt, uint32_t expectedResult) { uint8_t buf[4]; BOOST_CHECK_EQUAL(expectedResult, tt->read(buf, 4)); } -void readerWorkerMustThrow(boost::shared_ptr tt) { +void readerWorkerMustThrow(stdcxx::shared_ptr tt) { try { uint8_t buf[4]; tt->read(buf, 4); @@ -55,8 +56,8 @@ BOOST_AUTO_TEST_CASE(test_interruptable_child_read) { int port = sock1.getPort(); TSocket clientSock("localhost", port); clientSock.open(); - boost::shared_ptr accepted = sock1.accept(); - boost::thread readThread(boost::bind(readerWorkerMustThrow, accepted)); + stdcxx::shared_ptr accepted = sock1.accept(); + boost::thread readThread(stdcxx::bind(readerWorkerMustThrow, accepted)); boost::this_thread::sleep(boost::posix_time::milliseconds(50)); // readThread is practically guaranteed to be blocking now sock1.interruptChildren(); @@ -74,8 +75,8 @@ BOOST_AUTO_TEST_CASE(test_non_interruptable_child_read) { int port = sock1.getPort(); TSocket clientSock("localhost", port); clientSock.open(); - boost::shared_ptr accepted = sock1.accept(); - boost::thread readThread(boost::bind(readerWorker, accepted, 0)); + stdcxx::shared_ptr accepted = sock1.accept(); + boost::thread readThread(stdcxx::bind(readerWorker, accepted, 0)); boost::this_thread::sleep(boost::posix_time::milliseconds(50)); // readThread is practically guaranteed to be blocking here sock1.interruptChildren(); @@ -96,7 +97,7 @@ BOOST_AUTO_TEST_CASE(test_cannot_change_after_listen) { sock1.close(); } -void peekerWorker(boost::shared_ptr tt, bool expectedResult) { +void peekerWorker(stdcxx::shared_ptr tt, bool expectedResult) { BOOST_CHECK_EQUAL(expectedResult, tt->peek()); } @@ -106,9 +107,9 @@ BOOST_AUTO_TEST_CASE(test_interruptable_child_peek) { int port = sock1.getPort(); TSocket clientSock("localhost", port); clientSock.open(); - boost::shared_ptr accepted = sock1.accept(); + stdcxx::shared_ptr accepted = sock1.accept(); // peek() will return false if child is interrupted - boost::thread peekThread(boost::bind(peekerWorker, accepted, false)); + boost::thread peekThread(stdcxx::bind(peekerWorker, accepted, false)); boost::this_thread::sleep(boost::posix_time::milliseconds(50)); // peekThread is practically guaranteed to be blocking now sock1.interruptChildren(); @@ -126,9 +127,9 @@ BOOST_AUTO_TEST_CASE(test_non_interruptable_child_peek) { int port = sock1.getPort(); TSocket clientSock("localhost", port); clientSock.open(); - boost::shared_ptr accepted = sock1.accept(); + stdcxx::shared_ptr accepted = sock1.accept(); // peek() will return false when remote side is closed - boost::thread peekThread(boost::bind(peekerWorker, accepted, false)); + boost::thread peekThread(stdcxx::bind(peekerWorker, accepted, false)); boost::this_thread::sleep(boost::posix_time::milliseconds(50)); // peekThread is practically guaranteed to be blocking now sock1.interruptChildren(); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/TransportTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/TransportTest.cpp index ccef9d5..d6ab457 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/TransportTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/TransportTest.cpp @@ -26,7 +26,7 @@ #endif #include #include -#include +#include #include #include @@ -43,10 +43,12 @@ #include #if _WIN32 +#include #include #endif using namespace apache::thrift::transport; +using namespace apache::thrift; static boost::mt19937 rng; @@ -112,7 +114,7 @@ public: std::string describe() const { return generator_->describe(); } private: - boost::shared_ptr generator_; + stdcxx::shared_ptr generator_; }; /************************************************************************** @@ -135,8 +137,8 @@ public: CoupledTransports() : in(), out() {} - boost::shared_ptr in; - boost::shared_ptr out; + stdcxx::shared_ptr in; + stdcxx::shared_ptr out; private: CoupledTransports(const CoupledTransports&); @@ -153,7 +155,7 @@ public: out = buf; } - boost::shared_ptr buf; + stdcxx::shared_ptr buf; }; /** @@ -219,6 +221,22 @@ public: out.reset(new TFDTransport(pipes[1], TFDTransport::CLOSE_ON_DESTROY)); } }; +#else +/** + * Coupled pipe transports + */ +class CoupledPipeTransports : public CoupledTransports { +public: + HANDLE hRead; + HANDLE hWrite; + + CoupledPipeTransports() { + BOOST_REQUIRE(CreatePipe(&hRead, &hWrite, NULL, 1048576 * 2)); + in.reset(new TPipe(hRead, hWrite)); + in->open(); + out = in; + } +}; #endif /** @@ -323,11 +341,11 @@ public: **************************************************************************/ struct TriggerInfo { - TriggerInfo(int seconds, const boost::shared_ptr& transport, uint32_t writeLength) + TriggerInfo(int seconds, const stdcxx::shared_ptr& transport, uint32_t writeLength) : timeoutSeconds(seconds), transport(transport), writeLength(writeLength), next(NULL) {} int timeoutSeconds; - boost::shared_ptr transport; + stdcxx::shared_ptr transport; uint32_t writeLength; TriggerInfo* next; }; @@ -402,7 +420,7 @@ void alarm_handler_wrapper() { * to the end.) */ void add_trigger(unsigned int seconds, - const boost::shared_ptr& transport, + const stdcxx::shared_ptr& transport, uint32_t write_len) { TriggerInfo* info = new TriggerInfo(seconds, transport, write_len); { @@ -442,7 +460,7 @@ void clear_triggers() { } void set_trigger(unsigned int seconds, - const boost::shared_ptr& transport, + const stdcxx::shared_ptr& transport, uint32_t write_len) { clear_triggers(); add_trigger(seconds, transport, write_len); @@ -840,6 +858,19 @@ public: TEST_RW(CoupledFDTransports, 1024 * 16, 1, 1, rand4k, rand4k, fd_max_outstanding); TEST_BLOCKING_BEHAVIOR(CoupledFDTransports); +#else + // TPipe tests (WIN32 only) + TEST_RW(CoupledPipeTransports, 1024 * 1024, 0, 0); + TEST_RW(CoupledPipeTransports, 1024 * 256, rand4k, rand4k); + TEST_RW(CoupledPipeTransports, 1024 * 256, 167, 163); + TEST_RW(CoupledPipeTransports, 1024 * 16, 1, 1); + + TEST_RW(CoupledPipeTransports, 1024 * 256, 0, 0, rand4k, rand4k); + TEST_RW(CoupledPipeTransports, 1024 * 256, rand4k, rand4k, rand4k, rand4k); + TEST_RW(CoupledPipeTransports, 1024 * 256, 167, 163, rand4k, rand4k); + TEST_RW(CoupledPipeTransports, 1024 * 16, 1, 1, rand4k, rand4k); + + TEST_BLOCKING_BEHAVIOR(CoupledPipeTransports); #endif //_WIN32 // TSocket tests @@ -945,11 +976,11 @@ private: << rChunkSizeGen.describe() << ", " << maxOutstanding << ")"; #if (BOOST_VERSION >= 105900) - boost::function test_func + stdcxx::function test_func #else boost::unit_test::callback0<> test_func #endif - = apache::thrift::stdcxx::bind(test_rw, + = stdcxx::bind(test_rw, totalSize, wSizeGen, rSizeGen, @@ -995,7 +1026,7 @@ private: **************************************************************************/ struct global_fixture { - boost::shared_ptr alarmThread_; + stdcxx::shared_ptr alarmThread_; global_fixture() { #if _WIN32 apache::thrift::transport::TWinsockSingleton::create(); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/ZlibTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/ZlibTest.cpp index e155970..ea54487 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/ZlibTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/ZlibTest.cpp @@ -17,22 +17,27 @@ * under the License. */ -#define __STDC_FORMAT_MACROS - #ifndef _GNU_SOURCE #define _GNU_SOURCE // needed for getopt_long #endif +#if defined(_MSC_VER) && (_MSC_VER <= 1700) +// polynomial and std::fill_t warning happens in MSVC 2010, 2013, maybe others +// https://svn.boost.org/trac/boost/ticket/11426 +#pragma warning(disable:4996) +#endif + +#ifdef HAVE_STDINT_H #include +#endif #ifdef HAVE_INTTYPES_H #include #endif #include #include #include -#include +#include -#include #include #include #include @@ -41,8 +46,9 @@ #include #include -using namespace std; using namespace apache::thrift::transport; +using apache::thrift::stdcxx::shared_ptr; +using std::string; boost::mt19937 rng; @@ -141,8 +147,8 @@ boost::shared_array gen_random_buffer(uint32_t buf_len) { */ void test_write_then_read(const boost::shared_array buf, uint32_t buf_len) { - boost::shared_ptr membuf(new TMemoryBuffer()); - boost::shared_ptr zlib_trans(new TZlibTransport(membuf)); + shared_ptr membuf(new TMemoryBuffer()); + shared_ptr zlib_trans(new TZlibTransport(membuf)); zlib_trans->write(buf.get(), buf_len); zlib_trans->finish(); @@ -160,8 +166,8 @@ void test_separate_checksum(const boost::shared_array buf, uint32_t buf // it isn't there. The original implementation complained that // the stream was not complete. I'm about to go fix that. // It worked. Awesome. - boost::shared_ptr membuf(new TMemoryBuffer()); - boost::shared_ptr zlib_trans(new TZlibTransport(membuf)); + shared_ptr membuf(new TMemoryBuffer()); + shared_ptr zlib_trans(new TZlibTransport(membuf)); zlib_trans->write(buf.get(), buf_len); zlib_trans->finish(); string tmp_buf; @@ -180,8 +186,8 @@ void test_separate_checksum(const boost::shared_array buf, uint32_t buf void test_incomplete_checksum(const boost::shared_array buf, uint32_t buf_len) { // Make sure we still get that "not complete" error if // it really isn't complete. - boost::shared_ptr membuf(new TMemoryBuffer()); - boost::shared_ptr zlib_trans(new TZlibTransport(membuf)); + shared_ptr membuf(new TMemoryBuffer()); + shared_ptr zlib_trans(new TZlibTransport(membuf)); zlib_trans->write(buf.get(), buf_len); zlib_trans->finish(); string tmp_buf; @@ -204,11 +210,11 @@ void test_incomplete_checksum(const boost::shared_array buf, uint32_t b void test_read_write_mix(const boost::shared_array buf, uint32_t buf_len, - const boost::shared_ptr& write_gen, - const boost::shared_ptr& read_gen) { + const shared_ptr& write_gen, + const shared_ptr& read_gen) { // Try it with a mix of read/write sizes. - boost::shared_ptr membuf(new TMemoryBuffer()); - boost::shared_ptr zlib_trans(new TZlibTransport(membuf)); + shared_ptr membuf(new TMemoryBuffer()); + shared_ptr zlib_trans(new TZlibTransport(membuf)); unsigned int tot; tot = 0; @@ -243,8 +249,8 @@ void test_read_write_mix(const boost::shared_array buf, void test_invalid_checksum(const boost::shared_array buf, uint32_t buf_len) { // Verify checksum checking. - boost::shared_ptr membuf(new TMemoryBuffer()); - boost::shared_ptr zlib_trans(new TZlibTransport(membuf)); + shared_ptr membuf(new TMemoryBuffer()); + shared_ptr zlib_trans(new TZlibTransport(membuf)); zlib_trans->write(buf.get(), buf_len); zlib_trans->finish(); string tmp_buf; @@ -280,8 +286,8 @@ void test_invalid_checksum(const boost::shared_array buf, uint32_t buf_ void test_write_after_flush(const boost::shared_array buf, uint32_t buf_len) { // write some data - boost::shared_ptr membuf(new TMemoryBuffer()); - boost::shared_ptr zlib_trans(new TZlibTransport(membuf)); + shared_ptr membuf(new TMemoryBuffer()); + shared_ptr zlib_trans(new TZlibTransport(membuf)); zlib_trans->write(buf.get(), buf_len); // call finish() @@ -316,7 +322,7 @@ void test_write_after_flush(const boost::shared_array buf, uint32_t buf void test_no_write() { // Verify that no data is written to the underlying transport if we // never write data to the TZlibTransport. - boost::shared_ptr membuf(new TMemoryBuffer()); + shared_ptr membuf(new TMemoryBuffer()); { // Create a TZlibTransport object, and immediately destroy it // when it goes out of scope. @@ -326,6 +332,12 @@ void test_no_write() { BOOST_CHECK_EQUAL(membuf->available_read(), (uint32_t)0); } +void test_get_underlying_transport() { + shared_ptr membuf(new TMemoryBuffer()); + shared_ptr zlib_trans(new TZlibTransport(membuf)); + BOOST_CHECK_EQUAL(membuf.get(), zlib_trans->getUnderlyingTransport().get()); +} + /* * Initialization */ @@ -335,7 +347,8 @@ void test_no_write() { do { \ ::std::ostringstream name_ss; \ name_ss << name << "-" << BOOST_STRINGIZE(_FUNC); \ - boost::function test_func = ::apache::thrift::stdcxx::bind(_FUNC, ##__VA_ARGS__); \ + ::apache::thrift::stdcxx::function test_func = \ + ::apache::thrift::stdcxx::bind(_FUNC, ##__VA_ARGS__); \ ::boost::unit_test::test_case* tc \ = ::boost::unit_test::make_test_case(test_func, name_ss.str(), __FILE__, __LINE__); \ (suite)->add(tc); \ @@ -363,8 +376,8 @@ void add_tests(boost::unit_test::test_suite* suite, ADD_TEST_CASE(suite, name, test_invalid_checksum, buf, buf_len); ADD_TEST_CASE(suite, name, test_write_after_flush, buf, buf_len); - boost::shared_ptr size_32k(new ConstantSizeGenerator(1 << 15)); - boost::shared_ptr size_lognormal(new LogNormalSizeGenerator(20, 30)); + shared_ptr size_32k(new ConstantSizeGenerator(1 << 15)); + shared_ptr size_lognormal(new LogNormalSizeGenerator(20, 30)); ADD_TEST_CASE(suite, name << "-constant", test_read_write_mix, buf, buf_len, size_32k, size_32k); ADD_TEST_CASE(suite, name << "-lognormal-write", @@ -394,8 +407,8 @@ void add_tests(boost::unit_test::test_suite* suite, // Because the SizeGenerator makes a copy of the random number generator, // both SizeGenerators should return the exact same set of values, since they // both start with random number generators in the same state. - boost::shared_ptr write_size_gen(new LogNormalSizeGenerator(20, 30)); - boost::shared_ptr read_size_gen(new LogNormalSizeGenerator(20, 30)); + shared_ptr write_size_gen(new LogNormalSizeGenerator(20, 30)); + shared_ptr read_size_gen(new LogNormalSizeGenerator(20, 30)); ADD_TEST_CASE(suite, name << "-lognormal-same-distribution", test_read_write_mix, @@ -429,6 +442,7 @@ bool init_unit_test_suite() { add_tests(suite, gen_random_buffer(buf_len), buf_len, "random"); suite->add(BOOST_TEST_CASE(test_no_write)); + suite->add(BOOST_TEST_CASE(test_get_underlying_transport)); return true; } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/MutexTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/MutexTest.cpp new file mode 100644 index 0000000..781ec1a --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/MutexTest.cpp @@ -0,0 +1,123 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +// This is linked into the UnitTests test executable + +#include + +#include "thrift/concurrency/Exception.h" +#include "thrift/concurrency/Mutex.h" + +using boost::unit_test::test_suite; +using boost::unit_test::framework::master_test_suite; + +using namespace apache::thrift::concurrency; + +struct LFAT +{ + LFAT() + : uut(Mutex::ERRORCHECK_INITIALIZER) + { + BOOST_CHECK_EQUAL(0, pthread_mutex_init(&mx, 0)); + BOOST_CHECK_EQUAL(0, pthread_cond_init(&cv, 0)); + } + + Mutex uut; + pthread_mutex_t mx; + pthread_cond_t cv; +}; + +// Helper for testing mutex behavior when locked by another thread +void * lockFromAnotherThread(void *ptr) +{ + struct LFAT *lfat = (LFAT *)ptr; + BOOST_CHECK_EQUAL (0, pthread_mutex_lock(&lfat->mx)); // synchronize with testing thread + BOOST_CHECK_NO_THROW( lfat->uut.lock()); + BOOST_CHECK_EQUAL (0, pthread_cond_signal(&lfat->cv)); // tell testing thread we have locked the mutex + BOOST_CHECK_EQUAL (0, pthread_cond_wait(&lfat->cv, &lfat->mx)); // wait for testing thread to signal condition variable telling us to unlock + BOOST_CHECK_NO_THROW( lfat->uut.unlock()); + return ptr; // testing thread should join to ensure completeness +} + +BOOST_AUTO_TEST_SUITE(MutexTest) + +BOOST_AUTO_TEST_CASE(happy_path) +{ + Mutex uut(Mutex::ERRORCHECK_INITIALIZER); // needed to test unlocking twice without undefined behavior + + BOOST_CHECK_NO_THROW( uut.lock()); + BOOST_CHECK_THROW ( uut.lock(), SystemResourceException); // EDEADLK (this thread owns it) + BOOST_CHECK_NO_THROW( uut.unlock()); +} + +BOOST_AUTO_TEST_CASE(recursive_happy_path) +{ + Mutex uut(Mutex::RECURSIVE_INITIALIZER); + + BOOST_CHECK_NO_THROW( uut.lock()); + BOOST_CHECK_NO_THROW( uut.lock()); + BOOST_CHECK_NO_THROW( uut.unlock()); + BOOST_CHECK_NO_THROW( uut.lock()); + BOOST_CHECK_NO_THROW( uut.lock()); + BOOST_CHECK_NO_THROW( uut.unlock()); + BOOST_CHECK_NO_THROW( uut.lock()); + BOOST_CHECK_NO_THROW( uut.unlock()); + BOOST_CHECK_NO_THROW( uut.unlock()); + BOOST_CHECK_NO_THROW( uut.unlock()); +} + +BOOST_AUTO_TEST_CASE(trylock) +{ + Mutex uut(Mutex::ADAPTIVE_INITIALIZER); // just using another initializer for coverage + + BOOST_CHECK ( uut.trylock()); + BOOST_CHECK (!uut.trylock()); + BOOST_CHECK_NO_THROW( uut.unlock()); +} + +BOOST_AUTO_TEST_CASE(timedlock) +{ + pthread_t th; + struct LFAT lfat; + + BOOST_CHECK ( lfat.uut.timedlock(100)); + BOOST_CHECK_THROW ( lfat.uut.timedlock(100), + SystemResourceException); // EDEADLK (current thread owns mutex - logic error) + BOOST_CHECK_NO_THROW( lfat.uut.unlock()); + + BOOST_CHECK_EQUAL (0, pthread_mutex_lock(&lfat.mx)); // synchronize with helper thread + BOOST_CHECK_EQUAL (0, pthread_create(&th, NULL, + lockFromAnotherThread, &lfat)); // create helper thread + BOOST_CHECK_EQUAL (0, pthread_cond_wait(&lfat.cv, &lfat.mx)); // wait for helper thread to lock mutex + + BOOST_CHECK (!lfat.uut.timedlock(100)); // false: another thread owns the lock + + BOOST_CHECK_EQUAL (0, pthread_cond_signal(&lfat.cv)); // tell helper thread we are done + BOOST_CHECK_EQUAL (0, pthread_mutex_unlock(&lfat.mx)); // let helper thread clean up + BOOST_CHECK_EQUAL (0, pthread_join(th, 0)); // wait for testing thread to unlock and be done +} + +BOOST_AUTO_TEST_CASE(underlying) +{ + Mutex uut; + + BOOST_CHECK ( uut.getUnderlyingImpl()); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/RWMutexStarveTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/RWMutexStarveTest.cpp similarity index 82% rename from vendor/git.apache.org/thrift.git/lib/cpp/test/RWMutexStarveTest.cpp rename to vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/RWMutexStarveTest.cpp index 32c1531..849e078 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/RWMutexStarveTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/RWMutexStarveTest.cpp @@ -17,25 +17,23 @@ * under the License. */ -#include -#include +// This is linked into the UnitTests test executable -#include #include #include "thrift/concurrency/Mutex.h" #include "thrift/concurrency/PosixThreadFactory.h" +#include -using boost::shared_ptr; +using apache::thrift::stdcxx::shared_ptr; using boost::unit_test::test_suite; using boost::unit_test::framework::master_test_suite; using namespace apache::thrift::concurrency; -using namespace std; class Locker : public Runnable { protected: - Locker(boost::shared_ptr rwlock, bool writer) + Locker(shared_ptr rwlock, bool writer) : rwlock_(rwlock), writer_(writer), started_(false), gotLock_(false), signaled_(false) {} public: @@ -58,7 +56,7 @@ public: void signal() { signaled_ = true; } protected: - boost::shared_ptr rwlock_; + shared_ptr rwlock_; bool writer_; volatile bool started_; volatile bool gotLock_; @@ -67,12 +65,12 @@ protected: class Reader : public Locker { public: - Reader(boost::shared_ptr rwlock) : Locker(rwlock, false) {} + Reader(shared_ptr rwlock) : Locker(rwlock, false) {} }; class Writer : public Locker { public: - Writer(boost::shared_ptr rwlock) : Locker(rwlock, true) {} + Writer(shared_ptr rwlock) : Locker(rwlock, true) {} }; void test_starve(PosixThreadFactory::POLICY policy) { @@ -82,15 +80,15 @@ void test_starve(PosixThreadFactory::POLICY policy) { PosixThreadFactory factory(policy); factory.setDetached(false); - boost::shared_ptr rwlock(new NoStarveReadWriteMutex()); + shared_ptr rwlock(new NoStarveReadWriteMutex()); - boost::shared_ptr reader1(new Reader(rwlock)); - boost::shared_ptr reader2(new Reader(rwlock)); - boost::shared_ptr writer(new Writer(rwlock)); + shared_ptr reader1(new Reader(rwlock)); + shared_ptr reader2(new Reader(rwlock)); + shared_ptr writer(new Writer(rwlock)); - boost::shared_ptr treader1 = factory.newThread(reader1); - boost::shared_ptr treader2 = factory.newThread(reader2); - boost::shared_ptr twriter = factory.newThread(writer); + shared_ptr treader1 = factory.newThread(reader1); + shared_ptr treader2 = factory.newThread(reader2); + shared_ptr twriter = factory.newThread(writer); // launch a reader and make sure he has the lock treader1->start(); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/Tests.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/Tests.cpp index 33af392..fc0ba7f 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/Tests.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/Tests.cpp @@ -25,6 +25,10 @@ #include "TimerManagerTests.h" #include "ThreadManagerTests.h" +// The test weight, where 10 is 10 times more threads than baseline +// and the baseline is optimized for running in valgrind +static int WEIGHT = 10; + int main(int argc, char** argv) { std::string arg; @@ -37,6 +41,11 @@ int main(int argc, char** argv) { args[ix - 1] = std::string(argv[ix]); } + if (getenv("VALGRIND") != 0) { + // lower the scale of every test + WEIGHT = 1; + } + bool runAll = args[0].compare("all") == 0; if (runAll || args[0].compare("thread-factory") == 0) { @@ -45,10 +54,10 @@ int main(int argc, char** argv) { std::cout << "ThreadFactory tests..." << std::endl; - int reapLoops = 20; - int reapCount = 1000; + int reapLoops = 2 * WEIGHT; + int reapCount = 100 * WEIGHT; size_t floodLoops = 3; - size_t floodCount = 20000; + size_t floodCount = 500 * WEIGHT; std::cout << "\t\tThreadFactory reap N threads test: N = " << reapLoops << "x" << reapCount << std::endl; @@ -114,6 +123,34 @@ int main(int argc, char** argv) { std::cerr << "\t\tTimerManager tests FAILED" << std::endl; return 1; } + + std::cout << "\t\tTimerManager test01" << std::endl; + + if (!timerManagerTests.test01()) { + std::cerr << "\t\tTimerManager tests FAILED" << std::endl; + return 1; + } + + std::cout << "\t\tTimerManager test02" << std::endl; + + if (!timerManagerTests.test02()) { + std::cerr << "\t\tTimerManager tests FAILED" << std::endl; + return 1; + } + + std::cout << "\t\tTimerManager test03" << std::endl; + + if (!timerManagerTests.test03()) { + std::cerr << "\t\tTimerManager tests FAILED" << std::endl; + return 1; + } + + std::cout << "\t\tTimerManager test04" << std::endl; + + if (!timerManagerTests.test04()) { + std::cerr << "\t\tTimerManager tests FAILED" << std::endl; + return 1; + } } if (runAll || args[0].compare("thread-manager") == 0) { @@ -121,8 +158,8 @@ int main(int argc, char** argv) { std::cout << "ThreadManager tests..." << std::endl; { - size_t workerCount = 100; - size_t taskCount = 50000; + size_t workerCount = 10 * WEIGHT; + size_t taskCount = 500 * WEIGHT; int64_t delay = 10LL; ThreadManagerTests threadManagerTests; @@ -160,13 +197,13 @@ int main(int argc, char** argv) { size_t minWorkerCount = 2; - size_t maxWorkerCount = 64; + size_t maxWorkerCount = 8; - size_t tasksPerWorker = 1000; + size_t tasksPerWorker = 100 * WEIGHT; int64_t delay = 5LL; - for (size_t workerCount = minWorkerCount; workerCount < maxWorkerCount; workerCount *= 4) { + for (size_t workerCount = minWorkerCount; workerCount <= maxWorkerCount; workerCount *= 4) { size_t taskCount = workerCount * tasksPerWorker; diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/ThreadFactoryTests.h b/vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/ThreadFactoryTests.h index 4fc688c..48330f3 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/ThreadFactoryTests.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/ThreadFactoryTests.h @@ -21,18 +21,19 @@ #include #include #include +#include #include #include #include -#include +#include namespace apache { namespace thrift { namespace concurrency { namespace test { -using boost::shared_ptr; +using stdcxx::shared_ptr; using namespace apache::thrift::concurrency; /** @@ -53,39 +54,33 @@ public: void run() { Synchronized s(_monitor); - - _count--; - - // std::cout << "\t\t\tthread count: " << _count << std::endl; - - if (_count == 0) { + + if (--_count == 0) { _monitor.notify(); } } Monitor& _monitor; - int& _count; }; bool reapNThreads(int loop = 1, int count = 10) { PlatformThreadFactory threadFactory = PlatformThreadFactory(); - shared_ptr monitor(new Monitor); for (int lix = 0; lix < loop; lix++) { - int* activeCount = new int(count); - - std::set > threads; + int activeCount = 0; + std::vector > threads; int tix; for (tix = 0; tix < count; tix++) { try { - threads.insert( - threadFactory.newThread(shared_ptr(new ReapNTask(*monitor, *activeCount)))); + ++activeCount; + threads.push_back( + threadFactory.newThread(shared_ptr(new ReapNTask(*monitor, activeCount)))); } catch (SystemResourceException& e) { std::cout << "\t\t\tfailed to create " << lix* count + tix << " thread " << e.what() << std::endl; @@ -94,7 +89,7 @@ public: } tix = 0; - for (std::set >::const_iterator thread = threads.begin(); + for (std::vector >::const_iterator thread = threads.begin(); thread != threads.end(); tix++, ++thread) { @@ -109,16 +104,15 @@ public: { Synchronized s(*monitor); - while (*activeCount > 0) { + while (activeCount > 0) { monitor->wait(1000); } } - delete activeCount; + std::cout << "\t\t\treaped " << lix* count << " threads" << std::endl; } std::cout << "\t\t\tSuccess!" << std::endl; - return true; } @@ -253,19 +247,22 @@ public: class FloodTask : public Runnable { public: - FloodTask(const size_t id) : _id(id) {} + FloodTask(const size_t id, Monitor& mon) : _id(id), _mon(mon) {} ~FloodTask() { if (_id % 10000 == 0) { + Synchronized sync(_mon); std::cout << "\t\tthread " << _id << " done" << std::endl; } } void run() { if (_id % 10000 == 0) { + Synchronized sync(_mon); std::cout << "\t\tthread " << _id << " started" << std::endl; } } const size_t _id; + Monitor& _mon; }; void foo(PlatformThreadFactory* tf) { (void)tf; } @@ -273,7 +270,8 @@ public: bool floodNTest(size_t loop = 1, size_t count = 100000) { bool success = false; - + Monitor mon; + for (size_t lix = 0; lix < loop; lix++) { PlatformThreadFactory threadFactory = PlatformThreadFactory(); @@ -283,10 +281,8 @@ public: try { - shared_ptr task(new FloodTask(lix * count + tix)); - + shared_ptr task(new FloodTask(lix * count + tix, mon)); shared_ptr thread = threadFactory.newThread(task); - thread->start(); } catch (TException& e) { @@ -298,8 +294,8 @@ public: } } + Synchronized sync(mon); std::cout << "\t\t\tflooded " << (lix + 1) * count << " threads" << std::endl; - success = true; } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/ThreadManagerTests.h b/vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/ThreadManagerTests.h index b5925ac..9ecd6ba 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/ThreadManagerTests.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/ThreadManagerTests.h @@ -36,8 +36,8 @@ namespace test { using namespace apache::thrift::concurrency; -static std::deque > m_expired; -static void expiredNotifier(boost::shared_ptr runnable) +static std::deque > m_expired; +static void expiredNotifier(stdcxx::shared_ptr runnable) { m_expired.push_back(runnable); } @@ -109,7 +109,7 @@ public: shared_ptr threadManager = ThreadManager::newSimpleThreadManager(workerCount); shared_ptr threadFactory - = shared_ptr(new PlatformThreadFactory()); + = shared_ptr(new PlatformThreadFactory(false)); #if !USE_BOOST_THREAD && !USE_STD_THREAD threadFactory->setPriority(PosixThreadFactory::HIGHEST); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/TimerManagerTests.h b/vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/TimerManagerTests.h index 32d3935..1c52c47 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/TimerManagerTests.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/concurrency/TimerManagerTests.h @@ -79,14 +79,13 @@ public: = shared_ptr(new TimerManagerTests::Task(_monitor, 10 * timeout)); { - TimerManager timerManager; - timerManager.threadFactory(shared_ptr(new PlatformThreadFactory())); - timerManager.start(); - - assert(timerManager.state() == TimerManager::STARTED); + if (timerManager.state() != TimerManager::STARTED) { + std::cerr << "timerManager is not in the STARTED state, but should be" << std::endl; + return false; + } // Don't create task yet, because its constructor sets the expected completion time, and we // need to delay between inserting the two tasks into the run queue. @@ -94,34 +93,161 @@ public: { Synchronized s(_monitor); - timerManager.add(orphanTask, 10 * timeout); - try { - // Wait for 1 second in order to give timerManager a chance to start sleeping in response - // to adding orphanTask. We need to do this so we can verify that adding the second task - // kicks the dispatcher out of the current wait and starts the new 1 second wait. - _monitor.wait(1000); - assert( - 0 == "ERROR: This wait should time out. TimerManager dispatcher may have a problem."); - } catch (TimedOutException&) { - } + THRIFT_SLEEP_USEC(timeout * 1000); task.reset(new TimerManagerTests::Task(_monitor, timeout)); - timerManager.add(task, timeout); - _monitor.wait(); } - assert(task->_done); + if (!task->_done) { + std::cerr << "task is not done, but it should have executed" << std::endl; + return false; + } std::cout << "\t\t\t" << (task->_success ? "Success" : "Failure") << "!" << std::endl; } - // timerManager.stop(); This is where it happens via destructor + if (orphanTask->_done) { + std::cerr << "orphan task is done, but it should not have executed" << std::endl; + return false; + } - assert(!orphanTask->_done); + return true; + } + + /** + * This test creates two tasks, removes the first one then waits for the second one. It then + * verifies that the timer manager properly clean up itself and the remaining orphaned timeout + * task when the manager goes out of scope and its destructor is called. + */ + bool test01(int64_t timeout = 1000LL) { + TimerManager timerManager; + timerManager.threadFactory(shared_ptr(new PlatformThreadFactory())); + timerManager.start(); + assert(timerManager.state() == TimerManager::STARTED); + + Synchronized s(_monitor); + + // Setup the two tasks + shared_ptr taskToRemove + = shared_ptr(new TimerManagerTests::Task(_monitor, timeout / 2)); + timerManager.add(taskToRemove, taskToRemove->_timeout); + + shared_ptr task + = shared_ptr(new TimerManagerTests::Task(_monitor, timeout)); + timerManager.add(task, task->_timeout); + + // Remove one task and wait until the other has completed + timerManager.remove(taskToRemove); + _monitor.wait(timeout * 2); + + assert(!taskToRemove->_done); + assert(task->_done); + + return true; + } + + /** + * This test creates two tasks with the same callback and another one, then removes the two + * duplicated then waits for the last one. It then verifies that the timer manager properly + * clean up itself and the remaining orphaned timeout task when the manager goes out of scope + * and its destructor is called. + */ + bool test02(int64_t timeout = 1000LL) { + TimerManager timerManager; + timerManager.threadFactory(shared_ptr(new PlatformThreadFactory())); + timerManager.start(); + assert(timerManager.state() == TimerManager::STARTED); + + Synchronized s(_monitor); + + // Setup the one tasks and add it twice + shared_ptr taskToRemove + = shared_ptr(new TimerManagerTests::Task(_monitor, timeout / 3)); + timerManager.add(taskToRemove, taskToRemove->_timeout); + timerManager.add(taskToRemove, taskToRemove->_timeout * 2); + + shared_ptr task + = shared_ptr(new TimerManagerTests::Task(_monitor, timeout)); + timerManager.add(task, task->_timeout); + + // Remove the first task (e.g. two timers) and wait until the other has completed + timerManager.remove(taskToRemove); + _monitor.wait(timeout * 2); + + assert(!taskToRemove->_done); + assert(task->_done); + + return true; + } + + /** + * This test creates two tasks, removes the first one then waits for the second one. It then + * verifies that the timer manager properly clean up itself and the remaining orphaned timeout + * task when the manager goes out of scope and its destructor is called. + */ + bool test03(int64_t timeout = 1000LL) { + TimerManager timerManager; + timerManager.threadFactory(shared_ptr(new PlatformThreadFactory())); + timerManager.start(); + assert(timerManager.state() == TimerManager::STARTED); + + Synchronized s(_monitor); + + // Setup the two tasks + shared_ptr taskToRemove + = shared_ptr(new TimerManagerTests::Task(_monitor, timeout / 2)); + TimerManager::Timer timer = timerManager.add(taskToRemove, taskToRemove->_timeout); + + shared_ptr task + = shared_ptr(new TimerManagerTests::Task(_monitor, timeout)); + timerManager.add(task, task->_timeout); + + // Remove one task and wait until the other has completed + timerManager.remove(timer); + _monitor.wait(timeout * 2); + + assert(!taskToRemove->_done); + assert(task->_done); + + // Verify behavior when removing the removed task + try { + timerManager.remove(timer); + assert(0 == "ERROR: This remove should send a NoSuchTaskException exception."); + } catch (NoSuchTaskException&) { + } + + return true; + } + + /** + * This test creates one tasks, and tries to remove it after it has expired. + */ + bool test04(int64_t timeout = 1000LL) { + TimerManager timerManager; + timerManager.threadFactory(shared_ptr(new PlatformThreadFactory())); + timerManager.start(); + assert(timerManager.state() == TimerManager::STARTED); + + Synchronized s(_monitor); + + // Setup the task + shared_ptr task + = shared_ptr(new TimerManagerTests::Task(_monitor, timeout / 10)); + TimerManager::Timer timer = timerManager.add(task, task->_timeout); + + // Wait until the task has completed + _monitor.wait(timeout); + + // Verify behavior when removing the expired task + try { + timerManager.remove(timer); + assert(0 == "ERROR: This remove should send a NoSuchTaskException exception."); + } catch (NoSuchTaskException&) { + } return true; } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/processor/EventLog.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/processor/EventLog.cpp index 360307a..e3ddbcc 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/processor/EventLog.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/processor/EventLog.cpp @@ -21,7 +21,6 @@ #include #include -using namespace std; using namespace apache::thrift::concurrency; namespace { @@ -82,7 +81,7 @@ EventLog::EventLog() { void EventLog::append(EventType type, uint32_t connectionId, uint32_t callId, - const string& message) { + const std::string& message) { Synchronized s(monitor_); debug("%d <-- %u, %u, %s \"%s\"", id_, connectionId, callId, type, message.c_str()); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/processor/Handlers.h b/vendor/git.apache.org/thrift.git/lib/cpp/test/processor/Handlers.h index 041fd3d..ad47229 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/processor/Handlers.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/processor/Handlers.h @@ -29,7 +29,7 @@ namespace test { class ParentHandler : virtual public ParentServiceIf { public: - ParentHandler(const boost::shared_ptr& log) + ParentHandler(const stdcxx::shared_ptr& log) : triggerMonitor(&mutex_), generation_(0), wait_(false), log_(log) {} int32_t incrementGeneration() { @@ -136,7 +136,7 @@ protected: int32_t generation_; bool wait_; std::vector strings_; - boost::shared_ptr log_; + stdcxx::shared_ptr log_; }; #ifdef _WIN32 @@ -146,7 +146,7 @@ protected: class ChildHandler : public ParentHandler, virtual public ChildServiceIf { public: - ChildHandler(const boost::shared_ptr& log) : ParentHandler(log), value_(0) {} + ChildHandler(const stdcxx::shared_ptr& log) : ParentHandler(log), value_(0) {} int32_t setValue(const int32_t value) { concurrency::Guard g(mutex_); @@ -174,13 +174,13 @@ protected: struct ConnContext { public: - ConnContext(boost::shared_ptr in, - boost::shared_ptr out, + ConnContext(stdcxx::shared_ptr in, + stdcxx::shared_ptr out, uint32_t id) : input(in), output(out), id(id) {} - boost::shared_ptr input; - boost::shared_ptr output; + stdcxx::shared_ptr input; + stdcxx::shared_ptr output; uint32_t id; }; @@ -196,12 +196,12 @@ public: class ServerEventHandler : public server::TServerEventHandler { public: - ServerEventHandler(const boost::shared_ptr& log) : nextId_(1), log_(log) {} + ServerEventHandler(const stdcxx::shared_ptr& log) : nextId_(1), log_(log) {} virtual void preServe() {} - virtual void* createContext(boost::shared_ptr input, - boost::shared_ptr output) { + virtual void* createContext(stdcxx::shared_ptr input, + stdcxx::shared_ptr output) { ConnContext* context = new ConnContext(input, output, nextId_); ++nextId_; log_->append(EventLog::ET_CONN_CREATED, context->id, 0); @@ -209,8 +209,8 @@ public: } virtual void deleteContext(void* serverContext, - boost::shared_ptr input, - boost::shared_ptr output) { + stdcxx::shared_ptr input, + stdcxx::shared_ptr output) { ConnContext* context = reinterpret_cast(serverContext); if (input != context->input) { @@ -226,7 +226,7 @@ public: } virtual void processContext(void* serverContext, - boost::shared_ptr transport) { + stdcxx::shared_ptr transport) { // TODO: We currently don't test the behavior of the processContext() // calls. The various server implementations call processContext() at // slightly different times, and it is too annoying to try and account for @@ -251,12 +251,12 @@ public: protected: uint32_t nextId_; - boost::shared_ptr log_; + stdcxx::shared_ptr log_; }; class ProcessorEventHandler : public TProcessorEventHandler { public: - ProcessorEventHandler(const boost::shared_ptr& log) : nextId_(1), log_(log) {} + ProcessorEventHandler(const stdcxx::shared_ptr& log) : nextId_(1), log_(log) {} void* getContext(const char* fnName, void* serverContext) { ConnContext* connContext = reinterpret_cast(serverContext); @@ -329,7 +329,7 @@ protected: } uint32_t nextId_; - boost::shared_ptr log_; + stdcxx::shared_ptr log_; }; } } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/processor/ProcessorTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/processor/ProcessorTest.cpp index a4e984c..c9e186f 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/processor/ProcessorTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/processor/ProcessorTest.cpp @@ -33,21 +33,21 @@ #include #include #include +#include #include "EventLog.h" #include "ServerThread.h" #include "Handlers.h" #include "gen-cpp/ChildService.h" -using namespace std; -using namespace boost; using namespace apache::thrift; using namespace apache::thrift::concurrency; using namespace apache::thrift::protocol; using namespace apache::thrift::server; -using namespace apache::thrift::transport; - using namespace apache::thrift::test; +using namespace apache::thrift::transport; +using std::string; +using std::vector; /* * Traits classes that encapsulate how to create various types of servers. @@ -57,13 +57,13 @@ class TSimpleServerTraits { public: typedef TSimpleServer ServerType; - boost::shared_ptr createServer( - const boost::shared_ptr& processor, + stdcxx::shared_ptr createServer( + const stdcxx::shared_ptr& processor, uint16_t port, - const boost::shared_ptr& transportFactory, - const boost::shared_ptr& protocolFactory) { - boost::shared_ptr socket(new TServerSocket(port)); - return boost::shared_ptr( + const stdcxx::shared_ptr& transportFactory, + const stdcxx::shared_ptr& protocolFactory) { + stdcxx::shared_ptr socket(new TServerSocket(port)); + return stdcxx::shared_ptr( new TSimpleServer(processor, socket, transportFactory, protocolFactory)); } }; @@ -72,13 +72,13 @@ class TThreadedServerTraits { public: typedef TThreadedServer ServerType; - boost::shared_ptr createServer( - const boost::shared_ptr& processor, + stdcxx::shared_ptr createServer( + const stdcxx::shared_ptr& processor, uint16_t port, - const boost::shared_ptr& transportFactory, - const boost::shared_ptr& protocolFactory) { - boost::shared_ptr socket(new TServerSocket(port)); - return boost::shared_ptr( + const stdcxx::shared_ptr& transportFactory, + const stdcxx::shared_ptr& protocolFactory) { + stdcxx::shared_ptr socket(new TServerSocket(port)); + return stdcxx::shared_ptr( new TThreadedServer(processor, socket, transportFactory, protocolFactory)); } }; @@ -87,19 +87,19 @@ class TThreadPoolServerTraits { public: typedef TThreadPoolServer ServerType; - boost::shared_ptr createServer( - const boost::shared_ptr& processor, + stdcxx::shared_ptr createServer( + const stdcxx::shared_ptr& processor, uint16_t port, - const boost::shared_ptr& transportFactory, - const boost::shared_ptr& protocolFactory) { - boost::shared_ptr socket(new TServerSocket(port)); + const stdcxx::shared_ptr& transportFactory, + const stdcxx::shared_ptr& protocolFactory) { + stdcxx::shared_ptr socket(new TServerSocket(port)); - boost::shared_ptr threadFactory(new PlatformThreadFactory); - boost::shared_ptr threadManager = ThreadManager::newSimpleThreadManager(8); + stdcxx::shared_ptr threadFactory(new PlatformThreadFactory); + stdcxx::shared_ptr threadManager = ThreadManager::newSimpleThreadManager(8); threadManager->threadFactory(threadFactory); threadManager->start(); - return boost::shared_ptr( + return stdcxx::shared_ptr( new TThreadPoolServer(processor, socket, transportFactory, protocolFactory, threadManager)); } }; @@ -108,11 +108,11 @@ class TNonblockingServerTraits { public: typedef TNonblockingServer ServerType; - boost::shared_ptr createServer( - const boost::shared_ptr& processor, + stdcxx::shared_ptr createServer( + const stdcxx::shared_ptr& processor, uint16_t port, - const boost::shared_ptr& transportFactory, - const boost::shared_ptr& protocolFactory) { + const stdcxx::shared_ptr& transportFactory, + const stdcxx::shared_ptr& protocolFactory) { // TNonblockingServer automatically uses TFramedTransport. // Raise an exception if the supplied transport factory is not a // TFramedTransportFactory @@ -122,13 +122,14 @@ public: throw TException("TNonblockingServer must use TFramedTransport"); } - boost::shared_ptr threadFactory(new PlatformThreadFactory); - boost::shared_ptr threadManager = ThreadManager::newSimpleThreadManager(8); + stdcxx::shared_ptr socket(new TNonblockingServerSocket(port)); + stdcxx::shared_ptr threadFactory(new PlatformThreadFactory); + stdcxx::shared_ptr threadManager = ThreadManager::newSimpleThreadManager(8); threadManager->threadFactory(threadFactory); threadManager->start(); - return boost::shared_ptr( - new TNonblockingServer(processor, protocolFactory, port, threadManager)); + return stdcxx::shared_ptr( + new TNonblockingServer(processor, protocolFactory, socket, threadManager)); } }; @@ -136,11 +137,11 @@ class TNonblockingServerNoThreadsTraits { public: typedef TNonblockingServer ServerType; - boost::shared_ptr createServer( - const boost::shared_ptr& processor, + stdcxx::shared_ptr createServer( + const stdcxx::shared_ptr& processor, uint16_t port, - const boost::shared_ptr& transportFactory, - const boost::shared_ptr& protocolFactory) { + const stdcxx::shared_ptr& transportFactory, + const stdcxx::shared_ptr& protocolFactory) { // TNonblockingServer automatically uses TFramedTransport. // Raise an exception if the supplied transport factory is not a // TFramedTransportFactory @@ -150,10 +151,11 @@ public: throw TException("TNonblockingServer must use TFramedTransport"); } + stdcxx::shared_ptr socket(new TNonblockingServerSocket(port)); // Use a NULL ThreadManager - boost::shared_ptr threadManager; - return boost::shared_ptr( - new TNonblockingServer(processor, protocolFactory, port, threadManager)); + stdcxx::shared_ptr threadManager; + return stdcxx::shared_ptr( + new TNonblockingServer(processor, protocolFactory, socket, threadManager)); } }; @@ -242,48 +244,48 @@ public: processor_->setEventHandler(processorEventHandler_); } - boost::shared_ptr createServer(uint16_t port) { + stdcxx::shared_ptr createServer(uint16_t port) { ServerTraits_ serverTraits; return serverTraits.createServer(processor_, port, transportFactory_, protocolFactory_); } - boost::shared_ptr getServerEventHandler() { return serverEventHandler_; } + stdcxx::shared_ptr getServerEventHandler() { return serverEventHandler_; } void bindSuccessful(uint16_t port) { port_ = port; } uint16_t getPort() const { return port_; } - const boost::shared_ptr& getLog() const { return log_; } + const stdcxx::shared_ptr& getLog() const { return log_; } - const boost::shared_ptr& getHandler() const { return handler_; } + const stdcxx::shared_ptr& getHandler() const { return handler_; } - boost::shared_ptr createClient() { + stdcxx::shared_ptr createClient() { typedef typename ServiceTraits_::Protocol Protocol; - boost::shared_ptr socket(new TSocket("127.0.0.1", port_)); - boost::shared_ptr transport(new Transport_(socket)); - boost::shared_ptr protocol(new Protocol(transport)); + stdcxx::shared_ptr socket(new TSocket("127.0.0.1", port_)); + stdcxx::shared_ptr transport(new Transport_(socket)); + stdcxx::shared_ptr protocol(new Protocol(transport)); transport->open(); - boost::shared_ptr client(new Client(protocol)); + stdcxx::shared_ptr client(new Client(protocol)); return client; } private: uint16_t port_; - boost::shared_ptr log_; - boost::shared_ptr handler_; - boost::shared_ptr processor_; - boost::shared_ptr transportFactory_; - boost::shared_ptr protocolFactory_; - boost::shared_ptr serverEventHandler_; - boost::shared_ptr processorEventHandler_; + stdcxx::shared_ptr log_; + stdcxx::shared_ptr handler_; + stdcxx::shared_ptr processor_; + stdcxx::shared_ptr transportFactory_; + stdcxx::shared_ptr protocolFactory_; + stdcxx::shared_ptr serverEventHandler_; + stdcxx::shared_ptr processorEventHandler_; }; /** * Check that there are no more events in the log */ -void checkNoEvents(const boost::shared_ptr& log) { +void checkNoEvents(const stdcxx::shared_ptr& log) { // Wait for an event with a very short timeout period. We don't expect // anything to be present, so we will normally wait for the full timeout. // On the other hand, a non-zero timeout is nice since it does give a short @@ -297,7 +299,7 @@ void checkNoEvents(const boost::shared_ptr& log) { * * Returns the connection ID allocated by the server. */ -uint32_t checkNewConnEvents(const boost::shared_ptr& log) { +uint32_t checkNewConnEvents(const stdcxx::shared_ptr& log) { // Check for an ET_CONN_CREATED event Event event = log->waitForEvent(2500); BOOST_CHECK_EQUAL(EventLog::ET_CONN_CREATED, event.type); @@ -312,7 +314,7 @@ uint32_t checkNewConnEvents(const boost::shared_ptr& log) { /** * Check for the events that should be logged when a connection is closed. */ -void checkCloseEvents(const boost::shared_ptr& log, uint32_t connId) { +void checkCloseEvents(const stdcxx::shared_ptr& log, uint32_t connId) { // Check for an ET_CONN_DESTROYED event Event event = log->waitForEvent(); BOOST_CHECK_EQUAL(EventLog::ET_CONN_DESTROYED, event.type); @@ -330,7 +332,7 @@ void checkCloseEvents(const boost::shared_ptr& log, uint32_t connId) { * * Returns the call ID allocated by the server. */ -uint32_t checkCallHandlerEvents(const boost::shared_ptr& log, +uint32_t checkCallHandlerEvents(const stdcxx::shared_ptr& log, uint32_t connId, EventType callType, const string& callName) { @@ -367,7 +369,7 @@ uint32_t checkCallHandlerEvents(const boost::shared_ptr& log, /** * Check for the events that should be after a handler returns. */ -void checkCallPostHandlerEvents(const boost::shared_ptr& log, +void checkCallPostHandlerEvents(const stdcxx::shared_ptr& log, uint32_t connId, uint32_t callId, const string& callName) { @@ -407,7 +409,7 @@ void checkCallPostHandlerEvents(const boost::shared_ptr& log, * * Returns the call ID allocated by the server. */ -uint32_t checkCallEvents(const boost::shared_ptr& log, +uint32_t checkCallEvents(const stdcxx::shared_ptr& log, uint32_t connId, EventType callType, const string& callName) { @@ -422,8 +424,8 @@ uint32_t checkCallEvents(const boost::shared_ptr& log, */ template -void testParentService(const boost::shared_ptr& state) { - boost::shared_ptr client = state->createClient(); +void testParentService(const stdcxx::shared_ptr& state) { + stdcxx::shared_ptr client = state->createClient(); int32_t gen = client->getGeneration(); int32_t newGen = client->incrementGeneration(); @@ -444,8 +446,8 @@ void testParentService(const boost::shared_ptr& state) { } template -void testChildService(const boost::shared_ptr& state) { - boost::shared_ptr client = state->createClient(); +void testChildService(const stdcxx::shared_ptr& state) { + stdcxx::shared_ptr client = state->createClient(); // Test calling some of the parent methids via the a child client int32_t gen = client->getGeneration(); @@ -466,7 +468,7 @@ void testBasicService() { typedef ServiceState > State; // Start the server - boost::shared_ptr state(new State); + stdcxx::shared_ptr state(new State); ServerThread serverThread(state, true); testParentService(state); @@ -477,7 +479,7 @@ void testInheritedService() { typedef ServiceState > State; // Start the server - boost::shared_ptr state(new State); + stdcxx::shared_ptr state(new State); ServerThread serverThread(state, true); testParentService(state); @@ -500,10 +502,10 @@ void testEventSequencing() { TBufferedTransport> State; // Start the server - boost::shared_ptr state(new State); + stdcxx::shared_ptr state(new State); ServerThread serverThread(state, true); - const boost::shared_ptr& log = state->getLog(); + const stdcxx::shared_ptr& log = state->getLog(); // Make sure we're at the end of the log checkNoEvents(log); @@ -512,7 +514,7 @@ void testEventSequencing() { // Make sure createContext() is called after a connection has been // established. We open a plain socket instead of creating a client. - boost::shared_ptr socket(new TSocket("127.0.0.1", state->getPort())); + stdcxx::shared_ptr socket(new TSocket("127.0.0.1", state->getPort())); socket->open(); // Make sure the proper events occurred after a new connection @@ -590,7 +592,7 @@ void testEventSequencing() { checkNoEvents(log); // Read the response header - std::string responseName; + string responseName; int32_t responseSeqid = 0; apache::thrift::protocol::TMessageType responseType; protocol.readMessageBegin(responseName, responseType, responseSeqid); @@ -633,19 +635,19 @@ void testSeparateConnections() { typedef ServiceState > State; // Start the server - boost::shared_ptr state(new State); + stdcxx::shared_ptr state(new State); ServerThread serverThread(state, true); - const boost::shared_ptr& log = state->getLog(); + const stdcxx::shared_ptr& log = state->getLog(); // Create a client - boost::shared_ptr client1 = state->createClient(); + stdcxx::shared_ptr client1 = state->createClient(); // Make sure the expected events were logged uint32_t client1Id = checkNewConnEvents(log); // Create a second client - boost::shared_ptr client2 = state->createClient(); + stdcxx::shared_ptr client2 = state->createClient(); // Make sure the expected events were logged uint32_t client2Id = checkNewConnEvents(log); @@ -681,13 +683,13 @@ void testOnewayCall() { typedef ServiceState > State; // Start the server - boost::shared_ptr state(new State); + stdcxx::shared_ptr state(new State); ServerThread serverThread(state, true); - const boost::shared_ptr& log = state->getLog(); + const stdcxx::shared_ptr& log = state->getLog(); // Create a client - boost::shared_ptr client = state->createClient(); + stdcxx::shared_ptr client = state->createClient(); uint32_t connId = checkNewConnEvents(log); // Make a oneway call @@ -733,13 +735,13 @@ void testExpectedError() { typedef ServiceState > State; // Start the server - boost::shared_ptr state(new State); + stdcxx::shared_ptr state(new State); ServerThread serverThread(state, true); - const boost::shared_ptr& log = state->getLog(); + const stdcxx::shared_ptr& log = state->getLog(); // Create a client - boost::shared_ptr client = state->createClient(); + stdcxx::shared_ptr client = state->createClient(); uint32_t connId = checkNewConnEvents(log); // Send the exceptionWait() call @@ -766,8 +768,8 @@ void testExpectedError() { } catch (const MyError& e) { BOOST_CHECK_EQUAL(message, e.message); // Check if std::exception::what() is handled properly - size_t message_pos = std::string(e.what()).find("TException - service has thrown: MyError"); - BOOST_CHECK_NE(message_pos, std::string::npos); + size_t message_pos = string(e.what()).find("TException - service has thrown: MyError"); + BOOST_CHECK_NE(message_pos, string::npos); } // Now we should see the events for a normal call finish @@ -788,13 +790,13 @@ void testUnexpectedError() { typedef ServiceState > State; // Start the server - boost::shared_ptr state(new State); + stdcxx::shared_ptr state(new State); ServerThread serverThread(state, true); - const boost::shared_ptr& log = state->getLog(); + const stdcxx::shared_ptr& log = state->getLog(); // Create a client - boost::shared_ptr client = state->createClient(); + stdcxx::shared_ptr client = state->createClient(); uint32_t connId = checkNewConnEvents(log); // Send the unexpectedExceptionWait() call @@ -910,7 +912,7 @@ DEFINE_NOFRAME_TESTS(TSimpleServer, Untemplated) // For now, it is known not to work correctly with TProcessorEventHandler. #ifdef BOOST_TEST_DYN_LINK bool init_unit_test_suite() { - unit_test::framework::master_test_suite().p_name.value = "ProcessorTest"; + ::boost::unit_test::framework::master_test_suite().p_name.value = "ProcessorTest"; return true; } @@ -918,10 +920,10 @@ int main( int argc, char* argv[] ) { return ::boost::unit_test::unit_test_main(&init_unit_test_suite,argc,argv); } #else -unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]) { +::boost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]) { THRIFT_UNUSED_VARIABLE(argc); THRIFT_UNUSED_VARIABLE(argv); - unit_test::framework::master_test_suite().p_name.value = "ProcessorTest"; + ::boost::unit_test::framework::master_test_suite().p_name.value = "ProcessorTest"; return NULL; } #endif diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/processor/ServerThread.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/processor/ServerThread.cpp index e9d468f..e752d5e 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/processor/ServerThread.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/processor/ServerThread.cpp @@ -35,6 +35,8 @@ void ServerThread::start() { assert(!running_); running_ = true; + helper_.reset(new Helper(this)); + // Start the other thread concurrency::PlatformThreadFactory threadFactory; threadFactory.setDetached(false); @@ -128,7 +130,7 @@ void ServerThread::preServe() { serverState_->bindSuccessful(port_); // Set the real server event handler (replacing ourself) - boost::shared_ptr serverEventHandler + stdcxx::shared_ptr serverEventHandler = serverState_->getServerEventHandler(); server_->setServerEventHandler(serverEventHandler); diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/processor/ServerThread.h b/vendor/git.apache.org/thrift.git/lib/cpp/test/processor/ServerThread.h index eed3469..21c3b60 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/processor/ServerThread.h +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/processor/ServerThread.h @@ -43,7 +43,7 @@ public: * If the server returned fails to bind to the specified port when serve() is * called on it, createServer() may be called again on a different port. */ - virtual boost::shared_ptr createServer(uint16_t port) = 0; + virtual stdcxx::shared_ptr createServer(uint16_t port) = 0; /** * Get the TServerEventHandler to set on the server. @@ -52,8 +52,8 @@ public: * start serving traffic. It is invoked from the server thread, rather than * the main thread. */ - virtual boost::shared_ptr getServerEventHandler() { - return boost::shared_ptr(); + virtual stdcxx::shared_ptr getServerEventHandler() { + return stdcxx::shared_ptr(); } /** @@ -70,9 +70,8 @@ public: */ class ServerThread { public: - ServerThread(const boost::shared_ptr& state, bool autoStart) - : helper_(new Helper(this)), - port_(0), + ServerThread(const stdcxx::shared_ptr& state, bool autoStart) + : port_(0), running_(false), serving_(false), error_(false), @@ -117,7 +116,7 @@ protected: void run(); void preServe(); - boost::shared_ptr helper_; + stdcxx::shared_ptr helper_; uint16_t port_; bool running_; @@ -125,9 +124,9 @@ protected: bool error_; concurrency::Monitor serverMonitor_; - boost::shared_ptr serverState_; - boost::shared_ptr server_; - boost::shared_ptr thread_; + stdcxx::shared_ptr serverState_; + stdcxx::shared_ptr server_; + stdcxx::shared_ptr thread_; }; } } diff --git a/vendor/git.apache.org/thrift.git/lib/cpp/test/qt/TQTcpServerTest.cpp b/vendor/git.apache.org/thrift.git/lib/cpp/test/qt/TQTcpServerTest.cpp index 422d771..8a327aa 100644 --- a/vendor/git.apache.org/thrift.git/lib/cpp/test/qt/TQTcpServerTest.cpp +++ b/vendor/git.apache.org/thrift.git/lib/cpp/test/qt/TQTcpServerTest.cpp @@ -8,12 +8,12 @@ #include #ifndef Q_MOC_RUN - #include + #include "thrift/stdcxx.h" #include "thrift/protocol/TBinaryProtocol.h" #include "thrift/async/TAsyncProcessor.h" #include "thrift/qt/TQTcpServer.h" #include "thrift/qt/TQIODeviceTransport.h" - + #include "gen-cpp/ParentService.h" #endif @@ -21,25 +21,25 @@ using namespace apache::thrift; struct AsyncHandler : public test::ParentServiceCobSvIf { std::vector strings; - virtual void addString(tcxx::function cob, const std::string& s) { + virtual void addString(stdcxx::function cob, const std::string& s) { strings.push_back(s); cob(); } - virtual void getStrings(tcxx::function const& _return)> cob) { + virtual void getStrings(stdcxx::function const& _return)> cob) { cob(strings); } // Overrides not used in this test - virtual void incrementGeneration(tcxx::function cob) {} - virtual void getGeneration(tcxx::function cob) {} - virtual void getDataWait(tcxx::function cob, + virtual void incrementGeneration(stdcxx::function cob) {} + virtual void getGeneration(stdcxx::function cob) {} + virtual void getDataWait(stdcxx::function cob, const int32_t length) {} - virtual void onewayWait(tcxx::function cob) {} + virtual void onewayWait(stdcxx::function cob) {} virtual void exceptionWait( - tcxx::function cob, - tcxx::function /* exn_cob */, + stdcxx::function cob, + stdcxx::function /* exn_cob */, const std::string& message) {} - virtual void unexpectedExceptionWait(tcxx::function cob, const std::string& message) {} + virtual void unexpectedExceptionWait(stdcxx::function cob, const std::string& message) {} }; class TQTcpServerTest : public QObject { @@ -51,18 +51,18 @@ private slots: void test_communicate(); private: - boost::shared_ptr serverThread; - boost::shared_ptr server; - boost::shared_ptr client; + stdcxx::shared_ptr serverThread; + stdcxx::shared_ptr server; + stdcxx::shared_ptr client; }; void TQTcpServerTest::initTestCase() { // setup server - boost::shared_ptr serverSocket = boost::make_shared(); + stdcxx::shared_ptr serverSocket = stdcxx::make_shared(); server.reset(new async::TQTcpServer(serverSocket, - boost::make_shared( - boost::make_shared()), - boost::make_shared())); + stdcxx::make_shared( + stdcxx::make_shared()), + stdcxx::make_shared())); QVERIFY(serverSocket->listen(QHostAddress::LocalHost)); int port = serverSocket->serverPort(); QVERIFY(port > 0); @@ -74,9 +74,9 @@ void TQTcpServerTest::initTestCase() { serverThread->start(); // setup client - boost::shared_ptr socket = boost::make_shared(); - client.reset(new test::ParentServiceClient(boost::make_shared( - boost::make_shared(socket)))); + stdcxx::shared_ptr socket = stdcxx::make_shared(); + client.reset(new test::ParentServiceClient(stdcxx::make_shared( + stdcxx::make_shared(socket)))); socket->connectToHost(QHostAddress::LocalHost, port); QVERIFY(socket->waitForConnected()); } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/Makefile.am b/vendor/git.apache.org/thrift.git/lib/csharp/Makefile.am index bf02c87..be49d5e 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/Makefile.am +++ b/vendor/git.apache.org/thrift.git/lib/csharp/Makefile.am @@ -52,6 +52,7 @@ THRIFTCODE = \ src/Transport/TBufferedTransport.cs \ src/Transport/TTransport.cs \ src/Transport/TSocket.cs \ + src/Transport/TSocketVersionizer.cs \ src/Transport/TTransportException.cs \ src/Transport/TStreamTransport.cs \ src/Transport/TFramedTransport.cs \ @@ -83,23 +84,28 @@ if NET_2_0 export CSC_DEFINES = -d:NET_2_0 endif -all-local: Thrift.dll +all-local: Thrift.dll Thrift.45.dll Thrift.dll: $(THRIFTCODE) $(CSC) $(CSC_DEFINES) -out:$@ -target:library -reference:System.Web $(THRIFTCODE) +Thrift.45.dll: $(THRIFTCODE) + $(CSC) $(CSC_DEFINES) -out:$@ -target:library -reference:System.Web $(THRIFTCODE) + clean-local: - $(RM) Thrift.dll + $(RM) Thrift.dll \ + $(RM) Thrift.45.dll EXTRA_DIST = \ - $(THRIFTCODE) \ - ThriftMSBuildTask \ - src/Thrift.csproj \ - src/Thrift.45.csproj \ - src/Thrift.sln \ - src/Transport/TSilverlightSocket.cs \ - src/Transport/THttpTaskAsyncHandler.cs \ - src/TAsyncProcessor.cs \ - test \ - coding_standards.md \ - README.md + $(THRIFTCODE) \ + ThriftMSBuildTask \ + src/Thrift.csproj \ + src/Thrift.45.csproj \ + src/Thrift.sln \ + src/Net35/ExtensionsNet35.cs \ + src/Transport/TSilverlightSocket.cs \ + src/Transport/THttpTaskAsyncHandler.cs \ + src/TAsyncProcessor.cs \ + test \ + coding_standards.md \ + README.md diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/ThriftMSBuildTask/Properties/AssemblyInfo.cs b/vendor/git.apache.org/thrift.git/lib/csharp/ThriftMSBuildTask/Properties/AssemblyInfo.cs index 64cec97..19abcf7 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/ThriftMSBuildTask/Properties/AssemblyInfo.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/ThriftMSBuildTask/Properties/AssemblyInfo.cs @@ -56,5 +56,5 @@ using System.Runtime.InteropServices; // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("0.10.0.*")] -[assembly: AssemblyFileVersion("0.10.0.*")] +[assembly: AssemblyVersion("0.12.0.*")] +[assembly: AssemblyFileVersion("0.12.0.*")] diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/ThriftMSBuildTask/ThriftMSBuildTask.csproj b/vendor/git.apache.org/thrift.git/lib/csharp/ThriftMSBuildTask/ThriftMSBuildTask.csproj index ae86081..68427c3 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/ThriftMSBuildTask/ThriftMSBuildTask.csproj +++ b/vendor/git.apache.org/thrift.git/lib/csharp/ThriftMSBuildTask/ThriftMSBuildTask.csproj @@ -45,7 +45,7 @@ false true 0 - 1.0.0.%2a + 0.12.0.%2a false false true @@ -115,4 +115,4 @@ --> - \ No newline at end of file + diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Collections/TCollections.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Collections/TCollections.cs index f0bb1de..84afb6a 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Collections/TCollections.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Collections/TCollections.cs @@ -79,7 +79,7 @@ namespace Thrift.Collections } int hashcode = 0; - foreach (Object obj in enumerable) + foreach (object obj in enumerable) { IEnumerable enum2 = obj as IEnumerable; int objHash = enum2 == null ? obj.GetHashCode () : GetHashCode (enum2); @@ -91,4 +91,4 @@ namespace Thrift.Collections return hashcode; } } -} \ No newline at end of file +} diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Net35/ExtensionsNet35.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Net35/ExtensionsNet35.cs new file mode 100644 index 0000000..73a4232 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Net35/ExtensionsNet35.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +#if (!NET45) +namespace Thrift +{ + static class StreamExtensionsNet35 + { + // CopyTo() has been added in 4.0 + public static long CopyTo(this Stream source, Stream target) + { + byte[] buffer = new byte[8192]; // multiple of 4096 + long nTotal = 0; + while (true) + { + int nRead = source.Read(buffer, 0, buffer.Length); + if (nRead <= 0) // done? + return nTotal; + + target.Write(buffer, 0, nRead); + nTotal += nRead; + } + } + } + +} +#endif + diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Properties/AssemblyInfo.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Properties/AssemblyInfo.cs index 22d53dc..23fbc73 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Properties/AssemblyInfo.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Properties/AssemblyInfo.cs @@ -51,5 +51,5 @@ using System.Runtime.InteropServices; // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: -[assembly: AssemblyVersion("0.10.0.1")] -[assembly: AssemblyFileVersion("0.10.0.1")] +[assembly: AssemblyVersion("0.12.0.1")] +[assembly: AssemblyFileVersion("0.12.0.1")] diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TAbstractBase.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TAbstractBase.cs index c0d5abe..f5a61cd 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TAbstractBase.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TAbstractBase.cs @@ -21,9 +21,9 @@ namespace Thrift.Protocol { public interface TAbstractBase { - /// - /// Writes the objects out to the protocol - /// + /// + /// Writes the objects out to the protocol. + /// void Write(TProtocol tProtocol); } } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TBase.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TBase.cs index 350ff49..411e4d9 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TBase.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TBase.cs @@ -21,9 +21,9 @@ namespace Thrift.Protocol { public interface TBase : TAbstractBase { - /// + /// /// Reads the TObject from the given input protocol. - /// + /// void Read(TProtocol tProtocol); } } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TBinaryProtocol.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TBinaryProtocol.cs index 4eceb86..a4faa94 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TBinaryProtocol.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TBinaryProtocol.cs @@ -36,29 +36,28 @@ namespace Thrift.Protocol protected bool strictWrite_ = true; #region BinaryProtocol Factory - /** - * Factory - */ - public class Factory : TProtocolFactory { - protected bool strictRead_ = false; - protected bool strictWrite_ = true; + public class Factory : TProtocolFactory + { + protected bool strictRead_ = false; + protected bool strictWrite_ = true; - public Factory() - :this(false, true) - { - } - - public Factory(bool strictRead, bool strictWrite) - { - strictRead_ = strictRead; - strictWrite_ = strictWrite; - } - - public TProtocol GetProtocol(TTransport trans) { - return new TBinaryProtocol(trans, strictRead_, strictWrite_); + public Factory() + : this(false, true) + { } - } + + public Factory(bool strictRead, bool strictWrite) + { + strictRead_ = strictRead; + strictWrite_ = strictWrite; + } + + public TProtocol GetProtocol(TTransport trans) + { + return new TBinaryProtocol(trans, strictRead_, strictWrite_); + } + } #endregion @@ -68,7 +67,7 @@ namespace Thrift.Protocol } public TBinaryProtocol(TTransport trans, bool strictRead, bool strictWrite) - :base(trans) + : base(trans) { strictRead_ = strictRead; strictWrite_ = strictWrite; @@ -345,16 +344,17 @@ namespace Thrift.Protocol public override long ReadI64() { ReadAll(i64in, 0, 8); - unchecked { - return (long)( - ((long)(i64in[0] & 0xff) << 56) | - ((long)(i64in[1] & 0xff) << 48) | - ((long)(i64in[2] & 0xff) << 40) | - ((long)(i64in[3] & 0xff) << 32) | - ((long)(i64in[4] & 0xff) << 24) | - ((long)(i64in[5] & 0xff) << 16) | - ((long)(i64in[6] & 0xff) << 8) | - ((long)(i64in[7] & 0xff))); + unchecked + { + return (long)( + ((long)(i64in[0] & 0xff) << 56) | + ((long)(i64in[1] & 0xff) << 48) | + ((long)(i64in[2] & 0xff) << 40) | + ((long)(i64in[3] & 0xff) << 32) | + ((long)(i64in[4] & 0xff) << 24) | + ((long)(i64in[5] & 0xff) << 16) | + ((long)(i64in[6] & 0xff) << 8) | + ((long)(i64in[7] & 0xff))); } } @@ -378,7 +378,7 @@ namespace Thrift.Protocol trans.ReadAll(buf, 0, size); return buf; } - private string ReadStringBody(int size) + private string ReadStringBody(int size) { byte[] buf = new byte[size]; trans.ReadAll(buf, 0, size); diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TCompactProtocol.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TCompactProtocol.cs index 2b4f6f1..ff67397 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TCompactProtocol.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TCompactProtocol.cs @@ -44,9 +44,9 @@ namespace Thrift.Protocol private const byte TYPE_BITS = 0x07; // 0000 0111 private const int TYPE_SHIFT_AMOUNT = 5; - /** - * All of the on-wire type codes. - */ + /// + /// All of the on-wire type codes. + /// private static class Types { public const byte STOP = 0x00; @@ -64,32 +64,29 @@ namespace Thrift.Protocol public const byte STRUCT = 0x0C; } - /** - * Used to keep track of the last field for the current and previous structs, - * so we can do the delta stuff. - */ + /// + /// Used to keep track of the last field for the current and previous structs, + /// so we can do the delta stuff. + /// private Stack lastField_ = new Stack(15); private short lastFieldId_ = 0; - /** - * If we encounter a boolean field begin, save the TField here so it can - * have the value incorporated. - */ + /// + /// If we encounter a boolean field begin, save the TField here so it can + /// have the value incorporated. + /// private Nullable booleanField_; - /** - * If we Read a field header, and it's a boolean field, save the boolean - * value here so that ReadBool can use it. - */ - private Nullable boolValue_; + /// + /// If we Read a field header, and it's a boolean field, save the boolean + /// value here so that ReadBool can use it. + /// + private Nullable boolValue_; #region CompactProtocol Factory - /** - * Factory - */ public class Factory : TProtocolFactory { public Factory() { } @@ -127,31 +124,32 @@ namespace Thrift.Protocol #region Write Methods - - /** - * Writes a byte without any possibility of all that field header nonsense. - * Used internally by other writing methods that know they need to Write a byte. - */ + /// + /// Writes a byte without any possibility of all that field header nonsense. + /// Used internally by other writing methods that know they need to Write a byte. + /// private byte[] byteDirectBuffer = new byte[1]; + private void WriteByteDirect(byte b) { byteDirectBuffer[0] = b; trans.Write(byteDirectBuffer); } - /** - * Writes a byte without any possibility of all that field header nonsense. - */ + /// + /// Writes a byte without any possibility of all that field header nonsense. + /// private void WriteByteDirect(int n) { WriteByteDirect((byte)n); } - /** - * Write an i32 as a varint. Results in 1-5 bytes on the wire. - * TODO: make a permanent buffer like WriteVarint64? - */ + /// + /// Write an i32 as a varint. Results in 1-5 bytes on the wire. + /// TODO: make a permanent buffer like WriteVarint64? + /// byte[] i32buf = new byte[5]; + private void WriteVarint32(uint n) { int idx = 0; @@ -174,10 +172,10 @@ namespace Thrift.Protocol trans.Write(i32buf, 0, idx); } - /** - * Write a message header to the wire. Compact Protocol messages contain the - * protocol version so we can migrate forwards in the future if need be. - */ + /// + /// Write a message header to the wire. Compact Protocol messages contain the + /// protocol version so we can migrate forwards in the future if need be. + /// public override void WriteMessageBegin(TMessage message) { WriteByteDirect(PROTOCOL_ID); @@ -186,33 +184,33 @@ namespace Thrift.Protocol WriteString(message.Name); } - /** - * Write a struct begin. This doesn't actually put anything on the wire. We - * use it as an opportunity to put special placeholder markers on the field - * stack so we can get the field id deltas correct. - */ + /// + /// Write a struct begin. This doesn't actually put anything on the wire. We + /// use it as an opportunity to put special placeholder markers on the field + /// stack so we can get the field id deltas correct. + /// public override void WriteStructBegin(TStruct strct) { lastField_.Push(lastFieldId_); lastFieldId_ = 0; } - /** - * Write a struct end. This doesn't actually put anything on the wire. We use - * this as an opportunity to pop the last field from the current struct off - * of the field stack. - */ + /// + /// Write a struct end. This doesn't actually put anything on the wire. We use + /// this as an opportunity to pop the last field from the current struct off + /// of the field stack. + /// public override void WriteStructEnd() { lastFieldId_ = lastField_.Pop(); } - /** - * Write a field header containing the field id and field type. If the - * difference between the current field id and the last one is small (< 15), - * then the field id will be encoded in the 4 MSB as a delta. Otherwise, the - * field id will follow the type header as a zigzag varint. - */ + /// + /// Write a field header containing the field id and field type. If the + /// difference between the current field id and the last one is small (< 15), + /// then the field id will be encoded in the 4 MSB as a delta. Otherwise, the + /// field id will follow the type header as a zigzag varint. + /// public override void WriteFieldBegin(TField field) { if (field.Type == TType.Bool) @@ -226,11 +224,11 @@ namespace Thrift.Protocol } } - /** - * The workhorse of WriteFieldBegin. It has the option of doing a - * 'type override' of the type header. This is used specifically in the - * boolean field case. - */ + /// + /// The workhorse of WriteFieldBegin. It has the option of doing a + /// 'type override' of the type header. This is used specifically in the + /// boolean field case. + /// private void WriteFieldBeginInternal(TField field, byte typeOverride) { // short lastField = lastField_.Pop(); @@ -255,18 +253,18 @@ namespace Thrift.Protocol // lastField_.push(field.id); } - /** - * Write the STOP symbol so we know there are no more fields in this struct. - */ + /// + /// Write the STOP symbol so we know there are no more fields in this struct. + /// public override void WriteFieldStop() { WriteByteDirect(Types.STOP); } - /** - * Write a map header. If the map is empty, omit the key and value type - * headers, as we don't need any additional information to skip it. - */ + /// + /// Write a map header. If the map is empty, omit the key and value type + /// headers, as we don't need any additional information to skip it. + /// public override void WriteMapBegin(TMap map) { if (map.Count == 0) @@ -280,28 +278,28 @@ namespace Thrift.Protocol } } - /** - * Write a list header. - */ + /// + /// Write a list header. + /// public override void WriteListBegin(TList list) { WriteCollectionBegin(list.ElementType, list.Count); } - /** - * Write a set header. - */ + /// + /// Write a set header. + /// public override void WriteSetBegin(TSet set) { WriteCollectionBegin(set.ElementType, set.Count); } - /** - * Write a boolean value. Potentially, this could be a boolean field, in - * which case the field header info isn't written yet. If so, decide what the - * right type header is for the value and then Write the field header. - * Otherwise, Write a single byte. - */ + /// + /// Write a boolean value. Potentially, this could be a boolean field, in + /// which case the field header info isn't written yet. If so, decide what the + /// right type header is for the value and then Write the field header. + /// Otherwise, Write a single byte. + /// public override void WriteBool(Boolean b) { if (booleanField_ != null) @@ -317,41 +315,41 @@ namespace Thrift.Protocol } } - /** - * Write a byte. Nothing to see here! - */ + /// + /// Write a byte. Nothing to see here! + /// public override void WriteByte(sbyte b) { WriteByteDirect((byte)b); } - /** - * Write an I16 as a zigzag varint. - */ + /// + /// Write an I16 as a zigzag varint. + /// public override void WriteI16(short i16) { WriteVarint32(intToZigZag(i16)); } - /** - * Write an i32 as a zigzag varint. - */ + /// + /// Write an i32 as a zigzag varint. + /// public override void WriteI32(int i32) { WriteVarint32(intToZigZag(i32)); } - /** - * Write an i64 as a zigzag varint. - */ + /// + /// Write an i64 as a zigzag varint. + /// public override void WriteI64(long i64) { WriteVarint64(longToZigzag(i64)); } - /** - * Write a double to the wire as 8 bytes. - */ + /// + /// Write a double to the wire as 8 bytes. + /// public override void WriteDouble(double dub) { byte[] data = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }; @@ -359,18 +357,18 @@ namespace Thrift.Protocol trans.Write(data); } - /** - * Write a string to the wire with a varint size preceding. - */ - public override void WriteString(String str) + /// + /// Write a string to the wire with a varint size preceding. + /// + public override void WriteString(string str) { byte[] bytes = UTF8Encoding.UTF8.GetBytes(str); WriteBinary(bytes, 0, bytes.Length); } - /** - * Write a byte array, using a varint for the size. - */ + /// + /// Write a byte array, using a varint for the size. + /// public override void WriteBinary(byte[] bin) { WriteBinary(bin, 0, bin.Length); @@ -397,10 +395,10 @@ namespace Thrift.Protocol // Internal writing methods // - /** - * Abstract method for writing the start of lists and sets. List and sets on - * the wire differ only by the type indicator. - */ + /// + /// Abstract method for writing the start of lists and sets. List and sets on + /// the wire differ only by the type indicator. + /// protected void WriteCollectionBegin(TType elemType, int size) { if (size <= 14) @@ -414,9 +412,9 @@ namespace Thrift.Protocol } } - /** - * Write an i64 as a varint. Results in 1-10 bytes on the wire. - */ + /// + /// Write an i64 as a varint. Results in 1-10 bytes on the wire. + /// byte[] varint64out = new byte[10]; private void WriteVarint64(ulong n) { @@ -437,28 +435,28 @@ namespace Thrift.Protocol trans.Write(varint64out, 0, idx); } - /** - * Convert l into a zigzag long. This allows negative numbers to be - * represented compactly as a varint. - */ + /// + /// Convert l into a zigzag long. This allows negative numbers to be + /// represented compactly as a varint. + /// private ulong longToZigzag(long n) { return (ulong)(n << 1) ^ (ulong)(n >> 63); } - /** - * Convert n into a zigzag int. This allows negative numbers to be - * represented compactly as a varint. - */ + /// + /// Convert n into a zigzag int. This allows negative numbers to be + /// represented compactly as a varint. + /// private uint intToZigZag(int n) { return (uint)(n << 1) ^ (uint)(n >> 31); } - /** - * Convert a long into little-endian bytes in buf starting at off and going - * until off+7. - */ + /// + /// Convert a long into little-endian bytes in buf starting at off and going + /// until off+7. + /// private void fixedLongToBytes(long n, byte[] buf, int off) { buf[off + 0] = (byte)(n & 0xff); @@ -475,9 +473,9 @@ namespace Thrift.Protocol #region ReadMethods - /** - * Read a message header. - */ + /// + /// Read a message header. + /// public override TMessage ReadMessageBegin() { byte protocolId = (byte)ReadByte(); @@ -493,14 +491,14 @@ namespace Thrift.Protocol } byte type = (byte)((versionAndType >> TYPE_SHIFT_AMOUNT) & TYPE_BITS); int seqid = (int)ReadVarint32(); - String messageName = ReadString(); + string messageName = ReadString(); return new TMessage(messageName, (TMessageType)type, seqid); } - /** - * Read a struct begin. There's nothing on the wire for this, but it is our - * opportunity to push a new struct begin marker onto the field stack. - */ + /// + /// Read a struct begin. There's nothing on the wire for this, but it is our + /// opportunity to push a new struct begin marker onto the field stack. + /// public override TStruct ReadStructBegin() { lastField_.Push(lastFieldId_); @@ -508,19 +506,19 @@ namespace Thrift.Protocol return ANONYMOUS_STRUCT; } - /** - * Doesn't actually consume any wire data, just removes the last field for - * this struct from the field stack. - */ + /// + /// Doesn't actually consume any wire data, just removes the last field for + /// this struct from the field stack. + /// public override void ReadStructEnd() { // consume the last field we Read off the wire. lastFieldId_ = lastField_.Pop(); } - /** - * Read a field header off the wire. - */ + /// + /// Read a field header off the wire. + /// public override TField ReadFieldBegin() { byte type = (byte)ReadByte(); @@ -560,11 +558,11 @@ namespace Thrift.Protocol return field; } - /** - * Read a map header off the wire. If the size is zero, skip Reading the key - * and value type. This means that 0-length maps will yield TMaps without the - * "correct" types. - */ + /// + /// Read a map header off the wire. If the size is zero, skip Reading the key + /// and value type. This means that 0-length maps will yield TMaps without the + /// "correct" types. + /// public override TMap ReadMapBegin() { int size = (int)ReadVarint32(); @@ -572,12 +570,12 @@ namespace Thrift.Protocol return new TMap(getTType((byte)(keyAndValueType >> 4)), getTType((byte)(keyAndValueType & 0xf)), size); } - /** - * Read a list header off the wire. If the list size is 0-14, the size will - * be packed into the element type header. If it's a longer list, the 4 MSB - * of the element type header will be 0xF, and a varint will follow with the - * true size. - */ + /// + /// Read a list header off the wire. If the list size is 0-14, the size will + /// be packed into the element type header. If it's a longer list, the 4 MSB + /// of the element type header will be 0xF, and a varint will follow with the + /// true size. + /// public override TList ReadListBegin() { byte size_and_type = (byte)ReadByte(); @@ -590,22 +588,22 @@ namespace Thrift.Protocol return new TList(type, size); } - /** - * Read a set header off the wire. If the set size is 0-14, the size will - * be packed into the element type header. If it's a longer set, the 4 MSB - * of the element type header will be 0xF, and a varint will follow with the - * true size. - */ + /// + /// Read a set header off the wire. If the set size is 0-14, the size will + /// be packed into the element type header. If it's a longer set, the 4 MSB + /// of the element type header will be 0xF, and a varint will follow with the + /// true size. + /// public override TSet ReadSetBegin() { return new TSet(ReadListBegin()); } - /** - * Read a boolean off the wire. If this is a boolean field, the value should - * already have been Read during ReadFieldBegin, so we'll just consume the - * pre-stored value. Otherwise, Read a byte. - */ + /// + /// Read a boolean off the wire. If this is a boolean field, the value should + /// already have been Read during ReadFieldBegin, so we'll just consume the + /// pre-stored value. Otherwise, Read a byte. + /// public override Boolean ReadBool() { if (boolValue_ != null) @@ -618,42 +616,42 @@ namespace Thrift.Protocol } byte[] byteRawBuf = new byte[1]; - /** - * Read a single byte off the wire. Nothing interesting here. - */ + /// + /// Read a single byte off the wire. Nothing interesting here. + /// public override sbyte ReadByte() { trans.ReadAll(byteRawBuf, 0, 1); return (sbyte)byteRawBuf[0]; } - /** - * Read an i16 from the wire as a zigzag varint. - */ + /// + /// Read an i16 from the wire as a zigzag varint. + /// public override short ReadI16() { return (short)zigzagToInt(ReadVarint32()); } - /** - * Read an i32 from the wire as a zigzag varint. - */ + /// + /// Read an i32 from the wire as a zigzag varint. + /// public override int ReadI32() { return zigzagToInt(ReadVarint32()); } - /** - * Read an i64 from the wire as a zigzag varint. - */ + /// + /// Read an i64 from the wire as a zigzag varint. + /// public override long ReadI64() { return zigzagToLong(ReadVarint64()); } - /** - * No magic here - just Read a double off the wire. - */ + /// + /// No magic here - just Read a double off the wire. + /// public override double ReadDouble() { byte[] longBits = new byte[8]; @@ -661,10 +659,10 @@ namespace Thrift.Protocol return BitConverter.Int64BitsToDouble(bytesToLong(longBits)); } - /** - * Reads a byte[] (via ReadBinary), and then UTF-8 decodes it. - */ - public override String ReadString() + /// + /// Reads a byte[] (via ReadBinary), and then UTF-8 decodes it. + /// + public override string ReadString() { int length = (int)ReadVarint32(); @@ -676,9 +674,9 @@ namespace Thrift.Protocol return Encoding.UTF8.GetString(ReadBinary(length)); } - /** - * Read a byte[] from the wire. - */ + /// + /// Read a byte[] from the wire. + /// public override byte[] ReadBinary() { int length = (int)ReadVarint32(); @@ -689,9 +687,9 @@ namespace Thrift.Protocol return buf; } - /** - * Read a byte[] of a known length from the wire. - */ + /// + /// Read a byte[] of a known length from the wire. + /// private byte[] ReadBinary(int length) { if (length == 0) return new byte[0]; @@ -715,10 +713,10 @@ namespace Thrift.Protocol // Internal Reading methods // - /** - * Read an i32 from the wire as a varint. The MSB of each byte is set - * if there is another byte to follow. This can Read up to 5 bytes. - */ + /// + /// Read an i32 from the wire as a varint. The MSB of each byte is set + /// if there is another byte to follow. This can Read up to 5 bytes. + /// private uint ReadVarint32() { uint result = 0; @@ -733,10 +731,10 @@ namespace Thrift.Protocol return result; } - /** - * Read an i64 from the wire as a proper varint. The MSB of each byte is set - * if there is another byte to follow. This can Read up to 10 bytes. - */ + /// + /// Read an i64 from the wire as a proper varint. The MSB of each byte is set + /// if there is another byte to follow. This can Read up to 10 bytes. + /// private ulong ReadVarint64() { int shift = 0; @@ -758,27 +756,27 @@ namespace Thrift.Protocol // encoding helpers // - /** - * Convert from zigzag int to int. - */ + /// + /// Convert from zigzag int to int. + /// private int zigzagToInt(uint n) { return (int)(n >> 1) ^ (-(int)(n & 1)); } - /** - * Convert from zigzag long to long. - */ + /// + /// Convert from zigzag long to long. + /// private long zigzagToLong(ulong n) { return (long)(n >> 1) ^ (-(long)(n & 1)); } - /** - * Note that it's important that the mask bytes are long literals, - * otherwise they'll default to ints, and when you shift an int left 56 bits, - * you just get a messed up int. - */ + /// + /// Note that it's important that the mask bytes are long literals, + /// otherwise they'll default to ints, and when you shift an int left 56 bits, + /// you just get a messed up int. + /// private long bytesToLong(byte[] bytes) { return @@ -802,10 +800,10 @@ namespace Thrift.Protocol return lowerNibble == Types.BOOLEAN_TRUE || lowerNibble == Types.BOOLEAN_FALSE; } - /** - * Given a TCompactProtocol.Types constant, convert it to its corresponding - * TType value. - */ + /// + /// Given a TCompactProtocol.Types constant, convert it to its corresponding + /// TType value. + /// private TType getTType(byte type) { switch ((byte)(type & 0x0f)) @@ -840,9 +838,9 @@ namespace Thrift.Protocol } } - /** - * Given a TType value, find the appropriate TCompactProtocol.Types constant. - */ + /// + /// Given a TType value, find the appropriate TCompactProtocol.Types constant. + /// private byte getCompactType(TType ttype) { return ttypeToCompactType[(int)ttype]; diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TJSONProtocol.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TJSONProtocol.cs index 5e6589e..9dbdea9 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TJSONProtocol.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TJSONProtocol.cs @@ -29,18 +29,18 @@ namespace Thrift.Protocol { /// /// JSON protocol implementation for thrift. - /// + /// /// This is a full-featured protocol supporting Write and Read. - /// + /// /// Please see the C++ class header for a detailed description of the /// protocol's wire format. - /// + /// /// Adapted from the Java version. /// public class TJSONProtocol : TProtocol { /// - /// Factory for JSON protocol objects + /// Factory for JSON protocol objects. /// public class Factory : TProtocolFactory { @@ -179,11 +179,11 @@ namespace Thrift.Protocol return result; } - /// + /// /// Base class for tracking JSON contexts that may require /// inserting/Reading additional JSON syntax characters /// This base context does nothing. - /// + /// protected class JSONBaseContext { protected TJSONProtocol proto; @@ -200,10 +200,10 @@ namespace Thrift.Protocol public virtual bool EscapeNumbers() { return false; } } - /// + /// /// Context for JSON lists. Will insert/Read commas before each item except /// for the first one - /// + /// protected class JSONListContext : JSONBaseContext { public JSONListContext(TJSONProtocol protocol) @@ -239,12 +239,12 @@ namespace Thrift.Protocol } } - /// + /// /// Context for JSON records. Will insert/Read colons before the value portion /// of each record pair, and commas before each key except the first. In /// addition, will indicate that numbers in the key position need to be /// escaped in quotes (since JSON keys must be strings). - /// + /// protected class JSONPairContext : JSONBaseContext { public JSONPairContext(TJSONProtocol proto) @@ -290,9 +290,9 @@ namespace Thrift.Protocol } } - /// + /// /// Holds up to one byte from the transport - /// + /// protected class LookaheadReader { protected TJSONProtocol proto; @@ -305,10 +305,10 @@ namespace Thrift.Protocol private bool hasData; private byte[] data = new byte[1]; - /// + /// /// Return and consume the next byte to be Read, either taking it from the /// data buffer if present or getting it from the transport otherwise. - /// + /// public byte Read() { if (hasData) @@ -322,10 +322,10 @@ namespace Thrift.Protocol return data[0]; } - /// + /// /// Return the next byte to be Read without consuming, filling the data /// buffer if it has not been filled alReady. - /// + /// public byte Peek() { if (!hasData) @@ -349,26 +349,26 @@ namespace Thrift.Protocol // Reader that manages a 1-byte buffer protected LookaheadReader reader; - /// + /// /// Push a new JSON context onto the stack. - /// + /// protected void PushContext(JSONBaseContext c) { contextStack.Push(context); context = c; } - /// + /// /// Pop the last JSON context off the stack - /// + /// protected void PopContext() { context = contextStack.Pop(); } - /// + /// /// TJSONProtocol Constructor - /// + /// public TJSONProtocol(TTransport trans) : base(trans) { @@ -379,11 +379,11 @@ namespace Thrift.Protocol // Temporary buffer used by several methods private byte[] tempBuffer = new byte[4]; - /// + /// /// Read a byte that must match b[0]; otherwise an exception is thrown. /// Marked protected to avoid synthetic accessor in JSONListContext.Read /// and JSONPairContext.Read - /// + /// protected void ReadJSONSyntaxChar(byte[] b) { byte ch = reader.Read(); @@ -394,10 +394,10 @@ namespace Thrift.Protocol } } - /// + /// /// Convert a byte containing a hex char ('0'-'9' or 'a'-'f') into its /// corresponding hex value - /// + /// private static byte HexVal(byte ch) { if ((ch >= '0') && (ch <= '9')) @@ -416,9 +416,9 @@ namespace Thrift.Protocol } } - /// + /// /// Convert a byte containing a hex value to its corresponding hex character - /// + /// private static byte HexChar(byte val) { val &= 0x0F; @@ -433,9 +433,9 @@ namespace Thrift.Protocol } } - /// + /// /// Write the bytes in array buf as a JSON characters, escaping as needed - /// + /// private void WriteJSONString(byte[] b) { context.Write(); @@ -479,14 +479,14 @@ namespace Thrift.Protocol trans.Write(QUOTE); } - /// + /// /// Write out number as a JSON value. If the context dictates so, it will be /// wrapped in quotes to output as a JSON string. - /// + /// private void WriteJSONInteger(long num) { context.Write(); - String str = num.ToString(); + string str = num.ToString(); bool escapeNum = context.EscapeNumbers(); if (escapeNum) @@ -498,14 +498,14 @@ namespace Thrift.Protocol trans.Write(QUOTE); } - /// + /// /// Write out a double as a JSON value. If it is NaN or infinity or if the /// context dictates escaping, Write out as JSON string. - /// + /// private void WriteJSONDouble(double num) { context.Write(); - String str = num.ToString("G17", CultureInfo.InvariantCulture); + string str = num.ToString("G17", CultureInfo.InvariantCulture); bool special = false; switch (str[0]) @@ -532,10 +532,10 @@ namespace Thrift.Protocol if (escapeNum) trans.Write(QUOTE); } - /// + /// /// Write out contents of byte array b as a JSON string with base-64 encoded /// data - /// + /// private void WriteJSONBase64(byte[] b) { context.Write(); @@ -544,11 +544,6 @@ namespace Thrift.Protocol int len = b.Length; int off = 0; - // Ignore padding - int bound = len >= 2 ? len - 2 : 0; - for (int i = len - 1; i >= bound && b[i] == '='; --i) { - --len; - } while (len >= 3) { // Encode 3 bytes at a time @@ -703,7 +698,7 @@ namespace Thrift.Protocol WriteJSONDouble(dub); } - public override void WriteString(String str) + public override void WriteString(string str) { byte[] b = utf8Encoding.GetBytes(str); WriteJSONString(b); @@ -718,10 +713,10 @@ namespace Thrift.Protocol * Reading methods. */ - /// + /// /// Read in a JSON string, unescaping as appropriate.. Skip Reading from the /// context if skipContext is true. - /// + /// private byte[] ReadJSONString(bool skipContext) { MemoryStream buffer = new MemoryStream(); @@ -808,9 +803,9 @@ namespace Thrift.Protocol return buffer.ToArray(); } - /// + /// /// Return true if the given byte could be a valid part of a JSON number. - /// + /// private bool IsJSONNumeric(byte b) { switch (b) @@ -835,11 +830,11 @@ namespace Thrift.Protocol return false; } - /// + /// /// Read in a sequence of characters that are all valid in JSON numbers. Does /// not do a complete regex check to validate that this is actually a number. - //// - private String ReadJSONNumericChars() + /// + private string ReadJSONNumericChars() { StringBuilder strbld = new StringBuilder(); while (true) @@ -854,9 +849,9 @@ namespace Thrift.Protocol return strbld.ToString(); } - /// + /// /// Read in a JSON number. If the context dictates, Read in enclosing quotes. - /// + /// private long ReadJSONInteger() { context.Read(); @@ -864,36 +859,37 @@ namespace Thrift.Protocol { ReadJSONSyntaxChar(QUOTE); } - String str = ReadJSONNumericChars(); + + string str = ReadJSONNumericChars(); if (context.EscapeNumbers()) { ReadJSONSyntaxChar(QUOTE); } + try { return Int64.Parse(str); } - catch (FormatException) + catch (FormatException fex) { throw new TProtocolException(TProtocolException.INVALID_DATA, - "Bad data encounted in numeric data"); + "Bad data encounted in numeric data", fex); } } - /// + /// /// Read in a JSON double value. Throw if the value is not wrapped in quotes /// when expected or if wrapped in quotes when not expected. - /// + /// private double ReadJSONDouble() { context.Read(); if (reader.Peek() == QUOTE[0]) { byte[] arr = ReadJSONString(true); - double dub = Double.Parse(utf8Encoding.GetString(arr,0,arr.Length), CultureInfo.InvariantCulture); + double dub = Double.Parse(utf8Encoding.GetString(arr, 0, arr.Length), CultureInfo.InvariantCulture); - if (!context.EscapeNumbers() && !Double.IsNaN(dub) && - !Double.IsInfinity(dub)) + if (!context.EscapeNumbers() && !Double.IsNaN(dub) && !Double.IsInfinity(dub)) { // Throw exception -- we should not be in a string in this case throw new TProtocolException(TProtocolException.INVALID_DATA, @@ -912,17 +908,17 @@ namespace Thrift.Protocol { return Double.Parse(ReadJSONNumericChars(), CultureInfo.InvariantCulture); } - catch (FormatException) + catch (FormatException fex) { throw new TProtocolException(TProtocolException.INVALID_DATA, - "Bad data encounted in numeric data"); + "Bad data encounted in numeric data", fex); } } } - // + /// /// Read in a JSON string containing base-64 encoded data and decode it. - /// + /// private byte[] ReadJSONBase64() { byte[] b = ReadJSONString(false); @@ -994,7 +990,7 @@ namespace Thrift.Protocol } var buf = ReadJSONString(false); - message.Name = utf8Encoding.GetString(buf,0,buf.Length); + message.Name = utf8Encoding.GetString(buf, 0, buf.Length); message.Type = (TMessageType)ReadJSONInteger(); message.SeqID = (int)ReadJSONInteger(); return message; @@ -1113,10 +1109,10 @@ namespace Thrift.Protocol return ReadJSONDouble(); } - public override String ReadString() + public override string ReadString() { var buf = ReadJSONString(false); - return utf8Encoding.GetString(buf,0,buf.Length); + return utf8Encoding.GetString(buf, 0, buf.Length); } public override byte[] ReadBinary() diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TMultiplexedProcessor.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TMultiplexedProcessor.cs index 35d138c..aa91c52 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TMultiplexedProcessor.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TMultiplexedProcessor.cs @@ -29,74 +29,77 @@ using System.IO; namespace Thrift.Protocol { - - /** - * TMultiplexedProcessor is a TProcessor allowing a single TServer to provide multiple services. - * To do so, you instantiate the processor and then register additional processors with it, - * as shown in the following example: - * - * TMultiplexedProcessor processor = new TMultiplexedProcessor(); - * - * processor.registerProcessor( - * "Calculator", - * new Calculator.Processor(new CalculatorHandler())); - * - * processor.registerProcessor( - * "WeatherReport", - * new WeatherReport.Processor(new WeatherReportHandler())); - * - * TServerTransport t = new TServerSocket(9090); - * TSimpleServer server = new TSimpleServer(processor, t); - * - * server.serve(); - */ + /// + /// is a allowing a single + /// to provide multiple services. + /// + /// To do so, you instantiate the processor and then register additional processors with it, + /// as shown in the following example: + /// + /// + /// TMultiplexedProcessor processor = new TMultiplexedProcessor(); + /// + /// processor.registerProcessor( + /// "Calculator", + /// new Calculator.Processor(new CalculatorHandler())); + /// + /// processor.registerProcessor( + /// "WeatherReport", + /// new WeatherReport.Processor(new WeatherReportHandler())); + /// + /// TServerTransport t = new TServerSocket(9090); + /// TSimpleServer server = new TSimpleServer(processor, t); + /// + /// server.serve(); + /// + /// public class TMultiplexedProcessor : TProcessor { - private Dictionary ServiceProcessorMap = new Dictionary(); + private Dictionary ServiceProcessorMap = new Dictionary(); - /** - * 'Register' a service with this TMultiplexedProcessor. This allows us to broker - * requests to individual services by using the service name to select them at request time. - * - * Args: - * - serviceName Name of a service, has to be identical to the name - * declared in the Thrift IDL, e.g. "WeatherReport". - * - processor Implementation of a service, usually referred to as "handlers", - * e.g. WeatherReportHandler implementing WeatherReport.Iface. - */ - public void RegisterProcessor(String serviceName, TProcessor processor) + /// + /// 'Register' a service with this TMultiplexedProcessor. This allows us to broker + /// requests to individual services by using the service name to select them at request time. + /// + /// Args: + /// - serviceName Name of a service, has to be identical to the name + /// declared in the Thrift IDL, e.g. "WeatherReport". + /// - processor Implementation of a service, usually referred to as "handlers", + /// e.g. WeatherReportHandler implementing WeatherReport.Iface. + /// + public void RegisterProcessor(string serviceName, TProcessor processor) { ServiceProcessorMap.Add(serviceName, processor); } - private void Fail( TProtocol oprot, TMessage message, TApplicationException.ExceptionType extype, string etxt) + private void Fail(TProtocol oprot, TMessage message, TApplicationException.ExceptionType extype, string etxt) { - TApplicationException appex = new TApplicationException( extype, etxt); + TApplicationException appex = new TApplicationException(extype, etxt); TMessage newMessage = new TMessage(message.Name, TMessageType.Exception, message.SeqID); oprot.WriteMessageBegin(newMessage); - appex.Write( oprot); + appex.Write(oprot); oprot.WriteMessageEnd(); oprot.Transport.Flush(); } - /** - * This implementation of process performs the following steps: - * - * - Read the beginning of the message. - * - Extract the service name from the message. - * - Using the service name to locate the appropriate processor. - * - Dispatch to the processor, with a decorated instance of TProtocol - * that allows readMessageBegin() to return the original TMessage. - * - * Throws an exception if - * - the message type is not CALL or ONEWAY, - * - the service name was not found in the message, or - * - the service name has not been RegisterProcessor()ed. - */ + /// + /// This implementation of process performs the following steps: + /// + /// - Read the beginning of the message. + /// - Extract the service name from the message. + /// - Using the service name to locate the appropriate processor. + /// - Dispatch to the processor, with a decorated instance of TProtocol + /// that allows readMessageBegin() to return the original TMessage. + /// + /// Throws an exception if + /// - the message type is not CALL or ONEWAY, + /// - the service name was not found in the message, or + /// - the service name has not been RegisterProcessor()ed. + /// public bool Process(TProtocol iprot, TProtocol oprot) { /* Use the actual underlying protocol (e.g. TBinaryProtocol) to read the @@ -155,17 +158,17 @@ namespace Thrift.Protocol } - /** - * Our goal was to work with any protocol. In order to do that, we needed - * to allow them to call readMessageBegin() and get a TMessage in exactly - * the standard format, without the service name prepended to TMessage.name. - */ + /// + /// Our goal was to work with any protocol. In order to do that, we needed + /// to allow them to call readMessageBegin() and get a TMessage in exactly + /// the standard format, without the service name prepended to TMessage.name. + /// private class StoredMessageProtocol : TProtocolDecorator { TMessage MsgBegin; public StoredMessageProtocol(TProtocol protocol, TMessage messageBegin) - :base(protocol) + : base(protocol) { this.MsgBegin = messageBegin; } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TMultiplexedProtocol.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TMultiplexedProtocol.cs index 1e2af83..1bd420f 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TMultiplexedProtocol.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TMultiplexedProtocol.cs @@ -29,63 +29,62 @@ using System.Collections.Generic; namespace Thrift.Protocol { - /** - * TMultiplexedProtocol is a protocol-independent concrete decorator that allows a Thrift - * client to communicate with a multiplexing Thrift server, by prepending the service name - * to the function name during function calls. - * - * NOTE: THIS IS NOT TO BE USED BY SERVERS. - * On the server, use TMultiplexedProcessor to handle requests from a multiplexing client. - * - * This example uses a single socket transport to invoke two services: - * - * TSocket transport = new TSocket("localhost", 9090); - * transport.open(); - * - * TBinaryProtocol protocol = new TBinaryProtocol(transport); - * - * TMultiplexedProtocol mp = new TMultiplexedProtocol(protocol, "Calculator"); - * Calculator.Client service = new Calculator.Client(mp); - * - * TMultiplexedProtocol mp2 = new TMultiplexedProtocol(protocol, "WeatherReport"); - * WeatherReport.Client service2 = new WeatherReport.Client(mp2); - * - * System.out.println(service.add(2,2)); - * System.out.println(service2.getTemperature()); - * - */ + /// + /// TMultiplexedProtocol is a protocol-independent concrete decorator that allows a Thrift + /// client to communicate with a multiplexing Thrift server, by prepending the service name + /// to the function name during function calls. + /// + /// NOTE: THIS IS NOT TO BE USED BY SERVERS. + /// On the server, use TMultiplexedProcessor to handle requests from a multiplexing client. + /// + /// This example uses a single socket transport to invoke two services: + /// + /// TSocket transport = new TSocket("localhost", 9090); + /// transport.open(); + /// + /// TBinaryProtocol protocol = new TBinaryProtocol(transport); + /// + /// TMultiplexedProtocol mp = new TMultiplexedProtocol(protocol, "Calculator"); + /// Calculator.Client service = new Calculator.Client(mp); + /// + /// TMultiplexedProtocol mp2 = new TMultiplexedProtocol(protocol, "WeatherReport"); + /// WeatherReport.Client service2 = new WeatherReport.Client(mp2); + /// + /// System.out.println(service.add(2,2)); + /// System.out.println(service2.getTemperature()); + /// + /// public class TMultiplexedProtocol : TProtocolDecorator { - /** Used to delimit the service name from the function name */ - public static String SEPARATOR = ":"; + /// + /// Used to delimit the service name from the function name. + /// + public static string SEPARATOR = ":"; - private String ServiceName; + private string ServiceName; - /** - * Wrap the specified protocol, allowing it to be used to communicate with a - * multiplexing server. The serviceName is required as it is - * prepended to the message header so that the multiplexing server can broker - * the function call to the proper service. - * - * Args: - * protocol Your communication protocol of choice, e.g. TBinaryProtocol - * serviceName The service name of the service communicating via this protocol. - */ - public TMultiplexedProtocol(TProtocol protocol, String serviceName) + /// + /// Wrap the specified protocol, allowing it to be used to communicate with a + /// multiplexing server. The is required as it is + /// prepended to the message header so that the multiplexing server can broker + /// the function call to the proper service. + /// + /// Your communication protocol of choice, e.g. . + /// The service name of the service communicating via this protocol. + public TMultiplexedProtocol(TProtocol protocol, string serviceName) : base(protocol) { ServiceName = serviceName; } - /** - * Prepends the service name to the function name, separated by TMultiplexedProtocol.SEPARATOR. - * Args: - * tMessage The original message. - */ + /// + /// Prepends the service name to the function name, separated by TMultiplexedProtocol.SEPARATOR. + /// + /// The original message. public override void WriteMessageBegin(TMessage tMessage) { - switch(tMessage.Type) + switch (tMessage.Type) { case TMessageType.Call: case TMessageType.Oneway: @@ -101,5 +100,4 @@ namespace Thrift.Protocol } } } - } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TProtocol.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TProtocol.cs index bf481ab..dd7a6e0 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TProtocol.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TProtocol.cs @@ -108,7 +108,8 @@ namespace Thrift.Protocol public abstract void WriteI32(int i32); public abstract void WriteI64(long i64); public abstract void WriteDouble(double d); - public virtual void WriteString(string s) { + public virtual void WriteString(string s) + { WriteBinary(Encoding.UTF8.GetBytes(s)); } public abstract void WriteBinary(byte[] b); @@ -131,7 +132,8 @@ namespace Thrift.Protocol public abstract int ReadI32(); public abstract long ReadI64(); public abstract double ReadDouble(); - public virtual string ReadString() { + public virtual string ReadString() + { var buf = ReadBinary(); return Encoding.UTF8.GetString(buf, 0, buf.Length); } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TProtocolDecorator.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TProtocolDecorator.cs index 7bc34ef..8600002 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TProtocolDecorator.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TProtocolDecorator.cs @@ -28,26 +28,25 @@ using System.Collections.Generic; namespace Thrift.Protocol { - - /** - * TProtocolDecorator forwards all requests to an enclosed TProtocol instance, - * providing a way to author concise concrete decorator subclasses. While it has - * no abstract methods, it is marked abstract as a reminder that by itself, - * it does not modify the behaviour of the enclosed TProtocol. - * - * See p.175 of Design Patterns (by Gamma et al.) - * See TMultiplexedProtocol - */ + /// + /// forwards all requests to an enclosed instance, + /// providing a way to author concise concrete decorator subclasses. While it has + /// no abstract methods, it is marked abstract as a reminder that by itself, + /// it does not modify the behaviour of the enclosed . + /// + /// See p.175 of Design Patterns (by Gamma et al.) + /// + /// public abstract class TProtocolDecorator : TProtocol { private TProtocol WrappedProtocol; - /** - * Encloses the specified protocol. - * @param protocol All operations will be forward to this protocol. Must be non-null. - */ + /// + /// Encloses the specified protocol. + /// + /// All operations will be forward to this protocol. Must be non-null. public TProtocolDecorator(TProtocol protocol) - : base( protocol.Transport) + : base(protocol.Transport) { WrappedProtocol = protocol; @@ -104,7 +103,7 @@ namespace Thrift.Protocol } public override void WriteListEnd() -{ + { WrappedProtocol.WriteListEnd(); } @@ -148,7 +147,7 @@ namespace Thrift.Protocol WrappedProtocol.WriteDouble(v); } - public override void WriteString(String s) + public override void WriteString(string s) { WrappedProtocol.WriteString(s); } @@ -248,7 +247,7 @@ namespace Thrift.Protocol return WrappedProtocol.ReadDouble(); } - public override String ReadString() + public override string ReadString() { return WrappedProtocol.ReadString(); } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TProtocolException.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TProtocolException.cs index 76c749d..c0f007e 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TProtocolException.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TProtocolException.cs @@ -48,14 +48,14 @@ namespace Thrift.Protocol type_ = type; } - public TProtocolException(int type, String message) - : base(message) + public TProtocolException(int type, string message, Exception inner = null) + : base(message, inner) { type_ = type; } - public TProtocolException(String message) - : base(message) + public TProtocolException(string message, Exception inner = null) + : base(message, inner) { } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TProtocolUtil.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TProtocolUtil.cs index 0932a7f..d995c6c 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TProtocolUtil.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Protocol/TProtocolUtil.cs @@ -95,8 +95,9 @@ namespace Thrift.Protocol } prot.ReadListEnd(); break; + default: + throw new TProtocolException(TProtocolException.INVALID_DATA, "Unknown data type " + type.ToString("d")); } - } finally { diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Server/TServer.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Server/TServer.cs index 34f06a9..2bc04f3 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Server/TServer.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Server/TServer.cs @@ -28,128 +28,128 @@ using System.IO; namespace Thrift.Server { - public abstract class TServer - { - //Attributes - protected TProcessorFactory processorFactory; - protected TServerTransport serverTransport; - protected TTransportFactory inputTransportFactory; - protected TTransportFactory outputTransportFactory; - protected TProtocolFactory inputProtocolFactory; - protected TProtocolFactory outputProtocolFactory; - protected TServerEventHandler serverEventHandler = null; + public abstract class TServer + { + //Attributes + protected TProcessorFactory processorFactory; + protected TServerTransport serverTransport; + protected TTransportFactory inputTransportFactory; + protected TTransportFactory outputTransportFactory; + protected TProtocolFactory inputProtocolFactory; + protected TProtocolFactory outputProtocolFactory; + protected TServerEventHandler serverEventHandler = null; - //Methods - public void setEventHandler(TServerEventHandler seh) - { - serverEventHandler = seh; - } - public TServerEventHandler getEventHandler() - { - return serverEventHandler; - } + //Methods + public void setEventHandler(TServerEventHandler seh) + { + serverEventHandler = seh; + } + public TServerEventHandler getEventHandler() + { + return serverEventHandler; + } - //Log delegation - public delegate void LogDelegate(string str); - private LogDelegate _logDelegate; - protected LogDelegate logDelegate - { - get { return _logDelegate; } - set { _logDelegate = (value != null) ? value : DefaultLogDelegate; } - } - protected static void DefaultLogDelegate(string s) - { - Console.Error.WriteLine(s); - } + //Log delegation + public delegate void LogDelegate(string str); + private LogDelegate _logDelegate; + protected LogDelegate logDelegate + { + get { return _logDelegate; } + set { _logDelegate = (value != null) ? value : DefaultLogDelegate; } + } + protected static void DefaultLogDelegate(string s) + { + Console.Error.WriteLine(s); + } - //Construction - public TServer(TProcessor processor, - TServerTransport serverTransport) - : this(processor, serverTransport, - new TTransportFactory(), - new TTransportFactory(), - new TBinaryProtocol.Factory(), - new TBinaryProtocol.Factory(), - DefaultLogDelegate) - { - } + //Construction + public TServer(TProcessor processor, + TServerTransport serverTransport) + : this(processor, serverTransport, + new TTransportFactory(), + new TTransportFactory(), + new TBinaryProtocol.Factory(), + new TBinaryProtocol.Factory(), + DefaultLogDelegate) + { + } - public TServer(TProcessor processor, + public TServer(TProcessor processor, + TServerTransport serverTransport, + LogDelegate logDelegate) + : this(processor, + serverTransport, + new TTransportFactory(), + new TTransportFactory(), + new TBinaryProtocol.Factory(), + new TBinaryProtocol.Factory(), + logDelegate) + { + } + + public TServer(TProcessor processor, + TServerTransport serverTransport, + TTransportFactory transportFactory) + : this(processor, + serverTransport, + transportFactory, + transportFactory, + new TBinaryProtocol.Factory(), + new TBinaryProtocol.Factory(), + DefaultLogDelegate) + { + } + + public TServer(TProcessor processor, + TServerTransport serverTransport, + TTransportFactory transportFactory, + TProtocolFactory protocolFactory) + : this(processor, + serverTransport, + transportFactory, + transportFactory, + protocolFactory, + protocolFactory, + DefaultLogDelegate) + { + } + + public TServer(TProcessor processor, TServerTransport serverTransport, + TTransportFactory inputTransportFactory, + TTransportFactory outputTransportFactory, + TProtocolFactory inputProtocolFactory, + TProtocolFactory outputProtocolFactory, LogDelegate logDelegate) - : this(processor, - serverTransport, - new TTransportFactory(), - new TTransportFactory(), - new TBinaryProtocol.Factory(), - new TBinaryProtocol.Factory(), - logDelegate) - { - } + { + this.processorFactory = new TSingletonProcessorFactory(processor); + this.serverTransport = serverTransport; + this.inputTransportFactory = inputTransportFactory; + this.outputTransportFactory = outputTransportFactory; + this.inputProtocolFactory = inputProtocolFactory; + this.outputProtocolFactory = outputProtocolFactory; + this.logDelegate = (logDelegate != null) ? logDelegate : DefaultLogDelegate; + } - public TServer(TProcessor processor, - TServerTransport serverTransport, - TTransportFactory transportFactory) - : this(processor, - serverTransport, - transportFactory, - transportFactory, - new TBinaryProtocol.Factory(), - new TBinaryProtocol.Factory(), - DefaultLogDelegate) - { - } + public TServer(TProcessorFactory processorFactory, + TServerTransport serverTransport, + TTransportFactory inputTransportFactory, + TTransportFactory outputTransportFactory, + TProtocolFactory inputProtocolFactory, + TProtocolFactory outputProtocolFactory, + LogDelegate logDelegate) + { + this.processorFactory = processorFactory; + this.serverTransport = serverTransport; + this.inputTransportFactory = inputTransportFactory; + this.outputTransportFactory = outputTransportFactory; + this.inputProtocolFactory = inputProtocolFactory; + this.outputProtocolFactory = outputProtocolFactory; + this.logDelegate = (logDelegate != null) ? logDelegate : DefaultLogDelegate; + } - public TServer(TProcessor processor, - TServerTransport serverTransport, - TTransportFactory transportFactory, - TProtocolFactory protocolFactory) - : this(processor, - serverTransport, - transportFactory, - transportFactory, - protocolFactory, - protocolFactory, - DefaultLogDelegate) - { + //Abstract Interface + public abstract void Serve(); + public abstract void Stop(); } - - public TServer(TProcessor processor, - TServerTransport serverTransport, - TTransportFactory inputTransportFactory, - TTransportFactory outputTransportFactory, - TProtocolFactory inputProtocolFactory, - TProtocolFactory outputProtocolFactory, - LogDelegate logDelegate) - { - this.processorFactory = new TSingletonProcessorFactory(processor); - this.serverTransport = serverTransport; - this.inputTransportFactory = inputTransportFactory; - this.outputTransportFactory = outputTransportFactory; - this.inputProtocolFactory = inputProtocolFactory; - this.outputProtocolFactory = outputProtocolFactory; - this.logDelegate = (logDelegate != null) ? logDelegate : DefaultLogDelegate; - } - - public TServer(TProcessorFactory processorFactory, - TServerTransport serverTransport, - TTransportFactory inputTransportFactory, - TTransportFactory outputTransportFactory, - TProtocolFactory inputProtocolFactory, - TProtocolFactory outputProtocolFactory, - LogDelegate logDelegate) - { - this.processorFactory = processorFactory; - this.serverTransport = serverTransport; - this.inputTransportFactory = inputTransportFactory; - this.outputTransportFactory = outputTransportFactory; - this.inputProtocolFactory = inputProtocolFactory; - this.outputProtocolFactory = outputProtocolFactory; - this.logDelegate = (logDelegate != null) ? logDelegate : DefaultLogDelegate; - } - - //Abstract Interface - public abstract void Serve(); - public abstract void Stop(); - } } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Server/TServerEventHandler.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Server/TServerEventHandler.cs index 843b166..e81efc6 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Server/TServerEventHandler.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Server/TServerEventHandler.cs @@ -25,26 +25,29 @@ using System; namespace Thrift.Server { - /// - /// Interface implemented by server users to handle events from the server - /// - public interface TServerEventHandler - { /// - /// Called before the server begins */ + /// Interface implemented by server users to handle events from the server. /// - void preServe(); - /// - /// Called when a new client has connected and is about to being processing */ - /// - Object createContext(Thrift.Protocol.TProtocol input, Thrift.Protocol.TProtocol output); - /// - /// Called when a client has finished request-handling to delete server context */ - /// - void deleteContext(Object serverContext, Thrift.Protocol.TProtocol input, Thrift.Protocol.TProtocol output); - /// - /// Called when a client is about to call the processor */ - /// - void processContext(Object serverContext, Thrift.Transport.TTransport transport); - }; + public interface TServerEventHandler + { + /// + /// Called before the server begins. + /// + void preServe(); + + /// + /// Called when a new client has connected and is about to being processing. + /// + object createContext(Thrift.Protocol.TProtocol input, Thrift.Protocol.TProtocol output); + + /// + /// Called when a client has finished request-handling to delete server context. + /// + void deleteContext(object serverContext, Thrift.Protocol.TProtocol input, Thrift.Protocol.TProtocol output); + + /// + /// Called when a client is about to call the processor. + /// + void processContext(object serverContext, Thrift.Transport.TTransport transport); + }; } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Server/TSimpleServer.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Server/TSimpleServer.cs index c73fecf..4e7ea96 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Server/TSimpleServer.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Server/TSimpleServer.cs @@ -27,154 +27,154 @@ using Thrift.Protocol; namespace Thrift.Server { - /// - /// Simple single-threaded server for testing - /// - public class TSimpleServer : TServer - { - private bool stop = false; - - public TSimpleServer(TProcessor processor, - TServerTransport serverTransport) - : base(processor, serverTransport, new TTransportFactory(), new TTransportFactory(), new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), DefaultLogDelegate) + /// + /// Simple single-threaded server for testing. + /// + public class TSimpleServer : TServer { - } + private bool stop = false; - public TSimpleServer(TProcessor processor, - TServerTransport serverTransport, - LogDelegate logDel) - : base(processor, serverTransport, new TTransportFactory(), new TTransportFactory(), new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), logDel) - { - } - - public TSimpleServer(TProcessor processor, - TServerTransport serverTransport, - TTransportFactory transportFactory) - : base(processor, - serverTransport, - transportFactory, - transportFactory, - new TBinaryProtocol.Factory(), - new TBinaryProtocol.Factory(), - DefaultLogDelegate) - { - } - - public TSimpleServer(TProcessor processor, - TServerTransport serverTransport, - TTransportFactory transportFactory, - TProtocolFactory protocolFactory) - : base(processor, - serverTransport, - transportFactory, - transportFactory, - protocolFactory, - protocolFactory, - DefaultLogDelegate) - { - } - - public TSimpleServer(TProcessorFactory processorFactory, - TServerTransport serverTransport, - TTransportFactory transportFactory, - TProtocolFactory protocolFactory) - : base(processorFactory, - serverTransport, - transportFactory, - transportFactory, - protocolFactory, - protocolFactory, - DefaultLogDelegate) - { - } - - public override void Serve() - { - try - { - serverTransport.Listen(); - } - catch (TTransportException ttx) - { - logDelegate(ttx.ToString()); - return; - } - - //Fire the preServe server event when server is up but before any client connections - if (serverEventHandler != null) - serverEventHandler.preServe(); - - while (!stop) - { - TProcessor processor = null; - TTransport client = null; - TTransport inputTransport = null; - TTransport outputTransport = null; - TProtocol inputProtocol = null; - TProtocol outputProtocol = null; - Object connectionContext = null; - try + public TSimpleServer(TProcessor processor, + TServerTransport serverTransport) + : base(processor, serverTransport, new TTransportFactory(), new TTransportFactory(), new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), DefaultLogDelegate) { - using (client = serverTransport.Accept()) - { - processor = processorFactory.GetProcessor(client); - if (client != null) + } + + public TSimpleServer(TProcessor processor, + TServerTransport serverTransport, + LogDelegate logDel) + : base(processor, serverTransport, new TTransportFactory(), new TTransportFactory(), new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), logDel) + { + } + + public TSimpleServer(TProcessor processor, + TServerTransport serverTransport, + TTransportFactory transportFactory) + : base(processor, + serverTransport, + transportFactory, + transportFactory, + new TBinaryProtocol.Factory(), + new TBinaryProtocol.Factory(), + DefaultLogDelegate) + { + } + + public TSimpleServer(TProcessor processor, + TServerTransport serverTransport, + TTransportFactory transportFactory, + TProtocolFactory protocolFactory) + : base(processor, + serverTransport, + transportFactory, + transportFactory, + protocolFactory, + protocolFactory, + DefaultLogDelegate) + { + } + + public TSimpleServer(TProcessorFactory processorFactory, + TServerTransport serverTransport, + TTransportFactory transportFactory, + TProtocolFactory protocolFactory) + : base(processorFactory, + serverTransport, + transportFactory, + transportFactory, + protocolFactory, + protocolFactory, + DefaultLogDelegate) + { + } + + public override void Serve() + { + try { - using (inputTransport = inputTransportFactory.GetTransport(client)) - { - using (outputTransport = outputTransportFactory.GetTransport(client)) - { - inputProtocol = inputProtocolFactory.GetProtocol(inputTransport); - outputProtocol = outputProtocolFactory.GetProtocol(outputTransport); - - //Recover event handler (if any) and fire createContext server event when a client connects - if (serverEventHandler != null) - connectionContext = serverEventHandler.createContext(inputProtocol, outputProtocol); - - //Process client requests until client disconnects - while (!stop) - { - if (!inputTransport.Peek()) - break; - - //Fire processContext server event - //N.B. This is the pattern implemented in C++ and the event fires provisionally. - //That is to say it may be many minutes between the event firing and the client request - //actually arriving or the client may hang up without ever makeing a request. - if (serverEventHandler != null) - serverEventHandler.processContext(connectionContext, inputTransport); - //Process client request (blocks until transport is readable) - if (!processor.Process(inputProtocol, outputProtocol)) - break; - } - } - } + serverTransport.Listen(); + } + catch (TTransportException ttx) + { + logDelegate(ttx.ToString()); + return; + } + + //Fire the preServe server event when server is up but before any client connections + if (serverEventHandler != null) + serverEventHandler.preServe(); + + while (!stop) + { + TProcessor processor = null; + TTransport client = null; + TTransport inputTransport = null; + TTransport outputTransport = null; + TProtocol inputProtocol = null; + TProtocol outputProtocol = null; + object connectionContext = null; + try + { + using (client = serverTransport.Accept()) + { + processor = processorFactory.GetProcessor(client); + if (client != null) + { + using (inputTransport = inputTransportFactory.GetTransport(client)) + { + using (outputTransport = outputTransportFactory.GetTransport(client)) + { + inputProtocol = inputProtocolFactory.GetProtocol(inputTransport); + outputProtocol = outputProtocolFactory.GetProtocol(outputTransport); + + //Recover event handler (if any) and fire createContext server event when a client connects + if (serverEventHandler != null) + connectionContext = serverEventHandler.createContext(inputProtocol, outputProtocol); + + //Process client requests until client disconnects + while (!stop) + { + if (!inputTransport.Peek()) + break; + + //Fire processContext server event + //N.B. This is the pattern implemented in C++ and the event fires provisionally. + //That is to say it may be many minutes between the event firing and the client request + //actually arriving or the client may hang up without ever makeing a request. + if (serverEventHandler != null) + serverEventHandler.processContext(connectionContext, inputTransport); + //Process client request (blocks until transport is readable) + if (!processor.Process(inputProtocol, outputProtocol)) + break; + } + } + } + } + } + } + catch (TTransportException ttx) + { + if (!stop || ttx.Type != TTransportException.ExceptionType.Interrupted) + { + logDelegate(ttx.ToString()); + } + } + catch (Exception x) + { + //Unexpected + logDelegate(x.ToString()); + } + + //Fire deleteContext server event after client disconnects + if (serverEventHandler != null) + serverEventHandler.deleteContext(connectionContext, inputProtocol, outputProtocol); } - } - } - catch (TTransportException ttx) - { - if (!stop || ttx.Type != TTransportException.ExceptionType.Interrupted) - { - logDelegate(ttx.ToString()); - } - } - catch (Exception x) - { - //Unexpected - logDelegate(x.ToString()); } - //Fire deleteContext server event after client disconnects - if (serverEventHandler != null) - serverEventHandler.deleteContext(connectionContext, inputProtocol, outputProtocol); - } + public override void Stop() + { + stop = true; + serverTransport.Close(); + } } - - public override void Stop() - { - stop = true; - serverTransport.Close(); - } - } } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Server/TThreadPoolServer.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Server/TThreadPoolServer.cs index f0c7fe4..a494ce7 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Server/TThreadPoolServer.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Server/TThreadPoolServer.cs @@ -28,196 +28,268 @@ using Thrift.Transport; namespace Thrift.Server { - /// - /// Server that uses C# built-in ThreadPool to spawn threads when handling requests - /// - public class TThreadPoolServer : TServer - { - private const int DEFAULT_MIN_THREADS = 10; - private const int DEFAULT_MAX_THREADS = 100; - private volatile bool stop = false; - - public TThreadPoolServer(TProcessor processor, TServerTransport serverTransport) - : this(new TSingletonProcessorFactory(processor), serverTransport, - new TTransportFactory(), new TTransportFactory(), - new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), - DEFAULT_MIN_THREADS, DEFAULT_MAX_THREADS, DefaultLogDelegate) - { - } - - public TThreadPoolServer(TProcessor processor, TServerTransport serverTransport, LogDelegate logDelegate) - : this(new TSingletonProcessorFactory(processor), serverTransport, - new TTransportFactory(), new TTransportFactory(), - new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), - DEFAULT_MIN_THREADS, DEFAULT_MAX_THREADS, logDelegate) - { - } - - public TThreadPoolServer(TProcessor processor, - TServerTransport serverTransport, - TTransportFactory transportFactory, - TProtocolFactory protocolFactory) - : this(new TSingletonProcessorFactory(processor), serverTransport, - transportFactory, transportFactory, - protocolFactory, protocolFactory, - DEFAULT_MIN_THREADS, DEFAULT_MAX_THREADS, DefaultLogDelegate) - { - } - - public TThreadPoolServer(TProcessorFactory processorFactory, - TServerTransport serverTransport, - TTransportFactory transportFactory, - TProtocolFactory protocolFactory) - : this(processorFactory, serverTransport, - transportFactory, transportFactory, - protocolFactory, protocolFactory, - DEFAULT_MIN_THREADS, DEFAULT_MAX_THREADS, DefaultLogDelegate) - { - } - - public TThreadPoolServer(TProcessorFactory processorFactory, - TServerTransport serverTransport, - TTransportFactory inputTransportFactory, - TTransportFactory outputTransportFactory, - TProtocolFactory inputProtocolFactory, - TProtocolFactory outputProtocolFactory, - int minThreadPoolThreads, int maxThreadPoolThreads, LogDelegate logDel) - : base(processorFactory, serverTransport, inputTransportFactory, outputTransportFactory, - inputProtocolFactory, outputProtocolFactory, logDel) - { - lock (typeof(TThreadPoolServer)) - { - if (!ThreadPool.SetMaxThreads(maxThreadPoolThreads, maxThreadPoolThreads)) - { - throw new Exception("Error: could not SetMaxThreads in ThreadPool"); - } - if (!ThreadPool.SetMinThreads(minThreadPoolThreads, minThreadPoolThreads)) - { - throw new Exception("Error: could not SetMinThreads in ThreadPool"); - } - } - } - - /// - /// Use new ThreadPool thread for each new client connection + /// Server that uses C# built-in ThreadPool to spawn threads when handling requests. /// - public override void Serve() + public class TThreadPoolServer : TServer { - try - { - serverTransport.Listen(); - } - catch (TTransportException ttx) - { - logDelegate("Error, could not listen on ServerTransport: " + ttx); - return; - } + private const int DEFAULT_MIN_THREADS = -1; // use .NET ThreadPool defaults + private const int DEFAULT_MAX_THREADS = -1; // use .NET ThreadPool defaults + private volatile bool stop = false; - //Fire the preServe server event when server is up but before any client connections - if (serverEventHandler != null) - serverEventHandler.preServe(); + public struct Configuration + { + public int MinWorkerThreads; + public int MaxWorkerThreads; + public int MinIOThreads; + public int MaxIOThreads; - while (!stop) - { - int failureCount = 0; - try - { - TTransport client = serverTransport.Accept(); - ThreadPool.QueueUserWorkItem(this.Execute, client); - } - catch (TTransportException ttx) - { - if (!stop || ttx.Type != TTransportException.ExceptionType.Interrupted) - { - ++failureCount; - logDelegate(ttx.ToString()); - } + public Configuration(int min = DEFAULT_MIN_THREADS, int max = DEFAULT_MAX_THREADS) + { + MinWorkerThreads = min; + MaxWorkerThreads = max; + MinIOThreads = min; + MaxIOThreads = max; + } + public Configuration(int minWork, int maxWork, int minIO, int maxIO) + { + MinWorkerThreads = minWork; + MaxWorkerThreads = maxWork; + MinIOThreads = minIO; + MaxIOThreads = maxIO; + } } - } - if (stop) - { - try + public TThreadPoolServer(TProcessor processor, TServerTransport serverTransport) + : this(new TSingletonProcessorFactory(processor), serverTransport, + new TTransportFactory(), new TTransportFactory(), + new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), + new Configuration(), DefaultLogDelegate) { - serverTransport.Close(); } - catch (TTransportException ttx) + + public TThreadPoolServer(TProcessor processor, TServerTransport serverTransport, LogDelegate logDelegate) + : this(new TSingletonProcessorFactory(processor), serverTransport, + new TTransportFactory(), new TTransportFactory(), + new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), + new Configuration(), logDelegate) { - logDelegate("TServerTransport failed on close: " + ttx.Message); } - stop = false; - } + + public TThreadPoolServer(TProcessor processor, + TServerTransport serverTransport, + TTransportFactory transportFactory, + TProtocolFactory protocolFactory) + : this(new TSingletonProcessorFactory(processor), serverTransport, + transportFactory, transportFactory, + protocolFactory, protocolFactory, + new Configuration(), DefaultLogDelegate) + { + } + + public TThreadPoolServer(TProcessorFactory processorFactory, + TServerTransport serverTransport, + TTransportFactory transportFactory, + TProtocolFactory protocolFactory) + : this(processorFactory, serverTransport, + transportFactory, transportFactory, + protocolFactory, protocolFactory, + new Configuration(), DefaultLogDelegate) + { + } + + public TThreadPoolServer(TProcessorFactory processorFactory, + TServerTransport serverTransport, + TTransportFactory inputTransportFactory, + TTransportFactory outputTransportFactory, + TProtocolFactory inputProtocolFactory, + TProtocolFactory outputProtocolFactory, + int minThreadPoolThreads, int maxThreadPoolThreads, LogDelegate logDel) + : this(processorFactory, serverTransport, inputTransportFactory, outputTransportFactory, + inputProtocolFactory, outputProtocolFactory, + new Configuration(minThreadPoolThreads, maxThreadPoolThreads), + logDel) + { + } + + public TThreadPoolServer(TProcessorFactory processorFactory, + TServerTransport serverTransport, + TTransportFactory inputTransportFactory, + TTransportFactory outputTransportFactory, + TProtocolFactory inputProtocolFactory, + TProtocolFactory outputProtocolFactory, + Configuration threadConfig, + LogDelegate logDel) + : base(processorFactory, serverTransport, inputTransportFactory, outputTransportFactory, + inputProtocolFactory, outputProtocolFactory, logDel) + { + lock (typeof(TThreadPoolServer)) + { + if ((threadConfig.MaxWorkerThreads > 0) || (threadConfig.MaxIOThreads > 0)) + { + int work, comm; + ThreadPool.GetMaxThreads(out work, out comm); + if (threadConfig.MaxWorkerThreads > 0) + work = threadConfig.MaxWorkerThreads; + if (threadConfig.MaxIOThreads > 0) + comm = threadConfig.MaxIOThreads; + if (!ThreadPool.SetMaxThreads(work, comm)) + throw new Exception("Error: could not SetMaxThreads in ThreadPool"); + } + + if ((threadConfig.MinWorkerThreads > 0) || (threadConfig.MinIOThreads > 0)) + { + int work, comm; + ThreadPool.GetMinThreads(out work, out comm); + if (threadConfig.MinWorkerThreads > 0) + work = threadConfig.MinWorkerThreads; + if (threadConfig.MinIOThreads > 0) + comm = threadConfig.MinIOThreads; + if (!ThreadPool.SetMinThreads(work, comm)) + throw new Exception("Error: could not SetMinThreads in ThreadPool"); + } + } + } + + + /// + /// Use new ThreadPool thread for each new client connection. + /// + public override void Serve() + { + try + { + serverTransport.Listen(); + } + catch (TTransportException ttx) + { + logDelegate("Error, could not listen on ServerTransport: " + ttx); + return; + } + + //Fire the preServe server event when server is up but before any client connections + if (serverEventHandler != null) + serverEventHandler.preServe(); + + while (!stop) + { + int failureCount = 0; + try + { + TTransport client = serverTransport.Accept(); + ThreadPool.QueueUserWorkItem(this.Execute, client); + } + catch (TTransportException ttx) + { + if (!stop || ttx.Type != TTransportException.ExceptionType.Interrupted) + { + ++failureCount; + logDelegate(ttx.ToString()); + } + + } + } + + if (stop) + { + try + { + serverTransport.Close(); + } + catch (TTransportException ttx) + { + logDelegate("TServerTransport failed on close: " + ttx.Message); + } + stop = false; + } + } + + /// + /// Loops on processing a client forever + /// threadContext will be a TTransport instance + /// + /// + private void Execute(object threadContext) + { + using (TTransport client = (TTransport)threadContext) + { + TProcessor processor = processorFactory.GetProcessor(client, this); + TTransport inputTransport = null; + TTransport outputTransport = null; + TProtocol inputProtocol = null; + TProtocol outputProtocol = null; + object connectionContext = null; + try + { + try + { + inputTransport = inputTransportFactory.GetTransport(client); + outputTransport = outputTransportFactory.GetTransport(client); + inputProtocol = inputProtocolFactory.GetProtocol(inputTransport); + outputProtocol = outputProtocolFactory.GetProtocol(outputTransport); + + //Recover event handler (if any) and fire createContext server event when a client connects + if (serverEventHandler != null) + connectionContext = serverEventHandler.createContext(inputProtocol, outputProtocol); + + //Process client requests until client disconnects + while (!stop) + { + if (!inputTransport.Peek()) + break; + + //Fire processContext server event + //N.B. This is the pattern implemented in C++ and the event fires provisionally. + //That is to say it may be many minutes between the event firing and the client request + //actually arriving or the client may hang up without ever makeing a request. + if (serverEventHandler != null) + serverEventHandler.processContext(connectionContext, inputTransport); + //Process client request (blocks until transport is readable) + if (!processor.Process(inputProtocol, outputProtocol)) + break; + } + } + catch (TTransportException) + { + //Usually a client disconnect, expected + } + catch (Exception x) + { + //Unexpected + logDelegate("Error: " + x); + } + + //Fire deleteContext server event after client disconnects + if (serverEventHandler != null) + serverEventHandler.deleteContext(connectionContext, inputProtocol, outputProtocol); + + } + finally + { + //Close transports + if (inputTransport != null) + inputTransport.Close(); + if (outputTransport != null) + outputTransport.Close(); + + // disposable stuff should be disposed + if (inputProtocol != null) + inputProtocol.Dispose(); + if (outputProtocol != null) + outputProtocol.Dispose(); + if (inputTransport != null) + inputTransport.Dispose(); + if (outputTransport != null) + outputTransport.Dispose(); + } + } + } + + public override void Stop() + { + stop = true; + serverTransport.Close(); + } } - - /// - /// Loops on processing a client forever - /// threadContext will be a TTransport instance - /// - /// - private void Execute(Object threadContext) - { - TTransport client = (TTransport)threadContext; - TProcessor processor = processorFactory.GetProcessor(client, this); - TTransport inputTransport = null; - TTransport outputTransport = null; - TProtocol inputProtocol = null; - TProtocol outputProtocol = null; - Object connectionContext = null; - try - { - inputTransport = inputTransportFactory.GetTransport(client); - outputTransport = outputTransportFactory.GetTransport(client); - inputProtocol = inputProtocolFactory.GetProtocol(inputTransport); - outputProtocol = outputProtocolFactory.GetProtocol(outputTransport); - - //Recover event handler (if any) and fire createContext server event when a client connects - if (serverEventHandler != null) - connectionContext = serverEventHandler.createContext(inputProtocol, outputProtocol); - - //Process client requests until client disconnects - while (!stop) - { - if (!inputTransport.Peek()) - break; - - //Fire processContext server event - //N.B. This is the pattern implemented in C++ and the event fires provisionally. - //That is to say it may be many minutes between the event firing and the client request - //actually arriving or the client may hang up without ever makeing a request. - if (serverEventHandler != null) - serverEventHandler.processContext(connectionContext, inputTransport); - //Process client request (blocks until transport is readable) - if (!processor.Process(inputProtocol, outputProtocol)) - break; - } - } - catch (TTransportException) - { - //Usually a client disconnect, expected - } - catch (Exception x) - { - //Unexpected - logDelegate("Error: " + x); - } - - //Fire deleteContext server event after client disconnects - if (serverEventHandler != null) - serverEventHandler.deleteContext(connectionContext, inputProtocol, outputProtocol); - - //Close transports - if (inputTransport != null) - inputTransport.Close(); - if (outputTransport != null) - outputTransport.Close(); - } - - public override void Stop() - { - stop = true; - serverTransport.Close(); - } - } } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Server/TThreadedServer.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Server/TThreadedServer.cs index fe13dfd..cc051a3 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Server/TThreadedServer.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Server/TThreadedServer.cs @@ -26,243 +26,257 @@ using Thrift.Transport; namespace Thrift.Server { - /// - /// Server that uses C# threads (as opposed to the ThreadPool) when handling requests - /// - public class TThreadedServer : TServer - { - private const int DEFAULT_MAX_THREADS = 100; - private volatile bool stop = false; - private readonly int maxThreads; - - private Queue clientQueue; - private THashSet clientThreads; - private object clientLock; - private Thread workerThread; - - public int ClientThreadsCount { - get { return clientThreads.Count; } - } - - public TThreadedServer(TProcessor processor, TServerTransport serverTransport) - : this(new TSingletonProcessorFactory(processor), serverTransport, - new TTransportFactory(), new TTransportFactory(), - new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), - DEFAULT_MAX_THREADS, DefaultLogDelegate) - { - } - - public TThreadedServer(TProcessor processor, TServerTransport serverTransport, LogDelegate logDelegate) - : this(new TSingletonProcessorFactory(processor), serverTransport, - new TTransportFactory(), new TTransportFactory(), - new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), - DEFAULT_MAX_THREADS, logDelegate) - { - } - - - public TThreadedServer(TProcessor processor, - TServerTransport serverTransport, - TTransportFactory transportFactory, - TProtocolFactory protocolFactory) - : this(new TSingletonProcessorFactory(processor), serverTransport, - transportFactory, transportFactory, - protocolFactory, protocolFactory, - DEFAULT_MAX_THREADS, DefaultLogDelegate) - { - } - - public TThreadedServer(TProcessorFactory processorFactory, - TServerTransport serverTransport, - TTransportFactory transportFactory, - TProtocolFactory protocolFactory) - : this(processorFactory, serverTransport, - transportFactory, transportFactory, - protocolFactory, protocolFactory, - DEFAULT_MAX_THREADS, DefaultLogDelegate) - { - } - public TThreadedServer(TProcessorFactory processorFactory, - TServerTransport serverTransport, - TTransportFactory inputTransportFactory, - TTransportFactory outputTransportFactory, - TProtocolFactory inputProtocolFactory, - TProtocolFactory outputProtocolFactory, - int maxThreads, LogDelegate logDel) - : base(processorFactory, serverTransport, inputTransportFactory, outputTransportFactory, - inputProtocolFactory, outputProtocolFactory, logDel) - { - this.maxThreads = maxThreads; - clientQueue = new Queue(); - clientLock = new object(); - clientThreads = new THashSet(); - } - /// - /// Use new Thread for each new client connection. block until numConnections < maxThreads + /// Server that uses C# threads (as opposed to the ThreadPool) when handling requests. /// - public override void Serve() + public class TThreadedServer : TServer { - try - { - //start worker thread - workerThread = new Thread(new ThreadStart(Execute)); - workerThread.Start(); - serverTransport.Listen(); - } - catch (TTransportException ttx) - { - logDelegate("Error, could not listen on ServerTransport: " + ttx); - return; - } + private const int DEFAULT_MAX_THREADS = 100; + private volatile bool stop = false; + private readonly int maxThreads; - //Fire the preServe server event when server is up but before any client connections - if (serverEventHandler != null) - serverEventHandler.preServe(); + private Queue clientQueue; + private THashSet clientThreads; + private object clientLock; + private Thread workerThread; - while (!stop) - { - int failureCount = 0; - try + public int ClientThreadsCount { - TTransport client = serverTransport.Accept(); - lock (clientLock) - { - clientQueue.Enqueue(client); - Monitor.Pulse(clientLock); - } + get { return clientThreads.Count; } } - catch (TTransportException ttx) - { - if (!stop || ttx.Type != TTransportException.ExceptionType.Interrupted) - { - ++failureCount; - logDelegate(ttx.ToString()); - } + public TThreadedServer(TProcessor processor, TServerTransport serverTransport) + : this(new TSingletonProcessorFactory(processor), serverTransport, + new TTransportFactory(), new TTransportFactory(), + new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), + DEFAULT_MAX_THREADS, DefaultLogDelegate) + { } - } - if (stop) - { - try + public TThreadedServer(TProcessor processor, TServerTransport serverTransport, LogDelegate logDelegate) + : this(new TSingletonProcessorFactory(processor), serverTransport, + new TTransportFactory(), new TTransportFactory(), + new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), + DEFAULT_MAX_THREADS, logDelegate) { - serverTransport.Close(); } - catch (TTransportException ttx) + + + public TThreadedServer(TProcessor processor, + TServerTransport serverTransport, + TTransportFactory transportFactory, + TProtocolFactory protocolFactory) + : this(new TSingletonProcessorFactory(processor), serverTransport, + transportFactory, transportFactory, + protocolFactory, protocolFactory, + DEFAULT_MAX_THREADS, DefaultLogDelegate) { - logDelegate("TServeTransport failed on close: " + ttx.Message); } - stop = false; - } - } - /// - /// Loops on processing a client forever - /// threadContext will be a TTransport instance - /// - /// - private void Execute() - { - while (!stop) - { - TTransport client; - Thread t; - lock (clientLock) + public TThreadedServer(TProcessorFactory processorFactory, + TServerTransport serverTransport, + TTransportFactory transportFactory, + TProtocolFactory protocolFactory) + : this(processorFactory, serverTransport, + transportFactory, transportFactory, + protocolFactory, protocolFactory, + DEFAULT_MAX_THREADS, DefaultLogDelegate) { - //don't dequeue if too many connections - while (clientThreads.Count >= maxThreads) - { - Monitor.Wait(clientLock); - } - - while (clientQueue.Count == 0) - { - Monitor.Wait(clientLock); - } - - client = clientQueue.Dequeue(); - t = new Thread(new ParameterizedThreadStart(ClientWorker)); - clientThreads.Add(t); } - //start processing requests from client on new thread - t.Start(client); - } - } - - private void ClientWorker(Object context) - { - TTransport client = (TTransport)context; - TProcessor processor = processorFactory.GetProcessor(client); - TTransport inputTransport = null; - TTransport outputTransport = null; - TProtocol inputProtocol = null; - TProtocol outputProtocol = null; - Object connectionContext = null; - try - { - using (inputTransport = inputTransportFactory.GetTransport(client)) + public TThreadedServer(TProcessorFactory processorFactory, + TServerTransport serverTransport, + TTransportFactory inputTransportFactory, + TTransportFactory outputTransportFactory, + TProtocolFactory inputProtocolFactory, + TProtocolFactory outputProtocolFactory, + int maxThreads, LogDelegate logDel) + : base(processorFactory, serverTransport, inputTransportFactory, outputTransportFactory, + inputProtocolFactory, outputProtocolFactory, logDel) { - using (outputTransport = outputTransportFactory.GetTransport(client)) - { - inputProtocol = inputProtocolFactory.GetProtocol(inputTransport); - outputProtocol = outputProtocolFactory.GetProtocol(outputTransport); + this.maxThreads = maxThreads; + clientQueue = new Queue(); + clientLock = new object(); + clientThreads = new THashSet(); + } - //Recover event handler (if any) and fire createContext server event when a client connects + /// + /// Use new Thread for each new client connection. block until numConnections < maxThreads. + /// + public override void Serve() + { + try + { + //start worker thread + workerThread = new Thread(new ThreadStart(Execute)); + workerThread.Start(); + serverTransport.Listen(); + } + catch (TTransportException ttx) + { + logDelegate("Error, could not listen on ServerTransport: " + ttx); + return; + } + + //Fire the preServe server event when server is up but before any client connections if (serverEventHandler != null) - connectionContext = serverEventHandler.createContext(inputProtocol, outputProtocol); + serverEventHandler.preServe(); - //Process client requests until client disconnects while (!stop) { - if (!inputTransport.Peek()) - break; + int failureCount = 0; + try + { + TTransport client = serverTransport.Accept(); + lock (clientLock) + { + clientQueue.Enqueue(client); + Monitor.Pulse(clientLock); + } + } + catch (TTransportException ttx) + { + if (!stop || ttx.Type != TTransportException.ExceptionType.Interrupted) + { + ++failureCount; + logDelegate(ttx.ToString()); + } - //Fire processContext server event - //N.B. This is the pattern implemented in C++ and the event fires provisionally. - //That is to say it may be many minutes between the event firing and the client request - //actually arriving or the client may hang up without ever makeing a request. - if (serverEventHandler != null) - serverEventHandler.processContext(connectionContext, inputTransport); - //Process client request (blocks until transport is readable) - if (!processor.Process(inputProtocol, outputProtocol)) - break; + } + } + + if (stop) + { + try + { + serverTransport.Close(); + } + catch (TTransportException ttx) + { + logDelegate("TServeTransport failed on close: " + ttx.Message); + } + stop = false; } - } } - } - catch (TTransportException) - { - //Usually a client disconnect, expected - } - catch (Exception x) - { - //Unexpected - logDelegate("Error: " + x); - } - //Fire deleteContext server event after client disconnects - if (serverEventHandler != null) - serverEventHandler.deleteContext(connectionContext, inputProtocol, outputProtocol); + /// + /// Loops on processing a client forever + /// + private void Execute() + { + while (!stop) + { + TTransport client; + Thread t; + lock (clientLock) + { + //don't dequeue if too many connections + while (clientThreads.Count >= maxThreads) + { + Monitor.Wait(clientLock); + } - lock (clientLock) - { - clientThreads.Remove(Thread.CurrentThread); - Monitor.Pulse(clientLock); - } - return; + while (clientQueue.Count == 0) + { + Monitor.Wait(clientLock); + } + + client = clientQueue.Dequeue(); + t = new Thread(new ParameterizedThreadStart(ClientWorker)); + clientThreads.Add(t); + } + //start processing requests from client on new thread + t.Start(client); + } + } + + private void ClientWorker(object context) + { + using (TTransport client = (TTransport)context) + { + TProcessor processor = processorFactory.GetProcessor(client); + TTransport inputTransport = null; + TTransport outputTransport = null; + TProtocol inputProtocol = null; + TProtocol outputProtocol = null; + object connectionContext = null; + try + { + try + { + inputTransport = inputTransportFactory.GetTransport(client); + outputTransport = outputTransportFactory.GetTransport(client); + inputProtocol = inputProtocolFactory.GetProtocol(inputTransport); + outputProtocol = outputProtocolFactory.GetProtocol(outputTransport); + + //Recover event handler (if any) and fire createContext server event when a client connects + if (serverEventHandler != null) + connectionContext = serverEventHandler.createContext(inputProtocol, outputProtocol); + + //Process client requests until client disconnects + while (!stop) + { + if (!inputTransport.Peek()) + break; + + //Fire processContext server event + //N.B. This is the pattern implemented in C++ and the event fires provisionally. + //That is to say it may be many minutes between the event firing and the client request + //actually arriving or the client may hang up without ever makeing a request. + if (serverEventHandler != null) + serverEventHandler.processContext(connectionContext, inputTransport); + //Process client request (blocks until transport is readable) + if (!processor.Process(inputProtocol, outputProtocol)) + break; + } + } + catch (TTransportException) + { + //Usually a client disconnect, expected + } + catch (Exception x) + { + //Unexpected + logDelegate("Error: " + x); + } + + //Fire deleteContext server event after client disconnects + if (serverEventHandler != null) + serverEventHandler.deleteContext(connectionContext, inputProtocol, outputProtocol); + + lock (clientLock) + { + clientThreads.Remove(Thread.CurrentThread); + Monitor.Pulse(clientLock); + } + + } + finally + { + //Close transports + if (inputTransport != null) + inputTransport.Close(); + if (outputTransport != null) + outputTransport.Close(); + + // disposable stuff should be disposed + if (inputProtocol != null) + inputProtocol.Dispose(); + if (outputProtocol != null) + outputProtocol.Dispose(); + } + } + } + + public override void Stop() + { + stop = true; + serverTransport.Close(); + //clean up all the threads myself + workerThread.Abort(); + foreach (Thread t in clientThreads) + { + t.Abort(); + } + } } - - public override void Stop() - { - stop = true; - serverTransport.Close(); - //clean up all the threads myself - workerThread.Abort(); - foreach (Thread t in clientThreads) - { - t.Abort(); - } - } - } } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/TApplicationException.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/TApplicationException.cs index 4c0d3a3..8dd7ae5 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/TApplicationException.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/TApplicationException.cs @@ -40,7 +40,7 @@ namespace Thrift } public TApplicationException(ExceptionType type, string message) - : base(message) + : base(message, null) // TApplicationException is serializable, but we never serialize InnerException { this.type = type; } @@ -103,7 +103,7 @@ namespace Thrift oprot.WriteStructBegin(struc); - if (!String.IsNullOrEmpty(Message)) + if (!string.IsNullOrEmpty(Message)) { field.Name = "message"; field.Type = TType.String; @@ -137,5 +137,10 @@ namespace Thrift InvalidProtocol, UnsupportedClientType } + + public ExceptionType Type + { + get { return type; } + } } } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/TException.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/TException.cs index 65509ec..aa9a210 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/TException.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/TException.cs @@ -31,8 +31,8 @@ namespace Thrift { } - public TException( string message) - : base(message) + public TException(string message, Exception inner) + : base(message, inner) { } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/TPrototypeProcessorFactory.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/TPrototypeProcessorFactory.cs index 6f56d33..0b47261 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/TPrototypeProcessorFactory.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/TPrototypeProcessorFactory.cs @@ -42,7 +42,7 @@ namespace Thrift public TProcessor GetProcessor(TTransport trans, TServer server = null) { - H handler = (H) Activator.CreateInstance(typeof(H), handlerArgs); + H handler = (H)Activator.CreateInstance(typeof(H), handlerArgs); TControllingHandler handlerServerRef = handler as TControllingHandler; if (handlerServerRef != null) diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/TSingletonProcessorFactory.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/TSingletonProcessorFactory.cs index 40dc44c..ed2897b 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/TSingletonProcessorFactory.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/TSingletonProcessorFactory.cs @@ -17,7 +17,7 @@ * under the License. */ - using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Thrift.45.csproj b/vendor/git.apache.org/thrift.git/lib/csharp/src/Thrift.45.csproj index 949f373..455916f 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Thrift.45.csproj +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Thrift.45.csproj @@ -17,8 +17,7 @@ specific language governing permissions and limitations under the License. --> - - + Debug AnyCPU @@ -35,7 +34,7 @@ full false bin\Debug\ - DEBUG;TRACE + TRACE;DEBUG;NET45 prompt 4 @@ -43,7 +42,7 @@ pdbonly true bin\Release\ - TRACE + TRACE;NET45 prompt 4 @@ -88,17 +87,17 @@ + - - + @@ -106,6 +105,7 @@ + diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Thrift.csproj b/vendor/git.apache.org/thrift.git/lib/csharp/src/Thrift.csproj index 99c6b46..ede152d 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Thrift.csproj +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Thrift.csproj @@ -45,7 +45,7 @@ false true 0 - 1.0.0.%2a + 0.12.0.%2a false false true @@ -79,8 +79,7 @@ - - + @@ -103,32 +102,35 @@ - - - + - + + + + + + - + @@ -151,4 +153,4 @@ - \ No newline at end of file + diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TBufferedTransport.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TBufferedTransport.cs index caedd87..8870988 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TBufferedTransport.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TBufferedTransport.cs @@ -76,19 +76,23 @@ namespace Thrift.Transport ValidateBufferArgs(buf, off, len); if (!IsOpen) throw new TTransportException(TTransportException.ExceptionType.NotOpen); + if (inputBuffer.Capacity < bufSize) inputBuffer.Capacity = bufSize; - int got = inputBuffer.Read(buf, off, len); - if (got > 0) - return got; - inputBuffer.Seek(0, SeekOrigin.Begin); - inputBuffer.SetLength(inputBuffer.Capacity); - int filled = transport.Read(inputBuffer.GetBuffer(), 0, (int)inputBuffer.Length); - inputBuffer.SetLength(filled); - if (filled == 0) - return 0; - return Read(buf, off, len); + while (true) + { + int got = inputBuffer.Read(buf, off, len); + if (got > 0) + return got; + + inputBuffer.Seek(0, SeekOrigin.Begin); + inputBuffer.SetLength(inputBuffer.Capacity); + int filled = transport.Read(inputBuffer.GetBuffer(), 0, (int)inputBuffer.Length); + inputBuffer.SetLength(filled); + if (filled == 0) + return 0; + } } public override void Write(byte[] buf, int off, int len) @@ -125,9 +129,8 @@ namespace Thrift.Transport } } - public override void Flush() + private void InternalFlush() { - CheckNotDisposed(); if (!IsOpen) throw new TTransportException(TTransportException.ExceptionType.NotOpen); if (outputBuffer.Length > 0) @@ -135,17 +138,39 @@ namespace Thrift.Transport transport.Write(outputBuffer.GetBuffer(), 0, (int)outputBuffer.Length); outputBuffer.SetLength(0); } + } + + public override void Flush() + { + CheckNotDisposed(); + InternalFlush(); + transport.Flush(); } - private void CheckNotDisposed() + public override IAsyncResult BeginFlush(AsyncCallback callback, object state) + { + CheckNotDisposed(); + InternalFlush(); + + return transport.BeginFlush( callback, state); + } + + public override void EndFlush(IAsyncResult asyncResult) + { + transport.EndFlush( asyncResult); + } + + + + protected void CheckNotDisposed() { if (_IsDisposed) throw new ObjectDisposedException("TBufferedTransport"); } #region " IDisposable Support " - private bool _IsDisposed; + protected bool _IsDisposed { get; private set; } // IDisposable protected override void Dispose(bool disposing) @@ -154,8 +179,12 @@ namespace Thrift.Transport { if (disposing) { - inputBuffer.Dispose(); - outputBuffer.Dispose(); + if (inputBuffer != null) + inputBuffer.Dispose(); + if (outputBuffer != null) + outputBuffer.Dispose(); + if (transport != null) + transport.Dispose(); } } _IsDisposed = true; diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TFramedTransport.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TFramedTransport.cs index a369e8e..a746a32 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TFramedTransport.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TFramedTransport.cs @@ -108,7 +108,7 @@ namespace Thrift.Transport writeBuffer.Write(buf, off, len); } - public override void Flush() + private void InternalFlush() { CheckNotDisposed(); if (!IsOpen) @@ -116,8 +116,8 @@ namespace Thrift.Transport byte[] buf = writeBuffer.GetBuffer(); int len = (int)writeBuffer.Length; int data_len = len - HeaderSize; - if ( data_len < 0 ) - throw new System.InvalidOperationException (); // logic error actually + if (data_len < 0) + throw new System.InvalidOperationException(); // logic error actually // Inject message header into the reserved buffer space EncodeFrameSize(data_len, buf); @@ -126,11 +126,30 @@ namespace Thrift.Transport transport.Write(buf, 0, len); InitWriteBuffer(); + } + + public override void Flush() + { + CheckNotDisposed(); + InternalFlush(); transport.Flush(); } - private void InitWriteBuffer () + public override IAsyncResult BeginFlush(AsyncCallback callback, object state) + { + CheckNotDisposed(); + InternalFlush(); + + return transport.BeginFlush( callback, state); + } + + public override void EndFlush(IAsyncResult asyncResult) + { + transport.EndFlush( asyncResult); + } + + private void InitWriteBuffer() { // Reserve space for message header to be put right before sending it out writeBuffer.SetLength(HeaderSize); @@ -150,7 +169,7 @@ namespace Thrift.Transport return ((buf[0] & 0xff) << 24) | ((buf[1] & 0xff) << 16) | - ((buf[2] & 0xff) << 8) | + ((buf[2] & 0xff) << 8) | ((buf[3] & 0xff)); } @@ -171,8 +190,12 @@ namespace Thrift.Transport { if (disposing) { - readBuffer.Dispose(); - writeBuffer.Dispose(); + if (readBuffer != null) + readBuffer.Dispose(); + if (writeBuffer != null) + writeBuffer.Dispose(); + if (transport != null) + transport.Dispose(); } } _IsDisposed = true; diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/THttpClient.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/THttpClient.cs index a56a3e8..667fc25 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/THttpClient.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/THttpClient.cs @@ -26,10 +26,10 @@ using System.Net; using System.Threading; using System.Linq; using System.Security.Cryptography.X509Certificates; +using System.IO.Compression; namespace Thrift.Transport { - public class THttpClient : TTransport, IDisposable { private readonly Uri uri; @@ -42,7 +42,7 @@ namespace Thrift.Transport private int readTimeout = 30000; - private IDictionary customHeaders = new Dictionary(); + private IDictionary customHeaders = new Dictionary(); #if !SILVERLIGHT private IWebProxy proxy = WebRequest.DefaultWebProxy; @@ -63,7 +63,7 @@ namespace Thrift.Transport { set { - connectTimeout = value; + connectTimeout = value; } } @@ -75,7 +75,7 @@ namespace Thrift.Transport } } - public IDictionary CustomHeaders + public IDictionary CustomHeaders { get { @@ -139,7 +139,7 @@ namespace Thrift.Transport } catch (IOException iox) { - throw new TTransportException(TTransportException.ExceptionType.Unknown, iox.ToString()); + throw new TTransportException(TTransportException.ExceptionType.Unknown, iox.ToString(), iox); } } @@ -166,6 +166,7 @@ namespace Thrift.Transport try { HttpWebRequest connection = CreateRequest(); + connection.Headers.Add("Accept-Encoding", "gzip, deflate"); byte[] data = outputStream.ToArray(); connection.ContentLength = data.Length; @@ -184,26 +185,69 @@ namespace Thrift.Transport // Copy the response to a memory stream so that we can // cleanly close the response and response stream. inputStream = new MemoryStream(); - byte[] buffer = new byte[8096]; + byte[] buffer = new byte[8192]; // multiple of 4096 int bytesRead; while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0) { - inputStream.Write (buffer, 0, bytesRead); + inputStream.Write(buffer, 0, bytesRead); } inputStream.Seek(0, 0); } + + var encodings = response.Headers.GetValues("Content-Encoding"); + if (encodings != null) + { + foreach (var encoding in encodings) + { + switch (encoding) + { + case "gzip": + DecompressGZipped(ref inputStream); + break; + case "deflate": + DecompressDeflated(ref inputStream); + break; + default: + break; + } + } + } } } } catch (IOException iox) { - throw new TTransportException(TTransportException.ExceptionType.Unknown, iox.ToString()); + throw new TTransportException(TTransportException.ExceptionType.Unknown, iox.ToString(), iox); } catch (WebException wx) { - throw new TTransportException(TTransportException.ExceptionType.Unknown, "Couldn't connect to server: " + wx); + throw new TTransportException(TTransportException.ExceptionType.Unknown, "Couldn't connect to server: " + wx, wx); } } + + private void DecompressDeflated(ref Stream inputStream) + { + var tmp = new MemoryStream(); + using (var decomp = new DeflateStream(inputStream, CompressionMode.Decompress)) + { + decomp.CopyTo(tmp); + } + inputStream.Dispose(); + inputStream = tmp; + inputStream.Seek(0, 0); + } + + private void DecompressGZipped(ref Stream inputStream) + { + var tmp = new MemoryStream(); + using (var decomp = new GZipStream(inputStream, CompressionMode.Decompress)) + { + decomp.CopyTo(tmp); + } + inputStream.Dispose(); + inputStream = tmp; + inputStream.Seek(0, 0); + } #endif private HttpWebRequest CreateRequest() { @@ -272,7 +316,7 @@ namespace Thrift.Transport } catch (IOException iox) { - throw new TTransportException(iox.ToString()); + throw new TTransportException(iox.ToString(), iox); } } @@ -280,7 +324,7 @@ namespace Thrift.Transport { try { - var flushAsyncResult = (FlushAsyncResult) asyncResult; + var flushAsyncResult = (FlushAsyncResult)asyncResult; if (!flushAsyncResult.IsCompleted) { @@ -293,7 +337,8 @@ namespace Thrift.Transport { throw flushAsyncResult.AsyncException; } - } finally + } + finally { outputStream = new MemoryStream(); } @@ -315,7 +360,7 @@ namespace Thrift.Transport } catch (Exception exception) { - flushAsyncResult.AsyncException = new TTransportException(exception.ToString()); + flushAsyncResult.AsyncException = new TTransportException(exception.ToString(), exception); flushAsyncResult.UpdateStatusToComplete(); flushAsyncResult.NotifyCallbackWhenAvailable(); } @@ -330,7 +375,7 @@ namespace Thrift.Transport } catch (Exception exception) { - flushAsyncResult.AsyncException = new TTransportException(exception.ToString()); + flushAsyncResult.AsyncException = new TTransportException(exception.ToString(), exception); } flushAsyncResult.UpdateStatusToComplete(); flushAsyncResult.NotifyCallbackWhenAvailable(); @@ -342,9 +387,9 @@ namespace Thrift.Transport private volatile Boolean _isCompleted; private ManualResetEvent _evt; private readonly AsyncCallback _cbMethod; - private readonly Object _state; + private readonly object _state; - public FlushAsyncResult(AsyncCallback cbMethod, Object state) + public FlushAsyncResult(AsyncCallback cbMethod, object state) { _cbMethod = cbMethod; _state = state; @@ -370,7 +415,7 @@ namespace Thrift.Transport { get { return _isCompleted; } } - private readonly Object _locker = new Object(); + private readonly object _locker = new object(); private ManualResetEvent GetEvtHandle() { lock (_locker) @@ -407,7 +452,7 @@ namespace Thrift.Transport } } -#region " IDisposable Support " + #region " IDisposable Support " private bool _IsDisposed; // IDisposable @@ -425,6 +470,6 @@ namespace Thrift.Transport } _IsDisposed = true; } -#endregion + #endregion } } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TMemoryBuffer.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TMemoryBuffer.cs index d8ff9dc..303d083 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TMemoryBuffer.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TMemoryBuffer.cs @@ -22,45 +22,56 @@ using System.IO; using System.Reflection; using Thrift.Protocol; -namespace Thrift.Transport { - public class TMemoryBuffer : TTransport { +namespace Thrift.Transport +{ + public class TMemoryBuffer : TTransport + { private readonly MemoryStream byteStream; - public TMemoryBuffer() { + public TMemoryBuffer() + { byteStream = new MemoryStream(); } - public TMemoryBuffer(byte[] buf) { + public TMemoryBuffer(byte[] buf) + { byteStream = new MemoryStream(buf); } - public override void Open() { + public override void Open() + { /** do nothing **/ } - public override void Close() { + public override void Close() + { /** do nothing **/ } - public override int Read(byte[] buf, int off, int len) { + public override int Read(byte[] buf, int off, int len) + { return byteStream.Read(buf, off, len); } - public override void Write(byte[] buf, int off, int len) { + public override void Write(byte[] buf, int off, int len) + { byteStream.Write(buf, off, len); } - public byte[] GetBuffer() { + public byte[] GetBuffer() + { return byteStream.ToArray(); } - public override bool IsOpen { + public override bool IsOpen + { get { return true; } } - public static byte[] Serialize(TAbstractBase s) { + public static byte[] Serialize(TAbstractBase s) + { var t = new TMemoryBuffer(); var p = new TBinaryProtocol(t); @@ -69,26 +80,33 @@ namespace Thrift.Transport { return t.GetBuffer(); } - public static T DeSerialize(byte[] buf) where T : TAbstractBase { + public static T DeSerialize(byte[] buf) where T : TAbstractBase + { var trans = new TMemoryBuffer(buf); var p = new TBinaryProtocol(trans); - if (typeof (TBase).IsAssignableFrom(typeof (T))) { - var method = typeof (T).GetMethod("Read", BindingFlags.Instance | BindingFlags.Public); + if (typeof(TBase).IsAssignableFrom(typeof(T))) + { + var method = typeof(T).GetMethod("Read", BindingFlags.Instance | BindingFlags.Public); var t = Activator.CreateInstance(); - method.Invoke(t, new object[] {p}); + method.Invoke(t, new object[] { p }); return t; - } else { - var method = typeof (T).GetMethod("Read", BindingFlags.Static | BindingFlags.Public); - return (T) method.Invoke(null, new object[] {p}); + } + else + { + var method = typeof(T).GetMethod("Read", BindingFlags.Static | BindingFlags.Public); + return (T)method.Invoke(null, new object[] { p }); } } private bool _IsDisposed; // IDisposable - protected override void Dispose(bool disposing) { - if (!_IsDisposed) { - if (disposing) { + protected override void Dispose(bool disposing) + { + if (!_IsDisposed) + { + if (disposing) + { if (byteStream != null) byteStream.Dispose(); } @@ -96,4 +114,4 @@ namespace Thrift.Transport { _IsDisposed = true; } } -} \ No newline at end of file +} diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TNamedPipeClientTransport.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TNamedPipeClientTransport.cs index 9faa6e7..49a50aa 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TNamedPipeClientTransport.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TNamedPipeClientTransport.cs @@ -21,7 +21,9 @@ * details. */ +using System; using System.IO.Pipes; +using System.Threading; namespace Thrift.Transport { @@ -30,17 +32,20 @@ namespace Thrift.Transport private NamedPipeClientStream client; private string ServerName; private string PipeName; + private int ConnectTimeout; - public TNamedPipeClientTransport(string pipe) + public TNamedPipeClientTransport(string pipe, int timeout = Timeout.Infinite) { ServerName = "."; PipeName = pipe; + ConnectTimeout = timeout; } - public TNamedPipeClientTransport(string server, string pipe) + public TNamedPipeClientTransport(string server, string pipe, int timeout = Timeout.Infinite) { ServerName = (server != "") ? server : "."; PipeName = pipe; + ConnectTimeout = timeout; } public override bool IsOpen @@ -55,7 +60,7 @@ namespace Thrift.Transport throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen); } client = new NamedPipeClientStream(ServerName, PipeName, PipeDirection.InOut, PipeOptions.None); - client.Connect(); + client.Connect(ConnectTimeout); } public override void Close() @@ -84,7 +89,18 @@ namespace Thrift.Transport throw new TTransportException(TTransportException.ExceptionType.NotOpen); } - client.Write(buf, off, len); + // if necessary, send the data in chunks + // there's a system limit around 0x10000 bytes that we hit otherwise + // MSDN: "Pipe write operations across a network are limited to 65,535 bytes per write. For more information regarding pipes, see the Remarks section." + var nBytes = Math.Min(len, 15 * 4096); // 16 would exceed the limit + while (nBytes > 0) + { + client.Write(buf, off, nBytes); + + off += nBytes; + len -= nBytes; + nBytes = Math.Min(len, nBytes); + } } protected override void Dispose(bool disposing) @@ -92,4 +108,4 @@ namespace Thrift.Transport client.Dispose(); } } -} \ No newline at end of file +} diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TNamedPipeServerTransport.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TNamedPipeServerTransport.cs index c1e8400..32215cf 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TNamedPipeServerTransport.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TNamedPipeServerTransport.cs @@ -22,9 +22,9 @@ */ using System; -using System.Collections.Generic; using System.IO.Pipes; using System.Threading; +using System.Security.Principal; namespace Thrift.Transport { @@ -68,23 +68,32 @@ namespace Thrift.Transport if (stream == null) { var direction = PipeDirection.InOut; - var maxconn = 254; + var maxconn = NamedPipeServerStream.MaxAllowedServerInstances; var mode = PipeTransmissionMode.Byte; var options = asyncMode ? PipeOptions.Asynchronous : PipeOptions.None; - var inbuf = 4096; - var outbuf = 4096; - // TODO: security + const int INBUF_SIZE = 4096; + const int OUTBUF_SIZE = 4096; + + // security + var security = new PipeSecurity(); + security.AddAccessRule( + new PipeAccessRule( + new SecurityIdentifier(WellKnownSidType.WorldSid, null), + PipeAccessRights.Read | PipeAccessRights.Write | PipeAccessRights.Synchronize | PipeAccessRights.CreateNewInstance, + System.Security.AccessControl.AccessControlType.Allow + ) + ); try { - stream = new NamedPipeServerStream(pipeAddress, direction, maxconn, mode, options, inbuf, outbuf); + stream = new NamedPipeServerStream(pipeAddress, direction, maxconn, mode, options, INBUF_SIZE, OUTBUF_SIZE, security); } catch (NotImplementedException) // Mono still does not support async, fallback to sync { if (asyncMode) { options &= (~PipeOptions.Asynchronous); - stream = new NamedPipeServerStream(pipeAddress, direction, maxconn, mode, options, inbuf, outbuf); + stream = new NamedPipeServerStream(pipeAddress, direction, maxconn, mode, options, INBUF_SIZE, OUTBUF_SIZE, security); asyncMode = false; } else @@ -121,7 +130,7 @@ namespace Thrift.Transport if (stream != null) eOuter = e; else - eOuter = new TTransportException(TTransportException.ExceptionType.Interrupted, e.Message); + eOuter = new TTransportException(TTransportException.ExceptionType.Interrupted, e.Message, e); } evt.Set(); }, null); @@ -148,7 +157,7 @@ namespace Thrift.Transport catch (Exception e) { Close(); - throw new TTransportException(TTransportException.ExceptionType.NotOpen, e.Message); + throw new TTransportException(TTransportException.ExceptionType.NotOpen, e.Message, e); } } @@ -205,7 +214,7 @@ namespace Thrift.Transport if (stream != null) eOuter = e; else - eOuter = new TTransportException(TTransportException.ExceptionType.Interrupted, e.Message); + eOuter = new TTransportException(TTransportException.ExceptionType.Interrupted, e.Message, e); } evt.Set(); }, null); @@ -230,40 +239,51 @@ namespace Thrift.Transport throw new TTransportException(TTransportException.ExceptionType.NotOpen); } - if (asyncMode) + // if necessary, send the data in chunks + // there's a system limit around 0x10000 bytes that we hit otherwise + // MSDN: "Pipe write operations across a network are limited to 65,535 bytes per write. For more information regarding pipes, see the Remarks section." + var nBytes = Math.Min(len, 15 * 4096); // 16 would exceed the limit + while (nBytes > 0) { - Exception eOuter = null; - var evt = new ManualResetEvent(false); - stream.BeginWrite(buf, off, len, asyncResult => + if (asyncMode) { - try + Exception eOuter = null; + var evt = new ManualResetEvent(false); + + stream.BeginWrite(buf, off, nBytes, asyncResult => { - if (stream != null) - stream.EndWrite(asyncResult); - else - eOuter = new TTransportException(TTransportException.ExceptionType.Interrupted); - } - catch (Exception e) - { - if (stream != null) - eOuter = e; - else - eOuter = new TTransportException(TTransportException.ExceptionType.Interrupted, e.Message); - } - evt.Set(); - }, null); + try + { + if (stream != null) + stream.EndWrite(asyncResult); + else + eOuter = new TTransportException(TTransportException.ExceptionType.Interrupted); + } + catch (Exception e) + { + if (stream != null) + eOuter = e; + else + eOuter = new TTransportException(TTransportException.ExceptionType.Interrupted, e.Message, e); + } + evt.Set(); + }, null); - evt.WaitOne(); + evt.WaitOne(); - if (eOuter != null) - throw eOuter; // rethrow exception + if (eOuter != null) + throw eOuter; // rethrow exception + } + else + { + stream.Write(buf, off, nBytes); + } + + off += nBytes; + len -= nBytes; + nBytes = Math.Min(len, nBytes); } - else - { - stream.Write(buf, off, len); - } - } protected override void Dispose(bool disposing) diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TServerSocket.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TServerSocket.cs index 82a367c..d8ec62a 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TServerSocket.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TServerSocket.cs @@ -29,56 +29,56 @@ namespace Thrift.Transport { public class TServerSocket : TServerTransport { - /** - * Underlying server with socket - */ + /// + /// Underlying server with socket. + /// private TcpListener server = null; - /** - * Port to listen on - */ + /// + /// Port to listen on. + /// private int port = 0; - /** - * Timeout for client sockets from accept - */ + /// + /// Timeout for client sockets from accept. + /// private int clientTimeout = 0; - /** - * Whether or not to wrap new TSocket connections in buffers - */ + /// + /// Whether or not to wrap new TSocket connections in buffers. + /// private bool useBufferedSockets = false; - /** - * Creates a server socket from underlying socket object - */ + /// + /// Creates a server socket from underlying socket object. + /// public TServerSocket(TcpListener listener) - :this(listener, 0) + : this(listener, 0) { } - /** - * Creates a server socket from underlying socket object - */ + /// + /// Creates a server socket from underlying socket object. + /// public TServerSocket(TcpListener listener, int clientTimeout) { this.server = listener; this.clientTimeout = clientTimeout; } - /** - * Creates just a port listening server socket - */ + /// + /// Creates just a port listening server socket. + /// public TServerSocket(int port) : this(port, 0) { } - /** - * Creates just a port listening server socket - */ + /// + /// Creates just a port listening server socket. + /// public TServerSocket(int port, int clientTimeout) - :this(port, clientTimeout, false) + : this(port, clientTimeout, false) { } @@ -90,13 +90,13 @@ namespace Thrift.Transport try { // Make server socket - server = new TcpListener(System.Net.IPAddress.Any, this.port); - server.Server.NoDelay = true; + this.server = TSocketVersionizer.CreateTcpListener(this.port); + this.server.Server.NoDelay = true; } - catch (Exception) + catch (Exception ex) { server = null; - throw new TTransportException("Could not create ServerSocket on port " + port + "."); + throw new TTransportException("Could not create ServerSocket on port " + this.port + ".", ex); } } @@ -111,7 +111,7 @@ namespace Thrift.Transport } catch (SocketException sx) { - throw new TTransportException("Could not accept on listening socket: " + sx.Message); + throw new TTransportException("Could not accept on listening socket: " + sx.Message, sx); } } } @@ -153,7 +153,7 @@ namespace Thrift.Transport } catch (Exception ex) { - throw new TTransportException(ex.ToString()); + throw new TTransportException(ex.ToString(), ex); } } @@ -167,7 +167,7 @@ namespace Thrift.Transport } catch (Exception ex) { - throw new TTransportException("WARNING: Could not close server socket: " + ex); + throw new TTransportException("WARNING: Could not close server socket: " + ex, ex); } server = null; } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TServerTransport.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TServerTransport.cs index 05d7d0f..e63880b 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TServerTransport.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TServerTransport.cs @@ -34,10 +34,11 @@ namespace Thrift.Transport public TTransport Accept() { TTransport transport = AcceptImpl(); - if (transport == null) { - throw new TTransportException("accept() may not return NULL"); + if (transport == null) + { + throw new TTransportException("accept() may not return NULL"); } return transport; - } + } } } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TSilverlightSocket.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TSilverlightSocket.cs index cbd3baa..40469ab 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TSilverlightSocket.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TSilverlightSocket.cs @@ -112,7 +112,7 @@ namespace Thrift.Transport throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen, "Socket already connected"); } - if (String.IsNullOrEmpty(host)) + if (string.IsNullOrEmpty(host)) { throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open null host"); } @@ -282,9 +282,9 @@ namespace Thrift.Transport private volatile Boolean _isCompleted; private ManualResetEvent _evt; private readonly AsyncCallback _cbMethod; - private readonly Object _state; + private readonly object _state; - public FlushAsyncResult(AsyncCallback cbMethod, Object state) + public FlushAsyncResult(AsyncCallback cbMethod, object state) { _cbMethod = cbMethod; _state = state; @@ -314,7 +314,7 @@ namespace Thrift.Transport get { return _isCompleted; } } - private readonly Object _locker = new Object(); + private readonly object _locker = new object(); private ManualResetEvent GetEvtHandle() { @@ -362,7 +362,7 @@ namespace Thrift.Transport } } - #region " IDisposable Support " +#region " IDisposable Support " private bool _IsDisposed; // IDisposable @@ -385,7 +385,7 @@ namespace Thrift.Transport } _IsDisposed = true; } - #endregion +#endregion } } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TSocket.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TSocket.cs index cf1a440..d8fa335 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TSocket.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TSocket.cs @@ -60,9 +60,9 @@ namespace Thrift.Transport private void InitSocket() { - client = new TcpClient(); - client.ReceiveTimeout = client.SendTimeout = timeout; - client.Client.NoDelay = true; + this.client = TSocketVersionizer.CreateTcpClient(); + this.client.ReceiveTimeout = client.SendTimeout = timeout; + this.client.Client.NoDelay = true; } public int Timeout @@ -117,7 +117,7 @@ namespace Thrift.Transport throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen, "Socket already connected"); } - if (String.IsNullOrEmpty(host)) + if (string.IsNullOrEmpty(host)) { throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open null host"); } @@ -132,7 +132,7 @@ namespace Thrift.Transport InitSocket(); } - if( timeout == 0) // no timeout -> infinite + if (timeout == 0) // no timeout -> infinite { client.Connect(host, port); } @@ -145,7 +145,7 @@ namespace Thrift.Transport { lock (hlp.Mutex) { - if( hlp.CallbackDone) + if (hlp.CallbackDone) { asyncres.AsyncWaitHandle.Close(); client.Close(); @@ -174,7 +174,7 @@ namespace Thrift.Transport try { - if( hlp.Client.Client != null) + if (hlp.Client.Client != null) hlp.Client.EndConnect(asyncres); } catch (Exception) @@ -184,14 +184,18 @@ namespace Thrift.Transport if (hlp.DoCleanup) { - try { + try + { asyncres.AsyncWaitHandle.Close(); - } catch (Exception) {} + } + catch (Exception) { } - try { + try + { if (hlp.Client is IDisposable) ((IDisposable)hlp.Client).Dispose(); - } catch (Exception) {} + } + catch (Exception) { } hlp.Client = null; } } @@ -219,23 +223,23 @@ namespace Thrift.Transport } } - #region " IDisposable Support " - private bool _IsDisposed; + #region " IDisposable Support " + private bool _IsDisposed; - // IDisposable - protected override void Dispose(bool disposing) - { - if (!_IsDisposed) - { - if (disposing) + // IDisposable + protected override void Dispose(bool disposing) { - if (client != null) - ((IDisposable)client).Dispose(); - base.Dispose(disposing); + if (!_IsDisposed) + { + if (disposing) + { + if (client != null) + ((IDisposable)client).Dispose(); + base.Dispose(disposing); + } + } + _IsDisposed = true; } - } - _IsDisposed = true; + #endregion } - #endregion - } } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TSocketVersionizer.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TSocketVersionizer.cs new file mode 100644 index 0000000..bf4c0e4 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TSocketVersionizer.cs @@ -0,0 +1,78 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + * + * Contains some contributions under the Thrift Software License. + * Please see doc/old-thrift-license.txt in the Thrift distribution for + * details. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Sockets; +using System.Reflection; +using System.Text; +#if NET45 +using System.Threading.Tasks; +#endif + +namespace Thrift.Transport +{ + /// + /// PropertyInfo for the DualMode property of the System.Net.Sockets.Socket class. Used to determine if the sockets are capable of + /// automatic IPv4 and IPv6 handling. If DualMode is present the sockets automatically handle IPv4 and IPv6 connections. + /// If the DualMode is not available the system configuration determines whether IPv4 or IPv6 is used. + /// + internal static class TSocketVersionizer + { + /// + /// Creates a TcpClient according to the capabilitites of the used framework + /// + internal static TcpClient CreateTcpClient() + { + TcpClient client = null; + +#if NET45 + client = new TcpClient(AddressFamily.InterNetworkV6); + client.Client.DualMode = true; +#else + client = new TcpClient(AddressFamily.InterNetwork); +#endif + + return client; + } + + /// + /// Creates a TcpListener according to the capabilitites of the used framework. + /// + internal static TcpListener CreateTcpListener(Int32 port) + { + TcpListener listener = null; + +#if NET45 + listener = new TcpListener(System.Net.IPAddress.IPv6Any, port); + listener.Server.DualMode = true; +#else + + listener = new TcpListener(System.Net.IPAddress.Any, port); +#endif + + return listener; + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TStreamTransport.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TStreamTransport.cs index 468743c..304599f 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TStreamTransport.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TStreamTransport.cs @@ -105,24 +105,24 @@ namespace Thrift.Transport } - #region " IDisposable Support " - private bool _IsDisposed; + #region " IDisposable Support " + private bool _IsDisposed; - // IDisposable - protected override void Dispose(bool disposing) - { - if (!_IsDisposed) - { - if (disposing) + // IDisposable + protected override void Dispose(bool disposing) { - if (InputStream != null) - InputStream.Dispose(); - if (OutputStream != null) - OutputStream.Dispose(); + if (!_IsDisposed) + { + if (disposing) + { + if (InputStream != null) + InputStream.Dispose(); + if (OutputStream != null) + OutputStream.Dispose(); + } + } + _IsDisposed = true; } - } - _IsDisposed = true; + #endregion } - #endregion - } } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TTLSServerSocket.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TTLSServerSocket.cs index d6e69eb..716a97c 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TTLSServerSocket.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TTLSServerSocket.cs @@ -76,7 +76,7 @@ namespace Thrift.Transport /// The port where the server runs. /// The certificate object. public TTLSServerSocket(int port, X509Certificate2 certificate) - : this(port, 0, certificate) + : this(port, 0, certificate) { } @@ -108,7 +108,7 @@ namespace Thrift.Transport X509Certificate2 certificate, RemoteCertificateValidationCallback clientCertValidator = null, LocalCertificateSelectionCallback localCertificateSelectionCallback = null, - // TODO: Enable Tls1 and Tls2 (TLS 1.1 and 1.2) by default once we start using .NET 4.5+. + // TODO: Enable Tls11 and Tls12 (TLS 1.1 and 1.2) by default once we start using .NET 4.5+. SslProtocols sslProtocols = SslProtocols.Tls) { if (!certificate.HasPrivateKey) @@ -126,13 +126,13 @@ namespace Thrift.Transport try { // Create server socket - server = new TcpListener(System.Net.IPAddress.Any, this.port); - server.Server.NoDelay = true; + this.server = TSocketVersionizer.CreateTcpListener(this.port); + this.server.Server.NoDelay = true; } - catch (Exception) + catch (Exception ex) { server = null; - throw new TTransportException("Could not create ServerSocket on port " + port + "."); + throw new TTransportException("Could not create ServerSocket on port " + this.port + ".", ex); } } @@ -150,7 +150,7 @@ namespace Thrift.Transport } catch (SocketException sx) { - throw new TTransportException("Could not accept on listening socket: " + sx.Message); + throw new TTransportException("Could not accept on listening socket: " + sx.Message, sx); } } } @@ -197,7 +197,7 @@ namespace Thrift.Transport } catch (Exception ex) { - throw new TTransportException(ex.ToString()); + throw new TTransportException(ex.ToString(), ex); } } @@ -214,7 +214,7 @@ namespace Thrift.Transport } catch (Exception ex) { - throw new TTransportException("WARNING: Could not close server socket: " + ex); + throw new TTransportException("WARNING: Could not close server socket: " + ex, ex); } this.server = null; } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TTLSSocket.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TTLSSocket.cs index 08f0215..fd019c3 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TTLSSocket.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TTLSSocket.cs @@ -192,7 +192,7 @@ namespace Thrift.Transport /// private void InitSocket() { - this.client = new TcpClient(); + client = TSocketVersionizer.CreateTcpClient(); client.ReceiveTimeout = client.SendTimeout = timeout; client.Client.NoDelay = true; } @@ -263,7 +263,7 @@ namespace Thrift.Transport /// The sender-object. /// The used certificate. /// The certificate chain. - /// An enum, which lists all the errors from the .NET certificate check. + /// An enum, which lists all the errors from the .NET certificate check. /// private bool DefaultCertificateValidator(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslValidationErrors) { @@ -280,7 +280,7 @@ namespace Thrift.Transport throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen, "Socket already connected"); } - if (String.IsNullOrEmpty(host)) + if (string.IsNullOrEmpty(host)) { throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open null host"); } @@ -307,7 +307,7 @@ namespace Thrift.Transport { RemoteCertificateValidationCallback validator = this.certValidator ?? DefaultCertificateValidator; - if( this.localCertificateSelectionCallback != null) + if (this.localCertificateSelectionCallback != null) { this.secureStream = new SslStream( this.client.GetStream(), @@ -335,7 +335,7 @@ namespace Thrift.Transport else { // Client authentication - X509CertificateCollection certs = certificate != null ? new X509CertificateCollection { certificate } : new X509CertificateCollection(); + X509CertificateCollection certs = certificate != null ? new X509CertificateCollection { certificate } : new X509CertificateCollection(); this.secureStream.AuthenticateAsClient(host, certs, sslProtocols, true); } } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TTransport.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TTransport.cs index 6fb1077..5e4ac22 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TTransport.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TTransport.cs @@ -53,7 +53,7 @@ namespace Thrift.Transport if (bytes == 0) return false; } - catch( IOException) + catch (IOException) { return false; } @@ -108,7 +108,7 @@ namespace Thrift.Transport public virtual void Write(byte[] buf) { - Write (buf, 0, buf.Length); + Write(buf, 0, buf.Length); } public abstract void Write(byte[] buf, int off, int len); diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TTransportException.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TTransportException.cs index ae987d5..7f6cc18 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TTransportException.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TTransportException.cs @@ -40,14 +40,14 @@ namespace Thrift.Transport this.type = type; } - public TTransportException(ExceptionType type, string message) - : base(message) + public TTransportException(ExceptionType type, string message, Exception inner = null) + : base(message, inner) { this.type = type; } - public TTransportException(string message) - : base(message) + public TTransportException(string message, Exception inner = null) + : base(message, inner) { } diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TTransportFactory.cs b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TTransportFactory.cs index fa10033..47a0c62 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TTransportFactory.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/src/Transport/TTransportFactory.cs @@ -26,7 +26,7 @@ using System; namespace Thrift.Transport { /// - /// From Mark Slee & Aditya Agarwal of Facebook: + /// From Mark Slee & Aditya Agarwal of Facebook: /// Factory class used to create wrapped instance of Transports. /// This is used primarily in servers, which get Transports from /// a ServerTransport and then may want to mutate them (i.e. create diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/test/JSON/Properties/AssemblyInfo.cs b/vendor/git.apache.org/thrift.git/lib/csharp/test/JSON/Properties/AssemblyInfo.cs index 6788bc3..fdff4a1 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/test/JSON/Properties/AssemblyInfo.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/test/JSON/Properties/AssemblyInfo.cs @@ -27,9 +27,9 @@ using System.Runtime.InteropServices; [assembly: AssemblyTitle("JSONTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("JSONTest")] -[assembly: AssemblyCopyright("Copyright © 2014")] +[assembly: AssemblyCompany("The Apache Software Foundation")] +[assembly: AssemblyProduct("Thrift")] +[assembly: AssemblyCopyright("The Apache Software Foundation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/test/Multiplex/Client/MultiplexClient.csproj b/vendor/git.apache.org/thrift.git/lib/csharp/test/Multiplex/Client/MultiplexClient.csproj index 6221e14..4df1cbc 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/test/Multiplex/Client/MultiplexClient.csproj +++ b/vendor/git.apache.org/thrift.git/lib/csharp/test/Multiplex/Client/MultiplexClient.csproj @@ -46,7 +46,7 @@ false true 0 - 1.0.0.%2a + 0.12.0.%2a false true @@ -145,4 +145,4 @@ for %25%25I in ("%25THRIFT_FILE%25") do set THRIFT_SHORT=%25%25~fsI - \ No newline at end of file + diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/test/Multiplex/Client/Properties/AssemblyInfo.cs b/vendor/git.apache.org/thrift.git/lib/csharp/test/Multiplex/Client/Properties/AssemblyInfo.cs index ee234bf..5ee34a1 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/test/Multiplex/Client/Properties/AssemblyInfo.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/test/Multiplex/Client/Properties/AssemblyInfo.cs @@ -27,9 +27,9 @@ using System.Runtime.InteropServices; [assembly: AssemblyTitle("MultiplexClient")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("MultiplexClient")] -[assembly: AssemblyCopyright("Copyright © 2013 The Apache Software Foundation")] +[assembly: AssemblyCompany("The Apache Software Foundation")] +[assembly: AssemblyProduct("Thrift")] +[assembly: AssemblyCopyright("The Apache Software Foundation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] @@ -51,5 +51,5 @@ using System.Runtime.InteropServices; // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyVersion("0.12.0.0")] +[assembly: AssemblyFileVersion("0.12.0.0")] diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/test/Multiplex/Server/MultiplexServer.csproj b/vendor/git.apache.org/thrift.git/lib/csharp/test/Multiplex/Server/MultiplexServer.csproj index dc1d123..57ef76d 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/test/Multiplex/Server/MultiplexServer.csproj +++ b/vendor/git.apache.org/thrift.git/lib/csharp/test/Multiplex/Server/MultiplexServer.csproj @@ -46,7 +46,7 @@ false true 0 - 1.0.0.%2a + 0.12.0.%2a false true @@ -145,4 +145,4 @@ for %25%25I in ("%25THRIFT_FILE%25") do set THRIFT_SHORT=%25%25~fsI - \ No newline at end of file + diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/test/Multiplex/Server/Properties/AssemblyInfo.cs b/vendor/git.apache.org/thrift.git/lib/csharp/test/Multiplex/Server/Properties/AssemblyInfo.cs index 9b9dd6f..65fb4ce 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/test/Multiplex/Server/Properties/AssemblyInfo.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/test/Multiplex/Server/Properties/AssemblyInfo.cs @@ -27,9 +27,9 @@ using System.Runtime.InteropServices; [assembly: AssemblyTitle("MultiplexServer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("MultiplexServer")] -[assembly: AssemblyCopyright("Copyright © 2013 The Apache Software Foundation")] +[assembly: AssemblyCompany("The Apache Software Foundation")] +[assembly: AssemblyProduct("Thrift")] +[assembly: AssemblyCopyright("The Apache Software Foundation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] @@ -51,5 +51,5 @@ using System.Runtime.InteropServices; // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyVersion("0.12.0.0")] +[assembly: AssemblyFileVersion("0.12.0.0")] diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/test/ThriftMVCTest/Controllers/HomeController.cs b/vendor/git.apache.org/thrift.git/lib/csharp/test/ThriftMVCTest/Controllers/HomeController.cs index ab9eada..c9a1ec4 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/test/ThriftMVCTest/Controllers/HomeController.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/test/ThriftMVCTest/Controllers/HomeController.cs @@ -41,9 +41,8 @@ namespace ThriftMVCTest.Controllers SecondService.IAsync asyncService = new SecondService.Client(new TBinaryProtocol(new THttpClient(new Uri(baseUri, "Async.thrift")))); - await asyncService.blahBlahAsync(); var result = await asyncService.secondtestStringAsync("TestString"); - if (result != "TestString") + if (result != "testString(\"TestString\")") { throw new Exception("The wrong result was returned"); } @@ -59,9 +58,8 @@ namespace ThriftMVCTest.Controllers SecondService.ISync service = new SecondService.Client(new TBinaryProtocol(new THttpClient(new Uri(baseUri, "Sync.thrift")))); - service.blahBlah(); var result = service.secondtestString("TestString"); - if (result != "TestString") + if (result != "testString(\"TestString\")") { throw new Exception("The wrong result was returned"); } @@ -69,4 +67,4 @@ namespace ThriftMVCTest.Controllers return RedirectToAction("Index"); } } -} \ No newline at end of file +} diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/test/ThriftMVCTest/Properties/AssemblyInfo.cs b/vendor/git.apache.org/thrift.git/lib/csharp/test/ThriftMVCTest/Properties/AssemblyInfo.cs index 05556ac..186257d 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/test/ThriftMVCTest/Properties/AssemblyInfo.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/test/ThriftMVCTest/Properties/AssemblyInfo.cs @@ -27,7 +27,7 @@ using System.Runtime.InteropServices; [assembly: AssemblyDescription("A web project for testing the thrift ASP.NET features.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("The Apache Software Foundation")] -[assembly: AssemblyProduct("ThriftMVCTest")] +[assembly: AssemblyProduct("Thrift")] [assembly: AssemblyCopyright("The Apache Software Foundation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] @@ -49,5 +49,5 @@ using System.Runtime.InteropServices; // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: -[assembly: AssemblyVersion("1.0.0.1")] -[assembly: AssemblyFileVersion("1.0.0.1")] +[assembly: AssemblyVersion("0.12.0.0")] +[assembly: AssemblyFileVersion("0.12.0.0")] diff --git a/vendor/git.apache.org/thrift.git/lib/csharp/test/ThriftMVCTest/SecondServiceImpl.cs b/vendor/git.apache.org/thrift.git/lib/csharp/test/ThriftMVCTest/SecondServiceImpl.cs index dce0148..fad301a 100644 --- a/vendor/git.apache.org/thrift.git/lib/csharp/test/ThriftMVCTest/SecondServiceImpl.cs +++ b/vendor/git.apache.org/thrift.git/lib/csharp/test/ThriftMVCTest/SecondServiceImpl.cs @@ -24,24 +24,14 @@ namespace ThriftMVCTest { public class SecondServiceImpl : SecondService.IAsync, SecondService.ISync { - public Task blahBlahAsync() - { - return Task.FromResult(0); - } - public Task secondtestStringAsync(string thing) { return Task.FromResult(thing); } - public void blahBlah() - { - - } - public string secondtestString(string thing) { - return thing; + return "testString(\"" + thing + "\")"; } } -} \ No newline at end of file +} diff --git a/vendor/git.apache.org/thrift.git/lib/d/Makefile.am b/vendor/git.apache.org/thrift.git/lib/d/Makefile.am index 5c529ba..2a81218 100644 --- a/vendor/git.apache.org/thrift.git/lib/d/Makefile.am +++ b/vendor/git.apache.org/thrift.git/lib/d/Makefile.am @@ -177,7 +177,7 @@ unittest/.directory: touch $@ unittest/debug/%: src/%.d $(all_targets) unittest/emptymain.d - $(DMD) -gc -of$(subst /,$(DMD_OF_DIRSEP),$@) $(d_test_flags) $^ + $(DMD) -g -of$(subst /,$(DMD_OF_DIRSEP),$@) $(d_test_flags) $^ unittest/release/%: src/%.d $(all_targets) unittest/emptymain.d $(DMD) -O -release -of$(subst /,$(DMD_OF_DIRSEP),$@) $(d_test_flags) $^ diff --git a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/async/socket.d b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/async/socket.d index 6de13d9..a08f51d 100644 --- a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/async/socket.d +++ b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/async/socket.d @@ -18,6 +18,7 @@ */ module thrift.async.socket; +import core.stdc.errno: ECONNRESET; import core.thread : Fiber; import core.time : dur, Duration; import std.array : empty; diff --git a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/base.d b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/base.d index 1c963eb..260e155 100644 --- a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/base.d +++ b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/base.d @@ -50,7 +50,7 @@ class TCompoundOperationException : TException { /// The Thrift version string, used for informative purposes. // Note: This is currently hardcoded, but will likely be filled in by the build // system in future versions. -enum VERSION = "0.10.0"; +enum VERSION = "0.12.0"; /** * Functions used for logging inside Thrift. diff --git a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/internal/ssl_bio.d b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/internal/ssl_bio.d index 796be91..ae85027 100644 --- a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/internal/ssl_bio.d +++ b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/internal/ssl_bio.d @@ -73,7 +73,7 @@ private { void setError(Exception e) nothrow { ERR_put_error(ERR_LIB_D_EXCEPTION, ERR_F_D_EXCEPTION, ERR_R_D_EXCEPTION, ERR_FILE_D_EXCEPTION, ERR_LINE_D_EXCEPTION); - try { GC.addRoot(cast(void*)e); } catch {} + try { GC.addRoot(cast(void*)e); } catch (Throwable) {} ERR_set_error_data(cast(char*)e, ERR_FLAGS_D_EXCEPTION); } diff --git a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/base.d b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/base.d index f97adbe..a23b1c7 100644 --- a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/base.d +++ b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/base.d @@ -118,6 +118,38 @@ protected: TTransportFactory outputTransportFactory_; TProtocolFactory inputProtocolFactory_; TProtocolFactory outputProtocolFactory_; + +public: + + @property TProcessorFactory processorFactory() + { + return processorFactory_; + } + + @property TServerTransport serverTransport() + { + return serverTransport_; + } + + @property TTransportFactory inputTransportFactory() + { + return inputTransportFactory_; + } + + @property TTransportFactory outputTransportFactory() + { + return outputTransportFactory_; + } + + @property TProtocolFactory inputProtocolFactory() + { + return inputProtocolFactory_; + } + + @property TProtocolFactory outputProtocolFactory() + { + return outputProtocolFactory_; + } } /** diff --git a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/nonblocking.d b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/nonblocking.d index 0216799..5860c0c 100644 --- a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/nonblocking.d +++ b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/nonblocking.d @@ -893,14 +893,14 @@ private { callsSinceResize_ = 0; factoryInputTransport_ = - server_.inputTransportFactory_.getTransport(inputTransport_); + server_.inputTransportFactory.getTransport(inputTransport_); factoryOutputTransport_ = - server_.outputTransportFactory_.getTransport(outputTransport_); + server_.outputTransportFactory.getTransport(outputTransport_); inputProtocol_ = - server_.inputProtocolFactory_.getProtocol(factoryInputTransport_); + server_.inputProtocolFactory.getProtocol(factoryInputTransport_); outputProtocol_ = - server_.outputProtocolFactory_.getProtocol(factoryOutputTransport_); + server_.outputProtocolFactory.getProtocol(factoryOutputTransport_); if (server_.eventHandler) { connectionContext_ = @@ -908,7 +908,7 @@ private { } auto info = TConnectionInfo(inputProtocol_, outputProtocol_, socket_); - processor_ = server_.processorFactory_.getProcessor(info); + processor_ = server_.processorFactory.getProcessor(info); } ~this() { diff --git a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/simple.d b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/simple.d index f7183a7..5aba4c1 100644 --- a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/simple.d +++ b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/simple.d @@ -140,7 +140,9 @@ class TSimpleServer : TServer { } } } catch (TTransportException ttx) { - logError("Client died: %s", ttx); + if (ttx.type() != TTransportException.Type.END_OF_FILE) { + logError("Client died unexpectedly: %s", ttx); + } } catch (Exception e) { logError("Uncaught exception: %s", e); } diff --git a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/taskpool.d b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/taskpool.d index b4720a4..670e720 100644 --- a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/taskpool.d +++ b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/taskpool.d @@ -268,7 +268,9 @@ protected: } } } catch (TTransportException ttx) { - logError("Client died: %s", ttx); + if (ttx.type() != TTransportException.Type.END_OF_FILE) { + logError("Client died unexpectedly: %s", ttx); + } } catch (Exception e) { logError("Uncaught exception: %s", e); } diff --git a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/threaded.d b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/threaded.d index 1cde983..300cc84 100644 --- a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/threaded.d +++ b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/threaded.d @@ -173,7 +173,9 @@ private class WorkerThread : Thread { } } } catch (TTransportException ttx) { - logError("Client died: %s", ttx); + if (ttx.type() != TTransportException.Type.END_OF_FILE) { + logError("Client died unexpectedly: %s", ttx); + } } catch (Exception e) { logError("Uncaught exception: %s", e); } diff --git a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/transport/base.d b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/transport/base.d index da165d3..704e16d 100644 --- a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/transport/base.d +++ b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/server/transport/base.d @@ -95,16 +95,7 @@ class TServerTransportException : TException { /// this(Type type, string file = __FILE__, size_t line = __LINE__, Throwable next = null) { - string msg = "TTransportException: "; - switch (type) { - case Type.UNKNOWN: msg ~= "Unknown server transport exception"; break; - case Type.NOT_LISTENING: msg ~= "Server transport not listening"; break; - case Type.ALREADY_LISTENING: msg ~= "Server transport already listening"; break; - case Type.RESOURCE_FAILED: msg ~= "An underlying resource failed"; break; - default: msg ~= "(Invalid exception type)"; break; - } - - this(msg, type, file, line, next); + this(errorMsg(type), type, file, line, next); } /// @@ -129,5 +120,18 @@ class TServerTransportException : TException { protected: Type type_; + +private: + string errorMsg(Type type) { + string msg = "TTransportException: "; + switch (type) { + case Type.UNKNOWN: msg ~= "Unknown server transport exception"; break; + case Type.NOT_LISTENING: msg ~= "Server transport not listening"; break; + case Type.ALREADY_LISTENING: msg ~= "Server transport already listening"; break; + case Type.RESOURCE_FAILED: msg ~= "An underlying resource failed"; break; + default: msg ~= "(Invalid exception type)"; break; + } + return msg; + } } diff --git a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/transport/file.d b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/transport/file.d index 04d34ac..fe88e73 100644 --- a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/transport/file.d +++ b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/transport/file.d @@ -37,7 +37,8 @@ import std.array : empty; import std.algorithm : min, max; import std.concurrency; import std.conv : to; -import std.datetime : AutoStart, dur, Duration, StopWatch; +import std.datetime : dur, Duration; +import std.datetime.stopwatch : AutoStart, StopWatch; import std.exception; import std.stdio : File; import thrift.base; @@ -637,7 +638,7 @@ final class TFileWriterTransport : TBaseTransport { override void close() { if (!isOpen) return; - prioritySend(writerThread_, ShutdownMessage(), thisTid); // FIXME: Should use normal send here. + send(writerThread_, ShutdownMessage(), thisTid); receive((ShutdownMessage msg, Tid tid){}); isOpen_ = false; } @@ -1076,15 +1077,15 @@ unittest { // If any attempt takes more than 500ms, treat that as a fatal failure to // avoid looping over a potentially very slow operation. - enforce(sw.peek().msecs < 1500, - text("close() took ", sw.peek().msecs, "ms.")); + enforce(sw.peek().total!"msecs" < 1500, + text("close() took ", sw.peek().total!"msecs", "ms.")); // Normally, it takes less than 5ms on my dev box. // However, if the box is heavily loaded, some of the test runs can take // longer. Additionally, on a Windows Server 2008 instance running in // a VirtualBox VM, it has been observed that about a quarter of the runs // takes (217 ± 1) ms, for reasons not yet known. - if (sw.peek().msecs > 50) { + if (sw.peek().total!"msecs" > 50) { ++numOver; } diff --git a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/transport/http.d b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/transport/http.d index c7d1f50..0e58dee 100644 --- a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/transport/http.d +++ b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/transport/http.d @@ -330,7 +330,7 @@ protected: "Host: " ~ host_ ~ "\r\n" ~ "Content-Type: application/x-thrift\r\n" ~ "Content-Length: " ~ to!string(dataLength) ~ "\r\n" ~ - "Accept: application/x-thrift\r\n" + "Accept: application/x-thrift\r\n" ~ "User-Agent: Thrift/" ~ VERSION ~ " (D/TClientHttpTransport)\r\n" ~ "\r\n"; } diff --git a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/transport/socket.d b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/transport/socket.d index 38b567a..fcb38da 100644 --- a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/transport/socket.d +++ b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/transport/socket.d @@ -18,6 +18,7 @@ */ module thrift.transport.socket; +import core.stdc.errno: ECONNRESET; import core.thread : Thread; import core.time : dur, Duration; import std.array : empty; @@ -79,8 +80,8 @@ abstract class TSocketBase : TBaseTransport { version (none) assert(written <= buf.length, text("Implementation wrote " ~ "more data than requested to?! (", written, " vs. ", buf.length, ")")); } body { - assert(0, "DMD bug? – Why would contracts work for interfaces, but not " - "for abstract methods? " + assert(0, "DMD bug? – Why would contracts work for interfaces, but not " ~ + "for abstract methods? " ~ "(Error: function […] in and out contracts require function body"); } @@ -256,7 +257,7 @@ class TSocket : TSocketBase { new TCompoundOperationException( text( "All addresses tried failed (", - joiner(map!q{text(a._0, `: "`, a._1.msg, `"`)}(zip(addrs, errors)), ", "), + joiner(map!q{text(a[0], `: "`, a[1].msg, `"`)}(zip(addrs, errors)), ", "), ")." ), errors diff --git a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/transport/ssl.d b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/transport/ssl.d index a78a2ed..f8ce40e 100644 --- a/vendor/git.apache.org/thrift.git/lib/d/src/thrift/transport/ssl.d +++ b/vendor/git.apache.org/thrift.git/lib/d/src/thrift/transport/ssl.d @@ -249,7 +249,13 @@ class TSSLContext { } count_++; - ctx_ = SSL_CTX_new(TLSv1_method()); + static if (OPENSSL_VERSION_NUMBER >= 0x1010000f) { // OPENSSL_VERSION_AT_LEAST(1, 1)) { + ctx_ = SSL_CTX_new(TLS_method()); + } else { + ctx_ = SSL_CTX_new(SSLv23_method()); + SSL_CTX_set_options(ctx_, SSL_OP_NO_SSLv2); + } + SSL_CTX_set_options(ctx_, SSL_OP_NO_SSLv3); // THRIFT-3164 enforce(ctx_, getSSLException("SSL_CTX_new")); SSL_CTX_set_mode(ctx_, SSL_MODE_AUTO_RETRY); } @@ -446,6 +452,7 @@ private: } initialized_ = true; + static if (OPENSSL_VERSION_NUMBER < 0x1010000f) { // OPENSSL_VERSION_BEFORE(1, 1)) { SSL_library_init(); SSL_load_error_strings(); @@ -463,12 +470,14 @@ private: CRYPTO_set_dynlock_create_callback(assumeNothrow(&dynlockCreateCallback)); CRYPTO_set_dynlock_lock_callback(assumeNothrow(&dynlockLockCallback)); CRYPTO_set_dynlock_destroy_callback(assumeNothrow(&dynlockDestroyCallback)); + } } static void cleanupOpenSSL() { if (!initialized_) return; initialized_ = false; + static if (OPENSSL_VERSION_NUMBER < 0x1010000f) { // OPENSSL_VERSION_BEFORE(1, 1)) { CRYPTO_set_locking_callback(null); CRYPTO_set_dynlock_create_callback(null); CRYPTO_set_dynlock_lock_callback(null); @@ -476,6 +485,7 @@ private: CRYPTO_cleanup_all_ex_data(); ERR_free_strings(); ERR_remove_state(0); + } } static extern(C) { diff --git a/vendor/git.apache.org/thrift.git/lib/d/test/Makefile.am b/vendor/git.apache.org/thrift.git/lib/d/test/Makefile.am index c510471..3b6a6f1 100755 --- a/vendor/git.apache.org/thrift.git/lib/d/test/Makefile.am +++ b/vendor/git.apache.org/thrift.git/lib/d/test/Makefile.am @@ -24,8 +24,6 @@ BUILT_SOURCES = trusted-ca-certificate.pem server-certificate.pem # Thrift compiler rules -THRIFT = $(top_builddir)/compiler/cpp/thrift - debug_proto_gen = $(addprefix gen-d/, DebugProtoTest_types.d) $(debug_proto_gen): $(top_srcdir)/test/DebugProtoTest.thrift diff --git a/vendor/git.apache.org/thrift.git/lib/d/test/client_pool_test.d b/vendor/git.apache.org/thrift.git/lib/d/test/client_pool_test.d index 85bcb29..b24c97a 100644 --- a/vendor/git.apache.org/thrift.git/lib/d/test/client_pool_test.d +++ b/vendor/git.apache.org/thrift.git/lib/d/test/client_pool_test.d @@ -18,6 +18,7 @@ */ module client_pool_test; +import core.sync.semaphore : Semaphore; import core.time : Duration, dur; import core.thread : Thread; import std.algorithm; @@ -28,6 +29,7 @@ import std.getopt; import std.range; import std.stdio; import std.typecons; +import std.variant : Variant; import thrift.base; import thrift.async.libevent; import thrift.async.socket; @@ -37,9 +39,12 @@ import thrift.codegen.async_client_pool; import thrift.codegen.client; import thrift.codegen.client_pool; import thrift.codegen.processor; +import thrift.protocol.base; import thrift.protocol.binary; +import thrift.server.base; import thrift.server.simple; import thrift.server.transport.socket; +import thrift.transport.base; import thrift.transport.buffered; import thrift.transport.socket; import thrift.util.cancellation; @@ -108,11 +113,29 @@ private: } } +class ServerPreServeHandler : TServerEventHandler { + this(Semaphore sem) { + sem_ = sem; + } + + override void preServe() { + sem_.notify(); + } + + Variant createContext(TProtocol input, TProtocol output) { return Variant.init; } + void deleteContext(Variant serverContext, TProtocol input, TProtocol output) {} + void preProcess(Variant serverContext, TTransport transport) {} + +private: + Semaphore sem_; +} + class ServerThread : Thread { - this(ExTestHandler handler, TCancellation cancellation) { + this(ExTestHandler handler, ServerPreServeHandler serverHandler, TCancellation cancellation) { super(&run); handler_ = handler; cancellation_ = cancellation; + serverHandler_ = serverHandler; } private: void run() { @@ -123,16 +146,17 @@ private: serverTransport.recvTimeout = dur!"seconds"(3); auto transportFactory = new TBufferedTransportFactory; - auto server = new TSimpleServer( - processor, serverTransport, transportFactory, protocolFactory); + auto server = new TSimpleServer(processor, serverTransport, transportFactory, protocolFactory); + server.eventHandler = serverHandler_; server.serve(cancellation_); } catch (Exception e) { writefln("Server thread on port %s failed: %s", handler_.port, e); } } - TCancellation cancellation_; ExTestHandler handler_; + ServerPreServeHandler serverHandler_; + TCancellation cancellation_; } void main(string[] args) { @@ -145,6 +169,9 @@ void main(string[] args) { immutable ports = cast(immutable)array(map!"cast(ushort)a"(iota(port, port + 6))); + // semaphore that will be incremented whenever each server thread has bound and started listening + Semaphore sem = new Semaphore(0); + version (none) { // Cannot use this due to multiple DMD @@BUG@@s: // 1. »function D main is a nested function and cannot be accessed from array« @@ -174,11 +201,10 @@ version (none) { } // Fire up the server threads. - foreach (h; handlers) (new ServerThread(h, serverCancellation)).start(); + foreach (h; handlers) (new ServerThread(h, new ServerPreServeHandler(sem), serverCancellation)).start(); - // Give the servers some time to get up. This should really be accomplished - // via a barrier here and in the preServe() hook. - Thread.sleep(dur!"msecs"(10)); + // wait until all the handlers signal that they're ready to serve + foreach (h; handlers) (sem.wait(dur!`seconds`(1))); syncClientPoolTest(ports, handlers); asyncClientPoolTest(ports, handlers); @@ -409,8 +435,8 @@ void asyncAggregatorTest(const(ushort)[] ports, ExTestHandler[] handlers) { )(); Thread.sleep(dur!"msecs"(20)); auto resultTuple = partialResult.finishGet(); - enforce(resultTuple._0 == ports[0 .. 2]); - enforce(equal(map!"a.port"(cast(TestServiceException[])resultTuple._1), + enforce(resultTuple[0] == ports[0 .. 2]); + enforce(equal(map!"a.port"(cast(TestServiceException[])resultTuple[1]), ports[3 .. $ - 1])); } } diff --git a/vendor/git.apache.org/thrift.git/lib/d/test/serialization_benchmark.d b/vendor/git.apache.org/thrift.git/lib/d/test/serialization_benchmark.d index 35515c8..40d0480 100644 --- a/vendor/git.apache.org/thrift.git/lib/d/test/serialization_benchmark.d +++ b/vendor/git.apache.org/thrift.git/lib/d/test/serialization_benchmark.d @@ -13,7 +13,7 @@ */ module serialization_benchmark; -import std.datetime : AutoStart, StopWatch; +import std.datetime.stopwatch : AutoStart, StopWatch; import std.math : PI; import std.stdio; import thrift.protocol.binary; @@ -46,7 +46,7 @@ void main() { } sw.stop(); - auto msecs = sw.peek().msecs; + auto msecs = sw.peek().total!"msecs"; writefln("Write: %s ms (%s kHz)", msecs, ITERATIONS / msecs); } @@ -64,7 +64,7 @@ void main() { } sw.stop(); - auto msecs = sw.peek().msecs; + auto msecs = sw.peek().total!"msecs"; writefln(" Read: %s ms (%s kHz)", msecs, ITERATIONS / msecs); } } diff --git a/vendor/git.apache.org/thrift.git/lib/d/test/thrift_test_server.d b/vendor/git.apache.org/thrift.git/lib/d/test/thrift_test_server.d index 71ab917..b582253 100644 --- a/vendor/git.apache.org/thrift.git/lib/d/test/thrift_test_server.d +++ b/vendor/git.apache.org/thrift.git/lib/d/test/thrift_test_server.d @@ -16,8 +16,11 @@ * specific language governing permissions and limitations * under the License. */ + module thrift_test_server; +import core.stdc.errno : errno; +import core.stdc.signal : signal, sigfn_t, SIGINT, SIG_DFL, SIG_ERR; import core.thread : dur, Thread; import std.algorithm; import std.exception : enforce; @@ -40,6 +43,7 @@ import thrift.transport.buffered; import thrift.transport.framed; import thrift.transport.http; import thrift.transport.ssl; +import thrift.util.cancellation; import thrift.util.hashset; import test_utils; @@ -205,14 +209,44 @@ private: bool trace_; } +shared(bool) gShutdown = false; + +nothrow @nogc extern(C) void handleSignal(int sig) { + gShutdown = true; +} + +// Runs a thread that waits for shutdown to be +// signaled and then triggers cancellation, +// causing the server to stop. While we could +// use a signalfd for this purpose, we are instead +// opting for a busy waiting scheme for maximum +// portability since signalfd is a linux thing. + +class ShutdownThread : Thread { + this(TCancellationOrigin cancellation) { + cancellation_ = cancellation; + super(&run); + } + +private: + void run() { + while (!gShutdown) { + Thread.sleep(dur!("msecs")(25)); + } + cancellation_.trigger(); + } + + TCancellationOrigin cancellation_; +} + void main(string[] args) { ushort port = 9090; ServerType serverType; ProtocolType protocolType; size_t numIOThreads = 1; TransportType transportType; - bool ssl; - bool trace; + bool ssl = false; + bool trace = true; size_t taskPoolSize = totalCPUs; getopt(args, "port", &port, "protocol", &protocolType, "server-type", @@ -279,8 +313,26 @@ void main(string[] args) { auto server = createServer(serverType, numIOThreads, taskPoolSize, processor, serverSocket, transportFactory, protocolFactory); + // Set up SIGINT signal handling + sigfn_t oldHandler = signal(SIGINT, &handleSignal); + enforce(oldHandler != SIG_ERR, + "Could not replace the SIGINT signal handler: errno {0}".format(errno())); + + // Set up a server cancellation trigger + auto cancel = new TCancellationOrigin(); + + // Set up a listener for the shutdown condition - this will + // wake up when the signal occurs and trigger cancellation. + auto shutdown = new ShutdownThread(cancel); + shutdown.start(); + + // Serve from this thread; the signal will stop the server + // and control will return here writefln("Starting %s/%s %s ThriftTest server %son port %s...", protocolType, transportType, serverType, ssl ? "(using SSL) ": "", port); - server.serve(); + server.serve(cancel); + shutdown.join(); + signal(SIGINT, SIG_DFL); + writeln("done."); } diff --git a/vendor/git.apache.org/thrift.git/lib/dart/Makefile.am b/vendor/git.apache.org/thrift.git/lib/dart/Makefile.am index a6e4556..ab6ddc0 100644 --- a/vendor/git.apache.org/thrift.git/lib/dart/Makefile.am +++ b/vendor/git.apache.org/thrift.git/lib/dart/Makefile.am @@ -24,5 +24,10 @@ clean-local: $(RM) -r .pub find . -type d -name "packages" | xargs $(RM) -r find . -type f -name ".packages" | xargs $(RM) + find . -type f -name "pubspec.lock" | xargs $(RM) check-local: all + +EXTRA_DIST = \ + .analysis_options + diff --git a/vendor/git.apache.org/thrift.git/lib/dart/lib/src/transport/t_framed_transport.dart b/vendor/git.apache.org/thrift.git/lib/dart/lib/src/transport/t_framed_transport.dart index 80ccf2c..2ef03f7 100644 --- a/vendor/git.apache.org/thrift.git/lib/dart/lib/src/transport/t_framed_transport.dart +++ b/vendor/git.apache.org/thrift.git/lib/dart/lib/src/transport/t_framed_transport.dart @@ -25,7 +25,14 @@ class TFramedTransport extends TBufferedTransport { final TTransport _transport; - final Uint8List headerBytes = new Uint8List(headerByteCount); + final Uint8List _headerBytes = new Uint8List(headerByteCount); + int _receivedHeaderBytes = 0; + + int _bodySize = 0; + Uint8List _body = null; + int _receivedBodyBytes = 0; + + Completer _frameCompleter = null; TFramedTransport(TTransport transport) : _transport = transport { if (transport == null) { @@ -51,33 +58,112 @@ class TFramedTransport extends TBufferedTransport { if (got > 0) return got; } - _readFrame(); + // IMPORTANT: by the time you've got here, + // an entire frame is available for reading return super.read(buffer, offset, length); } void _readFrame() { - _transport.readAll(headerBytes, 0, headerByteCount); - int size = headerBytes.buffer.asByteData().getUint32(0); - - if (size < 0) { - throw new TTransportError( - TTransportErrorType.UNKNOWN, "Read a negative frame size: $size"); + if (_body == null) { + bool gotFullHeader = _readFrameHeader(); + if (!gotFullHeader) { + return; + } } - Uint8List buffer = new Uint8List(size); - _transport.readAll(buffer, 0, size); - _setReadBuffer(buffer); + _readFrameBody(); + } + + bool _readFrameHeader() { + var remainingHeaderBytes = headerByteCount - _receivedHeaderBytes; + + int got = _transport.read(_headerBytes, _receivedHeaderBytes, remainingHeaderBytes); + if (got < 0) { + throw new TTransportError( + TTransportErrorType.UNKNOWN, "Socket closed during frame header read"); + } + + _receivedHeaderBytes += got; + + if (_receivedHeaderBytes == headerByteCount) { + int size = _headerBytes.buffer.asByteData().getUint32(0); + + _receivedHeaderBytes = 0; + + if (size < 0) { + throw new TTransportError( + TTransportErrorType.UNKNOWN, "Read a negative frame size: $size"); + } + + _bodySize = size; + _body = new Uint8List(_bodySize); + _receivedBodyBytes = 0; + + return true; + } else { + _registerForReadableBytes(); + return false; + } + } + + void _readFrameBody() { + var remainingBodyBytes = _bodySize - _receivedBodyBytes; + + int got = _transport.read(_body, _receivedBodyBytes, remainingBodyBytes); + if (got < 0) { + throw new TTransportError( + TTransportErrorType.UNKNOWN, "Socket closed during frame body read"); + } + + _receivedBodyBytes += got; + + if (_receivedBodyBytes == _bodySize) { + var body = _body; + + _bodySize = 0; + _body = null; + _receivedBodyBytes = 0; + + _setReadBuffer(body); + + var completer = _frameCompleter; + _frameCompleter = null; + completer.complete(new Uint8List(0)); + } else { + _registerForReadableBytes(); + } } Future flush() { - Uint8List buffer = consumeWriteBuffer(); - int length = buffer.length; + if (_frameCompleter == null) { + Uint8List buffer = consumeWriteBuffer(); + int length = buffer.length; - headerBytes.buffer.asByteData().setUint32(0, length); - _transport.write(headerBytes, 0, headerByteCount); - _transport.write(buffer, 0, length); + _headerBytes.buffer.asByteData().setUint32(0, length); + _transport.write(_headerBytes, 0, headerByteCount); + _transport.write(buffer, 0, length); - return _transport.flush(); + _frameCompleter = new Completer(); + _registerForReadableBytes(); + } + + return _frameCompleter.future; + } + + void _registerForReadableBytes() { + _transport.flush().then((_) { + _readFrame(); + }).catchError((e) { + var completer = _frameCompleter; + + _receivedHeaderBytes = 0; + _bodySize = 0; + _body = null; + _receivedBodyBytes = 0; + _frameCompleter = null; + + completer.completeError(e); + }); } } diff --git a/vendor/git.apache.org/thrift.git/lib/dart/lib/src/transport/t_socket_transport.dart b/vendor/git.apache.org/thrift.git/lib/dart/lib/src/transport/t_socket_transport.dart index 8dcdfde..c41374a 100644 --- a/vendor/git.apache.org/thrift.git/lib/dart/lib/src/transport/t_socket_transport.dart +++ b/vendor/git.apache.org/thrift.git/lib/dart/lib/src/transport/t_socket_transport.dart @@ -79,7 +79,9 @@ class TClientSocketTransport extends TSocketTransport { var completer = new Completer.sync(); _completers.add(completer); - socket.send(bytes); + if (bytes.lengthInBytes > 0) { + socket.send(bytes); + } return completer.future; } diff --git a/vendor/git.apache.org/thrift.git/lib/dart/pubspec.yaml b/vendor/git.apache.org/thrift.git/lib/dart/pubspec.yaml index 782aa82..365b2cd 100644 --- a/vendor/git.apache.org/thrift.git/lib/dart/pubspec.yaml +++ b/vendor/git.apache.org/thrift.git/lib/dart/pubspec.yaml @@ -16,7 +16,7 @@ # under the License. name: thrift -version: 0.10.0 +version: 0.12.0 description: > A Dart library for Apache Thrift author: Apache Thrift Developers diff --git a/vendor/git.apache.org/thrift.git/lib/dart/test/transport/t_framed_transport_test.dart b/vendor/git.apache.org/thrift.git/lib/dart/test/transport/t_framed_transport_test.dart new file mode 100644 index 0000000..e072e68 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/dart/test/transport/t_framed_transport_test.dart @@ -0,0 +1,175 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +library thrift.test.transport.t_framed_transport_test; + +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data' show Uint8List; + +import 'package:test/test.dart'; +import 'package:thrift/thrift.dart'; + +void main() { + group('TFramedTransport partial reads', () { + final flushAwaitDuration = new Duration(seconds: 10); + + FakeReadOnlySocket socket; + TSocketTransport socketTransport; + TFramedTransport transport; + var messageAvailable; + + setUp(() { + socket = new FakeReadOnlySocket(); + socketTransport = new TClientSocketTransport(socket); + transport = new TFramedTransport(socketTransport); + messageAvailable = false; + }); + + expectNoReadableBytes() { + var readBuffer = new Uint8List(128); + var readBytes = transport.read(readBuffer, 0, readBuffer.lengthInBytes); + expect(readBytes, 0); + expect(messageAvailable, false); + } + + test('Test transport reads messages where header and body are sent separately', () async { + // buffer into which we'll read + var readBuffer = new Uint8List(10); + var readBytes; + + // registers for readable bytes + var flushFuture = transport.flush().timeout(flushAwaitDuration); + flushFuture.then((_) { + messageAvailable = true; + }); + + // write header bytes + socket.messageController.add(new Uint8List.fromList([0x00, 0x00, 0x00, 0x06])); + + // you shouldn't be able to get any bytes from the read, + // because the header has been consumed internally + expectNoReadableBytes(); + + // write first batch of body + socket.messageController.add(new Uint8List.fromList(UTF8.encode("He"))); + + // you shouldn't be able to get any bytes from the read, + // because the frame has been consumed internally + expectNoReadableBytes(); + + // write second batch of body + socket.messageController.add(new Uint8List.fromList(UTF8.encode("llo!"))); + + // have to wait for the flush to complete, + // because it's only then that the frame is available for reading + await flushFuture; + expect(messageAvailable, true); + + // at this point the frame is complete, so we expect the read to complete + readBytes = transport.read(readBuffer, 0, readBuffer.lengthInBytes); + expect(readBytes, 6); + expect(readBuffer.sublist(0, 6), UTF8.encode("Hello!")); + }); + + test('Test transport reads messages where header is sent in pieces ' + 'and body is also sent in pieces', () async { + // buffer into which we'll read + var readBuffer = new Uint8List(10); + var readBytes; + + // registers for readable bytes + var flushFuture = transport.flush().timeout(flushAwaitDuration); + flushFuture.then((_) { + messageAvailable = true; + }); + + // write first part of header bytes + socket.messageController.add(new Uint8List.fromList([0x00, 0x00])); + + // you shouldn't be able to get any bytes from the read + expectNoReadableBytes(); + + // write second part of header bytes + socket.messageController.add(new Uint8List.fromList([0x00, 0x03])); + + // you shouldn't be able to get any bytes from the read again + // because only the header was read, and there's no frame body + readBytes = expectNoReadableBytes(); + + // write first batch of body + socket.messageController.add(new Uint8List.fromList(UTF8.encode("H"))); + + // you shouldn't be able to get any bytes from the read, + // because the frame has been consumed internally + expectNoReadableBytes(); + + // write second batch of body + socket.messageController.add(new Uint8List.fromList(UTF8.encode("i!"))); + + // have to wait for the flush to complete, + // because it's only then that the frame is available for reading + await flushFuture; + expect(messageAvailable, true); + + // at this point the frame is complete, so we expect the read to complete + readBytes = transport.read(readBuffer, 0, readBuffer.lengthInBytes); + expect(readBytes, 3); + expect(readBuffer.sublist(0, 3), UTF8.encode("Hi!")); + }); + }); +} + + + +class FakeReadOnlySocket extends TSocket { + + StreamController messageController = new StreamController(sync: true); + StreamController errorController = new StreamController(); + StreamController stateController = new StreamController(); + + @override + Future close() { + // noop + } + + @override + bool get isClosed => false; + + @override + bool get isOpen => true; + + @override + Stream get onError => errorController.stream; + + @override + Stream get onMessage => messageController.stream; + + @override + Stream get onState => stateController.stream; + + @override + Future open() { + // noop + } + + @override + void send(Uint8List data) { + // noop + } +} + diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/DelphiThrift.groupproj b/vendor/git.apache.org/thrift.git/lib/delphi/DelphiThrift.groupproj new file mode 100644 index 0000000..a172e49 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/delphi/DelphiThrift.groupproj @@ -0,0 +1,156 @@ + + + {6BD327A5-7688-4263-B6A8-B15207CF4EC5} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Default.Personality.12 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Exception.pas b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Exception.pas new file mode 100644 index 0000000..5d15c36 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Exception.pas @@ -0,0 +1,62 @@ +(* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + *) + +{$SCOPEDENUMS ON} + +unit Thrift.Exception; + +interface + +uses + Classes, SysUtils; + +type + // base class for all Thrift exceptions + TException = class( SysUtils.Exception) + public + function Message : string; // hide inherited property: allow read, but prevent accidental writes + procedure UpdateMessageProperty; // update inherited message property with toString() + end; + + + + +implementation + +{ TException } + +function TException.Message; +// allow read (exception summary), but prevent accidental writes +// read will return the exception summary +begin + result := Self.ToString; +end; + +procedure TException.UpdateMessageProperty; +// Update the inherited Message property to better conform to standard behaviour. +// Nice benefit: The IDE is now able to show the exception message again. +begin + inherited Message := Self.ToString; // produces a summary text +end; + + + + +end. + diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Processor.Multiplex.pas b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Processor.Multiplex.pas index 756daa1..8cf23db 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Processor.Multiplex.pas +++ b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Processor.Multiplex.pas @@ -53,11 +53,11 @@ uses type IMultiplexedProcessor = interface( IProcessor) - ['{810FF32D-22A2-4D58-B129-B0590703ECEC}'] + ['{807F9D19-6CF4-4789-840E-93E87A12EB63}'] // Register a service with this TMultiplexedProcessor. This allows us // to broker requests to individual services by using the service name // to select them at request time. - procedure RegisterProcessor( const serviceName : String; const processor : IProcessor); + procedure RegisterProcessor( const serviceName : String; const processor : IProcessor; const asDefault : Boolean = FALSE); end; @@ -68,16 +68,17 @@ type // the standard format, without the service name prepended to TMessage.name. TStoredMessageProtocol = class( TProtocolDecorator) private - FMessageBegin : IMessage; + FMessageBegin : TThriftMessage; public - constructor Create( const protocol : IProtocol; const aMsgBegin : IMessage); - function ReadMessageBegin: IMessage; override; + constructor Create( const protocol : IProtocol; const aMsgBegin : TThriftMessage); + function ReadMessageBegin: TThriftMessage; override; end; private FServiceProcessorMap : TDictionary; + FDefaultProcessor : IProcessor; - procedure Error( const oprot : IProtocol; const msg : IMessage; + procedure Error( const oprot : IProtocol; const msg : TThriftMessage; extype : TApplicationExceptionSpecializedClass; const etxt : string); public @@ -87,7 +88,7 @@ type // Register a service with this TMultiplexedProcessorImpl. This allows us // to broker requests to individual services by using the service name // to select them at request time. - procedure RegisterProcessor( const serviceName : String; const processor : IProcessor); + procedure RegisterProcessor( const serviceName : String; const processor : IProcessor; const asDefault : Boolean = FALSE); { This implementation of process performs the following steps: - Read the beginning of the message. @@ -105,14 +106,14 @@ type implementation -constructor TMultiplexedProcessorImpl.TStoredMessageProtocol.Create( const protocol : IProtocol; const aMsgBegin : IMessage); +constructor TMultiplexedProcessorImpl.TStoredMessageProtocol.Create( const protocol : IProtocol; const aMsgBegin : TThriftMessage); begin inherited Create( protocol); FMessageBegin := aMsgBegin; end; -function TMultiplexedProcessorImpl.TStoredMessageProtocol.ReadMessageBegin: IMessage; +function TMultiplexedProcessorImpl.TStoredMessageProtocol.ReadMessageBegin: TThriftMessage; begin result := FMessageBegin; end; @@ -135,21 +136,27 @@ begin end; -procedure TMultiplexedProcessorImpl.RegisterProcessor( const serviceName : String; const processor : IProcessor); +procedure TMultiplexedProcessorImpl.RegisterProcessor( const serviceName : String; const processor : IProcessor; const asDefault : Boolean); begin FServiceProcessorMap.Add( serviceName, processor); + + if asDefault then begin + if FDefaultProcessor = nil + then FDefaultProcessor := processor + else raise TApplicationExceptionInternalError.Create('Only one default service allowed'); + end; end; -procedure TMultiplexedProcessorImpl.Error( const oprot : IProtocol; const msg : IMessage; +procedure TMultiplexedProcessorImpl.Error( const oprot : IProtocol; const msg : TThriftMessage; extype : TApplicationExceptionSpecializedClass; const etxt : string); var appex : TApplicationException; - newMsg : IMessage; + newMsg : TThriftMessage; begin appex := extype.Create(etxt); try - newMsg := TMessageImpl.Create( msg.Name, TMessageType.Exception, msg.SeqID); + Init( newMsg, msg.Name, TMessageType.Exception, msg.SeqID); oprot.WriteMessageBegin(newMsg); appex.Write(oprot); @@ -163,7 +170,7 @@ end; function TMultiplexedProcessorImpl.Process(const iprot, oprot : IProtocol; const events : IProcessorEvents = nil): Boolean; -var msg, newMsg : IMessage; +var msg, newMsg : TThriftMessage; idx : Integer; sService : string; processor : IProcessor; @@ -184,28 +191,37 @@ begin end; // Extract the service name + // use FDefaultProcessor as fallback if there is no separator idx := Pos( TMultiplexedProtocol.SEPARATOR, msg.Name); - if idx < 1 then begin + if idx > 0 then begin + + // Create a new TMessage, something that can be consumed by any TProtocol + sService := Copy( msg.Name, 1, idx-1); + if not FServiceProcessorMap.TryGetValue( sService, processor) + then begin + Error( oprot, msg, + TApplicationExceptionInternalError, + Format(ERROR_UNKNOWN_SERVICE,[sService])); + Exit( FALSE); + end; + + // Create a new TMessage, removing the service name + Inc( idx, Length(TMultiplexedProtocol.SEPARATOR)); + Init( newMsg, Copy( msg.Name, idx, MAXINT), msg.Type_, msg.SeqID); + + end + else if FDefaultProcessor <> nil then begin + processor := FDefaultProcessor; + newMsg := msg; // no need to change + + end + else begin Error( oprot, msg, TApplicationExceptionInvalidProtocol, Format(ERROR_INCOMPATIBLE_PROT,[msg.Name])); Exit( FALSE); end; - // Create a new TMessage, something that can be consumed by any TProtocol - sService := Copy( msg.Name, 1, idx-1); - if not FServiceProcessorMap.TryGetValue( sService, processor) - then begin - Error( oprot, msg, - TApplicationExceptionInternalError, - Format(ERROR_UNKNOWN_SERVICE,[sService])); - Exit( FALSE); - end; - - // Create a new TMessage, removing the service name - Inc( idx, Length(TMultiplexedProtocol.SEPARATOR)); - newMsg := TMessageImpl.Create( Copy( msg.Name, idx, MAXINT), msg.Type_, msg.SeqID); - // Dispatch processing to the stored processor protocol := TStoredMessageProtocol.Create( iprot, newMsg); result := processor.process( protocol, oprot, events); @@ -213,4 +229,3 @@ end; end. - diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Protocol.Compact.pas b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Protocol.Compact.pas index e9944d6..1c1b3da 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Protocol.Compact.pas +++ b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Protocol.Compact.pas @@ -123,7 +123,7 @@ type // If we encounter a boolean field begin, save the TField here so it can // have the value incorporated. - private booleanField_ : IField; + private booleanField_ : TThriftField; // If we Read a field header, and it's a boolean field, save the boolean // value here so that ReadBool can use it. @@ -148,21 +148,21 @@ type private // The workhorse of WriteFieldBegin. It has the option of doing a 'type override' // of the type header. This is used specifically in the boolean field case. - procedure WriteFieldBeginInternal( const field : IField; typeOverride : Byte); + procedure WriteFieldBeginInternal( const field : TThriftField; typeOverride : Byte); public - procedure WriteMessageBegin( const msg: IMessage); override; + procedure WriteMessageBegin( const msg: TThriftMessage); override; procedure WriteMessageEnd; override; - procedure WriteStructBegin( const struc: IStruct); override; + procedure WriteStructBegin( const struc: TThriftStruct); override; procedure WriteStructEnd; override; - procedure WriteFieldBegin( const field: IField); override; + procedure WriteFieldBegin( const field: TThriftField); override; procedure WriteFieldEnd; override; procedure WriteFieldStop; override; - procedure WriteMapBegin( const map: IMap); override; + procedure WriteMapBegin( const map: TThriftMap); override; procedure WriteMapEnd; override; - procedure WriteListBegin( const list: IList); override; + procedure WriteListBegin( const list: TThriftList); override; procedure WriteListEnd(); override; - procedure WriteSetBegin( const set_: ISet ); override; + procedure WriteSetBegin( const set_: TThriftSet ); override; procedure WriteSetEnd(); override; procedure WriteBool( b: Boolean); override; procedure WriteByte( b: ShortInt); override; @@ -194,17 +194,17 @@ type class procedure fixedLongToBytes( const n : Int64; var buf : TBytes); public - function ReadMessageBegin: IMessage; override; + function ReadMessageBegin: TThriftMessage; override; procedure ReadMessageEnd(); override; - function ReadStructBegin: IStruct; override; + function ReadStructBegin: TThriftStruct; override; procedure ReadStructEnd; override; - function ReadFieldBegin: IField; override; + function ReadFieldBegin: TThriftField; override; procedure ReadFieldEnd(); override; - function ReadMapBegin: IMap; override; + function ReadMapBegin: TThriftMap; override; procedure ReadMapEnd(); override; - function ReadListBegin: IList; override; + function ReadListBegin: TThriftList; override; procedure ReadListEnd(); override; - function ReadSetBegin: ISet; override; + function ReadSetBegin: TThriftSet; override; procedure ReadSetEnd(); override; function ReadBool: Boolean; override; function ReadByte: ShortInt; override; @@ -273,7 +273,7 @@ begin lastFieldId_ := 0; lastField_ := TStack.Create; - booleanField_ := nil; + Init( booleanField_, '', TType.Stop, 0); boolValue_ := unused; end; @@ -293,7 +293,7 @@ procedure TCompactProtocolImpl.Reset; begin lastField_.Clear(); lastFieldId_ := 0; - booleanField_ := nil; + Init( booleanField_, '', TType.Stop, 0); boolValue_ := unused; end; @@ -301,11 +301,8 @@ end; // Writes a byte without any possibility of all that field header nonsense. // Used internally by other writing methods that know they need to Write a byte. procedure TCompactProtocolImpl.WriteByteDirect( const b : Byte); -var data : TBytes; begin - SetLength( data, 1); - data[0] := b; - Transport.Write( data); + Transport.Write( @b, SizeOf(b)); end; @@ -344,7 +341,7 @@ end; // Write a message header to the wire. Compact Protocol messages contain the // protocol version so we can migrate forwards in the future if need be. -procedure TCompactProtocolImpl.WriteMessageBegin( const msg: IMessage); +procedure TCompactProtocolImpl.WriteMessageBegin( const msg: TThriftMessage); var versionAndType : Byte; begin Reset; @@ -362,7 +359,7 @@ end; // Write a struct begin. This doesn't actually put anything on the wire. We use it as an // opportunity to put special placeholder markers on the field stack so we can get the // field id deltas correct. -procedure TCompactProtocolImpl.WriteStructBegin( const struc: IStruct); +procedure TCompactProtocolImpl.WriteStructBegin( const struc: TThriftStruct); begin lastField_.Push(lastFieldId_); lastFieldId_ := 0; @@ -380,7 +377,7 @@ end; // Write a field header containing the field id and field type. If the difference between the // current field id and the last one is small (< 15), then the field id will be encoded in // the 4 MSB as a delta. Otherwise, the field id will follow the type header as a zigzag varint. -procedure TCompactProtocolImpl.WriteFieldBegin( const field: IField); +procedure TCompactProtocolImpl.WriteFieldBegin( const field: TThriftField); begin case field.Type_ of TType.Bool_ : booleanField_ := field; // we want to possibly include the value, so we'll wait. @@ -392,7 +389,7 @@ end; // The workhorse of WriteFieldBegin. It has the option of doing a 'type override' // of the type header. This is used specifically in the boolean field case. -procedure TCompactProtocolImpl.WriteFieldBeginInternal( const field : IField; typeOverride : Byte); +procedure TCompactProtocolImpl.WriteFieldBeginInternal( const field : TThriftField; typeOverride : Byte); var typeToWrite : Byte; begin // if there's a type override, use that. @@ -425,7 +422,7 @@ end; // Write a map header. If the map is empty, omit the key and value type // headers, as we don't need any additional information to skip it. -procedure TCompactProtocolImpl.WriteMapBegin( const map: IMap); +procedure TCompactProtocolImpl.WriteMapBegin( const map: TThriftMap); var key, val : Byte; begin if (map.Count = 0) @@ -440,14 +437,14 @@ end; // Write a list header. -procedure TCompactProtocolImpl.WriteListBegin( const list: IList); +procedure TCompactProtocolImpl.WriteListBegin( const list: TThriftList); begin WriteCollectionBegin( list.ElementType, list.Count); end; // Write a set header. -procedure TCompactProtocolImpl.WriteSetBegin( const set_: ISet ); +procedure TCompactProtocolImpl.WriteSetBegin( const set_: TThriftSet ); begin WriteCollectionBegin( set_.ElementType, set_.Count); end; @@ -464,10 +461,10 @@ begin then bt := Types.BOOLEAN_TRUE else bt := Types.BOOLEAN_FALSE; - if booleanField_ <> nil then begin + if booleanField_.Type_ = TType.Bool_ then begin // we haven't written the field header yet WriteFieldBeginInternal( booleanField_, Byte(bt)); - booleanField_ := nil; + booleanField_.Type_ := TType.Stop; end else begin // we're not part of a field, so just Write the value. @@ -642,7 +639,7 @@ end; // Read a message header. -function TCompactProtocolImpl.ReadMessageBegin : IMessage; +function TCompactProtocolImpl.ReadMessageBegin : TThriftMessage; var protocolId, versionAndType, version, type_ : Byte; seqid : Integer; msgNm : String; @@ -663,17 +660,17 @@ begin type_ := Byte( (versionAndType shr TYPE_SHIFT_AMOUNT) and TYPE_BITS); seqid := Integer( ReadVarint32); msgNm := ReadString; - result := TMessageImpl.Create( msgNm, TMessageType(type_), seqid); + Init( result, msgNm, TMessageType(type_), seqid); end; // Read a struct begin. There's nothing on the wire for this, but it is our // opportunity to push a new struct begin marker onto the field stack. -function TCompactProtocolImpl.ReadStructBegin: IStruct; +function TCompactProtocolImpl.ReadStructBegin: TThriftStruct; begin lastField_.Push( lastFieldId_); lastFieldId_ := 0; - result := TStructImpl.Create(''); + Init( result); end; @@ -687,7 +684,7 @@ end; // Read a field header off the wire. -function TCompactProtocolImpl.ReadFieldBegin: IField; +function TCompactProtocolImpl.ReadFieldBegin: TThriftField; var type_ : Byte; fieldId, modifier : ShortInt; begin @@ -695,7 +692,7 @@ begin // if it's a stop, then we can return immediately, as the struct is over. if type_ = Byte(Types.STOP) then begin - result := TFieldImpl.Create( '', TType.Stop, 0); + Init( result, '', TType.Stop, 0); Exit; end; @@ -705,7 +702,7 @@ begin then fieldId := ReadI16 // not a delta. look ahead for the zigzag varint field id. else fieldId := ShortInt( lastFieldId_ + modifier); // add the delta to the last Read field id. - result := TFieldImpl.Create( '', getTType(Byte(type_ and $0F)), fieldId); + Init( result, '', getTType(Byte(type_ and $0F)), fieldId); // if this happens to be a boolean field, the value is encoded in the type // save the boolean value in a special instance variable. @@ -723,7 +720,7 @@ end; // Read a map header off the wire. If the size is zero, skip Reading the key // and value type. This means that 0-length maps will yield TMaps without the // "correct" types. -function TCompactProtocolImpl.ReadMapBegin: IMap; +function TCompactProtocolImpl.ReadMapBegin: TThriftMap; var size : Integer; keyAndValueType : Byte; key, val : TType; @@ -735,7 +732,7 @@ begin key := getTType( Byte( keyAndValueType shr 4)); val := getTType( Byte( keyAndValueType and $F)); - result := TMapImpl.Create( key, val, size); + Init( result, key, val, size); ASSERT( (result.KeyType = key) and (result.ValueType = val)); end; @@ -744,7 +741,7 @@ end; // be packed into the element type header. If it's a longer list, the 4 MSB // of the element type header will be $F, and a varint will follow with the // true size. -function TCompactProtocolImpl.ReadListBegin: IList; +function TCompactProtocolImpl.ReadListBegin: TThriftList; var size_and_type : Byte; size : Integer; type_ : TType; @@ -756,7 +753,7 @@ begin then size := Integer( ReadVarint32); type_ := getTType( size_and_type); - result := TListImpl.Create( type_, size); + Init( result, type_, size); end; @@ -764,7 +761,7 @@ end; // be packed into the element type header. If it's a longer set, the 4 MSB // of the element type header will be $F, and a varint will follow with the // true size. -function TCompactProtocolImpl.ReadSetBegin: ISet; +function TCompactProtocolImpl.ReadSetBegin: TThriftSet; var size_and_type : Byte; size : Integer; type_ : TType; @@ -776,7 +773,7 @@ begin then size := Integer( ReadVarint32); type_ := getTType( size_and_type); - result := TSetImpl.Create( type_, size); + Init( result, type_, size); end; @@ -797,11 +794,8 @@ end; // Read a single byte off the wire. Nothing interesting here. function TCompactProtocolImpl.ReadByte: ShortInt; -var data : TBytes; begin - SetLength( data, 1); - Transport.ReadAll( data, 0, 1); - result := ShortInt(data[0]); + Transport.ReadAll( @result, SizeOf(result), 0, 1); end; @@ -1094,11 +1088,29 @@ end; {$ENDIF} +{$IFDEF Debug} +procedure UnitTest; +var w : WORD; +const FPU_CW_DENORMALIZED = $0002; +begin + w := Get8087CW; + try + Set8087CW( w or FPU_CW_DENORMALIZED); + + TestDoubleToInt64Bits; + TestZigZag; + TestLongBytes; + + finally + Set8087CW( w); + end; +end; +{$ENDIF} + + initialization {$IFDEF Debug} - TestDoubleToInt64Bits; - TestZigZag; - TestLongBytes; + UnitTest; {$ENDIF} end. diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Protocol.JSON.pas b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Protocol.JSON.pas index 71ee7ae..30600aa 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Protocol.JSON.pas +++ b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Protocol.JSON.pas @@ -103,7 +103,7 @@ type private FHasData : Boolean; - FData : TBytes; + FData : Byte; public // Return and consume the next byte to be Read, either taking it from the @@ -169,18 +169,18 @@ type public // IProtocol - procedure WriteMessageBegin( const aMsg : IMessage); override; + procedure WriteMessageBegin( const aMsg : TThriftMessage); override; procedure WriteMessageEnd; override; - procedure WriteStructBegin( const struc: IStruct); override; + procedure WriteStructBegin( const struc: TThriftStruct); override; procedure WriteStructEnd; override; - procedure WriteFieldBegin( const field: IField); override; + procedure WriteFieldBegin( const field: TThriftField); override; procedure WriteFieldEnd; override; procedure WriteFieldStop; override; - procedure WriteMapBegin( const map: IMap); override; + procedure WriteMapBegin( const map: TThriftMap); override; procedure WriteMapEnd; override; - procedure WriteListBegin( const list: IList); override; + procedure WriteListBegin( const list: TThriftList); override; procedure WriteListEnd(); override; - procedure WriteSetBegin( const set_: ISet ); override; + procedure WriteSetBegin( const set_: TThriftSet ); override; procedure WriteSetEnd(); override; procedure WriteBool( b: Boolean); override; procedure WriteByte( b: ShortInt); override; @@ -191,17 +191,17 @@ type procedure WriteString( const s: string ); override; procedure WriteBinary( const b: TBytes); override; // - function ReadMessageBegin: IMessage; override; + function ReadMessageBegin: TThriftMessage; override; procedure ReadMessageEnd(); override; - function ReadStructBegin: IStruct; override; + function ReadStructBegin: TThriftStruct; override; procedure ReadStructEnd; override; - function ReadFieldBegin: IField; override; + function ReadFieldBegin: TThriftField; override; procedure ReadFieldEnd(); override; - function ReadMapBegin: IMap; override; + function ReadMapBegin: TThriftMap; override; procedure ReadMapEnd(); override; - function ReadListBegin: IList; override; + function ReadListBegin: TThriftList; override; procedure ReadListEnd(); override; - function ReadSetBegin: ISet; override; + function ReadSetBegin: TThriftSet; override; procedure ReadSetEnd(); override; function ReadBool: Boolean; override; function ReadByte: ShortInt; override; @@ -437,21 +437,19 @@ begin if FHasData then FHasData := FALSE else begin - SetLength( FData, 1); - IJSONProtocol(FProto).Transport.ReadAll( FData, 0, 1); + IJSONProtocol(FProto).Transport.ReadAll( @FData, SizeOf(FData), 0, 1); end; - result := FData[0]; + result := FData; end; function TJSONProtocolImpl.TLookaheadReader.Peek : Byte; begin if not FHasData then begin - SetLength( FData, 1); - IJSONProtocol(FProto).Transport.ReadAll( FData, 0, 1); + IJSONProtocol(FProto).Transport.ReadAll( @FData, SizeOf(FData), 0, 1); FHasData := TRUE; end; - result := FData[0]; + result := FData; end; @@ -681,7 +679,7 @@ begin end; -procedure TJSONProtocolImpl.WriteMessageBegin( const aMsg : IMessage); +procedure TJSONProtocolImpl.WriteMessageBegin( const aMsg : TThriftMessage); begin ResetContextStack; // THRIFT-1473 @@ -700,7 +698,7 @@ begin end; -procedure TJSONProtocolImpl.WriteStructBegin( const struc: IStruct); +procedure TJSONProtocolImpl.WriteStructBegin( const struc: TThriftStruct); begin WriteJSONObjectStart; end; @@ -712,7 +710,7 @@ begin end; -procedure TJSONProtocolImpl.WriteFieldBegin( const field : IField); +procedure TJSONProtocolImpl.WriteFieldBegin( const field : TThriftField); begin WriteJSONInteger(field.ID); WriteJSONObjectStart; @@ -731,7 +729,7 @@ begin // nothing to do end; -procedure TJSONProtocolImpl.WriteMapBegin( const map: IMap); +procedure TJSONProtocolImpl.WriteMapBegin( const map: TThriftMap); begin WriteJSONArrayStart; WriteJSONString( GetTypeNameForTypeID( map.KeyType)); @@ -748,7 +746,7 @@ begin end; -procedure TJSONProtocolImpl.WriteListBegin( const list: IList); +procedure TJSONProtocolImpl.WriteListBegin( const list: TThriftList); begin WriteJSONArrayStart; WriteJSONString( GetTypeNameForTypeID( list.ElementType)); @@ -762,7 +760,7 @@ begin end; -procedure TJSONProtocolImpl.WriteSetBegin( const set_: ISet); +procedure TJSONProtocolImpl.WriteSetBegin( const set_: TThriftSet); begin WriteJSONArrayStart; WriteJSONString( GetTypeNameForTypeID( set_.ElementType)); @@ -1051,11 +1049,11 @@ begin end; -function TJSONProtocolImpl.ReadMessageBegin: IMessage; +function TJSONProtocolImpl.ReadMessageBegin: TThriftMessage; begin ResetContextStack; // THRIFT-1473 - result := TMessageImpl.Create; + Init( result); ReadJSONArrayStart; if ReadJSONInteger <> VERSION @@ -1073,10 +1071,10 @@ begin end; -function TJSONProtocolImpl.ReadStructBegin : IStruct ; +function TJSONProtocolImpl.ReadStructBegin : TThriftStruct ; begin ReadJSONObjectStart; - result := TStructImpl.Create(''); + Init( result); end; @@ -1086,11 +1084,11 @@ begin end; -function TJSONProtocolImpl.ReadFieldBegin : IField; +function TJSONProtocolImpl.ReadFieldBegin : TThriftField; var ch : Byte; str : string; begin - result := TFieldImpl.Create; + Init( result); ch := FReader.Peek; if ch = RBRACE[0] then result.Type_ := TType.Stop @@ -1110,10 +1108,10 @@ begin end; -function TJSONProtocolImpl.ReadMapBegin : IMap; +function TJSONProtocolImpl.ReadMapBegin : TThriftMap; var str : string; begin - result := TMapImpl.Create; + Init( result); ReadJSONArrayStart; str := SysUtils.TEncoding.UTF8.GetString( ReadJSONString(FALSE)); @@ -1134,10 +1132,10 @@ begin end; -function TJSONProtocolImpl.ReadListBegin : IList; +function TJSONProtocolImpl.ReadListBegin : TThriftList; var str : string; begin - result := TListImpl.Create; + Init( result); ReadJSONArrayStart; str := SysUtils.TEncoding.UTF8.GetString( ReadJSONString(FALSE)); @@ -1152,10 +1150,10 @@ begin end; -function TJSONProtocolImpl.ReadSetBegin : ISet; +function TJSONProtocolImpl.ReadSetBegin : TThriftSet; var str : string; begin - result := TSetImpl.Create; + Init( result); ReadJSONArrayStart; str := SysUtils.TEncoding.UTF8.GetString( ReadJSONString(FALSE)); diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Protocol.Multiplex.pas b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Protocol.Multiplex.pas index 18b39b5..93a3838 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Protocol.Multiplex.pas +++ b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Protocol.Multiplex.pas @@ -71,7 +71,7 @@ type { Prepends the service name to the function name, separated by SEPARATOR. Args: The original message. } - procedure WriteMessageBegin( const msg: IMessage); override; + procedure WriteMessageBegin( const msg: TThriftMessage); override; end; @@ -86,14 +86,14 @@ begin end; -procedure TMultiplexedProtocol.WriteMessageBegin( const msg: IMessage); +procedure TMultiplexedProtocol.WriteMessageBegin( const msg: TThriftMessage); // Prepends the service name to the function name, separated by TMultiplexedProtocol.SEPARATOR. -var newMsg : IMessage; +var newMsg : TThriftMessage; begin case msg.Type_ of TMessageType.Call, TMessageType.Oneway : begin - newMsg := TMessageImpl.Create( FServiceName + SEPARATOR + msg.Name, msg.Type_, msg.SeqID); + Init( newMsg, FServiceName + SEPARATOR + msg.Name, msg.Type_, msg.SeqID); inherited WriteMessageBegin( newMsg); end; diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Protocol.pas b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Protocol.pas index 7ff2eae..36509ca 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Protocol.pas +++ b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Protocol.pas @@ -27,6 +27,7 @@ uses Classes, SysUtils, Contnrs, + Thrift.Exception, Thrift.Stream, Thrift.Collections, Thrift.Transport; @@ -70,7 +71,40 @@ const type IProtocol = interface; - IStruct = interface; + + TThriftMessage = record + Name: string; + Type_: TMessageType; + SeqID: Integer; + end; + + TThriftStruct = record + Name: string; + end; + + TThriftField = record + Name: string; + Type_: TType; + Id: SmallInt; + end; + + TThriftList = record + ElementType: TType; + Count: Integer; + end; + + TThriftMap = record + KeyType: TType; + ValueType: TType; + Count: Integer; + end; + + TThriftSet = record + ElementType: TType; + Count: Integer; + end; + + IProtocolFactory = interface ['{7CD64A10-4E9F-4E99-93BF-708A31F4A67B}'] @@ -83,7 +117,7 @@ type function Append(const Value: IThriftContainer): TStringBuilder; overload; end; - TProtocolException = class( Exception ) + TProtocolException = class( TException) public const // TODO(jensg): change into enum UNKNOWN = 0; @@ -117,146 +151,6 @@ type TProtocolExceptionNotImplemented = class (TProtocolExceptionSpecialized); TProtocolExceptionDepthLimit = class (TProtocolExceptionSpecialized); - IMap = interface - ['{30531D97-7E06-4233-B800-C3F53CCD23E7}'] - function GetKeyType: TType; - procedure SetKeyType( Value: TType); - function GetValueType: TType; - procedure SetValueType( Value: TType); - function GetCount: Integer; - procedure SetCount( Value: Integer); - property KeyType: TType read GetKeyType write SetKeyType; - property ValueType: TType read GetValueType write SetValueType; - property Count: Integer read GetCount write SetCount; - end; - - TMapImpl = class( TInterfacedObject, IMap) - private - FValueType: TType; - FKeyType: TType; - FCount: Integer; - protected - function GetKeyType: TType; - procedure SetKeyType( Value: TType); - function GetValueType: TType; - procedure SetValueType( Value: TType); - function GetCount: Integer; - procedure SetCount( Value: Integer); - public - constructor Create( AKeyType, AValueType: TType; ACount: Integer); overload; - constructor Create; overload; - end; - - IList = interface - ['{6763E1EA-A934-4472-904F-0083980B9B87}'] - function GetElementType: TType; - procedure SetElementType( Value: TType); - function GetCount: Integer; - procedure SetCount( Value: Integer); - property ElementType: TType read GetElementType write SetElementType; - property Count: Integer read GetCount write SetCount; - end; - - TListImpl = class( TInterfacedObject, IList) - private - FElementType: TType; - FCount : Integer; - protected - function GetElementType: TType; - procedure SetElementType( Value: TType); - function GetCount: Integer; - procedure SetCount( Value: Integer); - public - constructor Create( AElementType: TType; ACount: Integer); overload; - constructor Create; overload; - end; - - ISet = interface - ['{A8671700-7514-4C1E-8A05-62786872005F}'] - function GetElementType: TType; - procedure SetElementType( Value: TType); - function GetCount: Integer; - procedure SetCount( Value: Integer); - property ElementType: TType read GetElementType write SetElementType; - property Count: Integer read GetCount write SetCount; - end; - - TSetImpl = class( TInterfacedObject, ISet) - private - FCount: Integer; - FElementType: TType; - protected - function GetElementType: TType; - procedure SetElementType( Value: TType); - function GetCount: Integer; - procedure SetCount( Value: Integer); - public - constructor Create( AElementType: TType; ACount: Integer); overload; - constructor Create; overload; - end; - - IMessage = interface - ['{9E368B4A-B1FA-43E7-8CF5-56C66D256CA7}'] - function GetName: string; - procedure SetName( const Value: string); - function GetType: TMessageType; - procedure SetType( Value: TMessageType); - function GetSeqID: Integer; - procedure SetSeqID( Value: Integer); - property Name: string read GetName write SetName; - property Type_: TMessageType read GetType write SetType; - property SeqID: Integer read GetSeqID write SetSeqID; - end; - - TMessageImpl = class( TInterfacedObject, IMessage ) - private - FName: string; - FMessageType: TMessageType; - FSeqID: Integer; - protected - function GetName: string; - procedure SetName( const Value: string); - function GetType: TMessageType; - procedure SetType( Value: TMessageType); - function GetSeqID: Integer; - procedure SetSeqID( Value: Integer); - public - property Name: string read FName write FName; - property Type_: TMessageType read FMessageType write FMessageType; - property SeqID: Integer read FSeqID write FSeqID; - constructor Create( AName: string; AMessageType: TMessageType; ASeqID: Integer); overload; - constructor Create; overload; - end; - - IField = interface - ['{F0D43BE5-7883-442E-83FF-0580CC632B72}'] - function GetName: string; - procedure SetName( const Value: string); - function GetType: TType; - procedure SetType( Value: TType); - function GetId: SmallInt; - procedure SetId( Value: SmallInt); - property Name: string read GetName write SetName; - property Type_: TType read GetType write SetType; - property Id: SmallInt read GetId write SetId; - end; - - TFieldImpl = class( TInterfacedObject, IField) - private - FName : string; - FType : TType; - FId : SmallInt; - protected - function GetName: string; - procedure SetName( const Value: string); - function GetType: TType; - procedure SetType( Value: TType); - function GetId: SmallInt; - procedure SetId( Value: SmallInt); - public - constructor Create( const AName: string; const AType: TType; AId: SmallInt); overload; - constructor Create; overload; - end; TProtocolUtil = class public @@ -279,18 +173,18 @@ type IProtocol = interface ['{602A7FFB-0D9E-4CD8-8D7F-E5076660588A}'] function GetTransport: ITransport; - procedure WriteMessageBegin( const msg: IMessage); + procedure WriteMessageBegin( const msg: TThriftMessage); procedure WriteMessageEnd; - procedure WriteStructBegin( const struc: IStruct); + procedure WriteStructBegin( const struc: TThriftStruct); procedure WriteStructEnd; - procedure WriteFieldBegin( const field: IField); + procedure WriteFieldBegin( const field: TThriftField); procedure WriteFieldEnd; procedure WriteFieldStop; - procedure WriteMapBegin( const map: IMap); + procedure WriteMapBegin( const map: TThriftMap); procedure WriteMapEnd; - procedure WriteListBegin( const list: IList); + procedure WriteListBegin( const list: TThriftList); procedure WriteListEnd(); - procedure WriteSetBegin( const set_: ISet ); + procedure WriteSetBegin( const set_: TThriftSet ); procedure WriteSetEnd(); procedure WriteBool( b: Boolean); procedure WriteByte( b: ShortInt); @@ -302,17 +196,17 @@ type procedure WriteAnsiString( const s: AnsiString); procedure WriteBinary( const b: TBytes); - function ReadMessageBegin: IMessage; + function ReadMessageBegin: TThriftMessage; procedure ReadMessageEnd(); - function ReadStructBegin: IStruct; + function ReadStructBegin: TThriftStruct; procedure ReadStructEnd; - function ReadFieldBegin: IField; + function ReadFieldBegin: TThriftField; procedure ReadFieldEnd(); - function ReadMapBegin: IMap; + function ReadMapBegin: TThriftMap; procedure ReadMapEnd(); - function ReadListBegin: IList; + function ReadListBegin: TThriftList; procedure ReadListEnd(); - function ReadSetBegin: ISet; + function ReadSetBegin: TThriftSet; procedure ReadSetEnd(); function ReadBool: Boolean; function ReadByte: ShortInt; @@ -348,18 +242,18 @@ type function GetTransport: ITransport; public - procedure WriteMessageBegin( const msg: IMessage); virtual; abstract; + procedure WriteMessageBegin( const msg: TThriftMessage); virtual; abstract; procedure WriteMessageEnd; virtual; abstract; - procedure WriteStructBegin( const struc: IStruct); virtual; abstract; + procedure WriteStructBegin( const struc: TThriftStruct); virtual; abstract; procedure WriteStructEnd; virtual; abstract; - procedure WriteFieldBegin( const field: IField); virtual; abstract; + procedure WriteFieldBegin( const field: TThriftField); virtual; abstract; procedure WriteFieldEnd; virtual; abstract; procedure WriteFieldStop; virtual; abstract; - procedure WriteMapBegin( const map: IMap); virtual; abstract; + procedure WriteMapBegin( const map: TThriftMap); virtual; abstract; procedure WriteMapEnd; virtual; abstract; - procedure WriteListBegin( const list: IList); virtual; abstract; + procedure WriteListBegin( const list: TThriftList); virtual; abstract; procedure WriteListEnd(); virtual; abstract; - procedure WriteSetBegin( const set_: ISet ); virtual; abstract; + procedure WriteSetBegin( const set_: TThriftSet ); virtual; abstract; procedure WriteSetEnd(); virtual; abstract; procedure WriteBool( b: Boolean); virtual; abstract; procedure WriteByte( b: ShortInt); virtual; abstract; @@ -371,17 +265,17 @@ type procedure WriteAnsiString( const s: AnsiString); virtual; procedure WriteBinary( const b: TBytes); virtual; abstract; - function ReadMessageBegin: IMessage; virtual; abstract; + function ReadMessageBegin: TThriftMessage; virtual; abstract; procedure ReadMessageEnd(); virtual; abstract; - function ReadStructBegin: IStruct; virtual; abstract; + function ReadStructBegin: TThriftStruct; virtual; abstract; procedure ReadStructEnd; virtual; abstract; - function ReadFieldBegin: IField; virtual; abstract; + function ReadFieldBegin: TThriftField; virtual; abstract; procedure ReadFieldEnd(); virtual; abstract; - function ReadMapBegin: IMap; virtual; abstract; + function ReadMapBegin: TThriftMap; virtual; abstract; procedure ReadMapEnd(); virtual; abstract; - function ReadListBegin: IList; virtual; abstract; + function ReadListBegin: TThriftList; virtual; abstract; procedure ReadListEnd(); virtual; abstract; - function ReadSetBegin: ISet; virtual; abstract; + function ReadSetBegin: TThriftSet; virtual; abstract; procedure ReadSetEnd(); virtual; abstract; function ReadBool: Boolean; virtual; abstract; function ReadByte: ShortInt; virtual; abstract; @@ -405,22 +299,6 @@ type procedure Write( const iprot: IProtocol); end; - IStruct = interface - ['{5DCE39AA-C916-4BC7-A79B-96A0C36B2220}'] - procedure SetName(const Value: string); - function GetName: string; - property Name: string read GetName write SetName; - end; - - TStructImpl = class( TInterfacedObject, IStruct ) - private - FName: string; - protected - function GetName: string; - procedure SetName(const Value: string); - public - constructor Create( const AName: string); - end; TBinaryProtocolImpl = class( TProtocolImpl ) protected @@ -432,7 +310,7 @@ type FStrictWrite : Boolean; private - function ReadAll( var buf: TBytes; off: Integer; len: Integer ): Integer; + function ReadAll( const pBuf : Pointer; const buflen : Integer; off: Integer; len: Integer ): Integer; inline; function ReadStringBody( size: Integer): string; public @@ -451,18 +329,18 @@ type constructor Create( const trans: ITransport); overload; constructor Create( const trans: ITransport; strictRead: Boolean; strictWrite: Boolean); overload; - procedure WriteMessageBegin( const msg: IMessage); override; + procedure WriteMessageBegin( const msg: TThriftMessage); override; procedure WriteMessageEnd; override; - procedure WriteStructBegin( const struc: IStruct); override; + procedure WriteStructBegin( const struc: TThriftStruct); override; procedure WriteStructEnd; override; - procedure WriteFieldBegin( const field: IField); override; + procedure WriteFieldBegin( const field: TThriftField); override; procedure WriteFieldEnd; override; procedure WriteFieldStop; override; - procedure WriteMapBegin( const map: IMap); override; + procedure WriteMapBegin( const map: TThriftMap); override; procedure WriteMapEnd; override; - procedure WriteListBegin( const list: IList); override; + procedure WriteListBegin( const list: TThriftList); override; procedure WriteListEnd(); override; - procedure WriteSetBegin( const set_: ISet ); override; + procedure WriteSetBegin( const set_: TThriftSet ); override; procedure WriteSetEnd(); override; procedure WriteBool( b: Boolean); override; procedure WriteByte( b: ShortInt); override; @@ -472,17 +350,17 @@ type procedure WriteDouble( const d: Double); override; procedure WriteBinary( const b: TBytes); override; - function ReadMessageBegin: IMessage; override; + function ReadMessageBegin: TThriftMessage; override; procedure ReadMessageEnd(); override; - function ReadStructBegin: IStruct; override; + function ReadStructBegin: TThriftStruct; override; procedure ReadStructEnd; override; - function ReadFieldBegin: IField; override; + function ReadFieldBegin: TThriftField; override; procedure ReadFieldEnd(); override; - function ReadMapBegin: IMap; override; + function ReadMapBegin: TThriftMap; override; procedure ReadMapEnd(); override; - function ReadListBegin: IList; override; + function ReadListBegin: TThriftList; override; procedure ReadListEnd(); override; - function ReadSetBegin: ISet; override; + function ReadSetBegin: TThriftSet; override; procedure ReadSetEnd(); override; function ReadBool: Boolean; override; function ReadByte: ShortInt; override; @@ -510,18 +388,18 @@ type // All operations will be forward to the given protocol. Must be non-null. constructor Create( const aProtocol : IProtocol); - procedure WriteMessageBegin( const msg: IMessage); override; + procedure WriteMessageBegin( const msg: TThriftMessage); override; procedure WriteMessageEnd; override; - procedure WriteStructBegin( const struc: IStruct); override; + procedure WriteStructBegin( const struc: TThriftStruct); override; procedure WriteStructEnd; override; - procedure WriteFieldBegin( const field: IField); override; + procedure WriteFieldBegin( const field: TThriftField); override; procedure WriteFieldEnd; override; procedure WriteFieldStop; override; - procedure WriteMapBegin( const map: IMap); override; + procedure WriteMapBegin( const map: TThriftMap); override; procedure WriteMapEnd; override; - procedure WriteListBegin( const list: IList); override; + procedure WriteListBegin( const list: TThriftList); override; procedure WriteListEnd(); override; - procedure WriteSetBegin( const set_: ISet ); override; + procedure WriteSetBegin( const set_: TThriftSet ); override; procedure WriteSetEnd(); override; procedure WriteBool( b: Boolean); override; procedure WriteByte( b: ShortInt); override; @@ -533,17 +411,17 @@ type procedure WriteAnsiString( const s: AnsiString); override; procedure WriteBinary( const b: TBytes); override; - function ReadMessageBegin: IMessage; override; + function ReadMessageBegin: TThriftMessage; override; procedure ReadMessageEnd(); override; - function ReadStructBegin: IStruct; override; + function ReadStructBegin: TThriftStruct; override; procedure ReadStructEnd; override; - function ReadFieldBegin: IField; override; + function ReadFieldBegin: TThriftField; override; procedure ReadFieldEnd(); override; - function ReadMapBegin: IMap; override; + function ReadMapBegin: TThriftMap; override; procedure ReadMapEnd(); override; - function ReadListBegin: IList; override; + function ReadListBegin: TThriftList; override; procedure ReadListEnd(); override; - function ReadSetBegin: ISet; override; + function ReadSetBegin: TThriftSet; override; procedure ReadSetEnd(); override; function ReadBool: Boolean; override; function ReadByte: ShortInt; override; @@ -594,6 +472,13 @@ type end; +procedure Init( var rec : TThriftMessage; const AName: string = ''; const AMessageType: TMessageType = Low(TMessageType); const ASeqID: Integer = 0); overload; inline; +procedure Init( var rec : TThriftStruct; const AName: string = ''); overload; inline; +procedure Init( var rec : TThriftField; const AName: string = ''; const AType: TType = Low(TType); const AID: SmallInt = 0); overload; inline; +procedure Init( var rec : TThriftMap; const AKeyType: TType = Low(TType); const AValueType: TType = Low(TType); const ACount: Integer = 0); overload; inline; +procedure Init( var rec : TThriftSet; const AElementType: TType = Low(TType); const ACount: Integer = 0); overload; inline; +procedure Init( var rec : TThriftList; const AElementType: TType = Low(TType); const ACount: Integer = 0); overload; inline; + implementation @@ -609,54 +494,7 @@ begin System.Move( d, Result, SizeOf(Result)); end; -{ TFieldImpl } -constructor TFieldImpl.Create(const AName: string; const AType: TType; - AId: SmallInt); -begin - inherited Create; - FName := AName; - FType := AType; - FId := AId; -end; - -constructor TFieldImpl.Create; -begin - inherited Create; - FName := ''; - FType := Low(TType); - FId := 0; -end; - -function TFieldImpl.GetId: SmallInt; -begin - Result := FId; -end; - -function TFieldImpl.GetName: string; -begin - Result := FName; -end; - -function TFieldImpl.GetType: TType; -begin - Result := FType; -end; - -procedure TFieldImpl.SetId(Value: SmallInt); -begin - FId := Value; -end; - -procedure TFieldImpl.SetName(const Value: string); -begin - FName := Value; -end; - -procedure TFieldImpl.SetType(Value: TType); -begin - FType := Value; -end; { TProtocolRecursionTrackerImpl } @@ -769,10 +607,10 @@ end; { TProtocolUtil } class procedure TProtocolUtil.Skip( prot: IProtocol; type_: TType); -var field : IField; - map : IMap; - set_ : ISet; - list : IList; +var field : TThriftField; + map : TThriftMap; + set_ : TThriftSet; + list : TThriftList; i : Integer; tracker : IProtocolRecursionTracker; begin @@ -823,186 +661,10 @@ begin end; else - ASSERT( FALSE); // any new types? + raise TProtocolExceptionInvalidData.Create('Unexpected type '+IntToStr(Ord(type_))); end; end; -{ TStructImpl } - -constructor TStructImpl.Create(const AName: string); -begin - inherited Create; - FName := AName; -end; - -function TStructImpl.GetName: string; -begin - Result := FName; -end; - -procedure TStructImpl.SetName(const Value: string); -begin - FName := Value; -end; - -{ TMapImpl } - -constructor TMapImpl.Create( AKeyType, AValueType: TType; ACount: Integer); -begin - inherited Create; - FValueType := AValueType; - FKeyType := AKeyType; - FCount := ACount; -end; - -constructor TMapImpl.Create; -begin - inherited Create; -end; - -function TMapImpl.GetCount: Integer; -begin - Result := FCount; -end; - -function TMapImpl.GetKeyType: TType; -begin - Result := FKeyType; -end; - -function TMapImpl.GetValueType: TType; -begin - Result := FValueType; -end; - -procedure TMapImpl.SetCount(Value: Integer); -begin - FCount := Value; -end; - -procedure TMapImpl.SetKeyType(Value: TType); -begin - FKeyType := Value; -end; - -procedure TMapImpl.SetValueType(Value: TType); -begin - FValueType := Value; -end; - -{ IMessage } - -constructor TMessageImpl.Create(AName: string; AMessageType: TMessageType; - ASeqID: Integer); -begin - inherited Create; - FName := AName; - FMessageType := AMessageType; - FSeqID := ASeqID; -end; - -constructor TMessageImpl.Create; -begin - inherited; -end; - -function TMessageImpl.GetName: string; -begin - Result := FName; -end; - -function TMessageImpl.GetSeqID: Integer; -begin - Result := FSeqID; -end; - -function TMessageImpl.GetType: TMessageType; -begin - Result := FMessageType; -end; - -procedure TMessageImpl.SetName(const Value: string); -begin - FName := Value; -end; - -procedure TMessageImpl.SetSeqID(Value: Integer); -begin - FSeqID := Value; -end; - -procedure TMessageImpl.SetType(Value: TMessageType); -begin - FMessageType := Value; -end; - -{ ISet } - -constructor TSetImpl.Create( AElementType: TType; ACount: Integer); -begin - inherited Create; - FCount := ACount; - FElementType := AElementType; -end; - -constructor TSetImpl.Create; -begin - inherited Create; -end; - -function TSetImpl.GetCount: Integer; -begin - Result := FCount; -end; - -function TSetImpl.GetElementType: TType; -begin - Result := FElementType; -end; - -procedure TSetImpl.SetCount(Value: Integer); -begin - FCount := Value; -end; - -procedure TSetImpl.SetElementType(Value: TType); -begin - FElementType := Value; -end; - -{ IList } - -constructor TListImpl.Create( AElementType: TType; ACount: Integer); -begin - inherited Create; - FCount := ACount; - FElementType := AElementType; -end; - -constructor TListImpl.Create; -begin - inherited Create; -end; - -function TListImpl.GetCount: Integer; -begin - Result := FCount; -end; - -function TListImpl.GetElementType: TType; -begin - Result := FElementType; -end; - -procedure TListImpl.SetCount(Value: Integer); -begin - FCount := Value; -end; - -procedure TListImpl.SetElementType(Value: TType); -begin - FElementType := Value; -end; { TBinaryProtocolImpl } @@ -1020,10 +682,9 @@ begin FStrictWrite := strictWrite; end; -function TBinaryProtocolImpl.ReadAll( var buf: TBytes; off, - len: Integer): Integer; +function TBinaryProtocolImpl.ReadAll( const pBuf : Pointer; const buflen : Integer; off: Integer; len: Integer ): Integer; begin - Result := FTrans.ReadAll( buf, off, len ); + Result := FTrans.ReadAll( pBuf, buflen, off, len ); end; function TBinaryProtocolImpl.ReadBinary: TBytes; @@ -1039,16 +700,12 @@ end; function TBinaryProtocolImpl.ReadBool: Boolean; begin - Result := ReadByte = 1; + Result := (ReadByte = 1); end; function TBinaryProtocolImpl.ReadByte: ShortInt; -var - bin : TBytes; begin - SetLength( bin, 1); - ReadAll( bin, 0, 1 ); - Result := ShortInt( bin[0]); + ReadAll( @result, SizeOf(result), 0, 1); end; function TBinaryProtocolImpl.ReadDouble: Double; @@ -1056,17 +713,12 @@ begin Result := ConvertInt64ToDouble( ReadI64 ) end; -function TBinaryProtocolImpl.ReadFieldBegin: IField; -var - field : IField; +function TBinaryProtocolImpl.ReadFieldBegin: TThriftField; begin - field := TFieldImpl.Create; - field.Type_ := TType( ReadByte); - if ( field.Type_ <> TType.Stop ) then - begin - field.Id := ReadI16; + Init( result, '', TType( ReadByte), 0); + if ( result.Type_ <> TType.Stop ) then begin + result.Id := ReadI16; end; - Result := field; end; procedure TBinaryProtocolImpl.ReadFieldEnd; @@ -1075,20 +727,16 @@ begin end; function TBinaryProtocolImpl.ReadI16: SmallInt; -var - i16in : TBytes; +var i16in : packed array[0..1] of Byte; begin - SetLength( i16in, 2 ); - ReadAll( i16in, 0, 2); + ReadAll( @i16in, Sizeof(i16in), 0, 2); Result := SmallInt(((i16in[0] and $FF) shl 8) or (i16in[1] and $FF)); end; function TBinaryProtocolImpl.ReadI32: Integer; -var - i32in : TBytes; +var i32in : packed array[0..3] of Byte; begin - SetLength( i32in, 4 ); - ReadAll( i32in, 0, 4); + ReadAll( @i32in, SizeOf(i32in), 0, 4); Result := Integer( ((i32in[0] and $FF) shl 24) or @@ -1099,11 +747,9 @@ begin end; function TBinaryProtocolImpl.ReadI64: Int64; -var - i64in : TBytes; +var i64in : packed array[0..7] of Byte; begin - SetLength( i64in, 8); - ReadAll( i64in, 0, 8); + ReadAll( @i64in, SizeOf(i64in), 0, 8); Result := (Int64( i64in[0] and $FF) shl 56) or (Int64( i64in[1] and $FF) shl 48) or @@ -1115,14 +761,10 @@ begin (Int64( i64in[7] and $FF)); end; -function TBinaryProtocolImpl.ReadListBegin: IList; -var - list : IList; +function TBinaryProtocolImpl.ReadListBegin: TThriftList; begin - list := TListImpl.Create; - list.ElementType := TType( ReadByte ); - list.Count := ReadI32; - Result := list; + result.ElementType := TType(ReadByte); + result.Count := ReadI32; end; procedure TBinaryProtocolImpl.ReadListEnd; @@ -1130,15 +772,11 @@ begin end; -function TBinaryProtocolImpl.ReadMapBegin: IMap; -var - map : IMap; +function TBinaryProtocolImpl.ReadMapBegin: TThriftMap; begin - map := TMapImpl.Create; - map.KeyType := TType( ReadByte ); - map.ValueType := TType( ReadByte ); - map.Count := ReadI32; - Result := map; + result.KeyType := TType(ReadByte); + result.ValueType := TType(ReadByte); + result.Count := ReadI32; end; procedure TBinaryProtocolImpl.ReadMapEnd; @@ -1146,35 +784,30 @@ begin end; -function TBinaryProtocolImpl.ReadMessageBegin: IMessage; +function TBinaryProtocolImpl.ReadMessageBegin: TThriftMessage; var size : Integer; version : Integer; - message : IMessage; begin - message := TMessageImpl.Create; + Init( result); size := ReadI32; - if (size < 0) then - begin + if (size < 0) then begin version := size and Integer( VERSION_MASK); - if ( version <> Integer( VERSION_1)) then - begin + if ( version <> Integer( VERSION_1)) then begin raise TProtocolExceptionBadVersion.Create('Bad version in ReadMessageBegin: ' + IntToStr(version) ); end; - message.Type_ := TMessageType( size and $000000ff); - message.Name := ReadString; - message.SeqID := ReadI32; - end else - begin - if FStrictRead then - begin + result.Type_ := TMessageType( size and $000000ff); + result.Name := ReadString; + result.SeqID := ReadI32; + end + else begin + if FStrictRead then begin raise TProtocolExceptionBadVersion.Create('Missing version in readMessageBegin, old client?' ); end; - message.Name := ReadStringBody( size ); - message.Type_ := TMessageType( ReadByte ); - message.SeqID := ReadI32; + result.Name := ReadStringBody( size ); + result.Type_ := TMessageType( ReadByte ); + result.SeqID := ReadI32; end; - Result := message; end; procedure TBinaryProtocolImpl.ReadMessageEnd; @@ -1183,14 +816,10 @@ begin end; -function TBinaryProtocolImpl.ReadSetBegin: ISet; -var - set_ : ISet; +function TBinaryProtocolImpl.ReadSetBegin: TThriftSet; begin - set_ := TSetImpl.Create; - set_.ElementType := TType( ReadByte ); - set_.Count := ReadI32; - Result := set_; + result.ElementType := TType(ReadByte); + result.Count := ReadI32; end; procedure TBinaryProtocolImpl.ReadSetEnd; @@ -1207,9 +836,9 @@ begin Result := TEncoding.UTF8.GetString( buf); end; -function TBinaryProtocolImpl.ReadStructBegin: IStruct; +function TBinaryProtocolImpl.ReadStructBegin: TThriftStruct; begin - Result := TStructImpl.Create(''); + Init( Result); end; procedure TBinaryProtocolImpl.ReadStructEnd; @@ -1228,22 +857,16 @@ end; procedure TBinaryProtocolImpl.WriteBool(b: Boolean); begin - if b then - begin + if b then begin WriteByte( 1 ); - end else - begin + end else begin WriteByte( 0 ); end; end; procedure TBinaryProtocolImpl.WriteByte(b: ShortInt); -var - a : TBytes; begin - SetLength( a, 1); - a[0] := Byte( b ); - FTrans.Write( a, 0, 1 ); + FTrans.Write( @b, 0, 1); end; procedure TBinaryProtocolImpl.WriteDouble( const d: Double); @@ -1251,7 +874,7 @@ begin WriteI64(ConvertDoubleToInt64(d)); end; -procedure TBinaryProtocolImpl.WriteFieldBegin( const field: IField); +procedure TBinaryProtocolImpl.WriteFieldBegin( const field: TThriftField); begin WriteByte(ShortInt(field.Type_)); WriteI16(field.ID); @@ -1268,32 +891,26 @@ begin end; procedure TBinaryProtocolImpl.WriteI16(i16: SmallInt); -var - i16out : TBytes; +var i16out : packed array[0..1] of Byte; begin - SetLength( i16out, 2); i16out[0] := Byte($FF and (i16 shr 8)); i16out[1] := Byte($FF and i16); - FTrans.Write( i16out ); + FTrans.Write( @i16out, 0, 2); end; procedure TBinaryProtocolImpl.WriteI32(i32: Integer); -var - i32out : TBytes; +var i32out : packed array[0..3] of Byte; begin - SetLength( i32out, 4); i32out[0] := Byte($FF and (i32 shr 24)); i32out[1] := Byte($FF and (i32 shr 16)); i32out[2] := Byte($FF and (i32 shr 8)); i32out[3] := Byte($FF and i32); - FTrans.Write( i32out, 0, 4); + FTrans.Write( @i32out, 0, 4); end; procedure TBinaryProtocolImpl.WriteI64( const i64: Int64); -var - i64out : TBytes; +var i64out : packed array[0..7] of Byte; begin - SetLength( i64out, 8); i64out[0] := Byte($FF and (i64 shr 56)); i64out[1] := Byte($FF and (i64 shr 48)); i64out[2] := Byte($FF and (i64 shr 40)); @@ -1302,10 +919,10 @@ begin i64out[5] := Byte($FF and (i64 shr 16)); i64out[6] := Byte($FF and (i64 shr 8)); i64out[7] := Byte($FF and i64); - FTrans.Write( i64out, 0, 8); + FTrans.Write( @i64out, 0, 8); end; -procedure TBinaryProtocolImpl.WriteListBegin( const list: IList); +procedure TBinaryProtocolImpl.WriteListBegin( const list: TThriftList); begin WriteByte(ShortInt(list.ElementType)); WriteI32(list.Count); @@ -1316,7 +933,7 @@ begin end; -procedure TBinaryProtocolImpl.WriteMapBegin( const map: IMap); +procedure TBinaryProtocolImpl.WriteMapBegin( const map: TThriftMap); begin WriteByte(ShortInt(map.KeyType)); WriteByte(ShortInt(map.ValueType)); @@ -1328,7 +945,7 @@ begin end; -procedure TBinaryProtocolImpl.WriteMessageBegin( const msg: IMessage); +procedure TBinaryProtocolImpl.WriteMessageBegin( const msg: TThriftMessage); var version : Cardinal; begin @@ -1351,7 +968,7 @@ begin end; -procedure TBinaryProtocolImpl.WriteSetBegin( const set_: ISet); +procedure TBinaryProtocolImpl.WriteSetBegin( const set_: TThriftSet); begin WriteByte(ShortInt(set_.ElementType)); WriteI32(set_.Count); @@ -1362,7 +979,7 @@ begin end; -procedure TBinaryProtocolImpl.WriteStructBegin( const struc: IStruct); +procedure TBinaryProtocolImpl.WriteStructBegin( const struc: TThriftStruct); begin end; @@ -1461,7 +1078,7 @@ begin end; -procedure TProtocolDecorator.WriteMessageBegin( const msg: IMessage); +procedure TProtocolDecorator.WriteMessageBegin( const msg: TThriftMessage); begin FWrappedProtocol.WriteMessageBegin( msg); end; @@ -1473,7 +1090,7 @@ begin end; -procedure TProtocolDecorator.WriteStructBegin( const struc: IStruct); +procedure TProtocolDecorator.WriteStructBegin( const struc: TThriftStruct); begin FWrappedProtocol.WriteStructBegin( struc); end; @@ -1485,7 +1102,7 @@ begin end; -procedure TProtocolDecorator.WriteFieldBegin( const field: IField); +procedure TProtocolDecorator.WriteFieldBegin( const field: TThriftField); begin FWrappedProtocol.WriteFieldBegin( field); end; @@ -1503,7 +1120,7 @@ begin end; -procedure TProtocolDecorator.WriteMapBegin( const map: IMap); +procedure TProtocolDecorator.WriteMapBegin( const map: TThriftMap); begin FWrappedProtocol.WriteMapBegin( map); end; @@ -1515,7 +1132,7 @@ begin end; -procedure TProtocolDecorator.WriteListBegin( const list: IList); +procedure TProtocolDecorator.WriteListBegin( const list: TThriftList); begin FWrappedProtocol.WriteListBegin( list); end; @@ -1527,7 +1144,7 @@ begin end; -procedure TProtocolDecorator.WriteSetBegin( const set_: ISet ); +procedure TProtocolDecorator.WriteSetBegin( const set_: TThriftSet ); begin FWrappedProtocol.WriteSetBegin( set_); end; @@ -1593,7 +1210,7 @@ begin end; -function TProtocolDecorator.ReadMessageBegin: IMessage; +function TProtocolDecorator.ReadMessageBegin: TThriftMessage; begin result := FWrappedProtocol.ReadMessageBegin; end; @@ -1605,7 +1222,7 @@ begin end; -function TProtocolDecorator.ReadStructBegin: IStruct; +function TProtocolDecorator.ReadStructBegin: TThriftStruct; begin result := FWrappedProtocol.ReadStructBegin; end; @@ -1617,7 +1234,7 @@ begin end; -function TProtocolDecorator.ReadFieldBegin: IField; +function TProtocolDecorator.ReadFieldBegin: TThriftField; begin result := FWrappedProtocol.ReadFieldBegin; end; @@ -1629,7 +1246,7 @@ begin end; -function TProtocolDecorator.ReadMapBegin: IMap; +function TProtocolDecorator.ReadMapBegin: TThriftMap; begin result := FWrappedProtocol.ReadMapBegin; end; @@ -1641,7 +1258,7 @@ begin end; -function TProtocolDecorator.ReadListBegin: IList; +function TProtocolDecorator.ReadListBegin: TThriftList; begin result := FWrappedProtocol.ReadListBegin; end; @@ -1653,7 +1270,7 @@ begin end; -function TProtocolDecorator.ReadSetBegin: ISet; +function TProtocolDecorator.ReadSetBegin: TThriftSet; begin result := FWrappedProtocol.ReadSetBegin; end; @@ -1719,6 +1336,54 @@ begin end; +{ Init helper functions } + +procedure Init( var rec : TThriftMessage; const AName: string; const AMessageType: TMessageType; const ASeqID: Integer); +begin + rec.Name := AName; + rec.Type_ := AMessageType; + rec.SeqID := ASeqID; +end; + + +procedure Init( var rec : TThriftStruct; const AName: string = ''); +begin + rec.Name := AName; +end; + + +procedure Init( var rec : TThriftField; const AName: string; const AType: TType; const AID: SmallInt); +begin + rec.Name := AName; + rec.Type_ := AType; + rec.Id := AId; +end; + + +procedure Init( var rec : TThriftMap; const AKeyType, AValueType: TType; const ACount: Integer); +begin + rec.ValueType := AValueType; + rec.KeyType := AKeyType; + rec.Count := ACount; +end; + + +procedure Init( var rec : TThriftSet; const AElementType: TType; const ACount: Integer); +begin + rec.Count := ACount; + rec.ElementType := AElementType; +end; + + +procedure Init( var rec : TThriftList; const AElementType: TType; const ACount: Integer); +begin + rec.Count := ACount; + rec.ElementType := AElementType; +end; + + + + end. diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Stream.pas b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Stream.pas index 7c448d8..3308c53 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Stream.pas +++ b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Stream.pas @@ -38,9 +38,11 @@ uses type IThriftStream = interface - ['{732621B3-F697-4D76-A1B0-B4DD5A8E4018}'] - procedure Write( const buffer: TBytes; offset: Integer; count: Integer); - function Read( var buffer: TBytes; offset: Integer; count: Integer): Integer; + ['{2A77D916-7446-46C1-8545-0AEC0008DBCA}'] + procedure Write( const buffer: TBytes; offset: Integer; count: Integer); overload; + procedure Write( const pBuf : Pointer; offset: Integer; count: Integer); overload; + function Read( var buffer: TBytes; offset: Integer; count: Integer): Integer; overload; + function Read( const pBuf : Pointer; const buflen : Integer; offset: Integer; count: Integer): Integer; overload; procedure Open; procedure Close; procedure Flush; @@ -50,10 +52,12 @@ type TThriftStreamImpl = class( TInterfacedObject, IThriftStream) private - procedure CheckSizeAndOffset( const buffer: TBytes; offset: Integer; count: Integer); + procedure CheckSizeAndOffset( const pBuf : Pointer; const buflen : Integer; offset: Integer; count: Integer); overload; protected - procedure Write( const buffer: TBytes; offset: Integer; count: Integer); virtual; - function Read( var buffer: TBytes; offset: Integer; count: Integer): Integer; virtual; + procedure Write( const buffer: TBytes; offset: Integer; count: Integer); overload; inline; + procedure Write( const pBuf : Pointer; offset: Integer; count: Integer); overload; virtual; + function Read( var buffer: TBytes; offset: Integer; count: Integer): Integer; overload; inline; + function Read( const pBuf : Pointer; const buflen : Integer; offset: Integer; count: Integer): Integer; overload; virtual; procedure Open; virtual; abstract; procedure Close; virtual; abstract; procedure Flush; virtual; abstract; @@ -66,8 +70,8 @@ type FStream : TStream; FOwnsStream : Boolean; protected - procedure Write( const buffer: TBytes; offset: Integer; count: Integer); override; - function Read( var buffer: TBytes; offset: Integer; count: Integer): Integer; override; + procedure Write( const pBuf : Pointer; offset: Integer; count: Integer); override; + function Read( const pBuf : Pointer; const buflen : Integer; offset: Integer; count: Integer): Integer; override; procedure Open; override; procedure Close; override; procedure Flush; override; @@ -82,8 +86,8 @@ type private FStream : IStream; protected - procedure Write( const buffer: TBytes; offset: Integer; count: Integer); override; - function Read( var buffer: TBytes; offset: Integer; count: Integer): Integer; override; + procedure Write( const pBuf : Pointer; offset: Integer; count: Integer); override; + function Read( const pBuf : Pointer; const buflen : Integer; offset: Integer; count: Integer): Integer; override; procedure Open; override; procedure Close; override; procedure Flush; override; @@ -127,13 +131,20 @@ begin // nothing to do end; -function TThriftStreamAdapterCOM.Read( var buffer: TBytes; offset: Integer; count: Integer): Integer; +function TThriftStreamAdapterCOM.Read( const pBuf : Pointer; const buflen : Integer; offset: Integer; count: Integer): Integer; +var pTmp : PByte; begin inherited; + + if count >= buflen-offset + then count := buflen-offset; + Result := 0; if FStream <> nil then begin if count > 0 then begin - FStream.Read( @buffer[offset], count, @Result); + pTmp := pBuf; + Inc( pTmp, offset); + FStream.Read( pTmp, count, @Result); end; end; end; @@ -162,44 +173,56 @@ begin end; end; -procedure TThriftStreamAdapterCOM.Write( const buffer: TBytes; offset: Integer; count: Integer); +procedure TThriftStreamAdapterCOM.Write( const pBuf: Pointer; offset: Integer; count: Integer); var nWritten : Integer; + pTmp : PByte; begin inherited; if IsOpen then begin if count > 0 then begin - FStream.Write( @buffer[0], count, @nWritten); + pTmp := pBuf; + Inc( pTmp, offset); + FStream.Write( pTmp, count, @nWritten); end; end; end; { TThriftStreamImpl } -procedure TThriftStreamImpl.CheckSizeAndOffset(const buffer: TBytes; offset, - count: Integer); -var - len : Integer; +procedure TThriftStreamImpl.CheckSizeAndOffset( const pBuf : Pointer; const buflen : Integer; offset: Integer; count: Integer); begin if count > 0 then begin - len := Length( buffer ); - if (offset < 0) or ( offset >= len) then begin + if (offset < 0) or ( offset >= buflen) then begin raise ERangeError.Create( SBitsIndexError ); end; - if count > len then begin + if count > buflen then begin raise ERangeError.Create( SBitsIndexError ); end; end; end; function TThriftStreamImpl.Read(var buffer: TBytes; offset, count: Integer): Integer; +begin + if Length(buffer) > 0 + then Result := Read( @buffer[0], Length(buffer), offset, count) + else Result := 0; +end; + +function TThriftStreamImpl.Read( const pBuf : Pointer; const buflen : Integer; offset: Integer; count: Integer): Integer; begin Result := 0; - CheckSizeAndOffset( buffer, offset, count ); + CheckSizeAndOffset( pBuf, buflen, offset, count ); end; procedure TThriftStreamImpl.Write(const buffer: TBytes; offset, count: Integer); begin - CheckSizeAndOffset( buffer, offset, count ); + if Length(buffer) > 0 + then Write( @buffer[0], offset, count); +end; + +procedure TThriftStreamImpl.Write( const pBuf : Pointer; offset: Integer; count: Integer); +begin + CheckSizeAndOffset( pBuf, offset+count, offset, count); end; { TThriftStreamAdapterDelphi } @@ -241,14 +264,20 @@ begin // nothing to do end; -function TThriftStreamAdapterDelphi.Read(var buffer: TBytes; offset, - count: Integer): Integer; +function TThriftStreamAdapterDelphi.Read(const pBuf : Pointer; const buflen : Integer; offset, count: Integer): Integer; +var pTmp : PByte; begin inherited; - Result := 0; + + if count >= buflen-offset + then count := buflen-offset; + if count > 0 then begin - Result := FStream.Read( Pointer(@buffer[offset])^, count) - end; + pTmp := pBuf; + Inc( pTmp, offset); + Result := FStream.Read( pTmp^, count) + end + else Result := 0; end; function TThriftStreamAdapterDelphi.ToArray: TBytes; @@ -276,12 +305,14 @@ begin end end; -procedure TThriftStreamAdapterDelphi.Write(const buffer: TBytes; offset, - count: Integer); +procedure TThriftStreamAdapterDelphi.Write(const pBuf : Pointer; offset, count: Integer); +var pTmp : PByte; begin inherited; if count > 0 then begin - FStream.Write( Pointer(@buffer[offset])^, count) + pTmp := pBuf; + Inc( pTmp, offset); + FStream.Write( pTmp^, count) end; end; diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Transport.Pipes.pas b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Transport.Pipes.pas index d4f99ab..77a343b 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Transport.Pipes.pas +++ b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Transport.Pipes.pas @@ -48,16 +48,16 @@ type FOpenTimeOut : DWORD; // separate value to allow for fail-fast-on-open scenarios FOverlapped : Boolean; - procedure Write( const buffer: TBytes; offset: Integer; count: Integer); override; - function Read( var buffer: TBytes; offset: Integer; count: Integer): Integer; override; + procedure Write( const pBuf : Pointer; offset, count : Integer); override; + function Read( const pBuf : Pointer; const buflen : Integer; offset: Integer; count: Integer): Integer; override; //procedure Open; override; - see derived classes procedure Close; override; procedure Flush; override; - function ReadDirect( var buffer: TBytes; offset: Integer; count: Integer): Integer; - function ReadOverlapped( var buffer: TBytes; offset: Integer; count: Integer): Integer; - procedure WriteDirect( const buffer: TBytes; offset: Integer; count: Integer); - procedure WriteOverlapped( const buffer: TBytes; offset: Integer; count: Integer); + function ReadDirect( const pBuf : Pointer; const buflen : Integer; offset: Integer; count: Integer): Integer; overload; + function ReadOverlapped( const pBuf : Pointer; const buflen : Integer; offset: Integer; count: Integer): Integer; overload; + procedure WriteDirect( const pBuf : Pointer; offset: Integer; count: Integer); overload; + procedure WriteOverlapped( const pBuf : Pointer; offset: Integer; count: Integer); overload; function IsOpen: Boolean; override; function ToArray: TBytes; override; @@ -310,37 +310,98 @@ begin end; -procedure TPipeStreamBase.Write(const buffer: TBytes; offset, count: Integer); +procedure TPipeStreamBase.Write( const pBuf : Pointer; offset, count : Integer); begin if FOverlapped - then WriteOverlapped( buffer, offset, count) - else WriteDirect( buffer, offset, count); + then WriteOverlapped( pBuf, offset, count) + else WriteDirect( pBuf, offset, count); end; -function TPipeStreamBase.Read( var buffer: TBytes; offset, count: Integer): Integer; +function TPipeStreamBase.Read( const pBuf : Pointer; const buflen : Integer; offset: Integer; count: Integer): Integer; begin if FOverlapped - then result := ReadOverlapped( buffer, offset, count) - else result := ReadDirect( buffer, offset, count); + then result := ReadOverlapped( pBuf, buflen, offset, count) + else result := ReadDirect( pBuf, buflen, offset, count); end; -procedure TPipeStreamBase.WriteDirect(const buffer: TBytes; offset, count: Integer); -var cbWritten : DWORD; +procedure TPipeStreamBase.WriteDirect( const pBuf : Pointer; offset: Integer; count: Integer); +var cbWritten, nBytes : DWORD; + pData : PByte; begin if not IsOpen then raise TTransportExceptionNotOpen.Create('Called write on non-open pipe'); - if not WriteFile( FPipe, buffer[offset], count, cbWritten, nil) - then raise TTransportExceptionNotOpen.Create('Write to pipe failed'); + // if necessary, send the data in chunks + // there's a system limit around 0x10000 bytes that we hit otherwise + // MSDN: "Pipe write operations across a network are limited to 65,535 bytes per write. For more information regarding pipes, see the Remarks section." + nBytes := Min( 15*4096, count); // 16 would exceed the limit + pData := pBuf; + Inc( pData, offset); + while nBytes > 0 do begin + if not WriteFile( FPipe, pData^, nBytes, cbWritten, nil) + then raise TTransportExceptionNotOpen.Create('Write to pipe failed'); + + Inc( pData, cbWritten); + Dec( count, cbWritten); + nBytes := Min( nBytes, count); + end; end; -function TPipeStreamBase.ReadDirect( var buffer: TBytes; offset, count: Integer): Integer; -var cbRead, dwErr : DWORD; +procedure TPipeStreamBase.WriteOverlapped( const pBuf : Pointer; offset: Integer; count: Integer); +var cbWritten, dwWait, dwError, nBytes : DWORD; + overlapped : IOverlappedHelper; + pData : PByte; +begin + if not IsOpen + then raise TTransportExceptionNotOpen.Create('Called write on non-open pipe'); + + // if necessary, send the data in chunks + // there's a system limit around 0x10000 bytes that we hit otherwise + // MSDN: "Pipe write operations across a network are limited to 65,535 bytes per write. For more information regarding pipes, see the Remarks section." + nBytes := Min( 15*4096, count); // 16 would exceed the limit + pData := pBuf; + Inc( pData, offset); + while nBytes > 0 do begin + overlapped := TOverlappedHelperImpl.Create; + if not WriteFile( FPipe, pData^, nBytes, cbWritten, overlapped.OverlappedPtr) + then begin + dwError := GetLastError; + case dwError of + ERROR_IO_PENDING : begin + dwWait := overlapped.WaitFor(FTimeout); + + if (dwWait = WAIT_TIMEOUT) then begin + CancelIo( FPipe); // prevents possible AV on invalid overlapped ptr + raise TTransportExceptionTimedOut.Create('Pipe write timed out'); + end; + + if (dwWait <> WAIT_OBJECT_0) + or not GetOverlappedResult( FPipe, overlapped.Overlapped, cbWritten, TRUE) + then raise TTransportExceptionUnknown.Create('Pipe write error'); + end; + + else + raise TTransportExceptionUnknown.Create(SysErrorMessage(dwError)); + end; + end; + + ASSERT( DWORD(nBytes) = cbWritten); + + Inc( pData, cbWritten); + Dec( count, cbWritten); + nBytes := Min( nBytes, count); + end; +end; + + +function TPipeStreamBase.ReadDirect( const pBuf : Pointer; const buflen : Integer; offset: Integer; count: Integer): Integer; +var cbRead, dwErr, nRemaining : DWORD; bytes, retries : LongInt; bOk : Boolean; + pData : PByte; const INTERVAL = 10; // ms begin if not IsOpen @@ -373,81 +434,68 @@ begin end; end; - // read the data (or block INFINITE-ly) - bOk := ReadFile( FPipe, buffer[offset], count, cbRead, nil); - if (not bOk) and (GetLastError() <> ERROR_MORE_DATA) - then result := 0 // No more data, possibly because client disconnected. - else result := cbRead; -end; + result := 0; + nRemaining := count; + pData := pBuf; + Inc( pData, offset); + while nRemaining > 0 do begin + // read the data (or block INFINITE-ly) + bOk := ReadFile( FPipe, pData^, nRemaining, cbRead, nil); + if (not bOk) and (GetLastError() <> ERROR_MORE_DATA) + then Break; // No more data, possibly because client disconnected. - -procedure TPipeStreamBase.WriteOverlapped(const buffer: TBytes; offset, count: Integer); -var cbWritten, dwWait, dwError : DWORD; - overlapped : IOverlappedHelper; -begin - if not IsOpen - then raise TTransportExceptionNotOpen.Create('Called write on non-open pipe'); - - overlapped := TOverlappedHelperImpl.Create; - - if not WriteFile( FPipe, buffer[offset], count, cbWritten, overlapped.OverlappedPtr) - then begin - dwError := GetLastError; - case dwError of - ERROR_IO_PENDING : begin - dwWait := overlapped.WaitFor(FTimeout); - - if (dwWait = WAIT_TIMEOUT) - then raise TTransportExceptionTimedOut.Create('Pipe write timed out'); - - if (dwWait <> WAIT_OBJECT_0) - or not GetOverlappedResult( FPipe, overlapped.Overlapped, cbWritten, TRUE) - then raise TTransportExceptionUnknown.Create('Pipe write error'); - end; - - else - raise TTransportExceptionUnknown.Create(SysErrorMessage(dwError)); - end; + Dec( nRemaining, cbRead); + Inc( pData, cbRead); + Inc( result, cbRead); end; - - ASSERT( DWORD(count) = cbWritten); end; -function TPipeStreamBase.ReadOverlapped( var buffer: TBytes; offset, count: Integer): Integer; -var cbRead, dwWait, dwError : DWORD; +function TPipeStreamBase.ReadOverlapped( const pBuf : Pointer; const buflen : Integer; offset: Integer; count: Integer): Integer; +var cbRead, dwWait, dwError, nRemaining : DWORD; bOk : Boolean; overlapped : IOverlappedHelper; + pData : PByte; begin if not IsOpen then raise TTransportExceptionNotOpen.Create('Called read on non-open pipe'); - overlapped := TOverlappedHelperImpl.Create; + result := 0; + nRemaining := count; + pData := pBuf; + Inc( pData, offset); + while nRemaining > 0 do begin + overlapped := TOverlappedHelperImpl.Create; - // read the data - bOk := ReadFile( FPipe, buffer[offset], count, cbRead, overlapped.OverlappedPtr); - if not bOk then begin - dwError := GetLastError; - case dwError of - ERROR_IO_PENDING : begin - dwWait := overlapped.WaitFor(FTimeout); + // read the data + bOk := ReadFile( FPipe, pData^, nRemaining, cbRead, overlapped.OverlappedPtr); + if not bOk then begin + dwError := GetLastError; + case dwError of + ERROR_IO_PENDING : begin + dwWait := overlapped.WaitFor(FTimeout); - if (dwWait = WAIT_TIMEOUT) - then raise TTransportExceptionTimedOut.Create('Pipe read timed out'); + if (dwWait = WAIT_TIMEOUT) then begin + CancelIo( FPipe); // prevents possible AV on invalid overlapped ptr + raise TTransportExceptionTimedOut.Create('Pipe read timed out'); + end; - if (dwWait <> WAIT_OBJECT_0) - or not GetOverlappedResult( FPipe, overlapped.Overlapped, cbRead, TRUE) - then raise TTransportExceptionUnknown.Create('Pipe read error'); + if (dwWait <> WAIT_OBJECT_0) + or not GetOverlappedResult( FPipe, overlapped.Overlapped, cbRead, TRUE) + then raise TTransportExceptionUnknown.Create('Pipe read error'); + end; + + else + raise TTransportExceptionUnknown.Create(SysErrorMessage(dwError)); end; - - else - raise TTransportExceptionUnknown.Create(SysErrorMessage(dwError)); end; - end; - ASSERT( cbRead > 0); // see TTransportImpl.ReadAll() - ASSERT( cbRead = DWORD(count)); - result := cbRead; + ASSERT( cbRead > 0); // see TTransportImpl.ReadAll() + ASSERT( cbRead <= DWORD(nRemaining)); + Dec( nRemaining, cbRead); + Inc( pData, cbRead); + Inc( result, cbRead); + end; end; @@ -768,8 +816,6 @@ var sd : PSECURITY_DESCRIPTOR; sa : SECURITY_ATTRIBUTES; //TSecurityAttributes; hCAR, hPipeW, hCAW, hPipe : THandle; begin - result := FALSE; - sd := PSECURITY_DESCRIPTOR( LocalAlloc( LPTR,SECURITY_DESCRIPTOR_MIN_LENGTH)); try Win32Check( InitializeSecurityDescriptor( sd, SECURITY_DESCRIPTOR_REVISION)); @@ -779,12 +825,14 @@ begin sa.lpSecurityDescriptor := sd; sa.bInheritHandle := TRUE; //allow passing handle to child - if not CreatePipe( hCAR, hPipeW, @sa, FBufSize) then begin //create stdin pipe + Result := CreatePipe( hCAR, hPipeW, @sa, FBufSize); //create stdin pipe + if not Result then begin //create stdin pipe raise TTransportExceptionNotOpen.Create('TServerPipe CreatePipe (anon) failed, '+SysErrorMessage(GetLastError)); Exit; end; - if not CreatePipe( hPipe, hCAW, @sa, FBufSize) then begin //create stdout pipe + Result := CreatePipe( hPipe, hCAW, @sa, FBufSize); //create stdout pipe + if not Result then begin //create stdout pipe CloseHandle( hCAR); CloseHandle( hPipeW); raise TTransportExceptionNotOpen.Create('TServerPipe CreatePipe (anon) failed, '+SysErrorMessage(GetLastError)); @@ -795,9 +843,6 @@ begin FClientAnonWrite := hCAW; FReadHandle := hPipe; FWriteHandle := hPipeW; - - result := TRUE; - finally if sd <> nil then LocalFree( Cardinal(sd)); end; @@ -835,8 +880,10 @@ begin CreateNamedPipe; while not FConnected do begin - if QueryStopServer - then Abort; + if QueryStopServer then begin + InternalClose; + Abort; + end; if Assigned(fnAccepting) then fnAccepting(); diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Transport.pas b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Transport.pas index 5dfb14e..dad9ab7 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Transport.pas +++ b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Transport.pas @@ -39,21 +39,26 @@ uses {$ENDIF} {$ENDIF} Thrift.Collections, + Thrift.Exception, Thrift.Utils, Thrift.Stream; type ITransport = interface - ['{A4A9FC37-D620-44DC-AD21-662D16364CE4}'] + ['{DB84961E-8BB3-4532-99E1-A8C7AC2300F7}'] function GetIsOpen: Boolean; property IsOpen: Boolean read GetIsOpen; function Peek: Boolean; procedure Open; procedure Close; - function Read(var buf: TBytes; off: Integer; len: Integer): Integer; - function ReadAll(var buf: TBytes; off: Integer; len: Integer): Integer; + function Read(var buf: TBytes; off: Integer; len: Integer): Integer; overload; + function Read(const pBuf : Pointer; const buflen : Integer; off: Integer; len: Integer): Integer; overload; + function ReadAll(var buf: TBytes; off: Integer; len: Integer): Integer; overload; + function ReadAll(const pBuf : Pointer; const buflen : Integer; off: Integer; len: Integer): Integer; overload; procedure Write( const buf: TBytes); overload; procedure Write( const buf: TBytes; off: Integer; len: Integer); overload; + procedure Write( const pBuf : Pointer; off, len : Integer); overload; + procedure Write( const pBuf : Pointer; len : Integer); overload; procedure Flush; end; @@ -64,14 +69,18 @@ type function Peek: Boolean; virtual; procedure Open(); virtual; abstract; procedure Close(); virtual; abstract; - function Read(var buf: TBytes; off: Integer; len: Integer): Integer; virtual; abstract; - function ReadAll(var buf: TBytes; off: Integer; len: Integer): Integer; virtual; - procedure Write( const buf: TBytes); overload; virtual; - procedure Write( const buf: TBytes; off: Integer; len: Integer); overload; virtual; abstract; + function Read(var buf: TBytes; off: Integer; len: Integer): Integer; overload; inline; + function Read(const pBuf : Pointer; const buflen : Integer; off: Integer; len: Integer): Integer; overload; virtual; abstract; + function ReadAll(var buf: TBytes; off: Integer; len: Integer): Integer; overload; inline; + function ReadAll(const pBuf : Pointer; const buflen : Integer; off: Integer; len: Integer): Integer; overload; virtual; + procedure Write( const buf: TBytes); overload; inline; + procedure Write( const buf: TBytes; off: Integer; len: Integer); overload; inline; + procedure Write( const pBuf : Pointer; len : Integer); overload; inline; + procedure Write( const pBuf : Pointer; off, len : Integer); overload; virtual; abstract; procedure Flush; virtual; end; - TTransportException = class( Exception ) + TTransportException = class( TException) public type TExceptionType = ( @@ -109,14 +118,21 @@ type TTransportExceptionInterrupted = class (TTransportExceptionSpecialized); IHTTPClient = interface( ITransport ) - ['{0F5DB8AB-710D-4338-AAC9-46B5734C5057}'] + ['{BA142D12-8AE6-4B50-9E33-6B7843B21D73}'] + procedure SetDnsResolveTimeout(const Value: Integer); + function GetDnsResolveTimeout: Integer; procedure SetConnectionTimeout(const Value: Integer); function GetConnectionTimeout: Integer; + procedure SetSendTimeout(const Value: Integer); + function GetSendTimeout: Integer; procedure SetReadTimeout(const Value: Integer); function GetReadTimeout: Integer; function GetCustomHeaders: IThriftDictionary; procedure SendRequest; + + property DnsResolveTimeout: Integer read GetDnsResolveTimeout write SetDnsResolveTimeout; property ConnectionTimeout: Integer read GetConnectionTimeout write SetConnectionTimeout; + property SendTimeout: Integer read GetSendTimeout write SetSendTimeout; property ReadTimeout: Integer read GetReadTimeout write SetReadTimeout; property CustomHeaders: IThriftDictionary read GetCustomHeaders; end; @@ -126,7 +142,9 @@ type FUri : string; FInputStream : IThriftStream; FOutputStream : IThriftStream; + FDnsResolveTimeout : Integer; FConnectionTimeout : Integer; + FSendTimeout : Integer; FReadTimeout : Integer; FCustomHeaders : IThriftDictionary; @@ -135,17 +153,24 @@ type function GetIsOpen: Boolean; override; procedure Open(); override; procedure Close(); override; - function Read( var buf: TBytes; off: Integer; len: Integer): Integer; override; - procedure Write( const buf: TBytes; off: Integer; len: Integer); override; + function Read( const pBuf : Pointer; const buflen : Integer; off: Integer; len: Integer): Integer; override; + procedure Write( const pBuf : Pointer; off, len : Integer); override; procedure Flush; override; + procedure SetDnsResolveTimeout(const Value: Integer); + function GetDnsResolveTimeout: Integer; procedure SetConnectionTimeout(const Value: Integer); function GetConnectionTimeout: Integer; + procedure SetSendTimeout(const Value: Integer); + function GetSendTimeout: Integer; procedure SetReadTimeout(const Value: Integer); function GetReadTimeout: Integer; + function GetCustomHeaders: IThriftDictionary; procedure SendRequest; + property DnsResolveTimeout: Integer read GetDnsResolveTimeout write SetDnsResolveTimeout; property ConnectionTimeout: Integer read GetConnectionTimeout write SetConnectionTimeout; + property SendTimeout: Integer read GetSendTimeout write SetSendTimeout; property ReadTimeout: Integer read GetReadTimeout write SetReadTimeout; property CustomHeaders: IThriftDictionary read GetCustomHeaders; public @@ -193,8 +218,8 @@ type SLEEP_TIME = 200; {$ENDIF} protected - procedure Write( const buffer: TBytes; offset: Integer; count: Integer); override; - function Read( var buffer: TBytes; offset: Integer; count: Integer): Integer; override; + procedure Write( const pBuf : Pointer; offset, count: Integer); override; + function Read( const pBuf : Pointer; const buflen : Integer; offset: Integer; count: Integer): Integer; override; procedure Open; override; procedure Close; override; procedure Flush; override; @@ -233,8 +258,8 @@ type procedure Open; override; procedure Close; override; procedure Flush; override; - function Read(var buf: TBytes; off: Integer; len: Integer): Integer; override; - procedure Write( const buf: TBytes; off: Integer; len: Integer); override; + function Read( const pBuf : Pointer; const buflen : Integer; off: Integer; len: Integer): Integer; override; + procedure Write( const pBuf : Pointer; off, len : Integer); override; constructor Create( const AInputStream : IThriftStream; const AOutputStream : IThriftStream); destructor Destroy; override; end; @@ -246,8 +271,8 @@ type FReadBuffer : TMemoryStream; FWriteBuffer : TMemoryStream; protected - procedure Write( const buffer: TBytes; offset: Integer; count: Integer); override; - function Read( var buffer: TBytes; offset: Integer; count: Integer): Integer; override; + procedure Write( const pBuf : Pointer; offset: Integer; count: Integer); override; + function Read( const pBuf : Pointer; const buflen : Integer; offset: Integer; count: Integer): Integer; override; procedure Open; override; procedure Close; override; procedure Flush; override; @@ -299,8 +324,8 @@ type public procedure Open(); override; procedure Close(); override; - function Read(var buf: TBytes; off: Integer; len: Integer): Integer; override; - procedure Write( const buf: TBytes; off: Integer; len: Integer); override; + function Read( const pBuf : Pointer; const buflen : Integer; off: Integer; len: Integer): Integer; override; + procedure Write( const pBuf : Pointer; off, len : Integer); override; constructor Create( const ATransport : IStreamTransport ); overload; constructor Create( const ATransport : IStreamTransport; ABufSize: Integer); overload; property UnderlyingTransport: ITransport read GetUnderlyingTransport; @@ -377,8 +402,8 @@ type function GetIsOpen: Boolean; override; procedure Close(); override; - function Read(var buf: TBytes; off: Integer; len: Integer): Integer; override; - procedure Write( const buf: TBytes; off: Integer; len: Integer); override; + function Read( const pBuf : Pointer; const buflen : Integer; off: Integer; len: Integer): Integer; override; + procedure Write( const pBuf : Pointer; off, len : Integer); override; procedure Flush; override; end; @@ -404,38 +429,62 @@ begin Result := IsOpen; end; -function TTransportImpl.ReadAll( var buf: TBytes; off, len: Integer): Integer; -var - got : Integer; - ret : Integer; +function TTransportImpl.Read(var buf: TBytes; off: Integer; len: Integer): Integer; begin - got := 0; - while got < len do begin - ret := Read( buf, off + got, len - got); - if ret > 0 - then Inc( got, ret) - else raise TTransportExceptionNotOpen.Create( 'Cannot read, Remote side has closed' ); - end; - Result := got; + if Length(buf) > 0 + then result := Read( @buf[0], Length(buf), off, len) + else result := 0; +end; + +function TTransportImpl.ReadAll(var buf: TBytes; off: Integer; len: Integer): Integer; +begin + if Length(buf) > 0 + then result := ReadAll( @buf[0], Length(buf), off, len) + else result := 0; end; procedure TTransportImpl.Write( const buf: TBytes); begin - Self.Write( buf, 0, Length(buf) ); + if Length(buf) > 0 + then Write( @buf[0], 0, Length(buf)); +end; + +procedure TTransportImpl.Write( const buf: TBytes; off: Integer; len: Integer); +begin + if Length(buf) > 0 + then Write( @buf[0], off, len); +end; + +function TTransportImpl.ReadAll(const pBuf : Pointer; const buflen : Integer; off: Integer; len: Integer): Integer; +var ret : Integer; +begin + result := 0; + while result < len do begin + ret := Read( pBuf, buflen, off + result, len - result); + if ret > 0 + then Inc( result, ret) + else raise TTransportExceptionNotOpen.Create( 'Cannot read, Remote side has closed' ); + end; +end; + +procedure TTransportImpl.Write( const pBuf : Pointer; len : Integer); +begin + Self.Write( pBuf, 0, len); end; { THTTPClientImpl } -procedure THTTPClientImpl.Close; -begin - FInputStream := nil; - FOutputStream := nil; -end; - constructor THTTPClientImpl.Create(const AUri: string); begin inherited Create; FUri := AUri; + + // defaults according to MSDN + FDnsResolveTimeout := 0; // no timeout + FConnectionTimeout := 60 * 1000; + FSendTimeout := 30 * 1000; + FReadTimeout := 30 * 1000; + FCustomHeaders := TThriftDictionaryImpl.Create; FOutputStream := TThriftStreamAdapterDelphi.Create( TMemoryStream.Create, True); end; @@ -443,13 +492,18 @@ end; function THTTPClientImpl.CreateRequest: IXMLHTTPRequest; var pair : TPair; + srvHttp : IServerXMLHTTPRequest; begin {$IF CompilerVersion >= 21.0} - Result := CoXMLHTTP.Create; + Result := CoServerXMLHTTP.Create; {$ELSE} Result := CoXMLHTTPRequest.Create; {$IFEND} + // setting a timeout value to 0 (zero) means "no timeout" for that setting + if Supports( result, IServerXMLHTTPRequest, srvHttp) + then srvHttp.setTimeouts( DnsResolveTimeout, ConnectionTimeout, SendTimeout, ReadTimeout); + Result.open('POST', FUri, False, '', ''); Result.setRequestHeader( 'Content-Type', 'application/x-thrift'); Result.setRequestHeader( 'Accept', 'application/x-thrift'); @@ -466,14 +520,14 @@ begin inherited; end; -procedure THTTPClientImpl.Flush; +function THTTPClientImpl.GetDnsResolveTimeout: Integer; begin - try - SendRequest; - finally - FOutputStream := nil; - FOutputStream := TThriftStreamAdapterDelphi.Create( TMemoryStream.Create, True); - end; + Result := FDnsResolveTimeout; +end; + +procedure THTTPClientImpl.SetDnsResolveTimeout(const Value: Integer); +begin + FDnsResolveTimeout := Value; end; function THTTPClientImpl.GetConnectionTimeout: Integer; @@ -481,6 +535,31 @@ begin Result := FConnectionTimeout; end; +procedure THTTPClientImpl.SetConnectionTimeout(const Value: Integer); +begin + FConnectionTimeout := Value; +end; + +function THTTPClientImpl.GetSendTimeout: Integer; +begin + Result := FSendTimeout; +end; + +procedure THTTPClientImpl.SetSendTimeout(const Value: Integer); +begin + FSendTimeout := Value; +end; + +function THTTPClientImpl.GetReadTimeout: Integer; +begin + Result := FReadTimeout; +end; + +procedure THTTPClientImpl.SetReadTimeout(const Value: Integer); +begin + FReadTimeout := Value; +end; + function THTTPClientImpl.GetCustomHeaders: IThriftDictionary; begin Result := FCustomHeaders; @@ -491,24 +570,36 @@ begin Result := True; end; -function THTTPClientImpl.GetReadTimeout: Integer; -begin - Result := FReadTimeout; -end; - procedure THTTPClientImpl.Open; begin - // nothing to do + FOutputStream := TThriftStreamAdapterDelphi.Create( TMemoryStream.Create, True); end; -function THTTPClientImpl.Read( var buf: TBytes; off, len: Integer): Integer; +procedure THTTPClientImpl.Close; +begin + FInputStream := nil; + FOutputStream := nil; +end; + +procedure THTTPClientImpl.Flush; +begin + try + SendRequest; + finally + FOutputStream := nil; + FOutputStream := TThriftStreamAdapterDelphi.Create( TMemoryStream.Create, True); + ASSERT( FOutputStream <> nil); + end; +end; + +function THTTPClientImpl.Read( const pBuf : Pointer; const buflen : Integer; off: Integer; len: Integer): Integer; begin if FInputStream = nil then begin raise TTransportExceptionNotOpen.Create('No request has been sent'); end; try - Result := FInputStream.Read( buf, off, len ) + Result := FInputStream.Read( pBuf, buflen, off, len) except on E: Exception do raise TTransportExceptionUnknown.Create(E.Message); @@ -540,19 +631,9 @@ begin end; end; -procedure THTTPClientImpl.SetConnectionTimeout(const Value: Integer); +procedure THTTPClientImpl.Write( const pBuf : Pointer; off, len : Integer); begin - FConnectionTimeout := Value; -end; - -procedure THTTPClientImpl.SetReadTimeout(const Value: Integer); -begin - FReadTimeout := Value -end; - -procedure THTTPClientImpl.Write( const buf: TBytes; off, len: Integer); -begin - FOutputStream.Write( buf, off, len); + FOutputStream.Write( pBuf, off, len); end; { TTransportException } @@ -811,8 +892,13 @@ end; procedure TSocketImpl.Close; begin inherited Close; + + FInputStream := nil; + FOutputStream := nil; + if FOwnsClient - then FreeAndNil( FClient); + then FreeAndNil( FClient) + else FClient := nil; end; function TSocketImpl.GetIsOpen: Boolean; @@ -923,22 +1009,24 @@ function TBufferedStreamImpl.IsOpen: Boolean; begin Result := (FWriteBuffer <> nil) and (FReadBuffer <> nil) - and (FStream <> nil); + and (FStream <> nil) + and FStream.IsOpen; end; procedure TBufferedStreamImpl.Open; begin - // nothing to do + FStream.Open; end; -function TBufferedStreamImpl.Read( var buffer: TBytes; offset: Integer; count: Integer): Integer; +function TBufferedStreamImpl.Read( const pBuf : Pointer; const buflen : Integer; offset: Integer; count: Integer): Integer; var nRead : Integer; tempbuf : TBytes; + pTmp : PByte; begin inherited; Result := 0; - + if IsOpen then begin while count > 0 do begin @@ -953,8 +1041,10 @@ begin end; if FReadBuffer.Position < FReadBuffer.Size then begin - nRead := Min( FReadBuffer.Size - FReadBuffer.Position, count); - Inc( Result, FReadBuffer.Read( Pointer(@buffer[offset])^, nRead)); + nRead := Min( FReadBuffer.Size - FReadBuffer.Position, count); + pTmp := pBuf; + Inc( pTmp, offset); + Inc( Result, FReadBuffer.Read( pTmp^, nRead)); Dec( count, nRead); Inc( offset, nRead); end; @@ -979,12 +1069,15 @@ begin end; end; -procedure TBufferedStreamImpl.Write( const buffer: TBytes; offset: Integer; count: Integer); +procedure TBufferedStreamImpl.Write( const pBuf : Pointer; offset: Integer; count: Integer); +var pTmp : PByte; begin inherited; if count > 0 then begin if IsOpen then begin - FWriteBuffer.Write( Pointer(@buffer[offset])^, count ); + pTmp := pBuf; + Inc( pTmp, offset); + FWriteBuffer.Write( pTmp^, count ); if FWriteBuffer.Size > FBufSize then begin Flush; end; @@ -994,12 +1087,6 @@ end; { TStreamTransportImpl } -procedure TStreamTransportImpl.Close; -begin - FInputStream := nil; - FOutputStream := nil; -end; - constructor TStreamTransportImpl.Create( const AInputStream : IThriftStream; const AOutputStream : IThriftStream); begin inherited Create; @@ -1014,6 +1101,12 @@ begin inherited; end; +procedure TStreamTransportImpl.Close; +begin + FInputStream := nil; + FOutputStream := nil; +end; + procedure TStreamTransportImpl.Flush; begin if FOutputStream = nil then begin @@ -1035,7 +1128,7 @@ end; function TStreamTransportImpl.GetOutputStream: IThriftStream; begin - Result := FInputStream; + Result := FOutputStream; end; procedure TStreamTransportImpl.Open; @@ -1043,22 +1136,22 @@ begin end; -function TStreamTransportImpl.Read(var buf: TBytes; off, len: Integer): Integer; +function TStreamTransportImpl.Read( const pBuf : Pointer; const buflen : Integer; off: Integer; len: Integer): Integer; begin if FInputStream = nil then begin raise TTransportExceptionNotOpen.Create('Cannot read from null inputstream' ); end; - Result := FInputStream.Read( buf, off, len ); + Result := FInputStream.Read( pBuf,buflen, off, len ); end; -procedure TStreamTransportImpl.Write(const buf: TBytes; off, len: Integer); +procedure TStreamTransportImpl.Write( const pBuf : Pointer; off, len : Integer); begin if FOutputStream = nil then begin raise TTransportExceptionNotOpen.Create('Cannot write to null outputstream' ); end; - FOutputStream.Write( buf, off, len ); + FOutputStream.Write( pBuf, off, len ); end; { TBufferedTransportImpl } @@ -1069,11 +1162,6 @@ begin Create( ATransport, 1024 ); end; -procedure TBufferedTransportImpl.Close; -begin - FTransport.Close; -end; - constructor TBufferedTransportImpl.Create( const ATransport: IStreamTransport; ABufSize: Integer); begin inherited Create; @@ -1082,6 +1170,13 @@ begin InitBuffers; end; +procedure TBufferedTransportImpl.Close; +begin + FTransport.Close; + FInputBuffer := nil; + FOutputBuffer := nil; +end; + procedure TBufferedTransportImpl.Flush; begin if FOutputBuffer <> nil then begin @@ -1111,21 +1206,22 @@ end; procedure TBufferedTransportImpl.Open; begin - FTransport.Open + FTransport.Open; + InitBuffers; // we need to get the buffers to match FTransport substreams again end; -function TBufferedTransportImpl.Read(var buf: TBytes; off, len: Integer): Integer; +function TBufferedTransportImpl.Read( const pBuf : Pointer; const buflen : Integer; off: Integer; len: Integer): Integer; begin Result := 0; if FInputBuffer <> nil then begin - Result := FInputBuffer.Read( buf, off, len ); + Result := FInputBuffer.Read( pBuf,buflen, off, len ); end; end; -procedure TBufferedTransportImpl.Write(const buf: TBytes; off, len: Integer); +procedure TBufferedTransportImpl.Write( const pBuf : Pointer; off, len : Integer); begin if FOutputBuffer <> nil then begin - FOutputBuffer.Write( buf, off, len ); + FOutputBuffer.Write( pBuf, off, len ); end; end; @@ -1222,24 +1318,25 @@ begin FTransport.Open; end; -function TFramedTransportImpl.Read(var buf: TBytes; off, len: Integer): Integer; -var - got : Integer; +function TFramedTransportImpl.Read( const pBuf : Pointer; const buflen : Integer; off: Integer; len: Integer): Integer; +var pTmp : PByte; begin - if FReadBuffer <> nil then begin - if len > 0 - then got := FReadBuffer.Read( Pointer(@buf[off])^, len ) - else got := 0; - - if got > 0 then begin - Result := got; + if len > (buflen-off) + then len := buflen-off; + + pTmp := pBuf; + Inc( pTmp, off); + + if (FReadBuffer <> nil) and (len > 0) then begin + result := FReadBuffer.Read( pTmp^, len); + if result > 0 then begin Exit; end; end; ReadFrame; if len > 0 - then Result := FReadBuffer.Read( Pointer(@buf[off])^, len) + then Result := FReadBuffer.Read( pTmp^, len) else Result := 0; end; @@ -1260,14 +1357,20 @@ begin FTransport.ReadAll( buff, 0, size ); FReadBuffer.Free; FReadBuffer := TMemoryStream.Create; - FReadBuffer.Write( Pointer(@buff[0])^, size ); + if Length(buff) > 0 + then FReadBuffer.Write( Pointer(@buff[0])^, size ); FReadBuffer.Position := 0; end; -procedure TFramedTransportImpl.Write(const buf: TBytes; off, len: Integer); +procedure TFramedTransportImpl.Write( const pBuf : Pointer; off, len : Integer); +var pTmp : PByte; begin - if len > 0 - then FWriteBuffer.Write( Pointer(@buf[off])^, len ); + if len > 0 then begin + pTmp := pBuf; + Inc( pTmp, off); + + FWriteBuffer.Write( pTmp^, len ); + end; end; { TFramedTransport.TFactory } @@ -1447,13 +1550,13 @@ end; {$ENDIF} {$IFDEF OLD_SOCKETS} -function TTcpSocketStreamImpl.Read(var buffer: TBytes; offset, count: Integer): Integer; +function TTcpSocketStreamImpl.Read( const pBuf : Pointer; const buflen : Integer; offset: Integer; count: Integer): Integer; // old sockets version var wfd : TWaitForData; wsaError, msecs : Integer; nBytes : Integer; - pDest : PByte; + pTmp : PByte; begin inherited; @@ -1462,11 +1565,12 @@ begin else msecs := DEFAULT_THRIFT_TIMEOUT; result := 0; - pDest := Pointer(@buffer[offset]); + pTmp := pBuf; + Inc( pTmp, offset); while count > 0 do begin while TRUE do begin - wfd := WaitForData( msecs, pDest, count, wsaError, nBytes); + wfd := WaitForData( msecs, pTmp, count, wsaError, nBytes); case wfd of TWaitForData.wfd_Error : Exit; TWaitForData.wfd_HaveData : Break; @@ -1490,8 +1594,8 @@ begin msecs := Max( msecs, 200); ASSERT( nBytes <= count); - nBytes := FTcpClient.ReceiveBuf( pDest^, nBytes); - Inc( pDest, nBytes); + nBytes := FTcpClient.ReceiveBuf( pTmp^, nBytes); + Inc( pTmp, nBytes); Dec( count, nBytes); Inc( result, nBytes); end; @@ -1513,10 +1617,11 @@ begin end; end; -procedure TTcpSocketStreamImpl.Write(const buffer: TBytes; offset, count: Integer); +procedure TTcpSocketStreamImpl.Write( const pBuf : Pointer; offset, count: Integer); // old sockets version var bCanWrite, bError : Boolean; retval, wsaError : Integer; + pTmp : PByte; begin inherited; @@ -1537,24 +1642,27 @@ begin if bError or not bCanWrite then raise TTransportExceptionUnknown.Create('unknown error'); - FTcpClient.SendBuf( Pointer(@buffer[offset])^, count); + pTmp := pBuf; + Inc( pTmp, offset); + FTcpClient.SendBuf( pTmp^, count); end; {$ELSE} -function TTcpSocketStreamImpl.Read(var buffer: TBytes; offset, count: Integer): Integer; +function TTcpSocketStreamImpl.Read( const pBuf : Pointer; const buflen : Integer; offset: Integer; count: Integer): Integer; // new sockets version var nBytes : Integer; - pDest : PByte; + pTmp : PByte; begin inherited; result := 0; - pDest := Pointer(@buffer[offset]); + pTmp := pBuf; + Inc( pTmp, offset); while count > 0 do begin - nBytes := FTcpClient.Read(pDest^, count); + nBytes := FTcpClient.Read( pTmp^, count); if nBytes = 0 then Exit; - Inc( pDest, nBytes); + Inc( pTmp, nBytes); Dec( count, nBytes); Inc( result, nBytes); end; @@ -1579,15 +1687,18 @@ begin SetLength(Result, Length(Result) - 1024 + len); end; -procedure TTcpSocketStreamImpl.Write(const buffer: TBytes; offset, count: Integer); +procedure TTcpSocketStreamImpl.Write( const pBuf : Pointer; offset, count: Integer); // new sockets version +var pTmp : PByte; begin inherited; if not FTcpClient.IsOpen then raise TTransportExceptionNotOpen.Create('not open'); - FTcpClient.Write(buffer[offset], count); + pTmp := pBuf; + Inc( pTmp, offset); + FTcpClient.Write( pTmp^, count); end; {$ENDIF} diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Utils.pas b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Utils.pas index a0bf144..7e57863 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Utils.pas +++ b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Utils.pas @@ -69,8 +69,9 @@ type end; -function InterlockedCompareExchange64( var Target : Int64; Exchange, Comparand : Int64) : Int64; stdcall; -function InterlockedExchangeAdd64( var Addend : Int64; Value : Int64) : Int64; stdcall; +{$IFDEF Win64} +function InterlockedExchangeAdd64( var Addend : Int64; Value : Int64) : Int64; +{$ENDIF} implementation @@ -205,8 +206,12 @@ end; class function CharUtils.IsHighSurrogate( const c : Char) : Boolean; begin - {$IF CompilerVersion < 23.0} - result := Character.IsHighSurrogate( c); + {$IF CompilerVersion < 25.0} + {$IFDEF OLD_UNIT_NAMES} + result := Character.IsHighSurrogate(c); + {$ELSE} + result := System.Character.IsHighSurrogate(c); + {$ENDIF} {$ELSE} result := c.IsHighSurrogate(); {$IFEND} @@ -215,22 +220,31 @@ end; class function CharUtils.IsLowSurrogate( const c : Char) : Boolean; begin - {$IF CompilerVersion < 23.0} - result := Character.IsLowSurrogate( c); + {$IF CompilerVersion < 25.0} + {$IFDEF OLD_UNIT_NAMES} + result := Character.IsLowSurrogate(c); + {$ELSE} + result := System.Character.IsLowSurrogate(c); + {$ENDIF} {$ELSE} - result := c.IsLowSurrogate; + result := c.IsLowSurrogate(); {$IFEND} end; -// natively available since stone age -function InterlockedCompareExchange64; -external KERNEL32 name 'InterlockedCompareExchange64'; +{$IFDEF Win64} + +function InterlockedCompareExchange64( var Target : Int64; Exchange, Comparand : Int64) : Int64; inline; +begin + {$IFDEF OLD_UNIT_NAMES} + result := Windows.InterlockedCompareExchange64( Target, Exchange, Comparand); + {$ELSE} + result := WinApi.Windows.InterlockedCompareExchange64( Target, Exchange, Comparand); + {$ENDIF} +end; -// natively available >= Vista -// implemented this way since there are still some people running Windows XP :-( -function InterlockedExchangeAdd64( var Addend : Int64; Value : Int64) : Int64; stdcall; +function InterlockedExchangeAdd64( var Addend : Int64; Value : Int64) : Int64; var old : Int64; begin repeat @@ -239,6 +253,7 @@ begin result := Old; end; +{$ENDIF} end. diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.pas b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.pas index fe8f8d7..8293d07 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.pas +++ b/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.pas @@ -22,15 +22,19 @@ unit Thrift; interface uses - SysUtils, Thrift.Protocol; + SysUtils, + Thrift.Exception, + Thrift.Protocol; const - Version = '0.10.0'; + Version = '0.12.0'; type + TException = Thrift.Exception.TException; // compatibility alias + TApplicationExceptionSpecializedClass = class of TApplicationExceptionSpecialized; - TApplicationException = class( SysUtils.Exception ) + TApplicationException = class( TException) public type {$SCOPEDENUMS ON} @@ -83,31 +87,9 @@ type TApplicationExceptionInvalidProtocol = class (TApplicationExceptionSpecialized); TApplicationExceptionUnsupportedClientType = class (TApplicationExceptionSpecialized); - // base class for IDL-generated exceptions - TException = class( SysUtils.Exception) - public - function Message : string; // hide inherited property: allow read, but prevent accidental writes - procedure UpdateMessageProperty; // update inherited message property with toString() - end; implementation -{ TException } - -function TException.Message; -// allow read (exception summary), but prevent accidental writes -// read will return the exception summary -begin - result := Self.ToString; -end; - -procedure TException.UpdateMessageProperty; -// Update the inherited Message property to better conform to standard behaviour. -// Nice benefit: The IDE is now able to show the exception message again. -begin - inherited Message := Self.ToString; // produces a summary text -end; - { TApplicationException } function TApplicationException.GetType: TExceptionType; @@ -172,10 +154,10 @@ end; class function TApplicationException.Read( const iprot: IProtocol): TApplicationException; var - field : IField; + field : TThriftField; msg : string; typ : TExceptionType; - struc : IStruct; + struc : TThriftStruct; begin msg := ''; typ := TExceptionType.Unknown; @@ -220,12 +202,11 @@ end; procedure TApplicationException.Write( const oprot: IProtocol); var - struc : IStruct; - field : IField; - + struc : TThriftStruct; + field : TThriftField; begin - struc := TStructImpl.Create( 'TApplicationException' ); - field := TFieldImpl.Create; + Init(struc, 'TApplicationException'); + Init(field); oprot.WriteStructBegin( struc ); if Message <> '' then diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Console.pas b/vendor/git.apache.org/thrift.git/lib/delphi/test/ConsoleHelper.pas similarity index 96% rename from vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Console.pas rename to vendor/git.apache.org/thrift.git/lib/delphi/test/ConsoleHelper.pas index 1dbb309..0a8ddcf 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/src/Thrift.Console.pas +++ b/vendor/git.apache.org/thrift.git/lib/delphi/test/ConsoleHelper.pas @@ -17,7 +17,7 @@ * under the License. *) -unit Thrift.Console; +unit ConsoleHelper; interface @@ -99,10 +99,9 @@ begin begin idx := FMemo.Count - 1; if idx < 0 then - begin - FMemo.Add( S ); - end; - FMemo[idx] := FMemo[idx] + S; + FMemo.Add( S ) + else + FMemo[idx] := FMemo[idx] + S; end; FLineBreak := bWriteLine; end; diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/test/TestClient.pas b/vendor/git.apache.org/thrift.git/lib/delphi/test/TestClient.pas index 9f45a91..0fa43b0 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/test/TestClient.pas +++ b/vendor/git.apache.org/thrift.git/lib/delphi/test/TestClient.pas @@ -22,15 +22,22 @@ unit TestClient; {$I ../src/Thrift.Defines.inc} {.$DEFINE StressTest} // activate to stress-test the server with frequent connects/disconnects -{.$DEFINE PerfTest} // activate to activate the performance test +{.$DEFINE PerfTest} // activate the performance test +{$DEFINE Exceptions} // activate the exceptions test (or disable while debugging) + +{$if CompilerVersion >= 28} +{$DEFINE SupportsAsync} +{$ifend} interface uses - Windows, SysUtils, Classes, Math, + Windows, SysUtils, Classes, Math, ComObj, ActiveX, + {$IFDEF SupportsAsync} System.Threading, {$ENDIF} DateUtils, Generics.Collections, TestConstants, + ConsoleHelper, Thrift, Thrift.Protocol.Compact, Thrift.Protocol.JSON, @@ -39,8 +46,8 @@ uses Thrift.Transport, Thrift.Stream, Thrift.Test, - Thrift.Collections, - Thrift.Console; + Thrift.Utils, + Thrift.Collections; type TThreadConsole = class @@ -52,6 +59,17 @@ type constructor Create( AThread: TThread); end; + TTestSetup = record + protType : TKnownProtocol; + endpoint : TEndpointTransport; + layered : TLayeredTransports; + useSSL : Boolean; // include where appropriate (TLayeredTransport?) + host : string; + port : Integer; + sPipeName : string; + hAnonRead, hAnonWrite : THandle; + end; + TClientThread = class( TThread ) private type TTestGroup = ( @@ -64,7 +82,15 @@ type ); TTestGroups = set of TTestGroup; + TTestSize = ( + Empty, // Edge case: the zero-length empty binary + Normal, // Fairly small array of usual size (256 bytes) + ByteArrayTest, // THRIFT-4454 Large writes/reads may cause range check errors in debug mode + PipeWriteLimit // THRIFT-4372 Pipe write operations across a network are limited to 65,535 bytes per write. + ); + private + FSetup : TTestSetup; FTransport : ITransport; FProtocol : IProtocol; FNumIteration : Integer; @@ -83,15 +109,25 @@ type function CalculateExitCode : Byte; procedure ClientTest; + {$IFDEF SupportsAsync} + procedure ClientAsyncTest; + {$ENDIF} + + procedure InitializeProtocolTransportStack; + procedure ShutdownProtocolTransportStack; + procedure JSONProtocolReadWriteTest; - function PrepareBinaryData( aRandomDist : Boolean = FALSE) : TBytes; + function PrepareBinaryData( aRandomDist : Boolean; aSize : TTestSize) : TBytes; {$IFDEF StressTest} procedure StressTest(const client : TThriftTest.Iface); {$ENDIF} + {$IFDEF Win64} + procedure UseInterlockedExchangeAdd64; + {$ENDIF} protected procedure Execute; override; public - constructor Create( const ATransport: ITransport; const AProtocol : IProtocol; ANumIteration: Integer); + constructor Create( const aSetup : TTestSetup; const aNumIteration: Integer); destructor Destroy; override; end; @@ -172,38 +208,27 @@ end; class function TTestClient.Execute(const args: array of string) : Byte; var i : Integer; - host : string; - port : Integer; - sPipeName : string; - hAnonRead, hAnonWrite : THandle; + threadExitCode : Byte; s : string; threads : array of TThread; dtStart : TDateTime; test : Integer; thread : TThread; - trans : ITransport; - prot : IProtocol; - streamtrans : IStreamTransport; - http : IHTTPClient; - protType : TKnownProtocol; - endpoint : TEndpointTransport; - layered : TLayeredTransports; - UseSSL : Boolean; // include where appropriate (TLayeredTransport?) -const - // pipe timeouts to be used - DEBUG_TIMEOUT = 30 * 1000; - RELEASE_TIMEOUT = DEFAULT_THRIFT_TIMEOUT; - TIMEOUT = RELEASE_TIMEOUT; + setup : TTestSetup; begin - protType := prot_Binary; - endpoint := trns_Sockets; - layered := []; - UseSSL := FALSE; - host := 'localhost'; - port := 9090; - sPipeName := ''; - hAnonRead := INVALID_HANDLE_VALUE; - hAnonWrite := INVALID_HANDLE_VALUE; + // init record + with setup do begin + protType := prot_Binary; + endpoint := trns_Sockets; + layered := []; + useSSL := FALSE; + host := 'localhost'; + port := 9090; + sPipeName := ''; + hAnonRead := INVALID_HANDLE_VALUE; + hAnonWrite := INVALID_HANDLE_VALUE; + end; + try i := 0; while ( i < Length(args) ) do begin @@ -218,15 +243,15 @@ begin end else if s = '--host' then begin // --host arg (=localhost) Host to connect - host := args[i]; + setup.host := args[i]; Inc( i); end else if s = '--port' then begin // --port arg (=9090) Port number to connect s := args[i]; Inc( i); - port := StrToIntDef(s,0); - if port <= 0 then InvalidArgs; + setup.port := StrToIntDef(s,0); + if setup.port <= 0 then InvalidArgs; end else if s = '--domain-socket' then begin // --domain-socket arg Domain Socket (e.g. /tmp/ThriftTest.thrift), instead of host and port @@ -234,27 +259,29 @@ begin end else if s = '--named-pipe' then begin // --named-pipe arg Windows Named Pipe (e.g. MyThriftPipe) - endpoint := trns_NamedPipes; - sPipeName := args[i]; + setup.endpoint := trns_NamedPipes; + setup.sPipeName := args[i]; Inc( i); + Console.WriteLine('Using named pipe ('+setup.sPipeName+')'); end else if s = '--anon-pipes' then begin // --anon-pipes hRead hWrite Windows Anonymous Pipes pair (handles) - endpoint := trns_AnonPipes; - hAnonRead := THandle( StrToIntDef( args[i], Integer(INVALID_HANDLE_VALUE))); + setup.endpoint := trns_AnonPipes; + setup.hAnonRead := THandle( StrToIntDef( args[i], Integer(INVALID_HANDLE_VALUE))); Inc( i); - hAnonWrite := THandle( StrToIntDef( args[i], Integer(INVALID_HANDLE_VALUE))); + setup.hAnonWrite := THandle( StrToIntDef( args[i], Integer(INVALID_HANDLE_VALUE))); Inc( i); + Console.WriteLine('Using anonymous pipes ('+IntToStr(Integer(setup.hAnonRead))+' and '+IntToStr(Integer(setup.hAnonWrite))+')'); end else if s = '--transport' then begin // --transport arg (=sockets) Transport: buffered, framed, http, evhttp s := args[i]; Inc( i); - if s = 'buffered' then Include( layered, trns_Buffered) - else if s = 'framed' then Include( layered, trns_Framed) - else if s = 'http' then endpoint := trns_Http - else if s = 'evhttp' then endpoint := trns_AnonPipes + if s = 'buffered' then Include( setup.layered, trns_Buffered) + else if s = 'framed' then Include( setup.layered, trns_Framed) + else if s = 'http' then setup.endpoint := trns_Http + else if s = 'evhttp' then setup.endpoint := trns_EvHttp else InvalidArgs; end else if s = '--protocol' then begin @@ -262,14 +289,14 @@ begin s := args[i]; Inc( i); - if s = 'binary' then protType := prot_Binary - else if s = 'compact' then protType := prot_Compact - else if s = 'json' then protType := prot_JSON + if s = 'binary' then setup.protType := prot_Binary + else if s = 'compact' then setup.protType := prot_Compact + else if s = 'json' then setup.protType := prot_JSON else InvalidArgs; end else if s = '--ssl' then begin // --ssl Encrypted Transport using SSL - UseSSL := TRUE; + setup.useSSL := TRUE; end else if (s = '-n') or (s = '--testloops') then begin @@ -295,7 +322,7 @@ begin // In the anonymous pipes mode the client is launched by the test server // -> behave nicely and allow for attaching a debugger to this process - if (endpoint = trns_AnonPipes) and not IsDebuggerPresent + if (setup.endpoint = trns_AnonPipes) and not IsDebuggerPresent then MessageBox( 0, 'Attach Debugger and/or click OK to continue.', 'Thrift TestClient (Delphi)', MB_OK or MB_ICONEXCLAMATION); @@ -303,78 +330,30 @@ begin SetLength( threads, FNumThread); dtStart := Now; - for test := 0 to FNumThread - 1 do - begin - case endpoint of - trns_Sockets: begin - Console.WriteLine('Using sockets ('+host+' port '+IntToStr(port)+')'); - streamtrans := TSocketImpl.Create( host, port ); - end; + // layered transports are not really meant to be stacked upon each other + if (trns_Framed in setup.layered) then begin + Console.WriteLine('Using framed transport'); + end + else if (trns_Buffered in setup.layered) then begin + Console.WriteLine('Using buffered transport'); + end; - trns_Http: begin - Console.WriteLine('Using HTTPClient'); - http := THTTPClientImpl.Create( host); - trans := http; - end; + Console.WriteLine(THRIFT_PROTOCOLS[setup.protType]+' protocol'); - trns_EvHttp: begin - raise Exception.Create(ENDPOINT_TRANSPORTS[endpoint]+' transport not implemented'); - end; - - trns_NamedPipes: begin - Console.WriteLine('Using named pipe ('+sPipeName+')'); - streamtrans := TNamedPipeTransportClientEndImpl.Create( sPipeName, 0, nil, TIMEOUT, TIMEOUT); - end; - - trns_AnonPipes: begin - Console.WriteLine('Using anonymous pipes ('+IntToStr(Integer(hAnonRead))+' and '+IntToStr(Integer(hAnonWrite))+')'); - streamtrans := TAnonymousPipeTransportImpl.Create( hAnonRead, hAnonWrite, FALSE); - end; - - else - raise Exception.Create('Unhandled endpoint transport'); - end; - trans := streamtrans; - ASSERT( trans <> nil); - - if (trns_Buffered in layered) then begin - trans := TBufferedTransportImpl.Create( streamtrans, 32); // small buffer to test read() - Console.WriteLine('Using buffered transport'); - end; - - if (trns_Framed in layered) then begin - trans := TFramedTransportImpl.Create( trans ); - Console.WriteLine('Using framed transport'); - end; - - if UseSSL then begin - raise Exception.Create('SSL not implemented'); - end; - - // create protocol instance, default to BinaryProtocol - case protType of - prot_Binary : prot := TBinaryProtocolImpl.Create( trans, BINARY_STRICT_READ, BINARY_STRICT_WRITE); - prot_JSON : prot := TJSONProtocolImpl.Create( trans); - prot_Compact : prot := TCompactProtocolImpl.Create( trans); - else - raise Exception.Create('Unhandled protocol'); - end; - ASSERT( trans <> nil); - Console.WriteLine(THRIFT_PROTOCOLS[protType]+' protocol'); - - thread := TClientThread.Create( trans, prot, FNumIteration); + for test := 0 to FNumThread - 1 do begin + thread := TClientThread.Create( setup, FNumIteration); threads[test] := thread; thread.Start; end; result := 0; for test := 0 to FNumThread - 1 do begin - result := result or threads[test].WaitFor; + threadExitCode := threads[test].WaitFor; + result := result or threadExitCode; + threads[test].Free; + threads[test] := nil; end; - for test := 0 to FNumThread - 1 - do threads[test].Free; - Console.Write('Total time: ' + IntToStr( MilliSecondsBetween(Now, dtStart))); except @@ -449,7 +428,8 @@ var looney : IInsanity; first_map : IThriftDictionary; second_map : IThriftDictionary; - + pair : TPair; + testsize : TTestSize; begin client := TThriftTest.TClient.Create( FProtocol); FTransport.Open; @@ -458,6 +438,7 @@ begin StressTest( client); {$ENDIF StressTest} + {$IFDEF Exceptions} // in-depth exception test // (1) do we get an exception at all? // (2) do we get the right exception? @@ -474,7 +455,7 @@ begin Console.WriteLine( ' = ' + IntToStr(e.ErrorCode) + ', ' + e.Message_ ); end; on e:TTransportException do Expect( FALSE, 'Unexpected : "'+e.ToString+'"'); - on e:Exception do Expect( FALSE, 'Unexpected exception type "'+e.ClassName+'"'); + on e:Exception do Expect( FALSE, 'Unexpected exception "'+e.ClassName+'": '+e.Message); end; // case 2: exception type NOT declared in IDL at the function call @@ -489,8 +470,8 @@ begin on e:TApplicationException do begin Console.WriteLine( e.ClassName+' = '+e.Message); // this is what we get end; - on e:TException do Expect( FALSE, 'Unexpected exception type "'+e.ClassName+'"'); - on e:Exception do Expect( FALSE, 'Unexpected exception type "'+e.ClassName+'"'); + on e:TException do Expect( FALSE, 'Unexpected exception "'+e.ClassName+'": '+e.Message); + on e:Exception do Expect( FALSE, 'Unexpected exception "'+e.ClassName+'": '+e.Message); end; @@ -504,8 +485,9 @@ begin Expect( TRUE, 'testException(''something''): must not trow an exception'); except on e:TTransportException do Expect( FALSE, 'Unexpected : "'+e.ToString+'"'); - on e:Exception do Expect( FALSE, 'Unexpected exception "'+e.ClassName+'"'); + on e:Exception do Expect( FALSE, 'Unexpected exception "'+e.ClassName+'": '+e.Message); end; + {$ENDIF Exceptions} // simple things @@ -521,6 +503,9 @@ begin s := client.testString('Test'); Expect( s = 'Test', 'testString(''Test'') = "'+s+'"'); + s := client.testString(''); // empty string + Expect( s = '', 'testString('''') = "'+s+'"'); + s := client.testString(HUGE_TEST_STRING); Expect( length(s) = length(HUGE_TEST_STRING), 'testString( length(HUGE_TEST_STRING) = '+IntToStr(Length(HUGE_TEST_STRING))+') ' @@ -536,16 +521,19 @@ begin i64 := client.testI64(-34359738368); Expect( i64 = -34359738368, 'testI64(-34359738368) = ' + IntToStr( i64)); - binOut := PrepareBinaryData( TRUE); - Console.WriteLine('testBinary('+BytesToHex(binOut)+')'); - try - binIn := client.testBinary(binOut); - Expect( Length(binOut) = Length(binIn), 'testBinary(): length '+IntToStr(Length(binOut))+' = '+IntToStr(Length(binIn))); - i32 := Min( Length(binOut), Length(binIn)); - Expect( CompareMem( binOut, binIn, i32), 'testBinary('+BytesToHex(binOut)+') = '+BytesToHex(binIn)); - except - on e:TApplicationException do Console.WriteLine('testBinary(): '+e.Message); - on e:Exception do Expect( FALSE, 'testBinary(): Unexpected exception "'+e.ClassName+'": '+e.Message); + // random binary small + for testsize := Low(TTestSize) to High(TTestSize) do begin + binOut := PrepareBinaryData( TRUE, testsize); + Console.WriteLine('testBinary('+BytesToHex(binOut)+')'); + try + binIn := client.testBinary(binOut); + Expect( Length(binOut) = Length(binIn), 'testBinary(): length '+IntToStr(Length(binOut))+' = '+IntToStr(Length(binIn))); + i32 := Min( Length(binOut), Length(binIn)); + Expect( CompareMem( binOut, binIn, i32), 'testBinary('+BytesToHex(binOut)+') = '+BytesToHex(binIn)); + except + on e:TApplicationException do Console.WriteLine('testBinary(): '+e.Message); + on e:Exception do Expect( FALSE, 'testBinary(): Unexpected exception "'+e.ClassName+'": '+e.Message); + end; end; Console.WriteLine('testDouble(5.325098235)'); @@ -772,9 +760,9 @@ begin insane.UserMap.AddOrSetValue( TNumberz.FIVE, 5000); truck := TXtructImpl.Create; truck.String_thing := 'Truck'; - truck.Byte_thing := 8; - truck.I32_thing := 8; - truck.I64_thing := 8; + truck.Byte_thing := -8; // byte is signed + truck.I32_thing := 32; + truck.I64_thing := 64; insane.Xtructs := TThriftListImpl.Create; insane.Xtructs.Add( truck ); whoa := client.testInsanity( insane ); @@ -823,6 +811,18 @@ begin end; Console.WriteLine('}'); + (** + * So you think you've got this all worked, out eh? + * + * Creates a the returned map with these values and prints it out: + * { 1 => { 2 => argument, + * 3 => argument, + * }, + * 2 => { 6 => , }, + * } + * @return map> - a map with the above values + *) + // verify result data Expect( whoa.Count = 2, 'whoa.Count = '+IntToStr(whoa.Count)); // @@ -843,31 +843,20 @@ begin Expect( crazy.__isset_UserMap, 'crazy.__isset_UserMap = '+BoolToString(crazy.__isset_UserMap)); Expect( crazy.__isset_Xtructs, 'crazy.__isset_Xtructs = '+BoolToString(crazy.__isset_Xtructs)); - Expect( crazy.UserMap.Count = 2, 'crazy.UserMap.Count = '+IntToStr(crazy.UserMap.Count)); - Expect( crazy.UserMap[TNumberz.FIVE] = 5, 'crazy.UserMap[TNumberz.FIVE] = '+IntToStr(crazy.UserMap[TNumberz.FIVE])); - Expect( crazy.UserMap[TNumberz.EIGHT] = 8, 'crazy.UserMap[TNumberz.EIGHT] = '+IntToStr(crazy.UserMap[TNumberz.EIGHT])); + Expect( crazy.UserMap.Count = insane.UserMap.Count, 'crazy.UserMap.Count = '+IntToStr(crazy.UserMap.Count)); + for pair in insane.UserMap do begin + Expect( crazy.UserMap[pair.Key] = pair.Value, 'crazy.UserMap['+IntToStr(Ord(pair.key))+'] = '+IntToStr(crazy.UserMap[pair.Key])); + end; - Expect( crazy.Xtructs.Count = 2, 'crazy.Xtructs.Count = '+IntToStr(crazy.Xtructs.Count)); - goodbye := crazy.Xtructs[0]; // lists are ordered, so we are allowed to assume this order - hello := crazy.Xtructs[1]; - - Expect( goodbye.String_thing = 'Goodbye4', 'goodbye.String_thing = "'+goodbye.String_thing+'"'); - Expect( goodbye.Byte_thing = 4, 'goodbye.Byte_thing = '+IntToStr(goodbye.Byte_thing)); - Expect( goodbye.I32_thing = 4, 'goodbye.I32_thing = '+IntToStr(goodbye.I32_thing)); - Expect( goodbye.I64_thing = 4, 'goodbye.I64_thing = '+IntToStr(goodbye.I64_thing)); - Expect( goodbye.__isset_String_thing, 'goodbye.__isset_String_thing = '+BoolToString(goodbye.__isset_String_thing)); - Expect( goodbye.__isset_Byte_thing, 'goodbye.__isset_Byte_thing = '+BoolToString(goodbye.__isset_Byte_thing)); - Expect( goodbye.__isset_I32_thing, 'goodbye.__isset_I32_thing = '+BoolToString(goodbye.__isset_I32_thing)); - Expect( goodbye.__isset_I64_thing, 'goodbye.__isset_I64_thing = '+BoolToString(goodbye.__isset_I64_thing)); - - Expect( hello.String_thing = 'Hello2', 'hello.String_thing = "'+hello.String_thing+'"'); - Expect( hello.Byte_thing = 2, 'hello.Byte_thing = '+IntToStr(hello.Byte_thing)); - Expect( hello.I32_thing = 2, 'hello.I32_thing = '+IntToStr(hello.I32_thing)); - Expect( hello.I64_thing = 2, 'hello.I64_thing = '+IntToStr(hello.I64_thing)); - Expect( hello.__isset_String_thing, 'hello.__isset_String_thing = '+BoolToString(hello.__isset_String_thing)); - Expect( hello.__isset_Byte_thing, 'hello.__isset_Byte_thing = '+BoolToString(hello.__isset_Byte_thing)); - Expect( hello.__isset_I32_thing, 'hello.__isset_I32_thing = '+BoolToString(hello.__isset_I32_thing)); - Expect( hello.__isset_I64_thing, 'hello.__isset_I64_thing = '+BoolToString(hello.__isset_I64_thing)); + Expect( crazy.Xtructs.Count = insane.Xtructs.Count, 'crazy.Xtructs.Count = '+IntToStr(crazy.Xtructs.Count)); + for arg0 := 0 to insane.Xtructs.Count-1 do begin + hello := insane.Xtructs[arg0]; + goodbye := crazy.Xtructs[arg0]; + Expect( goodbye.String_thing = hello.String_thing, 'goodbye.String_thing = '+goodbye.String_thing); + Expect( goodbye.Byte_thing = hello.Byte_thing, 'goodbye.Byte_thing = '+IntToStr(goodbye.Byte_thing)); + Expect( goodbye.I32_thing = hello.I32_thing, 'goodbye.I32_thing = '+IntToStr(goodbye.I32_thing)); + Expect( goodbye.I64_thing = hello.I64_thing, 'goodbye.I64_thing = '+IntToStr(goodbye.I64_thing)); + end; end; @@ -907,7 +896,7 @@ begin Expect( not i.__isset_I64_thing, 'i.__isset_I64_thing = '+BoolToString(i.__isset_I64_thing)); } except - on e:Exception do Expect( FALSE, 'Unexpected exception "'+e.ClassName+'"'); + on e:Exception do Expect( FALSE, 'Unexpected exception "'+e.ClassName+'": '+e.Message); end; StartTestGroup( 'testMultiException(Xception)', test_Exceptions); @@ -921,7 +910,7 @@ begin Expect( x.ErrorCode = 1001, 'x.ErrorCode = '+IntToStr(x.ErrorCode)); Expect( x.Message_ = 'This is an Xception', 'x.Message = "'+x.Message_+'"'); end; - on e:Exception do Expect( FALSE, 'Unexpected exception "'+e.ClassName+'"'); + on e:Exception do Expect( FALSE, 'Unexpected exception "'+e.ClassName+'": '+e.Message); end; StartTestGroup( 'testMultiException(Xception2)', test_Exceptions); @@ -941,7 +930,7 @@ begin Expect( not x.Struct_thing.__isset_I64_thing, 'x.Struct_thing.__isset_I64_thing = '+BoolToString(x.Struct_thing.__isset_I64_thing)); } end; - on e:Exception do Expect( FALSE, 'Unexpected exception "'+e.ClassName+'"'); + on e:Exception do Expect( FALSE, 'Unexpected exception "'+e.ClassName+'": '+e.Message); end; @@ -966,6 +955,33 @@ begin end; +{$IFDEF SupportsAsync} +procedure TClientThread.ClientAsyncTest; +var + client : TThriftTest.IAsync; + s : string; + i8 : ShortInt; +begin + StartTestGroup( 'Async Tests', test_Unknown); + client := TThriftTest.TClient.Create( FProtocol); + FTransport.Open; + + // oneway void functions + client.testOnewayAsync(1).Wait; + Expect( TRUE, 'Test Oneway(1)'); // success := no exception + + // normal functions + s := client.testStringAsync(HUGE_TEST_STRING).Value; + Expect( length(s) = length(HUGE_TEST_STRING), + 'testString( length(HUGE_TEST_STRING) = '+IntToStr(Length(HUGE_TEST_STRING))+') ' + +'=> length(result) = '+IntToStr(Length(s))); + + i8 := client.testByte(1).Value; + Expect( i8 = 1, 'testByte(1) = ' + IntToStr( i8 )); +end; +{$ENDIF} + + {$IFDEF StressTest} procedure TClientThread.StressTest(const client : TThriftTest.Iface); begin @@ -986,33 +1002,49 @@ end; {$ENDIF} -function TClientThread.PrepareBinaryData( aRandomDist : Boolean = FALSE) : TBytes; -var i, nextPos : Integer; +function TClientThread.PrepareBinaryData( aRandomDist : Boolean; aSize : TTestSize) : TBytes; +var i : Integer; begin - SetLength( result, $100); + case aSize of + Empty : SetLength( result, 0); + Normal : SetLength( result, $100); + ByteArrayTest : SetLength( result, SizeOf(TByteArray) + 128); + PipeWriteLimit : SetLength( result, 65535 + 128); + else + raise EArgumentException.Create('aSize'); + end; + ASSERT( Low(result) = 0); + if Length(result) = 0 then Exit; // linear distribution, unless random is requested if not aRandomDist then begin for i := Low(result) to High(result) do begin - result[i] := i; + result[i] := i mod $100; end; Exit; end; // random distribution of all 256 values FillChar( result[0], Length(result) * SizeOf(result[0]), $0); - i := 1; - while i < Length(result) do begin - nextPos := Byte( Random($100)); - if result[nextPos] = 0 then begin // unused? - result[nextPos] := i; - Inc(i); - end; + for i := Low(result) to High(result) do begin + result[i] := Byte( Random($100)); end; end; +{$IFDEF Win64} +procedure TClientThread.UseInterlockedExchangeAdd64; +var a,b : Int64; +begin + a := 1; + b := 2; + Thrift.Utils.InterlockedExchangeAdd64( a,b); + Expect( a = 3, 'InterlockedExchangeAdd64'); +end; +{$ENDIF} + + procedure TClientThread.JSONProtocolReadWriteTest; // Tests only then read/write procedures of the JSON protocol // All tests succeed, if we can read what we wrote before @@ -1020,8 +1052,8 @@ procedure TClientThread.JSONProtocolReadWriteTest; // other clients or servers expect as the real JSON. This is beyond the scope of this test. var prot : IProtocol; stm : TStringStream; - list : IList; - binary, binRead : TBytes; + list : TThriftList; + binary, binRead, emptyBinary : TBytes; i,iErr : Integer; const TEST_SHORT = ShortInt( $FE); @@ -1043,7 +1075,8 @@ begin StartTestGroup( 'JsonProtocolTest', test_Unknown); // prepare binary data - binary := PrepareBinaryData( FALSE); + binary := PrepareBinaryData( FALSE, Normal); + SetLength( emptyBinary, 0); // empty binary data block // output setup prot := TJSONProtocolImpl.Create( @@ -1051,7 +1084,8 @@ begin nil, TThriftStreamAdapterDelphi.Create( stm, FALSE))); // write - prot.WriteListBegin( TListImpl.Create( TType.String_, 9)); + Init( list, TType.String_, 9); + prot.WriteListBegin( list); prot.WriteBool( TRUE); prot.WriteBool( FALSE); prot.WriteByte( TEST_SHORT); @@ -1061,6 +1095,8 @@ begin prot.WriteDouble( TEST_DOUBLE); prot.WriteString( TEST_STRING); prot.WriteBinary( binary); + prot.WriteString( ''); // empty string + prot.WriteBinary( emptyBinary); // empty binary data block prot.WriteListEnd; // input setup @@ -1083,6 +1119,8 @@ begin Expect( abs(prot.ReadDouble-TEST_DOUBLE) < abs(DELTA_DOUBLE), 'WriteDouble/ReadDouble'); Expect( prot.ReadString = TEST_STRING, 'WriteString/ReadString'); binRead := prot.ReadBinary; + Expect( Length(prot.ReadString) = 0, 'WriteString/ReadString (empty string)'); + Expect( Length(prot.ReadBinary) = 0, 'empty WriteBinary/ReadBinary (empty data block)'); prot.ReadListEnd; // test binary data @@ -1219,12 +1257,11 @@ begin end; -constructor TClientThread.Create( const ATransport: ITransport; const AProtocol : IProtocol; ANumIteration: Integer); +constructor TClientThread.Create( const aSetup : TTestSetup; const aNumIteration: Integer); begin - inherited Create( True ); + FSetup := aSetup; FNumIteration := ANumIteration; - FTransport := ATransport; - FProtocol := AProtocol; + FConsole := TThreadConsole.Create( Self ); FCurrentTest := test_Unknown; @@ -1232,6 +1269,8 @@ begin FErrors := TStringList.Create; FErrors.Sorted := FALSE; FErrors.Duplicates := dupAccept; + + inherited Create( TRUE); end; destructor TClientThread.Destroy; @@ -1244,34 +1283,136 @@ end; procedure TClientThread.Execute; var i : Integer; - proc : TThreadProcedure; begin // perform all tests try + {$IFDEF Win64} + UseInterlockedExchangeAdd64; + {$ENDIF} JSONProtocolReadWriteTest; - for i := 0 to FNumIteration - 1 do - begin - ClientTest; + + // must be run in the context of the thread + InitializeProtocolTransportStack; + try + for i := 0 to FNumIteration - 1 do begin + ClientTest; + {$IFDEF SupportsAsync} + ClientAsyncTest; + {$ENDIF} + end; + + // report the outcome + ReportResults; + SetReturnValue( CalculateExitCode); + + finally + ShutdownProtocolTransportStack; end; + except on e:Exception do Expect( FALSE, 'unexpected exception: "'+e.message+'"'); end; +end; - // report the outcome - ReportResults; - SetReturnValue( CalculateExitCode); - // shutdown - proc := procedure - begin - if FTransport <> nil then - begin +procedure TClientThread.InitializeProtocolTransportStack; +var + streamtrans : IStreamTransport; + http : IHTTPClient; + sUrl : string; +const + DEBUG_TIMEOUT = 30 * 1000; + RELEASE_TIMEOUT = DEFAULT_THRIFT_TIMEOUT; + PIPE_TIMEOUT = RELEASE_TIMEOUT; + HTTP_TIMEOUTS = 10 * 1000; +begin + // needed for HTTP clients as they utilize the MSXML COM components + OleCheck( CoInitialize( nil)); + + case FSetup.endpoint of + trns_Sockets: begin + Console.WriteLine('Using sockets ('+FSetup.host+' port '+IntToStr(FSetup.port)+')'); + streamtrans := TSocketImpl.Create( FSetup.host, FSetup.port ); + FTransport := streamtrans; + end; + + trns_Http: begin + Console.WriteLine('Using HTTPClient'); + if FSetup.useSSL + then sUrl := 'http://' + else sUrl := 'https://'; + sUrl := sUrl + FSetup.host; + case FSetup.port of + 80 : if FSetup.useSSL then sUrl := sUrl + ':'+ IntToStr(FSetup.port); + 443 : if not FSetup.useSSL then sUrl := sUrl + ':'+ IntToStr(FSetup.port); + else + if FSetup.port > 0 then sUrl := sUrl + ':'+ IntToStr(FSetup.port); + end; + http := THTTPClientImpl.Create( sUrl); + http.DnsResolveTimeout := HTTP_TIMEOUTS; + http.ConnectionTimeout := HTTP_TIMEOUTS; + http.SendTimeout := HTTP_TIMEOUTS; + http.ReadTimeout := HTTP_TIMEOUTS; + FTransport := http; + end; + + trns_EvHttp: begin + raise Exception.Create(ENDPOINT_TRANSPORTS[FSetup.endpoint]+' transport not implemented'); + end; + + trns_NamedPipes: begin + streamtrans := TNamedPipeTransportClientEndImpl.Create( FSetup.sPipeName, 0, nil, PIPE_TIMEOUT, PIPE_TIMEOUT); + FTransport := streamtrans; + end; + + trns_AnonPipes: begin + streamtrans := TAnonymousPipeTransportImpl.Create( FSetup.hAnonRead, FSetup.hAnonWrite, FALSE); + FTransport := streamtrans; + end; + + else + raise Exception.Create('Unhandled endpoint transport'); + end; + ASSERT( FTransport <> nil); + + // layered transports are not really meant to be stacked upon each other + if (trns_Framed in FSetup.layered) then begin + FTransport := TFramedTransportImpl.Create( FTransport); + end + else if (trns_Buffered in FSetup.layered) and (streamtrans <> nil) then begin + FTransport := TBufferedTransportImpl.Create( streamtrans, 32); // small buffer to test read() + end; + + if FSetup.useSSL then begin + raise Exception.Create('SSL/TLS not implemented'); + end; + + // create protocol instance, default to BinaryProtocol + case FSetup.protType of + prot_Binary : FProtocol := TBinaryProtocolImpl.Create( FTransport, BINARY_STRICT_READ, BINARY_STRICT_WRITE); + prot_JSON : FProtocol := TJSONProtocolImpl.Create( FTransport); + prot_Compact : FProtocol := TCompactProtocolImpl.Create( FTransport); + else + raise Exception.Create('Unhandled protocol'); + end; + + ASSERT( (FTransport <> nil) and (FProtocol <> nil)); +end; + + +procedure TClientThread.ShutdownProtocolTransportStack; +begin + try + FProtocol := nil; + + if FTransport <> nil then begin FTransport.Close; FTransport := nil; end; - end; - Synchronize( proc ); + finally + CoUninitialize; + end; end; diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/test/TestServer.pas b/vendor/git.apache.org/thrift.git/lib/delphi/test/TestServer.pas index d7917ca..69cb175 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/test/TestServer.pas +++ b/vendor/git.apache.org/thrift.git/lib/delphi/test/TestServer.pas @@ -29,7 +29,6 @@ interface uses Windows, SysUtils, Generics.Collections, - Thrift.Console, Thrift.Server, Thrift.Transport, Thrift.Transport.Pipes, @@ -42,6 +41,7 @@ uses Thrift, TestConstants, TestServerEvents, + ConsoleHelper, Contnrs; type @@ -164,7 +164,7 @@ begin if (arg = 'TException') then begin - raise TException.Create(''); + raise TException.Create('TException'); end; // else do not throw anything @@ -185,44 +185,33 @@ end; function TTestServer.TTestHandlerImpl.testInsanity( const argument: IInsanity): IThriftDictionary>; var - hello, goodbye : IXtruct; - crazy : IInsanity; looney : IInsanity; first_map : IThriftDictionary; second_map : IThriftDictionary; insane : IThriftDictionary>; begin - Console.WriteLine('testInsanity()'); - hello := TXtructImpl.Create; - hello.String_thing := 'Hello2'; - hello.Byte_thing := 2; - hello.I32_thing := 2; - hello.I64_thing := 2; - goodbye := TXtructImpl.Create; - goodbye.String_thing := 'Goodbye4'; - goodbye.Byte_thing := 4; - goodbye.I32_thing := 4; - goodbye.I64_thing := 4; - - crazy := TInsanityImpl.Create; - crazy.UserMap := TThriftDictionaryImpl.Create; - crazy.UserMap.AddOrSetValue( TNumberz.EIGHT, 8); - crazy.Xtructs := TThriftListImpl.Create; - crazy.Xtructs.Add(goodbye); - - looney := TInsanityImpl.Create; - crazy.UserMap.AddOrSetValue( TNumberz.FIVE, 5); - crazy.Xtructs.Add(hello); + (** + * So you think you've got this all worked, out eh? + * + * Creates a the returned map with these values and prints it out: + * { 1 => { 2 => argument, + * 3 => argument, + * }, + * 2 => { 6 => , }, + * } + * @return map> - a map with the above values + *) first_map := TThriftDictionaryImpl.Create; second_map := TThriftDictionaryImpl.Create; - first_map.AddOrSetValue( TNumberz.TWO, crazy); - first_map.AddOrSetValue( TNumberz.THREE, crazy); + first_map.AddOrSetValue( TNumberz.TWO, argument); + first_map.AddOrSetValue( TNumberz.THREE, argument); + looney := TInsanityImpl.Create; second_map.AddOrSetValue( TNumberz.SIX, looney); insane := TThriftDictionaryImpl>.Create; diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/test/TestServerEvents.pas b/vendor/git.apache.org/thrift.git/lib/delphi/test/TestServerEvents.pas index 2e776d2..2208cd4 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/test/TestServerEvents.pas +++ b/vendor/git.apache.org/thrift.git/lib/delphi/test/TestServerEvents.pas @@ -27,7 +27,7 @@ uses Thrift.Protocol, Thrift.Transport, Thrift.Server, - Thrift.Console; + ConsoleHelper; type TRequestEventsImpl = class( TInterfacedObject, IRequestEvents) diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/test/client.dpr b/vendor/git.apache.org/thrift.git/lib/delphi/test/client.dpr index f2e5250..06dbd3d 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/test/client.dpr +++ b/vendor/git.apache.org/thrift.git/lib/delphi/test/client.dpr @@ -29,6 +29,7 @@ uses Thrift in '..\src\Thrift.pas', Thrift.Transport in '..\src\Thrift.Transport.pas', Thrift.Socket in '..\src\Thrift.Socket.pas', + Thrift.Exception in '..\src\Thrift.Exception.pas', Thrift.Transport.Pipes in '..\src\Thrift.Transport.Pipes.pas', Thrift.Protocol in '..\src\Thrift.Protocol.pas', Thrift.Protocol.JSON in '..\src\Thrift.Protocol.JSON.pas', @@ -37,7 +38,6 @@ uses Thrift.Collections in '..\src\Thrift.Collections.pas', Thrift.Server in '..\src\Thrift.Server.pas', Thrift.Stream in '..\src\Thrift.Stream.pas', - Thrift.Console in '..\src\Thrift.Console.pas', Thrift.TypeRegistry in '..\src\Thrift.TypeRegistry.pas', Thrift.Utils in '..\src\Thrift.Utils.pas'; diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/test/codegen/ReservedKeywords.thrift b/vendor/git.apache.org/thrift.git/lib/delphi/test/keywords/ReservedIncluded.thrift similarity index 64% rename from vendor/git.apache.org/thrift.git/lib/delphi/test/codegen/ReservedKeywords.thrift rename to vendor/git.apache.org/thrift.git/lib/delphi/test/keywords/ReservedIncluded.thrift index 300adf9..8b47a50 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/test/codegen/ReservedKeywords.thrift +++ b/vendor/git.apache.org/thrift.git/lib/delphi/test/keywords/ReservedIncluded.thrift @@ -18,38 +18,8 @@ */ // make sure generated code does not produce name collisions with predefined keywords +namespace delphi SysUtils +const i32 integer = 42 - -typedef i32 Cardinal -typedef string message -typedef list< map< Cardinal, message>> program - -struct unit { - 1: Cardinal downto; - 2: program procedure; -} - -typedef set< unit> units - -exception exception1 { - 1: program message; - 2: unit array; -} - -service constructor { - unit Create(1: Cardinal asm; 2: message inherited) throws (1: exception1 label); - units Destroy(); -} - -const Cardinal downto = +1 -const Cardinal published = -1 - -enum keywords { - record = 1, - repeat = 2, - deprecated = 3 -} - - - +// EOF diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/test/keywords/ReservedKeywords.dpr b/vendor/git.apache.org/thrift.git/lib/delphi/test/keywords/ReservedKeywords.dpr new file mode 100644 index 0000000..1fbc8c1 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/delphi/test/keywords/ReservedKeywords.dpr @@ -0,0 +1,15 @@ +program ReservedKeywords; + +{$APPTYPE CONSOLE} + +uses + SysUtils, System_; + +begin + try + { TODO -oUser -cConsole Main : Code hier einfügen } + except + on E: Exception do + Writeln(E.ClassName, ': ', E.Message); + end; +end. diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/test/keywords/ReservedKeywords.thrift b/vendor/git.apache.org/thrift.git/lib/delphi/test/keywords/ReservedKeywords.thrift new file mode 100644 index 0000000..2f49d74 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/delphi/test/keywords/ReservedKeywords.thrift @@ -0,0 +1,138 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +// make sure generated code does not produce name collisions with predefined keywords +namespace delphi System + +include "ReservedIncluded.thrift" + + +typedef i32 Cardinal +typedef string message +typedef list< map< Cardinal, message>> program + +struct unit { + 1: Cardinal downto; + 2: program procedure; +} + +typedef set< unit> units + +exception exception1 { + 1: program message; + 2: unit array; +} + +service constructor { + unit Create(1: Cardinal asm; 2: message inherited) throws (1: exception1 label); + units Destroy(); +} + +const Cardinal downto = +1 +const Cardinal published = -1 + +enum keywords { + record = 1, + repeat = 2, + deprecated = 3 +} + + +struct Struct_lists { + 1: list init; + 2: list struc; + 3: list field; + 4: list field_; + 5: list tracker; + 6: list Self; +} + +struct Struct_structs { + 1: Struct_simple init; + 2: Struct_simple struc; + 3: Struct_simple field; + 4: Struct_simple field_; + 5: Struct_simple tracker; + 6: Struct_simple Self; +} + +struct Struct_simple { + 1: bool init; + 2: bool struc; + 3: bool field; + 4: bool field_; + 5: bool tracker; + 6: bool Self; +} + +struct Struct_strings { + 1: string init; + 2: string struc; + 3: string field; + 4: string field_; + 5: string tracker; + 6: string Self; +} + +struct Struct_binary { + 1: binary init; + 2: binary struc; + 3: binary field; + 4: binary field_; + 5: binary tracker; + 6: binary Self; +} + + +typedef i32 IProtocol +typedef i32 ITransport +typedef i32 IFace +typedef i32 IAsync +typedef i32 System +typedef i32 SysUtils +typedef i32 Generics +typedef i32 Thrift + +struct Struct_Thrift_Names { + 1: IProtocol IProtocol + 2: ITransport ITransport + 3: IFace IFace + 4: IAsync IAsync + 5: System System + 6: SysUtils SysUtils + 7: Generics Generics + 8: Thrift Thrift +} + + +enum Thrift4554_Enum { + Foo = 0, + Bar = 1, + Baz = 2, +} + +struct Thrift4554_Struct { + 1 : optional double MinValue + 2 : optional double MaxValue + 3 : optional bool Integer // causes issue + 4 : optional Thrift4554_Enum Foo +} + + +// EOF diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/test/multiplexed/Multiplex.Server.Main.pas b/vendor/git.apache.org/thrift.git/lib/delphi/test/multiplexed/Multiplex.Server.Main.pas index 37f84bb..3860f5a 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/test/multiplexed/Multiplex.Server.Main.pas +++ b/vendor/git.apache.org/thrift.git/lib/delphi/test/multiplexed/Multiplex.Server.Main.pas @@ -28,7 +28,6 @@ interface uses Windows, SysUtils, Generics.Collections, - Thrift.Console, Thrift.Server, Thrift.Transport, Thrift.Transport.Pipes, @@ -41,6 +40,7 @@ uses Benchmark, // in gen-delphi folder Aggr, // in gen-delphi folder Multiplex.Test.Common, + ConsoleHelper, Contnrs; type diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/test/multiplexed/Multiplex.Test.Client.dpr b/vendor/git.apache.org/thrift.git/lib/delphi/test/multiplexed/Multiplex.Test.Client.dpr index d6f93a1..4278d8f 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/test/multiplexed/Multiplex.Test.Client.dpr +++ b/vendor/git.apache.org/thrift.git/lib/delphi/test/multiplexed/Multiplex.Test.Client.dpr @@ -27,6 +27,7 @@ uses Multiplex.Client.Main in 'Multiplex.Client.Main.pas', Thrift in '..\..\src\Thrift.pas', Thrift.Socket in '..\..\src\Thrift.Socket.pas', + Thrift.Exception in '..\..\src\Thrift.Exception.pas', Thrift.Transport in '..\..\src\Thrift.Transport.pas', Thrift.Transport.Pipes in '..\..\src\Thrift.Transport.Pipes.pas', Thrift.Protocol in '..\..\src\Thrift.Protocol.pas', @@ -34,7 +35,6 @@ uses Thrift.Collections in '..\..\src\Thrift.Collections.pas', Thrift.Server in '..\..\src\Thrift.Server.pas', Thrift.Stream in '..\..\src\Thrift.Stream.pas', - Thrift.Console in '..\..\src\Thrift.Console.pas', Thrift.TypeRegistry in '..\..\src\Thrift.TypeRegistry.pas', Thrift.Utils in '..\..\src\Thrift.Utils.pas'; diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/test/multiplexed/Multiplex.Test.Server.dpr b/vendor/git.apache.org/thrift.git/lib/delphi/test/multiplexed/Multiplex.Test.Server.dpr index 5550036..120462b 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/test/multiplexed/Multiplex.Test.Server.dpr +++ b/vendor/git.apache.org/thrift.git/lib/delphi/test/multiplexed/Multiplex.Test.Server.dpr @@ -24,7 +24,9 @@ program Multiplex.Test.Server; uses SysUtils, Multiplex.Server.Main in 'Multiplex.Server.Main.pas', + ConsoleHelper in '..\ConsoleHelper.pas', Thrift in '..\..\src\Thrift.pas', + Thrift.Exception in '..\..\src\Thrift.Exception.pas', Thrift.Socket in '..\..\src\Thrift.Socket.pas', Thrift.Transport in '..\..\src\Thrift.Transport.pas', Thrift.Transport.Pipes in '..\..\src\Thrift.Transport.Pipes.pas', @@ -33,7 +35,6 @@ uses Thrift.Processor.Multiplex in '..\..\src\Thrift.Processor.Multiplex.pas', Thrift.Collections in '..\..\src\Thrift.Collections.pas', Thrift.Server in '..\..\src\Thrift.Server.pas', - Thrift.Console in '..\..\src\Thrift.Console.pas', Thrift.Utils in '..\..\src\Thrift.Utils.pas', Thrift.TypeRegistry in '..\..\src\Thrift.TypeRegistry.pas', Thrift.Stream in '..\..\src\Thrift.Stream.pas'; diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/test/serializer/TestSerializer.Data.pas b/vendor/git.apache.org/thrift.git/lib/delphi/test/serializer/TestSerializer.Data.pas index 30d9dd4..5fc0070 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/test/serializer/TestSerializer.Data.pas +++ b/vendor/git.apache.org/thrift.git/lib/delphi/test/serializer/TestSerializer.Data.pas @@ -22,6 +22,7 @@ unit TestSerializer.Data; interface uses + SysUtils, Thrift.Collections, DebugProtoTest; @@ -194,7 +195,7 @@ begin {$IF cDebugProtoTest_Option_AnsiStr_Binary} result.SetBase64('base64'); {$ELSE} - not yet impl + result.SetBase64( TEncoding.UTF8.GetBytes('base64')); {$IFEND} // byte, i16, and i64 lists are populated by default constructor @@ -338,7 +339,7 @@ begin {$IF cDebugProtoTest_Option_AnsiStr_Binary} result.A_binary := AnsiString( #0#1#2#3#4#5#6#7#8); {$ELSE} - not yet impl + result.A_binary := TEncoding.UTF8.GetBytes( #0#1#2#3#4#5#6#7#8); {$IFEND} end; diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/test/serializer/TestSerializer.dpr b/vendor/git.apache.org/thrift.git/lib/delphi/test/serializer/TestSerializer.dpr index 9e283e5..51e22a4 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/test/serializer/TestSerializer.dpr +++ b/vendor/git.apache.org/thrift.git/lib/delphi/test/serializer/TestSerializer.dpr @@ -24,17 +24,18 @@ program TestSerializer; uses Classes, Windows, SysUtils, Generics.Collections, Thrift in '..\..\src\Thrift.pas', + Thrift.Exception in '..\..\src\Thrift.Exception.pas', Thrift.Socket in '..\..\src\Thrift.Socket.pas', Thrift.Transport in '..\..\src\Thrift.Transport.pas', Thrift.Protocol in '..\..\src\Thrift.Protocol.pas', Thrift.Protocol.JSON in '..\..\src\Thrift.Protocol.JSON.pas', Thrift.Collections in '..\..\src\Thrift.Collections.pas', Thrift.Server in '..\..\src\Thrift.Server.pas', - Thrift.Console in '..\..\src\Thrift.Console.pas', Thrift.Utils in '..\..\src\Thrift.Utils.pas', Thrift.Serializer in '..\..\src\Thrift.Serializer.pas', Thrift.Stream in '..\..\src\Thrift.Stream.pas', Thrift.TypeRegistry in '..\..\src\Thrift.TypeRegistry.pas', + System_, DebugProtoTest, TestSerializer.Data; diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/test/server.dpr b/vendor/git.apache.org/thrift.git/lib/delphi/test/server.dpr index d87a331..b5e48a6 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/test/server.dpr +++ b/vendor/git.apache.org/thrift.git/lib/delphi/test/server.dpr @@ -27,6 +27,7 @@ uses TestServerEvents in 'TestServerEvents.pas', Thrift.Test, // in gen-delphi folder Thrift in '..\src\Thrift.pas', + Thrift.Exception in '..\src\Thrift.Exception.pas', Thrift.Transport in '..\src\Thrift.Transport.pas', Thrift.Socket in '..\src\Thrift.Socket.pas', Thrift.Transport.Pipes in '..\src\Thrift.Transport.Pipes.pas', @@ -37,7 +38,6 @@ uses Thrift.Processor.Multiplex in '..\src\Thrift.Processor.Multiplex.pas', Thrift.Collections in '..\src\Thrift.Collections.pas', Thrift.Server in '..\src\Thrift.Server.pas', - Thrift.Console in '..\src\Thrift.Console.pas', Thrift.TypeRegistry in '..\src\Thrift.TypeRegistry.pas', Thrift.Utils in '..\src\Thrift.Utils.pas', Thrift.Stream in '..\src\Thrift.Stream.pas'; diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/test/skip/skiptest_version1.dpr b/vendor/git.apache.org/thrift.git/lib/delphi/test/skip/skiptest_version1.dpr index c7092c9..803d6bd 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/test/skip/skiptest_version1.dpr +++ b/vendor/git.apache.org/thrift.git/lib/delphi/test/skip/skiptest_version1.dpr @@ -25,13 +25,13 @@ uses Classes, Windows, SysUtils, Skiptest.One, Thrift in '..\..\src\Thrift.pas', + Thrift.Exception in '..\..\src\Thrift.Exception.pas', Thrift.Socket in '..\..\src\Thrift.Socket.pas', Thrift.Transport in '..\..\src\Thrift.Transport.pas', Thrift.Protocol in '..\..\src\Thrift.Protocol.pas', Thrift.Protocol.JSON in '..\..\src\Thrift.Protocol.JSON.pas', Thrift.Collections in '..\..\src\Thrift.Collections.pas', Thrift.Server in '..\..\src\Thrift.Server.pas', - Thrift.Console in '..\..\src\Thrift.Console.pas', Thrift.Utils in '..\..\src\Thrift.Utils.pas', Thrift.TypeRegistry in '..\..\src\Thrift.TypeRegistry.pas', Thrift.Stream in '..\..\src\Thrift.Stream.pas'; @@ -44,7 +44,7 @@ const function CreatePing : IPing; begin result := TPingImpl.Create; - result.Version1 := Skiptest.One.TConstants.SKIPTESTSERVICE_VERSION; + result.Version1 := Tskiptest_version_1Constants.SKIPTESTSERVICE_VERSION; end; @@ -179,7 +179,7 @@ const FILE_JSON = 'pingpong.json'; begin try - Writeln( 'Delphi SkipTest '+IntToStr(TConstants.SKIPTESTSERVICE_VERSION)+' using '+Thrift.Version); + Writeln( 'Delphi SkipTest '+IntToStr(Tskiptest_version_1Constants.SKIPTESTSERVICE_VERSION)+' using '+Thrift.Version); Writeln; Writeln('Binary protocol'); diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/test/skip/skiptest_version2.dpr b/vendor/git.apache.org/thrift.git/lib/delphi/test/skip/skiptest_version2.dpr index e99e62e..633b247 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/test/skip/skiptest_version2.dpr +++ b/vendor/git.apache.org/thrift.git/lib/delphi/test/skip/skiptest_version2.dpr @@ -25,13 +25,13 @@ uses Classes, Windows, SysUtils, Skiptest.Two, Thrift in '..\..\src\Thrift.pas', + Thrift.Exception in '..\..\src\Thrift.Exception.pas', Thrift.Socket in '..\..\src\Thrift.Socket.pas', Thrift.Transport in '..\..\src\Thrift.Transport.pas', Thrift.Protocol in '..\..\src\Thrift.Protocol.pas', Thrift.Protocol.JSON in '..\..\src\Thrift.Protocol.JSON.pas', Thrift.Collections in '..\..\src\Thrift.Collections.pas', Thrift.Server in '..\..\src\Thrift.Server.pas', - Thrift.Console in '..\..\src\Thrift.Console.pas', Thrift.Utils in '..\..\src\Thrift.Utils.pas', Thrift.TypeRegistry in '..\..\src\Thrift.TypeRegistry.pas', Thrift.Stream in '..\..\src\Thrift.Stream.pas'; @@ -45,7 +45,7 @@ var list : IThriftList; set_ : IHashSet; begin result := TPingImpl.Create; - result.Version1 := Skiptest.Two.TConstants.SKIPTESTSERVICE_VERSION; + result.Version1 := Tskiptest_version_2Constants.SKIPTESTSERVICE_VERSION; result.BoolVal := TRUE; result.ByteVal := 2; result.DbVal := 3; @@ -206,7 +206,7 @@ const FILE_JSON = 'pingpong.json'; begin try - Writeln( 'Delphi SkipTest '+IntToStr(TConstants.SKIPTESTSERVICE_VERSION)+' using '+Thrift.Version); + Writeln( 'Delphi SkipTest '+IntToStr(Tskiptest_version_2Constants.SKIPTESTSERVICE_VERSION)+' using '+Thrift.Version); Writeln; Writeln('Binary protocol'); diff --git a/vendor/git.apache.org/thrift.git/lib/delphi/test/typeregistry/TestTypeRegistry.dpr b/vendor/git.apache.org/thrift.git/lib/delphi/test/typeregistry/TestTypeRegistry.dpr index 3a77aae..18a7c7d 100644 --- a/vendor/git.apache.org/thrift.git/lib/delphi/test/typeregistry/TestTypeRegistry.dpr +++ b/vendor/git.apache.org/thrift.git/lib/delphi/test/typeregistry/TestTypeRegistry.dpr @@ -25,12 +25,12 @@ uses Classes, Windows, SysUtils, Generics.Collections, TypInfo, Thrift in '..\..\src\Thrift.pas', Thrift.Transport in '..\..\src\Thrift.Transport.pas', + Thrift.Exception in '..\..\src\Thrift.Exception.pas', Thrift.Socket in '..\..\src\Thrift.Socket.pas', Thrift.Protocol in '..\..\src\Thrift.Protocol.pas', Thrift.Protocol.JSON in '..\..\src\Thrift.Protocol.JSON.pas', Thrift.Collections in '..\..\src\Thrift.Collections.pas', Thrift.Server in '..\..\src\Thrift.Server.pas', - Thrift.Console in '..\..\src\Thrift.Console.pas', Thrift.Utils in '..\..\src\Thrift.Utils.pas', Thrift.Serializer in '..\..\src\Thrift.Serializer.pas', Thrift.Stream in '..\..\src\Thrift.Stream.pas', diff --git a/vendor/git.apache.org/thrift.git/lib/erl/Makefile.am b/vendor/git.apache.org/thrift.git/lib/erl/Makefile.am index 2502d31..06323b4 100644 --- a/vendor/git.apache.org/thrift.git/lib/erl/Makefile.am +++ b/vendor/git.apache.org/thrift.git/lib/erl/Makefile.am @@ -18,8 +18,12 @@ # THRIFT = ../../compiler/cpp/thrift +THRIFT_OMIT_FILE = test/Thrift_omit_without.thrift THRIFT_FILES = $(wildcard test/*.thrift) \ + $(THRIFT_OMIT_FILE) \ + ../../test/ConstantsDemo.thrift \ ../../test/NameConflictTest.thrift \ + ../../test/DoubleConstantsTest.thrift \ ../../test/ThriftTest.thrift if ERLANG_OTP16 @@ -32,6 +36,10 @@ ERL_FLAG = erl ERL_FLAG_LEGACY = erl:legacynames ERL_FLAG_MAPS = erl:maps endif + +$(THRIFT_OMIT_FILE): test/Thrift_omit_with.thrift + grep -v omit $< >$@ + .generated: $(THRIFT) $(THRIFT_FILES) for f in $(THRIFT_FILES) ; do \ $(THRIFT) --gen $(ERL_FLAG) -o test $$f ; \ @@ -64,6 +72,7 @@ uninstall: clean: rm -f .generated rm -rf test/gen-erl/ + rm -f $(THRIFT_OMIT_FILE) $(REBAR) clean maintainer-clean-local: @@ -74,6 +83,7 @@ EXTRA_DIST = \ src \ coding_standards.md \ rebar.config \ + rebar.config.script \ rebar.test.config \ test \ README.md diff --git a/vendor/git.apache.org/thrift.git/lib/erl/coding_standards.md b/vendor/git.apache.org/thrift.git/lib/erl/coding_standards.md index fa0390b..4d37dbc 100644 --- a/vendor/git.apache.org/thrift.git/lib/erl/coding_standards.md +++ b/vendor/git.apache.org/thrift.git/lib/erl/coding_standards.md @@ -1 +1,3 @@ Please follow [General Coding Standards](/doc/coding_standards.md) + +Particularly for Erlang please follow the Erlang [Programming Rules and Conventions](http://www.erlang.se/doc/programming_rules.shtml). diff --git a/vendor/git.apache.org/thrift.git/lib/erl/include/thrift_protocol.hrl b/vendor/git.apache.org/thrift.git/lib/erl/include/thrift_protocol.hrl index f85f455..bc0acc8 100644 --- a/vendor/git.apache.org/thrift.git/lib/erl/include/thrift_protocol.hrl +++ b/vendor/git.apache.org/thrift.git/lib/erl/include/thrift_protocol.hrl @@ -20,12 +20,12 @@ -ifndef(THRIFT_PROTOCOL_INCLUDED). -define(THRIFT_PROTOCOL_INCLUDED, true). --record(protocol_message_begin, {name, type, seqid}). --record(protocol_struct_begin, {name}). --record(protocol_field_begin, {name, type, id}). --record(protocol_map_begin, {ktype, vtype, size}). --record(protocol_list_begin, {etype, size}). --record(protocol_set_begin, {etype, size}). +-record(protocol_message_begin, {name :: string(), type :: integer(), seqid :: integer()}). +-record(protocol_struct_begin, {name :: string()}). +-record(protocol_field_begin, {name :: string(), type :: integer(), id :: integer()}). +-record(protocol_map_begin, {ktype :: integer(), vtype :: integer(), size :: integer()}). +-record(protocol_list_begin, {etype :: integer(), size :: integer()}). +-record(protocol_set_begin, {etype :: integer(), size :: integer()}). -type tprot_header_val() :: #protocol_message_begin{} | #protocol_struct_begin{} diff --git a/vendor/git.apache.org/thrift.git/lib/erl/rebar.test.config b/vendor/git.apache.org/thrift.git/lib/erl/rebar.test.config index 12515b7..2ff2afb 100644 --- a/vendor/git.apache.org/thrift.git/lib/erl/rebar.test.config +++ b/vendor/git.apache.org/thrift.git/lib/erl/rebar.test.config @@ -1,5 +1,5 @@ {erl_opts, [{platform_define, "^R.*", otp16_or_less}, debug_info]}. {deps, [ - {meck, "", {git, "https://github.com/eproxus/meck.git", {tag, "0.8.2"}}} + {meck, "", {git, "https://github.com/eproxus/meck.git", {tag, "0.8.9"}}} ]}. diff --git a/vendor/git.apache.org/thrift.git/lib/erl/src/thrift_framed_transport.erl b/vendor/git.apache.org/thrift.git/lib/erl/src/thrift_framed_transport.erl index 715f090..9a5d6af 100644 --- a/vendor/git.apache.org/thrift.git/lib/erl/src/thrift_framed_transport.erl +++ b/vendor/git.apache.org/thrift.git/lib/erl/src/thrift_framed_transport.erl @@ -62,7 +62,8 @@ when is_integer(Len), Len >= 0 -> Give = min(iolist_size(NewBinary), Len), {Result, Remaining} = split_binary(NewBinary, Give), {State#t_framed{wrapped = NewState, read_buffer = Remaining}, {ok, Result}}; - Error -> Error + {NewState, Error} -> + {State#t_framed{wrapped = NewState}, Error} end; %% read of zero bytes <<>> -> {State, {ok, <<>>}}; diff --git a/vendor/git.apache.org/thrift.git/lib/erl/src/thrift_protocol.erl b/vendor/git.apache.org/thrift.git/lib/erl/src/thrift_protocol.erl index dc3bfef..2fe10d6 100644 --- a/vendor/git.apache.org/thrift.git/lib/erl/src/thrift_protocol.erl +++ b/vendor/git.apache.org/thrift.git/lib/erl/src/thrift_protocol.erl @@ -219,12 +219,11 @@ read_struct_loop(IProto0, SDict, RTuple) -> end. skip_field(FType, IProto0, SDict, RTuple) -> - FTypeAtom = thrift_protocol:typeid_to_atom(FType), - {IProto1, ok} = thrift_protocol:skip(IProto0, FTypeAtom), + {IProto1, ok} = skip(IProto0, typeid_to_atom(FType)), {IProto2, ok} = read(IProto1, field_end), read_struct_loop(IProto2, SDict, RTuple). --spec skip(#protocol{}, any()) -> {#protocol{}, ok}. +-spec skip(#protocol{}, atom()) -> {#protocol{}, ok}. skip(Proto0, struct) -> {Proto1, ok} = read(Proto0, struct_begin), @@ -261,7 +260,7 @@ skip_struct_loop(Proto0) -> ?tType_STOP -> {Proto1, ok}; _Else -> - {Proto2, ok} = skip(Proto1, Type), + {Proto2, ok} = skip(Proto1, typeid_to_atom(Type)), {Proto3, ok} = read(Proto2, field_end), skip_struct_loop(Proto3) end. @@ -271,8 +270,8 @@ skip_map_loop(Proto0, Map = #protocol_map_begin{ktype = Ktype, size = Size}) -> case Size of N when N > 0 -> - {Proto1, ok} = skip(Proto0, Ktype), - {Proto2, ok} = skip(Proto1, Vtype), + {Proto1, ok} = skip(Proto0, typeid_to_atom(Ktype)), + {Proto2, ok} = skip(Proto1, typeid_to_atom(Vtype)), skip_map_loop(Proto2, Map#protocol_map_begin{size = Size - 1}); 0 -> {Proto0, ok} @@ -282,7 +281,7 @@ skip_set_loop(Proto0, Map = #protocol_set_begin{etype = Etype, size = Size}) -> case Size of N when N > 0 -> - {Proto1, ok} = skip(Proto0, Etype), + {Proto1, ok} = skip(Proto0, typeid_to_atom(Etype)), skip_set_loop(Proto1, Map#protocol_set_begin{size = Size - 1}); 0 -> {Proto0, ok} @@ -292,7 +291,7 @@ skip_list_loop(Proto0, Map = #protocol_list_begin{etype = Etype, size = Size}) -> case Size of N when N > 0 -> - {Proto1, ok} = skip(Proto0, Etype), + {Proto1, ok} = skip(Proto0, typeid_to_atom(Etype)), skip_list_loop(Proto1, Map#protocol_list_begin{size = Size - 1}); 0 -> {Proto0, ok} diff --git a/vendor/git.apache.org/thrift.git/lib/erl/src/thrift_reconnecting_client.erl b/vendor/git.apache.org/thrift.git/lib/erl/src/thrift_reconnecting_client.erl index 468c38b..538fd3a 100644 --- a/vendor/git.apache.org/thrift.git/lib/erl/src/thrift_reconnecting_client.erl +++ b/vendor/git.apache.org/thrift.git/lib/erl/src/thrift_reconnecting_client.erl @@ -36,7 +36,7 @@ terminate/2, code_change/3 ]). --record( state, { client = nil, +-record( state, { client = nil, host, port, thrift_svc, @@ -226,9 +226,9 @@ timer_fun() -> end. -else. timer_fun() -> - T1 = erlang:now(), + T1 = erlang:timestamp(), fun() -> - T2 = erlang:now(), + T2 = erlang:timestamp(), timer:now_diff(T2, T1) end. -endif. diff --git a/vendor/git.apache.org/thrift.git/lib/erl/src/thrift_transport.erl b/vendor/git.apache.org/thrift.git/lib/erl/src/thrift_transport.erl index 526050f..2414bde 100644 --- a/vendor/git.apache.org/thrift.git/lib/erl/src/thrift_transport.erl +++ b/vendor/git.apache.org/thrift.git/lib/erl/src/thrift_transport.erl @@ -103,11 +103,9 @@ read_exact(Transport = #t_transport{module = Module}, Len) when is_integer(Len), Len >= 0 -> case lists:keyfind(read_exact, 1, Module:module_info(exports)) of {read_exact, 2} -> - io:fwrite("HAS EXACT"), {NewState, Result} = Module:read_exact(Transport#t_transport.state, Len), {Transport#t_transport{state = NewState}, Result}; _ -> - io:fwrite("~p NO EXACT", [Module]), read(Transport, Len) end. diff --git a/vendor/git.apache.org/thrift.git/lib/erl/test/Thrift_omit_with.thrift b/vendor/git.apache.org/thrift.git/lib/erl/test/Thrift_omit_with.thrift new file mode 100644 index 0000000..8bffc7c --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/erl/test/Thrift_omit_with.thrift @@ -0,0 +1,22 @@ +struct test1 { + 1: i32 one + 2: i32 two // omit + 3: i32 three +} + +struct test2 { + 1: i32 one + 2: test2 two // omit + 3: i32 three +} + +struct test3 { + 1: i32 one + 2: list two // omit +} + +struct test4 { + 1: i32 one + 2: map two // omit +} + diff --git a/vendor/git.apache.org/thrift.git/lib/erl/test/test_const.erl b/vendor/git.apache.org/thrift.git/lib/erl/test/test_const.erl new file mode 100644 index 0000000..627777b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/erl/test/test_const.erl @@ -0,0 +1,54 @@ +%% +%% Licensed to the Apache Software Foundation (ASF) under one +%% or more contributor license agreements. See the NOTICE file +%% distributed with this work for additional information +%% regarding copyright ownership. The ASF licenses this file +%% to you 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. +%% + +-module(test_const). + +-ifdef(TEST). +-include_lib("eunit/include/eunit.hrl"). + +-include("gen-erl/constants_demo_types.hrl"). + +namespace_test() -> + %% Verify that records produced by ConstantsDemo.thrift have the right namespace. + io:format(user, "in namespace_test()\n", []), + {struct, _} = constants_demo_types:struct_info('consts_thing'), + {struct, _} = constants_demo_types:struct_info('consts_Blah'), + ok. + +const_map_test() -> + ?assertEqual(233, constants_demo_constants:gen_map(35532)), + ?assertError(function_clause, constants_demo_constants:gen_map(0)), + + ?assertEqual(853, constants_demo_constants:gen_map(43523, default)), + ?assertEqual(default, constants_demo_constants:gen_map(10110, default)), + + ?assertEqual(98325, constants_demo_constants:gen_map2("lkjsdf")), + ?assertError(function_clause, constants_demo_constants:gen_map2("nonexist")), + + ?assertEqual(233, constants_demo_constants:gen_map2("hello", 321)), + ?assertEqual(321, constants_demo_constants:gen_map2("goodbye", 321)). + +const_list_test() -> + ?assertEqual(23598352, constants_demo_constants:gen_list(2)), + ?assertError(function_clause, constants_demo_constants:gen_list(0)), + + ?assertEqual(3253523, constants_demo_constants:gen_list(3, default)), + ?assertEqual(default, constants_demo_constants:gen_list(10, default)). + +-endif. %% TEST diff --git a/vendor/git.apache.org/thrift.git/lib/erl/test/test_omit.erl b/vendor/git.apache.org/thrift.git/lib/erl/test/test_omit.erl new file mode 100644 index 0000000..80841e2 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/erl/test/test_omit.erl @@ -0,0 +1,79 @@ +-module(test_omit). + +-include("gen-erl/thrift_omit_with_types.hrl"). + +-ifdef(TEST). +-include_lib("eunit/include/eunit.hrl"). + +omit_struct1_test() -> + %% In this test, the field that is deleted is a basic type (an i32). + A = #test1{one = 1, three = 3}, + B = #test1{one = 1, two = 2, three = 3}, + {ok, Transport} = thrift_membuffer_transport:new(), + {ok, P0} = thrift_binary_protocol:new(Transport), + + {P1, ok} = thrift_protocol:write(P0, {{struct, {thrift_omit_with_types, element(1, A)}}, A}), + {P2, {ok, O0}} = thrift_protocol:read(P1, {struct, {thrift_omit_without_types, element(1, A)}}), + ?assertEqual(element(1, A), element(1, O0)), + ?assertEqual(element(2, A), element(2, O0)), + ?assertEqual(element(4, A), element(3, O0)), + + {P3, ok} = thrift_protocol:write(P2, {{struct, {thrift_omit_with_types, element(1, B)}}, B}), + {_P4, {ok, O1}} = thrift_protocol:read(P3, {struct, {thrift_omit_without_types, element(1, A)}}), + ?assertEqual(element(1, A), element(1, O1)), + ?assertEqual(element(2, A), element(2, O1)), + ?assertEqual(element(4, A), element(3, O1)), + + ok. + +omit_struct2_test() -> + %% In this test, the field that is deleted is a struct. + A = #test2{one = 1, two = #test2{one = 10, three = 30}, three = 3}, + B = #test2{one = 1, two = #test2{one = 10, two = #test2{one = 100}, three = 30}, three = 3}, + + {ok, Transport} = thrift_membuffer_transport:new(), + {ok, P0} = thrift_binary_protocol:new(Transport), + + {P1, ok} = thrift_protocol:write(P0, {{struct, {thrift_omit_with_types, element(1, A)}}, A}), + {P2, {ok, O0}} = thrift_protocol:read(P1, {struct, {thrift_omit_without_types, element(1, A)}}), + ?assertEqual(element(1, A), element(1, O0)), + ?assertEqual(element(2, A), element(2, O0)), + ?assertEqual(element(4, A), element(3, O0)), + + {P3, ok} = thrift_protocol:write(P2, {{struct, {thrift_omit_with_types, element(1, B)}}, B}), + {_P4, {ok, O1}} = thrift_protocol:read(P3, {struct, {thrift_omit_without_types, element(1, A)}}), + ?assertEqual(element(1, A), element(1, O1)), + ?assertEqual(element(2, A), element(2, O1)), + ?assertEqual(element(4, A), element(3, O1)), + + ok. + +omit_list_test() -> + %% In this test, the field that is deleted is a list. + A = #test1{one = 1, two = 2, three = 3}, + B = #test3{one = 1, two = [ A ]}, + + {ok, Transport} = thrift_membuffer_transport:new(), + {ok, P0} = thrift_binary_protocol:new(Transport), + + {P1, ok} = thrift_protocol:write(P0, {{struct, {thrift_omit_with_types, element(1, B)}}, B}), + {_P2, {ok, O0}} = thrift_protocol:read(P1, {struct, {thrift_omit_without_types, element(1, B)}}), + ?assertEqual(element(2, B), element(2, O0)), + + ok. + +omit_map_test() -> + %% In this test, the field that is deleted is a map. + A = #test1{one = 1, two = 2, three = 3}, + B = #test4{one = 1, two = dict:from_list([ {2, A} ])}, + + {ok, Transport} = thrift_membuffer_transport:new(), + {ok, P0} = thrift_binary_protocol:new(Transport), + + {P1, ok} = thrift_protocol:write(P0, {{struct, {thrift_omit_with_types, element(1, B)}}, B}), + {_P2, {ok, O0}} = thrift_protocol:read(P1, {struct, {thrift_omit_without_types, element(1, B)}}), + ?assertEqual(element(2, B), element(2, O0)), + + ok. + +-endif. %% TEST diff --git a/vendor/git.apache.org/thrift.git/lib/erl/test/test_rendered_double_constants.erl b/vendor/git.apache.org/thrift.git/lib/erl/test/test_rendered_double_constants.erl new file mode 100644 index 0000000..87fce81 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/erl/test/test_rendered_double_constants.erl @@ -0,0 +1,68 @@ +%% +%% Licensed to the Apache Software Foundation (ASF) under one +%% or more contributor license agreements. See the NOTICE file +%% distributed with this work for additional information +%% regarding copyright ownership. The ASF licenses this file +%% to you 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. +%% + +-module(test_rendered_double_constants). + +-ifdef(TEST). +-include_lib("eunit/include/eunit.hrl"). + +-include("gen-erl/double_constants_test_constants.hrl"). + +-define(EPSILON, 0.0000001). + +rendered_double_constants_test() -> + ?assert(abs(1.0 - ?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST) =< ?EPSILON), + ?assert(abs(-100.0 - ?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST) =< ?EPSILON), + ?assert(abs(9223372036854775807.0 - ?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST) =< ?EPSILON), + ?assert(abs(-9223372036854775807.0 - ?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST) =< ?EPSILON), + ?assert(abs(3.14159265359 - ?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST) =< ?EPSILON), + ?assert(abs(1000000.1 - ?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST) =< ?EPSILON), + ?assert(abs(-1000000.1 - ?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST) =< ?EPSILON), + ?assert(abs(1.7e+308 - ?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST) =< ?EPSILON), + ?assert(abs(9223372036854775816.43 - ?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST) =< ?EPSILON), + ?assert(abs(-1.7e+308 - ?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST) =< ?EPSILON), + ?assert(abs(-9223372036854775816.43 - ?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST) =< ?EPSILON), + ?assert(is_float(?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST)), + ?assert(is_float(?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST)), + ?assert(is_float(?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST)), + ?assert(is_float(?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST)), + ?assert(is_float(?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST)), + ?assert(is_float(?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST)), + ?assert(is_float(?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST)), + ?assert(is_float(?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST)), + ?assert(is_float(?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST)), + ?assert(is_float(?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST)), + ?assert(is_float(?DOUBLE_CONSTANTS_TEST_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST)). + +rendered_double_list_test() -> + ?assertEqual(12, length(?DOUBLE_CONSTANTS_TEST_DOUBLE_LIST_TEST)), + ?assert(abs(1.0 - lists:nth(1, ?DOUBLE_CONSTANTS_TEST_DOUBLE_LIST_TEST)) =< ?EPSILON), + ?assert(abs(-100.0 - lists:nth(2, ?DOUBLE_CONSTANTS_TEST_DOUBLE_LIST_TEST)) =< ?EPSILON), + ?assert(abs(100.0 - lists:nth(3, ?DOUBLE_CONSTANTS_TEST_DOUBLE_LIST_TEST)) =< ?EPSILON), + ?assert(abs(9223372036854775807.0 - lists:nth(4, ?DOUBLE_CONSTANTS_TEST_DOUBLE_LIST_TEST)) =< ?EPSILON), + ?assert(abs(-9223372036854775807.0 - lists:nth(5, ?DOUBLE_CONSTANTS_TEST_DOUBLE_LIST_TEST)) =< ?EPSILON), + ?assert(abs(3.14159265359 - lists:nth(6, ?DOUBLE_CONSTANTS_TEST_DOUBLE_LIST_TEST)) =< ?EPSILON), + ?assert(abs(1000000.1 - lists:nth(7, ?DOUBLE_CONSTANTS_TEST_DOUBLE_LIST_TEST)) =< ?EPSILON), + ?assert(abs(-1000000.1 - lists:nth(8, ?DOUBLE_CONSTANTS_TEST_DOUBLE_LIST_TEST)) =< ?EPSILON), + ?assert(abs(1.7e+308 - lists:nth(9, ?DOUBLE_CONSTANTS_TEST_DOUBLE_LIST_TEST)) =< ?EPSILON), + ?assert(abs(-1.7e+308 - lists:nth(10, ?DOUBLE_CONSTANTS_TEST_DOUBLE_LIST_TEST)) =< ?EPSILON), + ?assert(abs(9223372036854775816.43 - lists:nth(11, ?DOUBLE_CONSTANTS_TEST_DOUBLE_LIST_TEST)) =< ?EPSILON), + ?assert(abs(-9223372036854775816.43 - lists:nth(12, ?DOUBLE_CONSTANTS_TEST_DOUBLE_LIST_TEST)) =< ?EPSILON). + +-endif. %% TEST \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/erl/test/thrift_test_test.erl b/vendor/git.apache.org/thrift.git/lib/erl/test/thrift_test_test.erl index ae20f31..77df61d 100644 --- a/vendor/git.apache.org/thrift.git/lib/erl/test/thrift_test_test.erl +++ b/vendor/git.apache.org/thrift.git/lib/erl/test/thrift_test_test.erl @@ -628,18 +628,6 @@ service_info_test_() -> {struct, []}, thrift_test_thrift:function_info(testOneway, exceptions) )}, - {"blahBlah params", ?_assertEqual( - {struct, []}, - second_service_thrift:function_info(blahBlah, params_type) - )}, - {"blahBlah reply", ?_assertEqual( - {struct, []}, - second_service_thrift:function_info(blahBlah, reply_type) - )}, - {"blahBlah exceptions", ?_assertEqual( - {struct, []}, - second_service_thrift:function_info(blahBlah, exceptions) - )}, {"secondtestString params", ?_assertEqual( {struct, [{1, string}]}, second_service_thrift:function_info(secondtestString, params_type) diff --git a/vendor/git.apache.org/thrift.git/lib/go/Makefile.am b/vendor/git.apache.org/thrift.git/lib/go/Makefile.am index ff946ea..0dfa5fa 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/Makefile.am +++ b/vendor/git.apache.org/thrift.git/lib/go/Makefile.am @@ -31,10 +31,13 @@ install: @echo '##############################################################' check-local: - $(GO) test ./thrift + GOPATH=`pwd` $(GO) test -race ./thrift + +clean-local: + $(RM) -rf pkg all-local: - $(GO) build ./thrift + GOPATH=`pwd` $(GO) build ./thrift EXTRA_DIST = \ thrift \ diff --git a/vendor/git.apache.org/thrift.git/lib/go/README.md b/vendor/git.apache.org/thrift.git/lib/go/README.md index 7440474..ce6d5ed 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/README.md +++ b/vendor/git.apache.org/thrift.git/lib/go/README.md @@ -24,10 +24,12 @@ under the License. Using Thrift with Go ==================== +Thrift supports Go 1.7+ + In following Go conventions, we recommend you use the 'go' tool to install Thrift for go. - $ go get git.apache.org/thrift.git/lib/go/thrift/... + $ go get github.com/apache/thrift/lib/go/thrift/... Will retrieve and install the most recent version of the package. diff --git a/vendor/git.apache.org/thrift.git/lib/go/test/Makefile.am b/vendor/git.apache.org/thrift.git/lib/go/test/Makefile.am index bbcec96..78d4681 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/test/Makefile.am +++ b/vendor/git.apache.org/thrift.git/lib/go/test/Makefile.am @@ -17,8 +17,7 @@ # under the License. # -THRIFT = $(top_builddir)/compiler/cpp/thrift -THRIFTARGS = -out gopath/src/ --gen go:thrift_import=thrift +THRIFTARGS = -out gopath/src/ --gen go:thrift_import=thrift$(COMPILER_EXTRAFLAG) THRIFTTEST = $(top_srcdir)/test/ThriftTest.thrift # Thrift for GO has problems with complex map keys: THRIFT-2063 @@ -28,11 +27,13 @@ gopath: $(THRIFT) $(THRIFTTEST) \ MultiplexedProtocolTest.thrift \ OnewayTest.thrift \ OptionalFieldsTest.thrift \ + RequiredFieldTest.thrift \ ServicesTest.thrift \ GoTagTest.thrift \ TypedefFieldTest.thrift \ RefAnnotationFieldsTest.thrift \ UnionDefaultValueTest.thrift \ + UnionBinaryTest.thrift \ ErrorTest.thrift \ NamesTest.thrift \ InitialismsTest.thrift \ @@ -46,16 +47,20 @@ gopath: $(THRIFT) $(THRIFTTEST) \ $(THRIFT) $(THRIFTARGS) MultiplexedProtocolTest.thrift $(THRIFT) $(THRIFTARGS) OnewayTest.thrift $(THRIFT) $(THRIFTARGS) OptionalFieldsTest.thrift + $(THRIFT) $(THRIFTARGS) RequiredFieldTest.thrift $(THRIFT) $(THRIFTARGS) ServicesTest.thrift $(THRIFT) $(THRIFTARGS) GoTagTest.thrift $(THRIFT) $(THRIFTARGS) TypedefFieldTest.thrift $(THRIFT) $(THRIFTARGS) RefAnnotationFieldsTest.thrift $(THRIFT) $(THRIFTARGS) UnionDefaultValueTest.thrift + $(THRIFT) $(THRIFTARGS) UnionBinaryTest.thrift $(THRIFT) $(THRIFTARGS) ErrorTest.thrift $(THRIFT) $(THRIFTARGS) NamesTest.thrift $(THRIFT) $(THRIFTARGS) InitialismsTest.thrift $(THRIFT) $(THRIFTARGS),read_write_private DontExportRWTest.thrift $(THRIFT) $(THRIFTARGS),ignore_initialisms IgnoreInitialismsTest.thrift + GOPATH=`pwd`/gopath $(GO) get github.com/golang/mock/gomock || true + sed -i 's/\"context\"/\"golang.org\/x\/net\/context\"/g' gopath/src/github.com/golang/mock/gomock/controller.go || true GOPATH=`pwd`/gopath $(GO) get github.com/golang/mock/gomock ln -nfs ../../../thrift gopath/src/thrift ln -nfs ../../tests gopath/src/tests @@ -73,7 +78,8 @@ check: gopath namestest \ initialismstest \ dontexportrwtest \ - ignoreinitialismstest + ignoreinitialismstest \ + unionbinarytest GOPATH=`pwd`/gopath $(GO) test thrift tests dontexportrwtest clean-local: @@ -92,8 +98,10 @@ EXTRA_DIST = \ NamespacedTest.thrift \ OnewayTest.thrift \ OptionalFieldsTest.thrift \ + RequiredFieldTest.thrift \ RefAnnotationFieldsTest.thrift \ UnionDefaultValueTest.thrift \ + UnionBinaryTest.thrift \ ServicesTest.thrift \ TypedefFieldTest.thrift \ ErrorTest.thrift \ diff --git a/vendor/git.apache.org/thrift.git/lib/go/test/RequiredFieldTest.thrift b/vendor/git.apache.org/thrift.git/lib/go/test/RequiredFieldTest.thrift new file mode 100644 index 0000000..4a2dcae --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/go/test/RequiredFieldTest.thrift @@ -0,0 +1,7 @@ +struct RequiredField { + 1: required string name +} + +struct OtherThing { + 1: required i16 value +} diff --git a/vendor/git.apache.org/thrift.git/lib/go/test/UnionBinaryTest.thrift b/vendor/git.apache.org/thrift.git/lib/go/test/UnionBinaryTest.thrift new file mode 100644 index 0000000..f77112b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/go/test/UnionBinaryTest.thrift @@ -0,0 +1,25 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +# See https://issues.apache.org/jira/browse/THRIFT-4573 +union Sample { + 1: map u1, + 2: binary u2, + 3: list u3 +} diff --git a/vendor/git.apache.org/thrift.git/lib/go/test/dontexportrwtest/compile_test.go b/vendor/git.apache.org/thrift.git/lib/go/test/dontexportrwtest/compile_test.go index 2b877e3..cf6763e 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/test/dontexportrwtest/compile_test.go +++ b/vendor/git.apache.org/thrift.git/lib/go/test/dontexportrwtest/compile_test.go @@ -20,7 +20,6 @@ package dontexportrwtest import ( - "fmt" "testing" ) @@ -29,10 +28,10 @@ import ( func TestReadWriteMethodsArePrivate(t *testing.T) { // This will only compile if read/write methods exist s := NewTestStruct() - fmt.Sprintf("%v", s.read) - fmt.Sprintf("%v", s.write) + _ = s.read + _ = s.write is := NewInnerStruct() - fmt.Sprintf("%v", is.read) - fmt.Sprintf("%v", is.write) + _ = is.read + _ = is.write } diff --git a/vendor/git.apache.org/thrift.git/lib/go/test/tests/client_error_test.go b/vendor/git.apache.org/thrift.git/lib/go/test/tests/client_error_test.go index 838883d..fdec4ea 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/test/tests/client_error_test.go +++ b/vendor/git.apache.org/thrift.git/lib/go/test/tests/client_error_test.go @@ -20,11 +20,13 @@ package tests import ( - "github.com/golang/mock/gomock" + "context" "errors" "errortest" "testing" "thrift" + + "github.com/golang/mock/gomock" ) // TestCase: Comprehensive call and reply workflow in the client. @@ -211,7 +213,7 @@ func prepareClientCallReply(protocol *MockTProtocol, failAt int, failWith error) if failAt == 25 { err = failWith } - last = protocol.EXPECT().Flush().Return(err).After(last) + last = protocol.EXPECT().Flush(context.Background()).Return(err).After(last) if failAt == 25 { return true } @@ -397,12 +399,44 @@ func prepareClientCallReply(protocol *MockTProtocol, failAt int, failWith error) // Expecting TTransportError on fail. func TestClientReportTTransportErrors(t *testing.T) { mockCtrl := gomock.NewController(t) - transport := thrift.NewTMemoryBuffer() thing := errortest.NewTestStruct() thing.M = make(map[string]string) thing.L = make([]string, 0) - thing.S = make(map[string]struct{}) + thing.S = make([]string, 0) + thing.I = 3 + + err := thrift.NewTTransportException(thrift.TIMED_OUT, "test") + for i := 0; ; i++ { + protocol := NewMockTProtocol(mockCtrl) + if !prepareClientCallReply(protocol, i, err) { + return + } + client := errortest.NewErrorTestClient(thrift.NewTStandardClient(protocol, protocol)) + _, retErr := client.TestStruct(defaultCtx, thing) + mockCtrl.Finish() + mockCtrl = gomock.NewController(t) + err2, ok := retErr.(thrift.TTransportException) + if !ok { + t.Fatal("Expected a TTrasportException") + } + + if err2.TypeId() != thrift.TIMED_OUT { + t.Fatal("Expected TIMED_OUT error") + } + } +} + +// TestCase: Comprehensive call and reply workflow in the client. +// Expecting TTransportError on fail. +// Similar to TestClientReportTTransportErrors, but using legacy client constructor. +func TestClientReportTTransportErrorsLegacy(t *testing.T) { + mockCtrl := gomock.NewController(t) + transport := thrift.NewTMemoryBuffer() + thing := errortest.NewTestStruct() + thing.M = make(map[string]string) + thing.L = make([]string, 0) + thing.S = make([]string, 0) thing.I = 3 err := thrift.NewTTransportException(thrift.TIMED_OUT, "test") @@ -412,8 +446,9 @@ func TestClientReportTTransportErrors(t *testing.T) { return } client := errortest.NewErrorTestClientProtocol(transport, protocol, protocol) - _, retErr := client.TestStruct(thing) + _, retErr := client.TestStruct(defaultCtx, thing) mockCtrl.Finish() + mockCtrl = gomock.NewController(t) err2, ok := retErr.(thrift.TTransportException) if !ok { t.Fatal("Expected a TTrasportException") @@ -429,12 +464,43 @@ func TestClientReportTTransportErrors(t *testing.T) { // Expecting TTProtocolErrors on fail. func TestClientReportTProtocolErrors(t *testing.T) { mockCtrl := gomock.NewController(t) - transport := thrift.NewTMemoryBuffer() thing := errortest.NewTestStruct() thing.M = make(map[string]string) thing.L = make([]string, 0) - thing.S = make(map[string]struct{}) + thing.S = make([]string, 0) + thing.I = 3 + + err := thrift.NewTProtocolExceptionWithType(thrift.INVALID_DATA, errors.New("test")) + for i := 0; ; i++ { + protocol := NewMockTProtocol(mockCtrl) + if !prepareClientCallReply(protocol, i, err) { + return + } + client := errortest.NewErrorTestClient(thrift.NewTStandardClient(protocol, protocol)) + _, retErr := client.TestStruct(defaultCtx, thing) + mockCtrl.Finish() + mockCtrl = gomock.NewController(t) + err2, ok := retErr.(thrift.TProtocolException) + if !ok { + t.Fatal("Expected a TProtocolException") + } + if err2.TypeId() != thrift.INVALID_DATA { + t.Fatal("Expected INVALID_DATA error") + } + } +} + +// TestCase: Comprehensive call and reply workflow in the client. +// Expecting TTProtocolErrors on fail. +// Similar to TestClientReportTProtocolErrors, but using legacy client constructor. +func TestClientReportTProtocolErrorsLegacy(t *testing.T) { + mockCtrl := gomock.NewController(t) + transport := thrift.NewTMemoryBuffer() + thing := errortest.NewTestStruct() + thing.M = make(map[string]string) + thing.L = make([]string, 0) + thing.S = make([]string, 0) thing.I = 3 err := thrift.NewTProtocolExceptionWithType(thrift.INVALID_DATA, errors.New("test")) @@ -444,8 +510,9 @@ func TestClientReportTProtocolErrors(t *testing.T) { return } client := errortest.NewErrorTestClientProtocol(transport, protocol, protocol) - _, retErr := client.TestStruct(thing) + _, retErr := client.TestStruct(defaultCtx, thing) mockCtrl.Finish() + mockCtrl = gomock.NewController(t) err2, ok := retErr.(thrift.TProtocolException) if !ok { t.Fatal("Expected a TProtocolException") @@ -470,7 +537,7 @@ func prepareClientCallException(protocol *MockTProtocol, failAt int, failWith er last = protocol.EXPECT().WriteFieldStop().After(last) last = protocol.EXPECT().WriteStructEnd().After(last) last = protocol.EXPECT().WriteMessageEnd().After(last) - last = protocol.EXPECT().Flush().After(last) + last = protocol.EXPECT().Flush(context.Background()).After(last) // Reading the exception, might fail. if failAt == 0 { @@ -557,16 +624,52 @@ func prepareClientCallException(protocol *MockTProtocol, failAt int, failWith er // TestCase: call and reply with exception workflow in the client. func TestClientCallException(t *testing.T) { mockCtrl := gomock.NewController(t) - transport := thrift.NewTMemoryBuffer() err := thrift.NewTTransportException(thrift.TIMED_OUT, "test") for i := 0; ; i++ { protocol := NewMockTProtocol(mockCtrl) willComplete := !prepareClientCallException(protocol, i, err) - client := errortest.NewErrorTestClientProtocol(transport, protocol, protocol) - _, retErr := client.TestString("test") + client := errortest.NewErrorTestClient(thrift.NewTStandardClient(protocol, protocol)) + _, retErr := client.TestString(defaultCtx, "test") mockCtrl.Finish() + mockCtrl = gomock.NewController(t) + + if !willComplete { + err2, ok := retErr.(thrift.TTransportException) + if !ok { + t.Fatal("Expected a TTransportException") + } + if err2.TypeId() != thrift.TIMED_OUT { + t.Fatal("Expected TIMED_OUT error") + } + } else { + err2, ok := retErr.(thrift.TApplicationException) + if !ok { + t.Fatal("Expected a TApplicationException") + } + if err2.TypeId() != thrift.PROTOCOL_ERROR { + t.Fatal("Expected PROTOCOL_ERROR error") + } + break + } + } +} + +// TestCase: call and reply with exception workflow in the client. +// Similar to TestClientCallException, but using legacy client constructor. +func TestClientCallExceptionLegacy(t *testing.T) { + mockCtrl := gomock.NewController(t) + transport := thrift.NewTMemoryBuffer() + err := thrift.NewTTransportException(thrift.TIMED_OUT, "test") + for i := 0; ; i++ { + protocol := NewMockTProtocol(mockCtrl) + willComplete := !prepareClientCallException(protocol, i, err) + + client := errortest.NewErrorTestClientProtocol(transport, protocol, protocol) + _, retErr := client.TestString(defaultCtx, "test") + mockCtrl.Finish() + mockCtrl = gomock.NewController(t) if !willComplete { err2, ok := retErr.(thrift.TTransportException) @@ -591,6 +694,36 @@ func TestClientCallException(t *testing.T) { // TestCase: Mismatching sequence id has been received in the client. func TestClientSeqIdMismatch(t *testing.T) { + mockCtrl := gomock.NewController(t) + protocol := NewMockTProtocol(mockCtrl) + gomock.InOrder( + protocol.EXPECT().WriteMessageBegin("testString", thrift.CALL, int32(1)), + protocol.EXPECT().WriteStructBegin("testString_args"), + protocol.EXPECT().WriteFieldBegin("s", thrift.TType(thrift.STRING), int16(1)), + protocol.EXPECT().WriteString("test"), + protocol.EXPECT().WriteFieldEnd(), + protocol.EXPECT().WriteFieldStop(), + protocol.EXPECT().WriteStructEnd(), + protocol.EXPECT().WriteMessageEnd(), + protocol.EXPECT().Flush(context.Background()), + protocol.EXPECT().ReadMessageBegin().Return("testString", thrift.REPLY, int32(2), nil), + ) + + client := errortest.NewErrorTestClient(thrift.NewTStandardClient(protocol, protocol)) + _, err := client.TestString(defaultCtx, "test") + mockCtrl.Finish() + appErr, ok := err.(thrift.TApplicationException) + if !ok { + t.Fatal("Expected TApplicationException") + } + if appErr.TypeId() != thrift.BAD_SEQUENCE_ID { + t.Fatal("Expected BAD_SEQUENCE_ID error") + } +} + +// TestCase: Mismatching sequence id has been received in the client. +// Similar to TestClientSeqIdMismatch, but using legacy client constructor. +func TestClientSeqIdMismatchLegeacy(t *testing.T) { mockCtrl := gomock.NewController(t) transport := thrift.NewTMemoryBuffer() protocol := NewMockTProtocol(mockCtrl) @@ -603,12 +736,12 @@ func TestClientSeqIdMismatch(t *testing.T) { protocol.EXPECT().WriteFieldStop(), protocol.EXPECT().WriteStructEnd(), protocol.EXPECT().WriteMessageEnd(), - protocol.EXPECT().Flush(), + protocol.EXPECT().Flush(context.Background()), protocol.EXPECT().ReadMessageBegin().Return("testString", thrift.REPLY, int32(2), nil), ) client := errortest.NewErrorTestClientProtocol(transport, protocol, protocol) - _, err := client.TestString("test") + _, err := client.TestString(defaultCtx, "test") mockCtrl.Finish() appErr, ok := err.(thrift.TApplicationException) if !ok { @@ -621,6 +754,36 @@ func TestClientSeqIdMismatch(t *testing.T) { // TestCase: Wrong method name has been received in the client. func TestClientWrongMethodName(t *testing.T) { + mockCtrl := gomock.NewController(t) + protocol := NewMockTProtocol(mockCtrl) + gomock.InOrder( + protocol.EXPECT().WriteMessageBegin("testString", thrift.CALL, int32(1)), + protocol.EXPECT().WriteStructBegin("testString_args"), + protocol.EXPECT().WriteFieldBegin("s", thrift.TType(thrift.STRING), int16(1)), + protocol.EXPECT().WriteString("test"), + protocol.EXPECT().WriteFieldEnd(), + protocol.EXPECT().WriteFieldStop(), + protocol.EXPECT().WriteStructEnd(), + protocol.EXPECT().WriteMessageEnd(), + protocol.EXPECT().Flush(context.Background()), + protocol.EXPECT().ReadMessageBegin().Return("unknown", thrift.REPLY, int32(1), nil), + ) + + client := errortest.NewErrorTestClient(thrift.NewTStandardClient(protocol, protocol)) + _, err := client.TestString(defaultCtx, "test") + mockCtrl.Finish() + appErr, ok := err.(thrift.TApplicationException) + if !ok { + t.Fatal("Expected TApplicationException") + } + if appErr.TypeId() != thrift.WRONG_METHOD_NAME { + t.Fatal("Expected WRONG_METHOD_NAME error") + } +} + +// TestCase: Wrong method name has been received in the client. +// Similar to TestClientWrongMethodName, but using legacy client constructor. +func TestClientWrongMethodNameLegacy(t *testing.T) { mockCtrl := gomock.NewController(t) transport := thrift.NewTMemoryBuffer() protocol := NewMockTProtocol(mockCtrl) @@ -633,12 +796,12 @@ func TestClientWrongMethodName(t *testing.T) { protocol.EXPECT().WriteFieldStop(), protocol.EXPECT().WriteStructEnd(), protocol.EXPECT().WriteMessageEnd(), - protocol.EXPECT().Flush(), + protocol.EXPECT().Flush(context.Background()), protocol.EXPECT().ReadMessageBegin().Return("unknown", thrift.REPLY, int32(1), nil), ) client := errortest.NewErrorTestClientProtocol(transport, protocol, protocol) - _, err := client.TestString("test") + _, err := client.TestString(defaultCtx, "test") mockCtrl.Finish() appErr, ok := err.(thrift.TApplicationException) if !ok { @@ -651,6 +814,36 @@ func TestClientWrongMethodName(t *testing.T) { // TestCase: Wrong message type has been received in the client. func TestClientWrongMessageType(t *testing.T) { + mockCtrl := gomock.NewController(t) + protocol := NewMockTProtocol(mockCtrl) + gomock.InOrder( + protocol.EXPECT().WriteMessageBegin("testString", thrift.CALL, int32(1)), + protocol.EXPECT().WriteStructBegin("testString_args"), + protocol.EXPECT().WriteFieldBegin("s", thrift.TType(thrift.STRING), int16(1)), + protocol.EXPECT().WriteString("test"), + protocol.EXPECT().WriteFieldEnd(), + protocol.EXPECT().WriteFieldStop(), + protocol.EXPECT().WriteStructEnd(), + protocol.EXPECT().WriteMessageEnd(), + protocol.EXPECT().Flush(context.Background()), + protocol.EXPECT().ReadMessageBegin().Return("testString", thrift.INVALID_TMESSAGE_TYPE, int32(1), nil), + ) + + client := errortest.NewErrorTestClient(thrift.NewTStandardClient(protocol, protocol)) + _, err := client.TestString(defaultCtx, "test") + mockCtrl.Finish() + appErr, ok := err.(thrift.TApplicationException) + if !ok { + t.Fatal("Expected TApplicationException") + } + if appErr.TypeId() != thrift.INVALID_MESSAGE_TYPE_EXCEPTION { + t.Fatal("Expected INVALID_MESSAGE_TYPE_EXCEPTION error") + } +} + +// TestCase: Wrong message type has been received in the client. +// Similar to TestClientWrongMessageType, but using legacy client constructor. +func TestClientWrongMessageTypeLegacy(t *testing.T) { mockCtrl := gomock.NewController(t) transport := thrift.NewTMemoryBuffer() protocol := NewMockTProtocol(mockCtrl) @@ -663,12 +856,12 @@ func TestClientWrongMessageType(t *testing.T) { protocol.EXPECT().WriteFieldStop(), protocol.EXPECT().WriteStructEnd(), protocol.EXPECT().WriteMessageEnd(), - protocol.EXPECT().Flush(), + protocol.EXPECT().Flush(context.Background()), protocol.EXPECT().ReadMessageBegin().Return("testString", thrift.INVALID_TMESSAGE_TYPE, int32(1), nil), ) client := errortest.NewErrorTestClientProtocol(transport, protocol, protocol) - _, err := client.TestString("test") + _, err := client.TestString(defaultCtx, "test") mockCtrl.Finish() appErr, ok := err.(thrift.TApplicationException) if !ok { diff --git a/vendor/git.apache.org/thrift.git/lib/go/test/tests/context.go b/vendor/git.apache.org/thrift.git/lib/go/test/tests/context.go new file mode 100644 index 0000000..a93a82b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/go/test/tests/context.go @@ -0,0 +1,26 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +package tests + +import ( + "context" +) + +var defaultCtx = context.Background() diff --git a/vendor/git.apache.org/thrift.git/lib/go/test/tests/multiplexed_protocol_test.go b/vendor/git.apache.org/thrift.git/lib/go/test/tests/multiplexed_protocol_test.go index b1674bd..61ac628 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/test/tests/multiplexed_protocol_test.go +++ b/vendor/git.apache.org/thrift.git/lib/go/test/tests/multiplexed_protocol_test.go @@ -20,6 +20,7 @@ package tests import ( + "context" "multiplexedprotocoltest" "net" "testing" @@ -38,24 +39,32 @@ func FindAvailableTCPServerPort() net.Addr { type FirstImpl struct{} -func (f *FirstImpl) ReturnOne() (r int64, err error) { +func (f *FirstImpl) ReturnOne(ctx context.Context) (r int64, err error) { return 1, nil } type SecondImpl struct{} -func (s *SecondImpl) ReturnTwo() (r int64, err error) { +func (s *SecondImpl) ReturnTwo(ctx context.Context) (r int64, err error) { return 2, nil } -var processor = thrift.NewTMultiplexedProcessor() +func createTransport(addr net.Addr) (thrift.TTransport, error) { + socket := thrift.NewTSocketFromAddrTimeout(addr, TIMEOUT) + transport := thrift.NewTFramedTransport(socket) + err := transport.Open() + if err != nil { + return nil, err + } + return transport, nil +} -func TestInitTwoServers(t *testing.T) { - var err error +func TestMultiplexedProtocolFirst(t *testing.T) { + processor := thrift.NewTMultiplexedProcessor() protocolFactory := thrift.NewTBinaryProtocolFactoryDefault() transportFactory := thrift.NewTTransportFactory() transportFactory = thrift.NewTFramedTransportFactory(transportFactory) - addr = FindAvailableTCPServerPort() + addr := FindAvailableTCPServerPort() serverTransport, err := thrift.NewTServerSocketTimeout(addr.String(), TIMEOUT) if err != nil { t.Fatal("Unable to create server socket", err) @@ -68,82 +77,117 @@ func TestInitTwoServers(t *testing.T) { secondProcessor := multiplexedprotocoltest.NewSecondProcessor(&SecondImpl{}) processor.RegisterProcessor("SecondService", secondProcessor) + defer server.Stop() go server.Serve() time.Sleep(10 * time.Millisecond) -} -var firstClient *multiplexedprotocoltest.FirstClient - -func TestInitClient1(t *testing.T) { - socket := thrift.NewTSocketFromAddrTimeout(addr, TIMEOUT) - transport := thrift.NewTFramedTransport(socket) - var protocol thrift.TProtocol = thrift.NewTBinaryProtocolTransport(transport) - protocol = thrift.NewTMultiplexedProtocol(protocol, "FirstService") - firstClient = multiplexedprotocoltest.NewFirstClientProtocol(transport, protocol, protocol) - err := transport.Open() + transport, err := createTransport(addr) if err != nil { - t.Fatal("Unable to open client socket", err) + t.Fatal(err) } -} + defer transport.Close() + protocol := thrift.NewTMultiplexedProtocol(thrift.NewTBinaryProtocolTransport(transport), "FirstService") -var secondClient *multiplexedprotocoltest.SecondClient + client := multiplexedprotocoltest.NewFirstClient(thrift.NewTStandardClient(protocol, protocol)) -func TestInitClient2(t *testing.T) { - socket := thrift.NewTSocketFromAddrTimeout(addr, TIMEOUT) - transport := thrift.NewTFramedTransport(socket) - var protocol thrift.TProtocol = thrift.NewTBinaryProtocolTransport(transport) - protocol = thrift.NewTMultiplexedProtocol(protocol, "SecondService") - secondClient = multiplexedprotocoltest.NewSecondClientProtocol(transport, protocol, protocol) - err := transport.Open() - if err != nil { - t.Fatal("Unable to open client socket", err) - } -} - -//create client without service prefix -func createLegacyClient(t *testing.T) *multiplexedprotocoltest.SecondClient { - socket := thrift.NewTSocketFromAddrTimeout(addr, TIMEOUT) - transport := thrift.NewTFramedTransport(socket) - var protocol thrift.TProtocol = thrift.NewTBinaryProtocolTransport(transport) - legacyClient := multiplexedprotocoltest.NewSecondClientProtocol(transport, protocol, protocol) - err := transport.Open() - if err != nil { - t.Fatal("Unable to open client socket", err) - } - return legacyClient -} - -func TestCallFirst(t *testing.T) { - ret, err := firstClient.ReturnOne() + ret, err := client.ReturnOne(defaultCtx) if err != nil { t.Fatal("Unable to call first server:", err) - } - if ret != 1 { + } else if ret != 1 { t.Fatal("Unexpected result from server: ", ret) } } -func TestCallSecond(t *testing.T) { - ret, err := secondClient.ReturnTwo() +func TestMultiplexedProtocolSecond(t *testing.T) { + processor := thrift.NewTMultiplexedProcessor() + protocolFactory := thrift.NewTBinaryProtocolFactoryDefault() + transportFactory := thrift.NewTTransportFactory() + transportFactory = thrift.NewTFramedTransportFactory(transportFactory) + addr := FindAvailableTCPServerPort() + serverTransport, err := thrift.NewTServerSocketTimeout(addr.String(), TIMEOUT) + if err != nil { + t.Fatal("Unable to create server socket", err) + } + server = thrift.NewTSimpleServer4(processor, serverTransport, transportFactory, protocolFactory) + + firstProcessor := multiplexedprotocoltest.NewFirstProcessor(&FirstImpl{}) + processor.RegisterProcessor("FirstService", firstProcessor) + + secondProcessor := multiplexedprotocoltest.NewSecondProcessor(&SecondImpl{}) + processor.RegisterProcessor("SecondService", secondProcessor) + + defer server.Stop() + go server.Serve() + time.Sleep(10 * time.Millisecond) + + transport, err := createTransport(addr) + if err != nil { + t.Fatal(err) + } + defer transport.Close() + protocol := thrift.NewTMultiplexedProtocol(thrift.NewTBinaryProtocolTransport(transport), "SecondService") + + client := multiplexedprotocoltest.NewSecondClient(thrift.NewTStandardClient(protocol, protocol)) + + ret, err := client.ReturnTwo(defaultCtx) if err != nil { t.Fatal("Unable to call second server:", err) - } - if ret != 2 { + } else if ret != 2 { t.Fatal("Unexpected result from server: ", ret) } } -func TestCallLegacy(t *testing.T) { - legacyClient := createLegacyClient(t) - ret, err := legacyClient.ReturnTwo() +func TestMultiplexedProtocolLegacy(t *testing.T) { + processor := thrift.NewTMultiplexedProcessor() + protocolFactory := thrift.NewTBinaryProtocolFactoryDefault() + transportFactory := thrift.NewTTransportFactory() + transportFactory = thrift.NewTFramedTransportFactory(transportFactory) + addr := FindAvailableTCPServerPort() + serverTransport, err := thrift.NewTServerSocketTimeout(addr.String(), TIMEOUT) + if err != nil { + t.Fatal("Unable to create server socket", err) + } + server = thrift.NewTSimpleServer4(processor, serverTransport, transportFactory, protocolFactory) + + firstProcessor := multiplexedprotocoltest.NewFirstProcessor(&FirstImpl{}) + processor.RegisterProcessor("FirstService", firstProcessor) + + secondProcessor := multiplexedprotocoltest.NewSecondProcessor(&SecondImpl{}) + processor.RegisterProcessor("SecondService", secondProcessor) + + defer server.Stop() + go server.Serve() + time.Sleep(10 * time.Millisecond) + + transport, err := createTransport(addr) + if err != nil { + t.Error(err) + return + } + defer transport.Close() + + protocol := thrift.NewTBinaryProtocolTransport(transport) + client := multiplexedprotocoltest.NewSecondClient(thrift.NewTStandardClient(protocol, protocol)) + + ret, err := client.ReturnTwo(defaultCtx) //expect error since default processor is not registered if err == nil { t.Fatal("Expecting error") } + //register default processor and call again processor.RegisterDefault(multiplexedprotocoltest.NewSecondProcessor(&SecondImpl{})) - legacyClient = createLegacyClient(t) - ret, err = legacyClient.ReturnTwo() + transport, err = createTransport(addr) + if err != nil { + t.Error(err) + return + } + defer transport.Close() + + protocol = thrift.NewTBinaryProtocolTransport(transport) + client = multiplexedprotocoltest.NewSecondClient(thrift.NewTStandardClient(protocol, protocol)) + + ret, err = client.ReturnTwo(defaultCtx) if err != nil { t.Fatal("Unable to call legacy server:", err) } @@ -151,9 +195,3 @@ func TestCallLegacy(t *testing.T) { t.Fatal("Unexpected result from server: ", ret) } } - -func TestShutdownServerAndClients(t *testing.T) { - firstClient.Transport.Close() - secondClient.Transport.Close() - server.Stop() -} diff --git a/vendor/git.apache.org/thrift.git/lib/go/test/tests/one_way_test.go b/vendor/git.apache.org/thrift.git/lib/go/test/tests/one_way_test.go index 5bb1dae..48d0bbe 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/test/tests/one_way_test.go +++ b/vendor/git.apache.org/thrift.git/lib/go/test/tests/one_way_test.go @@ -20,6 +20,7 @@ package tests import ( + "context" "fmt" "net" "onewaytest" @@ -39,9 +40,9 @@ func findPort() net.Addr { type impl struct{} -func (i *impl) Hi(in int64, s string) (err error) { fmt.Println("Hi!"); return } -func (i *impl) Emptyfunc() (err error) { return } -func (i *impl) EchoInt(param int64) (r int64, err error) { return param, nil } +func (i *impl) Hi(ctx context.Context, in int64, s string) (err error) { fmt.Println("Hi!"); return } +func (i *impl) Emptyfunc(ctx context.Context) (err error) { return } +func (i *impl) EchoInt(ctx context.Context, param int64) (r int64, err error) { return param, nil } const TIMEOUT = time.Second @@ -66,7 +67,7 @@ func TestInitOneway(t *testing.T) { func TestInitOnewayClient(t *testing.T) { transport := thrift.NewTSocketFromAddrTimeout(addr, TIMEOUT) protocol := thrift.NewTBinaryProtocolTransport(transport) - client = onewaytest.NewOneWayClientProtocol(transport, protocol, protocol) + client = onewaytest.NewOneWayClient(thrift.NewTStandardClient(protocol, protocol)) err := transport.Open() if err != nil { t.Fatal("Unable to open client socket", err) @@ -75,12 +76,12 @@ func TestInitOnewayClient(t *testing.T) { func TestCallOnewayServer(t *testing.T) { //call oneway function - err := client.Hi(1, "") + err := client.Hi(defaultCtx, 1, "") if err != nil { t.Fatal("Unexpected error: ", err) } //There is no way to detect protocol problems with single oneway call so we call it second time - i, err := client.EchoInt(42) + i, err := client.EchoInt(defaultCtx, 42) if err != nil { t.Fatal("Unexpected error: ", err) } diff --git a/vendor/git.apache.org/thrift.git/lib/go/test/tests/protocol_mock.go b/vendor/git.apache.org/thrift.git/lib/go/test/tests/protocol_mock.go index 9197fed..51d7a02 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/test/tests/protocol_mock.go +++ b/vendor/git.apache.org/thrift.git/lib/go/test/tests/protocol_mock.go @@ -23,7 +23,9 @@ package tests import ( + "context" thrift "thrift" + gomock "github.com/golang/mock/gomock" ) @@ -48,13 +50,13 @@ func (_m *MockTProtocol) EXPECT() *_MockTProtocolRecorder { return _m.recorder } -func (_m *MockTProtocol) Flush() error { +func (_m *MockTProtocol) Flush(ctx context.Context) error { ret := _m.ctrl.Call(_m, "Flush") ret0, _ := ret[0].(error) return ret0 } -func (_mr *_MockTProtocolRecorder) Flush() *gomock.Call { +func (_mr *_MockTProtocolRecorder) Flush(ctx context.Context) *gomock.Call { return _mr.mock.ctrl.RecordCall(_mr.mock, "Flush") } diff --git a/vendor/git.apache.org/thrift.git/lib/go/test/tests/protocols_test.go b/vendor/git.apache.org/thrift.git/lib/go/test/tests/protocols_test.go index 1580678..cffd9c3 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/test/tests/protocols_test.go +++ b/vendor/git.apache.org/thrift.git/lib/go/test/tests/protocols_test.go @@ -47,7 +47,7 @@ func RunSocketTestSuite(t *testing.T, protocolFactory thrift.TProtocolFactory, t.Fatal(err) } var protocol thrift.TProtocol = protocolFactory.GetProtocol(transport) - thriftTestClient := thrifttest.NewThriftTestClientProtocol(transport, protocol, protocol) + thriftTestClient := thrifttest.NewThriftTestClient(thrift.NewTStandardClient(protocol, protocol)) err = transport.Open() if err != nil { t.Fatal("Unable to open client socket", err) diff --git a/vendor/git.apache.org/thrift.git/lib/go/test/tests/required_fields_test.go b/vendor/git.apache.org/thrift.git/lib/go/test/tests/required_fields_test.go index 2053712..3fa414a 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/test/tests/required_fields_test.go +++ b/vendor/git.apache.org/thrift.git/lib/go/test/tests/required_fields_test.go @@ -20,12 +20,45 @@ package tests import ( + "context" "github.com/golang/mock/gomock" "optionalfieldstest" + "requiredfieldtest" "testing" "thrift" ) +func TestRequiredField_SucecssWhenSet(t *testing.T) { + // create a new RequiredField instance with the required field set + source := &requiredfieldtest.RequiredField{Name: "this is a test"} + sourceData, err := thrift.NewTSerializer().Write(context.Background(), source) + if err != nil { + t.Fatalf("failed to serialize %T: %v", source, err) + } + + d := thrift.NewTDeserializer() + err = d.Read(&requiredfieldtest.RequiredField{}, sourceData) + if err != nil { + t.Fatalf("Did not expect an error when trying to deserialize the requiredfieldtest.RequiredField: %v", err) + } +} + +func TestRequiredField_ErrorWhenMissing(t *testing.T) { + // create a new OtherThing instance, without setting the required field + source := &requiredfieldtest.OtherThing{} + sourceData, err := thrift.NewTSerializer().Write(context.Background(), source) + if err != nil { + t.Fatalf("failed to serialize %T: %v", source, err) + } + + // attempt to deserialize into a different type (which should fail) + d := thrift.NewTDeserializer() + err = d.Read(&requiredfieldtest.RequiredField{}, sourceData) + if err == nil { + t.Fatal("Expected an error when trying to deserialize an object which is missing a required field") + } +} + func TestStructReadRequiredFields(t *testing.T) { mockCtrl := gomock.NewController(t) protocol := NewMockTProtocol(mockCtrl) @@ -40,6 +73,7 @@ func TestStructReadRequiredFields(t *testing.T) { err := testStruct.Read(protocol) mockCtrl.Finish() + mockCtrl = gomock.NewController(t) if err == nil { t.Fatal("Expected read to fail") } @@ -63,6 +97,7 @@ func TestStructReadRequiredFields(t *testing.T) { err = testStruct.Read(protocol) mockCtrl.Finish() + mockCtrl = gomock.NewController(t) if err == nil { t.Fatal("Expected read to fail") } diff --git a/vendor/git.apache.org/thrift.git/lib/go/test/tests/struct_args_rets_test.go b/vendor/git.apache.org/thrift.git/lib/go/test/tests/struct_args_rets_test.go index 363423d..81e9b26 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/test/tests/struct_args_rets_test.go +++ b/vendor/git.apache.org/thrift.git/lib/go/test/tests/struct_args_rets_test.go @@ -30,7 +30,7 @@ func staticCheckStructArgsResults() { var iface st.AServ var err error - sa, err = iface.StructAFunc_1structA(sa) + sa, err = iface.StructAFunc_1structA(defaultCtx, sa) _ = err _ = sa } diff --git a/vendor/git.apache.org/thrift.git/lib/go/test/tests/thrifttest_driver.go b/vendor/git.apache.org/thrift.git/lib/go/test/tests/thrifttest_driver.go index 1e0cf86..de54cbc 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/test/tests/thrifttest_driver.go +++ b/vendor/git.apache.org/thrift.git/lib/go/test/tests/thrifttest_driver.go @@ -38,15 +38,15 @@ func (p *ThriftTestDriver) Start() { client := p.client t := p.t - if client.TestVoid() != nil { + if client.TestVoid(defaultCtx) != nil { t.Fatal("TestVoid failed") } - if r, err := client.TestString("Test"); r != "Test" || err != nil { + if r, err := client.TestString(defaultCtx, "Test"); r != "Test" || err != nil { t.Fatal("TestString with simple text failed") } - if r, err := client.TestString(""); r != "" || err != nil { + if r, err := client.TestString(defaultCtx, ""); r != "" || err != nil { t.Fatal("TestString with empty text failed") } @@ -76,7 +76,7 @@ func (p *ThriftTestDriver) Start() { "Walon, Winaray, å´è¯­, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, " + "Bân-lâm-gú, 粵語" - if r, err := client.TestString(stringTest); r != stringTest || err != nil { + if r, err := client.TestString(defaultCtx, stringTest); r != stringTest || err != nil { t.Fatal("TestString with all languages failed") } @@ -86,44 +86,44 @@ func (p *ThriftTestDriver) Start() { " now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><" + " char-to-test-json-parsing: ]] \"]] \\\" }}}{ [[[ " - if r, err := client.TestString(specialCharacters); r != specialCharacters || err != nil { + if r, err := client.TestString(defaultCtx, specialCharacters); r != specialCharacters || err != nil { t.Fatal("TestString with specialCharacters failed") } - if r, err := client.TestByte(1); r != 1 || err != nil { + if r, err := client.TestByte(defaultCtx, 1); r != 1 || err != nil { t.Fatal("TestByte(1) failed") } - if r, err := client.TestByte(0); r != 0 || err != nil { + if r, err := client.TestByte(defaultCtx, 0); r != 0 || err != nil { t.Fatal("TestByte(0) failed") } - if r, err := client.TestByte(-1); r != -1 || err != nil { + if r, err := client.TestByte(defaultCtx, -1); r != -1 || err != nil { t.Fatal("TestByte(-1) failed") } - if r, err := client.TestByte(-127); r != -127 || err != nil { + if r, err := client.TestByte(defaultCtx, -127); r != -127 || err != nil { t.Fatal("TestByte(-127) failed") } - if r, err := client.TestI32(-1); r != -1 || err != nil { + if r, err := client.TestI32(defaultCtx, -1); r != -1 || err != nil { t.Fatal("TestI32(-1) failed") } - if r, err := client.TestI32(1); r != 1 || err != nil { + if r, err := client.TestI32(defaultCtx, 1); r != 1 || err != nil { t.Fatal("TestI32(1) failed") } - if r, err := client.TestI64(-5); r != -5 || err != nil { + if r, err := client.TestI64(defaultCtx, -5); r != -5 || err != nil { t.Fatal("TestI64(-5) failed") } - if r, err := client.TestI64(5); r != 5 || err != nil { + if r, err := client.TestI64(defaultCtx, 5); r != 5 || err != nil { t.Fatal("TestI64(5) failed") } - if r, err := client.TestI64(-34359738368); r != -34359738368 || err != nil { + if r, err := client.TestI64(defaultCtx, -34359738368); r != -34359738368 || err != nil { t.Fatal("TestI64(-34359738368) failed") } - if r, err := client.TestDouble(-5.2098523); r != -5.2098523 || err != nil { + if r, err := client.TestDouble(defaultCtx, -5.2098523); r != -5.2098523 || err != nil { t.Fatal("TestDouble(-5.2098523) failed") } - if r, err := client.TestDouble(-7.012052175215044); r != -7.012052175215044 || err != nil { + if r, err := client.TestDouble(defaultCtx, -7.012052175215044); r != -7.012052175215044 || err != nil { t.Fatal("TestDouble(-7.012052175215044) failed") } @@ -134,7 +134,7 @@ func (p *ThriftTestDriver) Start() { out.ByteThing = 1 out.I32Thing = -3 out.I64Thing = 1000000 - if r, err := client.TestStruct(out); !reflect.DeepEqual(r, out) || err != nil { + if r, err := client.TestStruct(defaultCtx, out); !reflect.DeepEqual(r, out) || err != nil { t.Fatal("TestStruct failed") } @@ -142,7 +142,7 @@ func (p *ThriftTestDriver) Start() { out2.ByteThing = 1 out2.StructThing = out out2.I32Thing = 5 - if r, err := client.TestNest(out2); !reflect.DeepEqual(r, out2) || err != nil { + if r, err := client.TestNest(defaultCtx, out2); !reflect.DeepEqual(r, out2) || err != nil { t.Fatal("TestNest failed") } @@ -150,7 +150,7 @@ func (p *ThriftTestDriver) Start() { for i := int32(0); i < 5; i++ { mapout[i] = i - 10 } - if r, err := client.TestMap(mapout); !reflect.DeepEqual(r, mapout) || err != nil { + if r, err := client.TestMap(defaultCtx, mapout); !reflect.DeepEqual(r, mapout) || err != nil { t.Fatal("TestMap failed") } @@ -158,25 +158,25 @@ func (p *ThriftTestDriver) Start() { "a": "123", "a b": "with spaces ", "same": "same", "0": "numeric key", "longValue": stringTest, stringTest: "long key", } - if r, err := client.TestStringMap(mapTestInput); !reflect.DeepEqual(r, mapTestInput) || err != nil { + if r, err := client.TestStringMap(defaultCtx, mapTestInput); !reflect.DeepEqual(r, mapTestInput) || err != nil { t.Fatal("TestStringMap failed") } - setTestInput := map[int32]struct{}{1: {}, 2: {}, 3: {}} - if r, err := client.TestSet(setTestInput); !reflect.DeepEqual(r, setTestInput) || err != nil { + setTestInput := []int32{1, 2, 3} + if r, err := client.TestSet(defaultCtx, setTestInput); !reflect.DeepEqual(r, setTestInput) || err != nil { t.Fatal("TestSet failed") } listTest := []int32{1, 2, 3} - if r, err := client.TestList(listTest); !reflect.DeepEqual(r, listTest) || err != nil { + if r, err := client.TestList(defaultCtx, listTest); !reflect.DeepEqual(r, listTest) || err != nil { t.Fatal("TestList failed") } - if r, err := client.TestEnum(thrifttest.Numberz_ONE); r != thrifttest.Numberz_ONE || err != nil { + if r, err := client.TestEnum(defaultCtx, thrifttest.Numberz_ONE); r != thrifttest.Numberz_ONE || err != nil { t.Fatal("TestEnum failed") } - if r, err := client.TestTypedef(69); r != 69 || err != nil { + if r, err := client.TestTypedef(defaultCtx, 69); r != 69 || err != nil { t.Fatal("TestTypedef failed") } @@ -184,7 +184,7 @@ func (p *ThriftTestDriver) Start() { 4: {1: 1, 2: 2, 3: 3, 4: 4}, -4: {-4: -4, -3: -3, -2: -2, -1: -1}, } - if r, err := client.TestMapMap(1); !reflect.DeepEqual(r, mapMapTest) || err != nil { + if r, err := client.TestMapMap(defaultCtx, 1); !reflect.DeepEqual(r, mapMapTest) || err != nil { t.Fatal("TestMapMap failed") } @@ -212,25 +212,25 @@ func (p *ThriftTestDriver) Start() { 1: {thrifttest.Numberz_TWO: crazy, thrifttest.Numberz_THREE: crazy}, 2: {thrifttest.Numberz_SIX: crazyEmpty}, } - if r, err := client.TestInsanity(crazy); !reflect.DeepEqual(r, insanity) || err != nil { + if r, err := client.TestInsanity(defaultCtx, crazy); !reflect.DeepEqual(r, insanity) || err != nil { t.Fatal("TestInsanity failed") } - if err := client.TestException("TException"); err == nil { + if err := client.TestException(defaultCtx, "TException"); err == nil { t.Fatal("TestException TException failed") } - if err, ok := client.TestException("Xception").(*thrifttest.Xception); ok == false || err == nil { + if err, ok := client.TestException(defaultCtx, "Xception").(*thrifttest.Xception); ok == false || err == nil { t.Fatal("TestException Xception failed") } else if err.ErrorCode != 1001 || err.Message != "Xception" { t.Fatal("TestException Xception failed") } - if err := client.TestException("no Exception"); err != nil { + if err := client.TestException(defaultCtx, "no Exception"); err != nil { t.Fatal("TestException no Exception failed") } - if err := client.TestOneway(0); err != nil { + if err := client.TestOneway(defaultCtx, 0); err != nil { t.Fatal("TestOneway failed") } } diff --git a/vendor/git.apache.org/thrift.git/lib/go/test/tests/thrifttest_handler.go b/vendor/git.apache.org/thrift.git/lib/go/test/tests/thrifttest_handler.go index 822a6c7..31b9ee2 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/test/tests/thrifttest_handler.go +++ b/vendor/git.apache.org/thrift.git/lib/go/test/tests/thrifttest_handler.go @@ -20,6 +20,7 @@ package tests import ( + "context" "errors" "thrift" "thrifttest" @@ -33,11 +34,11 @@ func NewSecondServiceHandler() *SecondServiceHandler { return &SecondServiceHandler{} } -func (p *SecondServiceHandler) BlahBlah() (err error) { +func (p *SecondServiceHandler) BlahBlah(ctx context.Context) (err error) { return nil } -func (p *SecondServiceHandler) SecondtestString(thing string) (r string, err error) { +func (p *SecondServiceHandler) SecondtestString(ctx context.Context, thing string) (r string, err error) { return thing, nil } @@ -48,71 +49,71 @@ func NewThriftTestHandler() *ThriftTestHandler { return &ThriftTestHandler{} } -func (p *ThriftTestHandler) TestVoid() (err error) { +func (p *ThriftTestHandler) TestVoid(ctx context.Context) (err error) { return nil } -func (p *ThriftTestHandler) TestString(thing string) (r string, err error) { +func (p *ThriftTestHandler) TestString(ctx context.Context, thing string) (r string, err error) { return thing, nil } -func (p *ThriftTestHandler) TestBool(thing bool) (r bool, err error) { +func (p *ThriftTestHandler) TestBool(ctx context.Context, thing bool) (r bool, err error) { return thing, nil } -func (p *ThriftTestHandler) TestByte(thing int8) (r int8, err error) { +func (p *ThriftTestHandler) TestByte(ctx context.Context, thing int8) (r int8, err error) { return thing, nil } -func (p *ThriftTestHandler) TestI32(thing int32) (r int32, err error) { +func (p *ThriftTestHandler) TestI32(ctx context.Context, thing int32) (r int32, err error) { return thing, nil } -func (p *ThriftTestHandler) TestI64(thing int64) (r int64, err error) { +func (p *ThriftTestHandler) TestI64(ctx context.Context, thing int64) (r int64, err error) { return thing, nil } -func (p *ThriftTestHandler) TestDouble(thing float64) (r float64, err error) { +func (p *ThriftTestHandler) TestDouble(ctx context.Context, thing float64) (r float64, err error) { return thing, nil } -func (p *ThriftTestHandler) TestBinary(thing []byte) (r []byte, err error) { +func (p *ThriftTestHandler) TestBinary(ctx context.Context, thing []byte) (r []byte, err error) { return thing, nil } -func (p *ThriftTestHandler) TestStruct(thing *thrifttest.Xtruct) (r *thrifttest.Xtruct, err error) { +func (p *ThriftTestHandler) TestStruct(ctx context.Context, thing *thrifttest.Xtruct) (r *thrifttest.Xtruct, err error) { return thing, nil } -func (p *ThriftTestHandler) TestNest(thing *thrifttest.Xtruct2) (r *thrifttest.Xtruct2, err error) { +func (p *ThriftTestHandler) TestNest(ctx context.Context, thing *thrifttest.Xtruct2) (r *thrifttest.Xtruct2, err error) { return thing, nil } -func (p *ThriftTestHandler) TestMap(thing map[int32]int32) (r map[int32]int32, err error) { +func (p *ThriftTestHandler) TestMap(ctx context.Context, thing map[int32]int32) (r map[int32]int32, err error) { return thing, nil } -func (p *ThriftTestHandler) TestStringMap(thing map[string]string) (r map[string]string, err error) { +func (p *ThriftTestHandler) TestStringMap(ctx context.Context, thing map[string]string) (r map[string]string, err error) { return thing, nil } -func (p *ThriftTestHandler) TestSet(thing map[int32]struct{}) (r map[int32]struct{}, err error) { +func (p *ThriftTestHandler) TestSet(ctx context.Context, thing []int32) (r []int32, err error) { return thing, nil } -func (p *ThriftTestHandler) TestList(thing []int32) (r []int32, err error) { +func (p *ThriftTestHandler) TestList(ctx context.Context, thing []int32) (r []int32, err error) { return thing, nil } -func (p *ThriftTestHandler) TestEnum(thing thrifttest.Numberz) (r thrifttest.Numberz, err error) { +func (p *ThriftTestHandler) TestEnum(ctx context.Context, thing thrifttest.Numberz) (r thrifttest.Numberz, err error) { return thing, nil } -func (p *ThriftTestHandler) TestTypedef(thing thrifttest.UserId) (r thrifttest.UserId, err error) { +func (p *ThriftTestHandler) TestTypedef(ctx context.Context, thing thrifttest.UserId) (r thrifttest.UserId, err error) { return thing, nil } -func (p *ThriftTestHandler) TestMapMap(hello int32) (r map[int32]map[int32]int32, err error) { +func (p *ThriftTestHandler) TestMapMap(ctx context.Context, hello int32) (r map[int32]map[int32]int32, err error) { r = make(map[int32]map[int32]int32) pos := make(map[int32]int32) neg := make(map[int32]int32) @@ -127,7 +128,7 @@ func (p *ThriftTestHandler) TestMapMap(hello int32) (r map[int32]map[int32]int32 return r, nil } -func (p *ThriftTestHandler) TestInsanity(argument *thrifttest.Insanity) (r map[thrifttest.UserId]map[thrifttest.Numberz]*thrifttest.Insanity, err error) { +func (p *ThriftTestHandler) TestInsanity(ctx context.Context, argument *thrifttest.Insanity) (r map[thrifttest.UserId]map[thrifttest.Numberz]*thrifttest.Insanity, err error) { hello := thrifttest.NewXtruct() hello.StringThing = "Hello2" hello.ByteThing = 2 @@ -162,7 +163,7 @@ func (p *ThriftTestHandler) TestInsanity(argument *thrifttest.Insanity) (r map[t return insane, nil } -func (p *ThriftTestHandler) TestMulti(arg0 int8, arg1 int32, arg2 int64, arg3 map[int16]string, arg4 thrifttest.Numberz, arg5 thrifttest.UserId) (r *thrifttest.Xtruct, err error) { +func (p *ThriftTestHandler) TestMulti(ctx context.Context, arg0 int8, arg1 int32, arg2 int64, arg3 map[int16]string, arg4 thrifttest.Numberz, arg5 thrifttest.UserId) (r *thrifttest.Xtruct, err error) { r = thrifttest.NewXtruct() r.StringThing = "Hello2" r.ByteThing = arg0 @@ -171,7 +172,7 @@ func (p *ThriftTestHandler) TestMulti(arg0 int8, arg1 int32, arg2 int64, arg3 ma return r, nil } -func (p *ThriftTestHandler) TestException(arg string) (err error) { +func (p *ThriftTestHandler) TestException(ctx context.Context, arg string) (err error) { if arg == "Xception" { x := thrifttest.NewXception() x.ErrorCode = 1001 @@ -184,7 +185,7 @@ func (p *ThriftTestHandler) TestException(arg string) (err error) { } } -func (p *ThriftTestHandler) TestMultiException(arg0 string, arg1 string) (r *thrifttest.Xtruct, err error) { +func (p *ThriftTestHandler) TestMultiException(ctx context.Context, arg0 string, arg1 string) (r *thrifttest.Xtruct, err error) { if arg0 == "Xception" { x := thrifttest.NewXception() x.ErrorCode = 1001 @@ -203,7 +204,7 @@ func (p *ThriftTestHandler) TestMultiException(arg0 string, arg1 string) (r *thr return res, nil } -func (p *ThriftTestHandler) TestOneway(secondsToSleep int32) (err error) { +func (p *ThriftTestHandler) TestOneway(ctx context.Context, secondsToSleep int32) (err error) { time.Sleep(time.Second * time.Duration(secondsToSleep)) return nil } diff --git a/vendor/git.apache.org/thrift.git/lib/go/test/tests/union_binary_test.go b/vendor/git.apache.org/thrift.git/lib/go/test/tests/union_binary_test.go new file mode 100644 index 0000000..bdae2cb --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/go/test/tests/union_binary_test.go @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +package tests + +import ( + "testing" + "unionbinarytest" +) + + +// See https://issues.apache.org/jira/browse/THRIFT-4573 +func TestUnionBinary(t *testing.T) { + s := unionbinarytest.NewSample() + s.U1 = map[string]string{} + s.U2 = []byte{} + if n := s.CountSetFieldsSample(); n != 2 { + t.Errorf("Expected 2 set fields, got %d!", n) + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/application_exception.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/application_exception.go index 6655cc5..b9d7eed 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/application_exception.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/application_exception.go @@ -30,11 +30,22 @@ const ( PROTOCOL_ERROR = 7 ) +var defaultApplicationExceptionMessage = map[int32]string{ + UNKNOWN_APPLICATION_EXCEPTION: "unknown application exception", + UNKNOWN_METHOD: "unknown method", + INVALID_MESSAGE_TYPE_EXCEPTION: "invalid message type", + WRONG_METHOD_NAME: "wrong method name", + BAD_SEQUENCE_ID: "bad sequence ID", + MISSING_RESULT: "missing result", + INTERNAL_ERROR: "unknown internal error", + PROTOCOL_ERROR: "unknown protocol error", +} + // Application level Thrift exception type TApplicationException interface { TException TypeId() int32 - Read(iprot TProtocol) (TApplicationException, error) + Read(iprot TProtocol) error Write(oprot TProtocol) error } @@ -44,7 +55,10 @@ type tApplicationException struct { } func (e tApplicationException) Error() string { - return e.message + if e.message != "" { + return e.message + } + return defaultApplicationExceptionMessage[e.type_] } func NewTApplicationException(type_ int32, message string) TApplicationException { @@ -55,10 +69,11 @@ func (p *tApplicationException) TypeId() int32 { return p.type_ } -func (p *tApplicationException) Read(iprot TProtocol) (TApplicationException, error) { +func (p *tApplicationException) Read(iprot TProtocol) error { + // TODO: this should really be generated by the compiler _, err := iprot.ReadStructBegin() if err != nil { - return nil, err + return err } message := "" @@ -67,7 +82,7 @@ func (p *tApplicationException) Read(iprot TProtocol) (TApplicationException, er for { _, ttype, id, err := iprot.ReadFieldBegin() if err != nil { - return nil, err + return err } if ttype == STOP { break @@ -76,33 +91,40 @@ func (p *tApplicationException) Read(iprot TProtocol) (TApplicationException, er case 1: if ttype == STRING { if message, err = iprot.ReadString(); err != nil { - return nil, err + return err } } else { if err = SkipDefaultDepth(iprot, ttype); err != nil { - return nil, err + return err } } case 2: if ttype == I32 { if type_, err = iprot.ReadI32(); err != nil { - return nil, err + return err } } else { if err = SkipDefaultDepth(iprot, ttype); err != nil { - return nil, err + return err } } default: if err = SkipDefaultDepth(iprot, ttype); err != nil { - return nil, err + return err } } if err = iprot.ReadFieldEnd(); err != nil { - return nil, err + return err } } - return NewTApplicationException(type_, message), iprot.ReadStructEnd() + if err := iprot.ReadStructEnd(); err != nil { + return err + } + + p.message = message + p.type_ = type_ + + return nil } func (p *tApplicationException) Write(oprot TProtocol) (err error) { diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/application_exception_test.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/application_exception_test.go index 7010f86..7743357 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/application_exception_test.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/application_exception_test.go @@ -25,17 +25,17 @@ import ( func TestTApplicationException(t *testing.T) { exc := NewTApplicationException(UNKNOWN_APPLICATION_EXCEPTION, "") - if exc.Error() != "" { + if exc.Error() != defaultApplicationExceptionMessage[UNKNOWN_APPLICATION_EXCEPTION] { t.Fatalf("Expected empty string for exception but found '%s'", exc.Error()) } if exc.TypeId() != UNKNOWN_APPLICATION_EXCEPTION { - t.Fatalf("Expected type UNKNOWN for exception but found '%s'", exc.TypeId()) + t.Fatalf("Expected type UNKNOWN for exception but found '%v'", exc.TypeId()) } exc = NewTApplicationException(WRONG_METHOD_NAME, "junk_method") if exc.Error() != "junk_method" { t.Fatalf("Expected 'junk_method' for exception but found '%s'", exc.Error()) } if exc.TypeId() != WRONG_METHOD_NAME { - t.Fatalf("Expected type WRONG_METHOD_NAME for exception but found '%s'", exc.TypeId()) + t.Fatalf("Expected type WRONG_METHOD_NAME for exception but found '%v'", exc.TypeId()) } } diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/binary_protocol.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/binary_protocol.go index 690d341..1f90bf4 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/binary_protocol.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/binary_protocol.go @@ -21,6 +21,7 @@ package thrift import ( "bytes" + "context" "encoding/binary" "errors" "fmt" @@ -447,9 +448,6 @@ func (p *TBinaryProtocol) ReadBinary() ([]byte, error) { if size < 0 { return nil, invalidDataLength } - if uint64(size) > p.trans.RemainingBytes() { - return nil, invalidDataLength - } isize := int(size) buf := make([]byte, isize) @@ -457,8 +455,8 @@ func (p *TBinaryProtocol) ReadBinary() ([]byte, error) { return buf, NewTProtocolException(err) } -func (p *TBinaryProtocol) Flush() (err error) { - return NewTProtocolException(p.trans.Flush()) +func (p *TBinaryProtocol) Flush(ctx context.Context) (err error) { + return NewTProtocolException(p.trans.Flush(ctx)) } func (p *TBinaryProtocol) Skip(fieldType TType) (err error) { @@ -480,9 +478,6 @@ func (p *TBinaryProtocol) readStringBody(size int32) (value string, err error) { if size < 0 { return "", nil } - if uint64(size) > p.trans.RemainingBytes() { - return "", invalidDataLength - } var ( buf bytes.Buffer diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/buffered_transport.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/buffered_transport.go index b754f92..9670206 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/buffered_transport.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/buffered_transport.go @@ -21,6 +21,7 @@ package thrift import ( "bufio" + "context" ) type TBufferedTransportFactory struct { @@ -78,12 +79,12 @@ func (p *TBufferedTransport) Write(b []byte) (int, error) { return n, err } -func (p *TBufferedTransport) Flush() error { +func (p *TBufferedTransport) Flush(ctx context.Context) error { if err := p.ReadWriter.Flush(); err != nil { p.ReadWriter.Writer.Reset(p.tp) return err } - return p.tp.Flush() + return p.tp.Flush(ctx) } func (p *TBufferedTransport) RemainingBytes() (num_bytes uint64) { diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/client.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/client.go new file mode 100644 index 0000000..28791cc --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/client.go @@ -0,0 +1,85 @@ +package thrift + +import ( + "context" + "fmt" +) + +type TClient interface { + Call(ctx context.Context, method string, args, result TStruct) error +} + +type TStandardClient struct { + seqId int32 + iprot, oprot TProtocol +} + +// TStandardClient implements TClient, and uses the standard message format for Thrift. +// It is not safe for concurrent use. +func NewTStandardClient(inputProtocol, outputProtocol TProtocol) *TStandardClient { + return &TStandardClient{ + iprot: inputProtocol, + oprot: outputProtocol, + } +} + +func (p *TStandardClient) Send(ctx context.Context, oprot TProtocol, seqId int32, method string, args TStruct) error { + if err := oprot.WriteMessageBegin(method, CALL, seqId); err != nil { + return err + } + if err := args.Write(oprot); err != nil { + return err + } + if err := oprot.WriteMessageEnd(); err != nil { + return err + } + return oprot.Flush(ctx) +} + +func (p *TStandardClient) Recv(iprot TProtocol, seqId int32, method string, result TStruct) error { + rMethod, rTypeId, rSeqId, err := iprot.ReadMessageBegin() + if err != nil { + return err + } + + if method != rMethod { + return NewTApplicationException(WRONG_METHOD_NAME, fmt.Sprintf("%s: wrong method name", method)) + } else if seqId != rSeqId { + return NewTApplicationException(BAD_SEQUENCE_ID, fmt.Sprintf("%s: out of order sequence response", method)) + } else if rTypeId == EXCEPTION { + var exception tApplicationException + if err := exception.Read(iprot); err != nil { + return err + } + + if err := iprot.ReadMessageEnd(); err != nil { + return err + } + + return &exception + } else if rTypeId != REPLY { + return NewTApplicationException(INVALID_MESSAGE_TYPE_EXCEPTION, fmt.Sprintf("%s: invalid message type", method)) + } + + if err := result.Read(iprot); err != nil { + return err + } + + return iprot.ReadMessageEnd() +} + +func (p *TStandardClient) Call(ctx context.Context, method string, args, result TStruct) error { + p.seqId++ + seqId := p.seqId + + if err := p.Send(ctx, p.oprot, seqId, method, args); err != nil { + return err + } + + // method is oneway + if result == nil { + return nil + } + + return p.Recv(p.iprot, seqId, method, result) +} diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/processor.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/common_test.go similarity index 74% rename from vendor/git.apache.org/thrift.git/lib/go/thrift/processor.go rename to vendor/git.apache.org/thrift.git/lib/go/thrift/common_test.go index ca0d3fa..93597ff 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/processor.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/common_test.go @@ -19,12 +19,12 @@ package thrift -// A processor is a generic object which operates upon an input stream and -// writes to some output stream. -type TProcessor interface { - Process(in, out TProtocol) (bool, TException) +import "context" + +type mockProcessor struct { + ProcessFunc func(in, out TProtocol) (bool, TException) } -type TProcessorFunction interface { - Process(seqId int32, in, out TProtocol) (bool, TException) +func (m *mockProcessor) Process(ctx context.Context, in, out TProtocol) (bool, TException) { + return m.ProcessFunc(in, out) } diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/compact_protocol.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/compact_protocol.go index 0bc5fdd..1900d50 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/compact_protocol.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/compact_protocol.go @@ -20,6 +20,7 @@ package thrift import ( + "context" "encoding/binary" "fmt" "io" @@ -561,9 +562,6 @@ func (p *TCompactProtocol) ReadString() (value string, err error) { if length < 0 { return "", invalidDataLength } - if uint64(length) > p.trans.RemainingBytes() { - return "", invalidDataLength - } if length == 0 { return "", nil @@ -590,17 +588,14 @@ func (p *TCompactProtocol) ReadBinary() (value []byte, err error) { if length < 0 { return nil, invalidDataLength } - if uint64(length) > p.trans.RemainingBytes() { - return nil, invalidDataLength - } buf := make([]byte, length) _, e = io.ReadFull(p.trans, buf) return buf, NewTProtocolException(e) } -func (p *TCompactProtocol) Flush() (err error) { - return NewTProtocolException(p.trans.Flush()) +func (p *TCompactProtocol) Flush(ctx context.Context) (err error) { + return NewTProtocolException(p.trans.Flush(ctx)) } func (p *TCompactProtocol) Skip(fieldType TType) (err error) { @@ -806,7 +801,7 @@ func (p *TCompactProtocol) getTType(t tCompactType) (TType, error) { case COMPACT_STRUCT: return STRUCT, nil } - return STOP, TException(fmt.Errorf("don't know what type: %s", t&0x0f)) + return STOP, TException(fmt.Errorf("don't know what type: %v", t&0x0f)) } // Given a TType value, find the appropriate TCompactProtocol.Types constant. diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/compact_protocol_test.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/compact_protocol_test.go index f940b4e..65f77f2 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/compact_protocol_test.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/compact_protocol_test.go @@ -26,11 +26,18 @@ import ( func TestReadWriteCompactProtocol(t *testing.T) { ReadWriteProtocolTest(t, NewTCompactProtocolFactory()) + transports := []TTransport{ NewTMemoryBuffer(), NewStreamTransportRW(bytes.NewBuffer(make([]byte, 0, 16384))), NewTFramedTransport(NewTMemoryBuffer()), } + + zlib0, _ := NewTZlibTransport(NewTMemoryBuffer(), 0) + zlib6, _ := NewTZlibTransport(NewTMemoryBuffer(), 6) + zlib9, _ := NewTZlibTransport(NewTFramedTransport(NewTMemoryBuffer()), 9) + transports = append(transports, zlib0, zlib6, zlib9) + for _, trans := range transports { p := NewTCompactProtocol(trans) ReadWriteBool(t, p, trans) diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/context.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/context.go new file mode 100644 index 0000000..d15c1bc --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/context.go @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +package thrift + +import "context" + +var defaultCtx = context.Background() diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/debug_protocol.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/debug_protocol.go index d37252c..57943e0 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/debug_protocol.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/debug_protocol.go @@ -20,6 +20,7 @@ package thrift import ( + "context" "log" ) @@ -258,8 +259,8 @@ func (tdp *TDebugProtocol) Skip(fieldType TType) (err error) { log.Printf("%sSkip(fieldType=%#v) (err=%#v)", tdp.LogPrefix, fieldType, err) return } -func (tdp *TDebugProtocol) Flush() (err error) { - err = tdp.Delegate.Flush() +func (tdp *TDebugProtocol) Flush(ctx context.Context) (err error) { + err = tdp.Delegate.Flush(ctx) log.Printf("%sFlush() (err=%#v)", tdp.LogPrefix, err) return } diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/framed_transport.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/framed_transport.go index 4ae1425..81fa65a 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/framed_transport.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/framed_transport.go @@ -22,6 +22,7 @@ package thrift import ( "bufio" "bytes" + "context" "encoding/binary" "fmt" "io" @@ -135,21 +136,23 @@ func (p *TFramedTransport) WriteString(s string) (n int, err error) { return p.buf.WriteString(s) } -func (p *TFramedTransport) Flush() error { +func (p *TFramedTransport) Flush(ctx context.Context) error { size := p.buf.Len() buf := p.buffer[:4] binary.BigEndian.PutUint32(buf, uint32(size)) _, err := p.transport.Write(buf) if err != nil { + p.buf.Truncate(0) return NewTTransportExceptionFromError(err) } if size > 0 { if n, err := p.buf.WriteTo(p.transport); err != nil { print("Error while flushing write buffer of size ", size, " to transport, only wrote ", n, " bytes: ", err.Error(), "\n") + p.buf.Truncate(0) return NewTTransportExceptionFromError(err) } } - err = p.transport.Flush() + err = p.transport.Flush(ctx) return NewTTransportExceptionFromError(err) } diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/http_client.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/http_client.go index 33f2aa4..5c82bf5 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/http_client.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/http_client.go @@ -21,6 +21,7 @@ package thrift import ( "bytes" + "context" "io" "io/ioutil" "net/http" @@ -181,7 +182,7 @@ func (p *THttpClient) WriteString(s string) (n int, err error) { return p.requestBuffer.WriteString(s) } -func (p *THttpClient) Flush() error { +func (p *THttpClient) Flush(ctx context.Context) error { // Close any previous response body to avoid leaking connections. p.closeResponse() @@ -190,6 +191,9 @@ func (p *THttpClient) Flush() error { return NewTTransportExceptionFromError(err) } req.Header = p.header + if ctx != nil { + req = req.WithContext(ctx) + } response, err := p.client.Do(req) if err != nil { return NewTTransportExceptionFromError(err) diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/http_transport.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/http_transport.go index f6d7458..66f0f38 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/http_transport.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/http_transport.go @@ -19,16 +19,45 @@ package thrift -import "net/http" +import ( + "compress/gzip" + "io" + "net/http" + "strings" +) // NewThriftHandlerFunc is a function that create a ready to use Apache Thrift Handler function func NewThriftHandlerFunc(processor TProcessor, inPfactory, outPfactory TProtocolFactory) func(w http.ResponseWriter, r *http.Request) { - return func(w http.ResponseWriter, r *http.Request) { + return gz(func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Content-Type", "application/x-thrift") transport := NewStreamTransport(r.Body, w) - processor.Process(inPfactory.GetProtocol(transport), outPfactory.GetProtocol(transport)) + processor.Process(r.Context(), inPfactory.GetProtocol(transport), outPfactory.GetProtocol(transport)) + }) +} + +// gz transparently compresses the HTTP response if the client supports it. +func gz(handler http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { + handler(w, r) + return + } + w.Header().Set("Content-Encoding", "gzip") + gz := gzip.NewWriter(w) + defer gz.Close() + gzw := gzipResponseWriter{Writer: gz, ResponseWriter: w} + handler(gzw, r) } } + +type gzipResponseWriter struct { + io.Writer + http.ResponseWriter +} + +func (w gzipResponseWriter) Write(b []byte) (int, error) { + return w.Writer.Write(b) +} diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/iostream_transport.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/iostream_transport.go index b18be81..fea93bc 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/iostream_transport.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/iostream_transport.go @@ -21,6 +21,7 @@ package thrift import ( "bufio" + "context" "io" ) @@ -138,7 +139,7 @@ func (p *StreamTransport) Close() error { } // Flushes the underlying output stream if not null. -func (p *StreamTransport) Flush() error { +func (p *StreamTransport) Flush(ctx context.Context) error { if p.Writer == nil { return NewTTransportException(NOT_OPEN, "Cannot flush null outputStream") } diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/json_protocol.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/json_protocol.go index 442fa91..7be685d 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/json_protocol.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/json_protocol.go @@ -20,6 +20,7 @@ package thrift import ( + "context" "encoding/base64" "fmt" ) @@ -438,10 +439,10 @@ func (p *TJSONProtocol) ReadBinary() ([]byte, error) { return v, p.ParsePostValue() } -func (p *TJSONProtocol) Flush() (err error) { +func (p *TJSONProtocol) Flush(ctx context.Context) (err error) { err = p.writer.Flush() if err == nil { - err = p.trans.Flush() + err = p.trans.Flush(ctx) } return NewTProtocolException(err) } diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/json_protocol_test.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/json_protocol_test.go index 7104ce3..59c4d64 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/json_protocol_test.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/json_protocol_test.go @@ -20,6 +20,7 @@ package thrift import ( + "context" "encoding/base64" "encoding/json" "fmt" @@ -36,7 +37,7 @@ func TestWriteJSONProtocolBool(t *testing.T) { if e := p.WriteBool(value); e != nil { t.Fatalf("Unable to write %s value %v due to error: %s", thetype, value, e.Error()) } - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s value %v due to error flushing: %s", thetype, value, e.Error()) } s := trans.String() @@ -68,7 +69,7 @@ func TestReadJSONProtocolBool(t *testing.T) { } else { trans.Write([]byte{'0'}) // not JSON_FALSE } - trans.Flush() + trans.Flush(context.Background()) s := trans.String() v, e := p.ReadBool() if e != nil { @@ -94,7 +95,7 @@ func TestWriteJSONProtocolByte(t *testing.T) { if e := p.WriteByte(value); e != nil { t.Fatalf("Unable to write %s value %v due to error: %s", thetype, value, e.Error()) } - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s value %v due to error flushing: %s", thetype, value, e.Error()) } s := trans.String() @@ -116,7 +117,7 @@ func TestReadJSONProtocolByte(t *testing.T) { trans := NewTMemoryBuffer() p := NewTJSONProtocol(trans) trans.WriteString(strconv.Itoa(int(value))) - trans.Flush() + trans.Flush(context.Background()) s := trans.String() v, e := p.ReadByte() if e != nil { @@ -141,7 +142,7 @@ func TestWriteJSONProtocolI16(t *testing.T) { if e := p.WriteI16(value); e != nil { t.Fatalf("Unable to write %s value %v due to error: %s", thetype, value, e.Error()) } - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s value %v due to error flushing: %s", thetype, value, e.Error()) } s := trans.String() @@ -163,7 +164,7 @@ func TestReadJSONProtocolI16(t *testing.T) { trans := NewTMemoryBuffer() p := NewTJSONProtocol(trans) trans.WriteString(strconv.Itoa(int(value))) - trans.Flush() + trans.Flush(context.Background()) s := trans.String() v, e := p.ReadI16() if e != nil { @@ -188,7 +189,7 @@ func TestWriteJSONProtocolI32(t *testing.T) { if e := p.WriteI32(value); e != nil { t.Fatalf("Unable to write %s value %v due to error: %s", thetype, value, e.Error()) } - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s value %v due to error flushing: %s", thetype, value, e.Error()) } s := trans.String() @@ -210,7 +211,7 @@ func TestReadJSONProtocolI32(t *testing.T) { trans := NewTMemoryBuffer() p := NewTJSONProtocol(trans) trans.WriteString(strconv.Itoa(int(value))) - trans.Flush() + trans.Flush(context.Background()) s := trans.String() v, e := p.ReadI32() if e != nil { @@ -235,7 +236,7 @@ func TestWriteJSONProtocolI64(t *testing.T) { if e := p.WriteI64(value); e != nil { t.Fatalf("Unable to write %s value %v due to error: %s", thetype, value, e.Error()) } - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s value %v due to error flushing: %s", thetype, value, e.Error()) } s := trans.String() @@ -257,7 +258,7 @@ func TestReadJSONProtocolI64(t *testing.T) { trans := NewTMemoryBuffer() p := NewTJSONProtocol(trans) trans.WriteString(strconv.FormatInt(value, 10)) - trans.Flush() + trans.Flush(context.Background()) s := trans.String() v, e := p.ReadI64() if e != nil { @@ -282,7 +283,7 @@ func TestWriteJSONProtocolDouble(t *testing.T) { if e := p.WriteDouble(value); e != nil { t.Fatalf("Unable to write %s value %v due to error: %s", thetype, value, e.Error()) } - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s value %v due to error flushing: %s", thetype, value, e.Error()) } s := trans.String() @@ -319,7 +320,7 @@ func TestReadJSONProtocolDouble(t *testing.T) { p := NewTJSONProtocol(trans) n := NewNumericFromDouble(value) trans.WriteString(n.String()) - trans.Flush() + trans.Flush(context.Background()) s := trans.String() v, e := p.ReadDouble() if e != nil { @@ -358,7 +359,7 @@ func TestWriteJSONProtocolString(t *testing.T) { if e := p.WriteString(value); e != nil { t.Fatalf("Unable to write %s value %v due to error: %s", thetype, value, e.Error()) } - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s value %v due to error flushing: %s", thetype, value, e.Error()) } s := trans.String() @@ -380,7 +381,7 @@ func TestReadJSONProtocolString(t *testing.T) { trans := NewTMemoryBuffer() p := NewTJSONProtocol(trans) trans.WriteString(jsonQuote(value)) - trans.Flush() + trans.Flush(context.Background()) s := trans.String() v, e := p.ReadString() if e != nil { @@ -409,7 +410,7 @@ func TestWriteJSONProtocolBinary(t *testing.T) { if e := p.WriteBinary(value); e != nil { t.Fatalf("Unable to write %s value %v due to error: %s", thetype, value, e.Error()) } - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s value %v due to error flushing: %s", thetype, value, e.Error()) } s := trans.String() @@ -441,7 +442,7 @@ func TestReadJSONProtocolBinary(t *testing.T) { trans := NewTMemoryBuffer() p := NewTJSONProtocol(trans) trans.WriteString(jsonQuote(b64String)) - trans.Flush() + trans.Flush(context.Background()) s := trans.String() v, e := p.ReadBinary() if e != nil { @@ -474,7 +475,7 @@ func TestWriteJSONProtocolList(t *testing.T) { } } p.WriteListEnd() - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s due to error flushing: %s", thetype, e.Error()) } str := trans.String() @@ -528,7 +529,7 @@ func TestWriteJSONProtocolSet(t *testing.T) { } } p.WriteSetEnd() - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s due to error flushing: %s", thetype, e.Error()) } str := trans.String() @@ -585,12 +586,12 @@ func TestWriteJSONProtocolMap(t *testing.T) { } } p.WriteMapEnd() - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s due to error flushing: %s", thetype, e.Error()) } str := trans.String() if str[0] != '[' || str[len(str)-1] != ']' { - t.Fatalf("Bad value for %s, wrote: %q, in go: %q", thetype, str, DOUBLE_VALUES) + t.Fatalf("Bad value for %s, wrote: %v, in go: %v", thetype, str, DOUBLE_VALUES) } expectedKeyType, expectedValueType, expectedSize, err := p.ReadMapBegin() if err != nil { diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/memory_buffer.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/memory_buffer.go index 97a4edf..5936d27 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/memory_buffer.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/memory_buffer.go @@ -21,6 +21,7 @@ package thrift import ( "bytes" + "context" ) // Memory buffer-based implementation of the TTransport interface. @@ -70,7 +71,7 @@ func (p *TMemoryBuffer) Close() error { } // Flushing a memory buffer is a no-op -func (p *TMemoryBuffer) Flush() error { +func (p *TMemoryBuffer) Flush(ctx context.Context) error { return nil } diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/multiplexed_protocol.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/multiplexed_protocol.go index 3157e0d..d028a30 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/multiplexed_protocol.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/multiplexed_protocol.go @@ -20,6 +20,7 @@ package thrift import ( + "context" "fmt" "strings" ) @@ -127,7 +128,7 @@ func (t *TMultiplexedProcessor) RegisterProcessor(name string, processor TProces t.serviceProcessorMap[name] = processor } -func (t *TMultiplexedProcessor) Process(in, out TProtocol) (bool, TException) { +func (t *TMultiplexedProcessor) Process(ctx context.Context, in, out TProtocol) (bool, TException) { name, typeId, seqid, err := in.ReadMessageBegin() if err != nil { return false, err @@ -140,7 +141,7 @@ func (t *TMultiplexedProcessor) Process(in, out TProtocol) (bool, TException) { if len(v) != 2 { if t.DefaultProcessor != nil { smb := NewStoredMessageProtocol(in, name, typeId, seqid) - return t.DefaultProcessor.Process(smb, out) + return t.DefaultProcessor.Process(ctx, smb, out) } return false, fmt.Errorf("Service name not found in message name: %s. Did you forget to use a TMultiplexProtocol in your client?", name) } @@ -149,7 +150,7 @@ func (t *TMultiplexedProcessor) Process(in, out TProtocol) (bool, TException) { return false, fmt.Errorf("Service name not found: %s. Did you forget to call registerProcessor()?", v[0]) } smb := NewStoredMessageProtocol(in, v[1], typeId, seqid) - return actualProcessor.Process(smb, out) + return actualProcessor.Process(ctx, smb, out) } //Protocol that use stored message for ReadMessageBegin diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/processor_factory.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/processor_factory.go index 9d645df..e4b132b 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/processor_factory.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/processor_factory.go @@ -19,6 +19,18 @@ package thrift +import "context" + +// A processor is a generic object which operates upon an input stream and +// writes to some output stream. +type TProcessor interface { + Process(ctx context.Context, in, out TProtocol) (bool, TException) +} + +type TProcessorFunction interface { + Process(ctx context.Context, seqId int32, in, out TProtocol) (bool, TException) +} + // The default processor factory just returns a singleton // instance. type TProcessorFactory interface { diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/protocol.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/protocol.go index 5b77363..615b7a4 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/protocol.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/protocol.go @@ -20,7 +20,9 @@ package thrift import ( + "context" "errors" + "fmt" ) const ( @@ -73,7 +75,7 @@ type TProtocol interface { ReadBinary() (value []byte, err error) Skip(fieldType TType) (err error) - Flush() (err error) + Flush(ctx context.Context) (err error) Transport() TTransport } @@ -170,6 +172,8 @@ func Skip(self TProtocol, fieldType TType, maxDepth int) (err error) { } } return self.ReadListEnd() + default: + return NewTProtocolExceptionWithType(INVALID_DATA, errors.New(fmt.Sprintf("Unknown data type %d", fieldType))) } return nil } diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/protocol_test.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/protocol_test.go index 2573312..944055c 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/protocol_test.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/protocol_test.go @@ -21,6 +21,7 @@ package thrift import ( "bytes" + "context" "io/ioutil" "math" "net" @@ -31,7 +32,6 @@ import ( const PROTOCOL_BINARY_DATA_SIZE = 155 var ( - data string // test data for writing protocol_bdata []byte // test data for writing; same as data BOOL_VALUES []bool BYTE_VALUES []int8 @@ -47,7 +47,6 @@ func init() { for i := 0; i < PROTOCOL_BINARY_DATA_SIZE; i++ { protocol_bdata[i] = byte((i + 'a') % 255) } - data = string(protocol_bdata) BOOL_VALUES = []bool{false, true, false, false, true} BYTE_VALUES = []int8{117, 0, 1, 32, 127, -128, -1} INT16_VALUES = []int16{459, 0, 1, -1, -128, 127, 32767, -32768} @@ -120,6 +119,9 @@ func ReadWriteProtocolTest(t *testing.T, protocolFactory TProtocolFactory) { NewTMemoryBufferTransportFactory(1024), NewStreamTransportFactory(buf, buf, true), NewTFramedTransportFactory(NewTMemoryBufferTransportFactory(1024)), + NewTZlibTransportFactoryWithFactory(0, NewTMemoryBufferTransportFactory(1024)), + NewTZlibTransportFactoryWithFactory(6, NewTMemoryBufferTransportFactory(1024)), + NewTZlibTransportFactoryWithFactory(9, NewTFramedTransportFactory(NewTMemoryBufferTransportFactory(1024))), NewTHttpPostClientTransportFactory("http://" + addr.String()), } for _, tf := range transports { @@ -227,17 +229,17 @@ func ReadWriteBool(t testing.TB, p TProtocol, trans TTransport) { for k, v := range BOOL_VALUES { err = p.WriteBool(v) if err != nil { - t.Errorf("%s: %T %T %q Error writing bool in list at index %d: %q", "ReadWriteBool", p, trans, err, k, v) + t.Errorf("%s: %T %T %v Error writing bool in list at index %v: %v", "ReadWriteBool", p, trans, err, k, v) } } p.WriteListEnd() if err != nil { - t.Errorf("%s: %T %T %q Error writing list end: %q", "ReadWriteBool", p, trans, err, BOOL_VALUES) + t.Errorf("%s: %T %T %v Error writing list end: %v", "ReadWriteBool", p, trans, err, BOOL_VALUES) } - p.Flush() + p.Flush(context.Background()) thetype2, thelen2, err := p.ReadListBegin() if err != nil { - t.Errorf("%s: %T %T %q Error reading list: %q", "ReadWriteBool", p, trans, err, BOOL_VALUES) + t.Errorf("%s: %T %T %v Error reading list: %v", "ReadWriteBool", p, trans, err, BOOL_VALUES) } _, ok := p.(*TSimpleJSONProtocol) if !ok { @@ -245,16 +247,16 @@ func ReadWriteBool(t testing.TB, p TProtocol, trans TTransport) { t.Errorf("%s: %T %T type %s != type %s", "ReadWriteBool", p, trans, thetype, thetype2) } if thelen != thelen2 { - t.Errorf("%s: %T %T len %s != len %s", "ReadWriteBool", p, trans, thelen, thelen2) + t.Errorf("%s: %T %T len %v != len %v", "ReadWriteBool", p, trans, thelen, thelen2) } } for k, v := range BOOL_VALUES { value, err := p.ReadBool() if err != nil { - t.Errorf("%s: %T %T %q Error reading bool at index %d: %q", "ReadWriteBool", p, trans, err, k, v) + t.Errorf("%s: %T %T %v Error reading bool at index %v: %v", "ReadWriteBool", p, trans, err, k, v) } if v != value { - t.Errorf("%s: index %d %q %q %q != %q", "ReadWriteBool", k, p, trans, v, value) + t.Errorf("%s: index %v %v %v %v != %v", "ReadWriteBool", k, p, trans, v, value) } } err = p.ReadListEnd() @@ -280,7 +282,7 @@ func ReadWriteByte(t testing.TB, p TProtocol, trans TTransport) { if err != nil { t.Errorf("%s: %T %T %q Error writing list end: %q", "ReadWriteByte", p, trans, err, BYTE_VALUES) } - err = p.Flush() + err = p.Flush(context.Background()) if err != nil { t.Errorf("%s: %T %T %q Error flushing list of bytes: %q", "ReadWriteByte", p, trans, err, BYTE_VALUES) } @@ -294,7 +296,7 @@ func ReadWriteByte(t testing.TB, p TProtocol, trans TTransport) { t.Errorf("%s: %T %T type %s != type %s", "ReadWriteByte", p, trans, thetype, thetype2) } if thelen != thelen2 { - t.Errorf("%s: %T %T len %s != len %s", "ReadWriteByte", p, trans, thelen, thelen2) + t.Errorf("%s: %T %T len %v != len %v", "ReadWriteByte", p, trans, thelen, thelen2) } } for k, v := range BYTE_VALUES { @@ -320,7 +322,7 @@ func ReadWriteI16(t testing.TB, p TProtocol, trans TTransport) { p.WriteI16(v) } p.WriteListEnd() - p.Flush() + p.Flush(context.Background()) thetype2, thelen2, err := p.ReadListBegin() if err != nil { t.Errorf("%s: %T %T %q Error reading list: %q", "ReadWriteI16", p, trans, err, INT16_VALUES) @@ -331,7 +333,7 @@ func ReadWriteI16(t testing.TB, p TProtocol, trans TTransport) { t.Errorf("%s: %T %T type %s != type %s", "ReadWriteI16", p, trans, thetype, thetype2) } if thelen != thelen2 { - t.Errorf("%s: %T %T len %s != len %s", "ReadWriteI16", p, trans, thelen, thelen2) + t.Errorf("%s: %T %T len %v != len %v", "ReadWriteI16", p, trans, thelen, thelen2) } } for k, v := range INT16_VALUES { @@ -357,7 +359,7 @@ func ReadWriteI32(t testing.TB, p TProtocol, trans TTransport) { p.WriteI32(v) } p.WriteListEnd() - p.Flush() + p.Flush(context.Background()) thetype2, thelen2, err := p.ReadListBegin() if err != nil { t.Errorf("%s: %T %T %q Error reading list: %q", "ReadWriteI32", p, trans, err, INT32_VALUES) @@ -368,7 +370,7 @@ func ReadWriteI32(t testing.TB, p TProtocol, trans TTransport) { t.Errorf("%s: %T %T type %s != type %s", "ReadWriteI32", p, trans, thetype, thetype2) } if thelen != thelen2 { - t.Errorf("%s: %T %T len %s != len %s", "ReadWriteI32", p, trans, thelen, thelen2) + t.Errorf("%s: %T %T len %v != len %v", "ReadWriteI32", p, trans, thelen, thelen2) } } for k, v := range INT32_VALUES { @@ -393,7 +395,7 @@ func ReadWriteI64(t testing.TB, p TProtocol, trans TTransport) { p.WriteI64(v) } p.WriteListEnd() - p.Flush() + p.Flush(context.Background()) thetype2, thelen2, err := p.ReadListBegin() if err != nil { t.Errorf("%s: %T %T %q Error reading list: %q", "ReadWriteI64", p, trans, err, INT64_VALUES) @@ -404,7 +406,7 @@ func ReadWriteI64(t testing.TB, p TProtocol, trans TTransport) { t.Errorf("%s: %T %T type %s != type %s", "ReadWriteI64", p, trans, thetype, thetype2) } if thelen != thelen2 { - t.Errorf("%s: %T %T len %s != len %s", "ReadWriteI64", p, trans, thelen, thelen2) + t.Errorf("%s: %T %T len %v != len %v", "ReadWriteI64", p, trans, thelen, thelen2) } } for k, v := range INT64_VALUES { @@ -429,28 +431,28 @@ func ReadWriteDouble(t testing.TB, p TProtocol, trans TTransport) { p.WriteDouble(v) } p.WriteListEnd() - p.Flush() + p.Flush(context.Background()) thetype2, thelen2, err := p.ReadListBegin() if err != nil { - t.Errorf("%s: %T %T %q Error reading list: %q", "ReadWriteDouble", p, trans, err, DOUBLE_VALUES) + t.Errorf("%s: %T %T %v Error reading list: %v", "ReadWriteDouble", p, trans, err, DOUBLE_VALUES) } if thetype != thetype2 { t.Errorf("%s: %T %T type %s != type %s", "ReadWriteDouble", p, trans, thetype, thetype2) } if thelen != thelen2 { - t.Errorf("%s: %T %T len %s != len %s", "ReadWriteDouble", p, trans, thelen, thelen2) + t.Errorf("%s: %T %T len %v != len %v", "ReadWriteDouble", p, trans, thelen, thelen2) } for k, v := range DOUBLE_VALUES { value, err := p.ReadDouble() if err != nil { - t.Errorf("%s: %T %T %q Error reading double at index %d: %q", "ReadWriteDouble", p, trans, err, k, v) + t.Errorf("%s: %T %T %q Error reading double at index %d: %v", "ReadWriteDouble", p, trans, err, k, v) } if math.IsNaN(v) { if !math.IsNaN(value) { - t.Errorf("%s: %T %T math.IsNaN(%q) != math.IsNaN(%q)", "ReadWriteDouble", p, trans, v, value) + t.Errorf("%s: %T %T math.IsNaN(%v) != math.IsNaN(%v)", "ReadWriteDouble", p, trans, v, value) } } else if v != value { - t.Errorf("%s: %T %T %v != %q", "ReadWriteDouble", p, trans, v, value) + t.Errorf("%s: %T %T %v != %v", "ReadWriteDouble", p, trans, v, value) } } err = p.ReadListEnd() @@ -467,7 +469,7 @@ func ReadWriteString(t testing.TB, p TProtocol, trans TTransport) { p.WriteString(v) } p.WriteListEnd() - p.Flush() + p.Flush(context.Background()) thetype2, thelen2, err := p.ReadListBegin() if err != nil { t.Errorf("%s: %T %T %q Error reading list: %q", "ReadWriteString", p, trans, err, STRING_VALUES) @@ -478,7 +480,7 @@ func ReadWriteString(t testing.TB, p TProtocol, trans TTransport) { t.Errorf("%s: %T %T type %s != type %s", "ReadWriteString", p, trans, thetype, thetype2) } if thelen != thelen2 { - t.Errorf("%s: %T %T len %s != len %s", "ReadWriteString", p, trans, thelen, thelen2) + t.Errorf("%s: %T %T len %v != len %v", "ReadWriteString", p, trans, thelen, thelen2) } } for k, v := range STRING_VALUES { @@ -487,7 +489,7 @@ func ReadWriteString(t testing.TB, p TProtocol, trans TTransport) { t.Errorf("%s: %T %T %q Error reading string at index %d: %q", "ReadWriteString", p, trans, err, k, v) } if v != value { - t.Errorf("%s: %T %T %d != %d", "ReadWriteString", p, trans, v, value) + t.Errorf("%s: %T %T %v != %v", "ReadWriteString", p, trans, v, value) } } if err != nil { @@ -498,7 +500,7 @@ func ReadWriteString(t testing.TB, p TProtocol, trans TTransport) { func ReadWriteBinary(t testing.TB, p TProtocol, trans TTransport) { v := protocol_bdata p.WriteBinary(v) - p.Flush() + p.Flush(context.Background()) value, err := p.ReadBinary() if err != nil { t.Errorf("%s: %T %T Unable to read binary: %s", "ReadWriteBinary", p, trans, err.Error()) diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/serializer.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/serializer.go index 7712229..1ff4d37 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/serializer.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/serializer.go @@ -19,6 +19,10 @@ package thrift +import ( + "context" +) + type TSerializer struct { Transport *TMemoryBuffer Protocol TProtocol @@ -38,35 +42,35 @@ func NewTSerializer() *TSerializer { protocol} } -func (t *TSerializer) WriteString(msg TStruct) (s string, err error) { +func (t *TSerializer) WriteString(ctx context.Context, msg TStruct) (s string, err error) { t.Transport.Reset() if err = msg.Write(t.Protocol); err != nil { return } - if err = t.Protocol.Flush(); err != nil { + if err = t.Protocol.Flush(ctx); err != nil { return } - if err = t.Transport.Flush(); err != nil { + if err = t.Transport.Flush(ctx); err != nil { return } return t.Transport.String(), nil } -func (t *TSerializer) Write(msg TStruct) (b []byte, err error) { +func (t *TSerializer) Write(ctx context.Context, msg TStruct) (b []byte, err error) { t.Transport.Reset() if err = msg.Write(t.Protocol); err != nil { return } - if err = t.Protocol.Flush(); err != nil { + if err = t.Protocol.Flush(ctx); err != nil { return } - if err = t.Transport.Flush(); err != nil { + if err = t.Transport.Flush(ctx); err != nil { return } diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/serializer_test.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/serializer_test.go index 06d27a1..32227ef 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/serializer_test.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/serializer_test.go @@ -20,6 +20,7 @@ package thrift import ( + "context" "errors" "fmt" "testing" @@ -88,7 +89,7 @@ func ProtocolTest1(test *testing.T, pf ProtocolFactory) (bool, error) { m.StringSet = make(map[string]struct{}, 5) m.E = 2 - s, err := t.WriteString(&m) + s, err := t.WriteString(context.Background(), &m) if err != nil { return false, errors.New(fmt.Sprintf("Unable to Serialize struct\n\t %s", err)) } @@ -122,7 +123,7 @@ func ProtocolTest2(test *testing.T, pf ProtocolFactory) (bool, error) { m.StringSet = make(map[string]struct{}, 5) m.E = 2 - s, err := t.WriteString(&m) + s, err := t.WriteString(context.Background(), &m) if err != nil { return false, errors.New(fmt.Sprintf("Unable to Serialize struct\n\t %s", err)) diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/serializer_types_test.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/serializer_types_test.go index c8e3b3b..ef7cc3a 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/serializer_types_test.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/serializer_types_test.go @@ -19,7 +19,7 @@ package thrift -// Autogenerated by Thrift Compiler (1.0.0-dev) +// Autogenerated by Thrift Compiler (0.12.0) // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING /* THE FOLLOWING THRIFT FILE WAS USED TO CREATE THIS diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/server_socket.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/server_socket.go index d6e9495..7dd24ae 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/server_socket.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/server_socket.go @@ -47,7 +47,14 @@ func NewTServerSocketTimeout(listenAddr string, clientTimeout time.Duration) (*T return &TServerSocket{addr: addr, clientTimeout: clientTimeout}, nil } +// Creates a TServerSocket from a net.Addr +func NewTServerSocketFromAddrTimeout(addr net.Addr, clientTimeout time.Duration) *TServerSocket { + return &TServerSocket{addr: addr, clientTimeout: clientTimeout} +} + func (p *TServerSocket) Listen() error { + p.mu.Lock() + defer p.mu.Unlock() if p.IsListening() { return nil } @@ -67,10 +74,15 @@ func (p *TServerSocket) Accept() (TTransport, error) { if interrupted { return nil, errTransportInterrupted } - if p.listener == nil { + + p.mu.Lock() + listener := p.listener + p.mu.Unlock() + if listener == nil { return nil, NewTTransportException(NOT_OPEN, "No underlying server socket") } - conn, err := p.listener.Accept() + + conn, err := listener.Accept() if err != nil { return nil, NewTTransportExceptionFromError(err) } @@ -84,6 +96,8 @@ func (p *TServerSocket) IsListening() bool { // Connects the socket, creating a new socket object if necessary. func (p *TServerSocket) Open() error { + p.mu.Lock() + defer p.mu.Unlock() if p.IsListening() { return NewTTransportException(ALREADY_OPEN, "Server socket already open") } @@ -103,20 +117,21 @@ func (p *TServerSocket) Addr() net.Addr { } func (p *TServerSocket) Close() error { - defer func() { - p.listener = nil - }() + var err error + p.mu.Lock() if p.IsListening() { - return p.listener.Close() + err = p.listener.Close() + p.listener = nil } - return nil + p.mu.Unlock() + return err } func (p *TServerSocket) Interrupt() error { p.mu.Lock() p.interrupted = true - p.Close() p.mu.Unlock() + p.Close() return nil } diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/server_socket_test.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/server_socket_test.go index f08e8e9..f1e1983 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/server_socket_test.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/server_socket_test.go @@ -41,6 +41,16 @@ func TestSocketIsntListeningAfterInterrupt(t *testing.T) { } } +func TestSocketConcurrency(t *testing.T) { + host := "127.0.0.1" + port := 9090 + addr := fmt.Sprintf("%s:%d", host, port) + + socket := CreateServerSocket(t, addr) + go func() { socket.Listen() }() + go func() { socket.Interrupt() }() +} + func CreateServerSocket(t *testing.T, addr string) *TServerSocket { socket, err := NewTServerSocket(addr) if err != nil { diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/simple_json_protocol.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/simple_json_protocol.go index 7353322..2e8a711 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/simple_json_protocol.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/simple_json_protocol.go @@ -22,6 +22,7 @@ package thrift import ( "bufio" "bytes" + "context" "encoding/base64" "encoding/json" "fmt" @@ -552,7 +553,7 @@ func (p *TSimpleJSONProtocol) ReadBinary() ([]byte, error) { return v, p.ParsePostValue() } -func (p *TSimpleJSONProtocol) Flush() (err error) { +func (p *TSimpleJSONProtocol) Flush(ctx context.Context) (err error) { return NewTProtocolException(p.writer.Flush()) } @@ -1064,7 +1065,7 @@ func (p *TSimpleJSONProtocol) ParseListEnd() error { for _, char := range line { switch char { default: - e := fmt.Errorf("Expecting end of list \"]\", but found: \"", line, "\"") + e := fmt.Errorf("Expecting end of list \"]\", but found: \"%v\"", line) return NewTProtocolExceptionWithType(INVALID_DATA, e) case ' ', '\n', '\r', '\t', rune(JSON_RBRACKET[0]): break diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/simple_json_protocol_test.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/simple_json_protocol_test.go index 8f0dcc9..7b98082 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/simple_json_protocol_test.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/simple_json_protocol_test.go @@ -20,6 +20,7 @@ package thrift import ( + "context" "encoding/base64" "encoding/json" "fmt" @@ -37,7 +38,7 @@ func TestWriteSimpleJSONProtocolBool(t *testing.T) { if e := p.WriteBool(value); e != nil { t.Fatalf("Unable to write %s value %v due to error: %s", thetype, value, e.Error()) } - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s value %v due to error flushing: %s", thetype, value, e.Error()) } s := trans.String() @@ -63,7 +64,7 @@ func TestReadSimpleJSONProtocolBool(t *testing.T) { } else { trans.Write(JSON_FALSE) } - trans.Flush() + trans.Flush(context.Background()) s := trans.String() v, e := p.ReadBool() if e != nil { @@ -88,7 +89,7 @@ func TestWriteSimpleJSONProtocolByte(t *testing.T) { if e := p.WriteByte(value); e != nil { t.Fatalf("Unable to write %s value %v due to error: %s", thetype, value, e.Error()) } - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s value %v due to error flushing: %s", thetype, value, e.Error()) } s := trans.String() @@ -110,7 +111,7 @@ func TestReadSimpleJSONProtocolByte(t *testing.T) { trans := NewTMemoryBuffer() p := NewTSimpleJSONProtocol(trans) trans.WriteString(strconv.Itoa(int(value))) - trans.Flush() + trans.Flush(context.Background()) s := trans.String() v, e := p.ReadByte() if e != nil { @@ -135,7 +136,7 @@ func TestWriteSimpleJSONProtocolI16(t *testing.T) { if e := p.WriteI16(value); e != nil { t.Fatalf("Unable to write %s value %v due to error: %s", thetype, value, e.Error()) } - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s value %v due to error flushing: %s", thetype, value, e.Error()) } s := trans.String() @@ -157,7 +158,7 @@ func TestReadSimpleJSONProtocolI16(t *testing.T) { trans := NewTMemoryBuffer() p := NewTSimpleJSONProtocol(trans) trans.WriteString(strconv.Itoa(int(value))) - trans.Flush() + trans.Flush(context.Background()) s := trans.String() v, e := p.ReadI16() if e != nil { @@ -182,7 +183,7 @@ func TestWriteSimpleJSONProtocolI32(t *testing.T) { if e := p.WriteI32(value); e != nil { t.Fatalf("Unable to write %s value %v due to error: %s", thetype, value, e.Error()) } - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s value %v due to error flushing: %s", thetype, value, e.Error()) } s := trans.String() @@ -204,7 +205,7 @@ func TestReadSimpleJSONProtocolI32(t *testing.T) { trans := NewTMemoryBuffer() p := NewTSimpleJSONProtocol(trans) trans.WriteString(strconv.Itoa(int(value))) - trans.Flush() + trans.Flush(context.Background()) s := trans.String() v, e := p.ReadI32() if e != nil { @@ -228,7 +229,7 @@ func TestReadSimpleJSONProtocolI32Null(t *testing.T) { trans := NewTMemoryBuffer() p := NewTSimpleJSONProtocol(trans) trans.WriteString(value) - trans.Flush() + trans.Flush(context.Background()) s := trans.String() v, e := p.ReadI32() @@ -250,7 +251,7 @@ func TestWriteSimpleJSONProtocolI64(t *testing.T) { if e := p.WriteI64(value); e != nil { t.Fatalf("Unable to write %s value %v due to error: %s", thetype, value, e.Error()) } - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s value %v due to error flushing: %s", thetype, value, e.Error()) } s := trans.String() @@ -272,7 +273,7 @@ func TestReadSimpleJSONProtocolI64(t *testing.T) { trans := NewTMemoryBuffer() p := NewTSimpleJSONProtocol(trans) trans.WriteString(strconv.FormatInt(value, 10)) - trans.Flush() + trans.Flush(context.Background()) s := trans.String() v, e := p.ReadI64() if e != nil { @@ -296,7 +297,7 @@ func TestReadSimpleJSONProtocolI64Null(t *testing.T) { trans := NewTMemoryBuffer() p := NewTSimpleJSONProtocol(trans) trans.WriteString(value) - trans.Flush() + trans.Flush(context.Background()) s := trans.String() v, e := p.ReadI64() @@ -318,7 +319,7 @@ func TestWriteSimpleJSONProtocolDouble(t *testing.T) { if e := p.WriteDouble(value); e != nil { t.Fatalf("Unable to write %s value %v due to error: %s", thetype, value, e.Error()) } - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s value %v due to error flushing: %s", thetype, value, e.Error()) } s := trans.String() @@ -355,7 +356,7 @@ func TestReadSimpleJSONProtocolDouble(t *testing.T) { p := NewTSimpleJSONProtocol(trans) n := NewNumericFromDouble(value) trans.WriteString(n.String()) - trans.Flush() + trans.Flush(context.Background()) s := trans.String() v, e := p.ReadDouble() if e != nil { @@ -394,7 +395,7 @@ func TestWriteSimpleJSONProtocolString(t *testing.T) { if e := p.WriteString(value); e != nil { t.Fatalf("Unable to write %s value %v due to error: %s", thetype, value, e.Error()) } - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s value %v due to error flushing: %s", thetype, value, e.Error()) } s := trans.String() @@ -416,7 +417,7 @@ func TestReadSimpleJSONProtocolString(t *testing.T) { trans := NewTMemoryBuffer() p := NewTSimpleJSONProtocol(trans) trans.WriteString(jsonQuote(value)) - trans.Flush() + trans.Flush(context.Background()) s := trans.String() v, e := p.ReadString() if e != nil { @@ -440,7 +441,7 @@ func TestReadSimpleJSONProtocolStringNull(t *testing.T) { trans := NewTMemoryBuffer() p := NewTSimpleJSONProtocol(trans) trans.WriteString(value) - trans.Flush() + trans.Flush(context.Background()) s := trans.String() v, e := p.ReadString() if e != nil { @@ -464,7 +465,7 @@ func TestWriteSimpleJSONProtocolBinary(t *testing.T) { if e := p.WriteBinary(value); e != nil { t.Fatalf("Unable to write %s value %v due to error: %s", thetype, value, e.Error()) } - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s value %v due to error flushing: %s", thetype, value, e.Error()) } s := trans.String() @@ -487,7 +488,7 @@ func TestReadSimpleJSONProtocolBinary(t *testing.T) { trans := NewTMemoryBuffer() p := NewTSimpleJSONProtocol(trans) trans.WriteString(jsonQuote(b64String)) - trans.Flush() + trans.Flush(context.Background()) s := trans.String() v, e := p.ReadBinary() if e != nil { @@ -516,7 +517,7 @@ func TestReadSimpleJSONProtocolBinaryNull(t *testing.T) { trans := NewTMemoryBuffer() p := NewTSimpleJSONProtocol(trans) trans.WriteString(value) - trans.Flush() + trans.Flush(context.Background()) s := trans.String() b, e := p.ReadBinary() v := string(b) @@ -542,7 +543,7 @@ func TestWriteSimpleJSONProtocolList(t *testing.T) { } } p.WriteListEnd() - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s due to error flushing: %s", thetype, e.Error()) } str := trans.String() @@ -596,7 +597,7 @@ func TestWriteSimpleJSONProtocolSet(t *testing.T) { } } p.WriteSetEnd() - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s due to error flushing: %s", thetype, e.Error()) } str := trans.String() @@ -653,12 +654,12 @@ func TestWriteSimpleJSONProtocolMap(t *testing.T) { } } p.WriteMapEnd() - if e := p.Flush(); e != nil { + if e := p.Flush(context.Background()); e != nil { t.Fatalf("Unable to write %s due to error flushing: %s", thetype, e.Error()) } str := trans.String() if str[0] != '[' || str[len(str)-1] != ']' { - t.Fatalf("Bad value for %s, wrote: %q, in go: %q", thetype, str, DOUBLE_VALUES) + t.Fatalf("Bad value for %s, wrote: %v, in go: %v", thetype, str, DOUBLE_VALUES) } l := strings.Split(str[1:len(str)-1], ",") if len(l) < 3 { diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/simple_server.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/simple_server.go index 1d35b23..6035802 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/simple_server.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/simple_server.go @@ -23,11 +23,18 @@ import ( "log" "runtime/debug" "sync" + "sync/atomic" ) -// Simple, non-concurrent server for testing. +/* + * This is not a typical TSimpleServer as it is not blocked after accept a socket. + * It is more like a TThreadedServer that can handle different connections in different goroutines. + * This will work if golang user implements a conn-pool like thing in client side. + */ type TSimpleServer struct { - quit chan struct{} + closed int32 + wg sync.WaitGroup + mu sync.Mutex processorFactory TProcessorFactory serverTransport TServerTransport @@ -87,7 +94,6 @@ func NewTSimpleServerFactory6(processorFactory TProcessorFactory, serverTranspor outputTransportFactory: outputTransportFactory, inputProtocolFactory: inputProtocolFactory, outputProtocolFactory: outputProtocolFactory, - quit: make(chan struct{}, 1), } } @@ -119,23 +125,37 @@ func (p *TSimpleServer) Listen() error { return p.serverTransport.Listen() } +func (p *TSimpleServer) innerAccept() (int32, error) { + client, err := p.serverTransport.Accept() + p.mu.Lock() + defer p.mu.Unlock() + closed := atomic.LoadInt32(&p.closed) + if closed != 0 { + return closed, nil + } + if err != nil { + return 0, err + } + if client != nil { + p.wg.Add(1) + go func() { + defer p.wg.Done() + if err := p.processRequests(client); err != nil { + log.Println("error processing request:", err) + } + }() + } + return 0, nil +} + func (p *TSimpleServer) AcceptLoop() error { for { - client, err := p.serverTransport.Accept() + closed, err := p.innerAccept() if err != nil { - select { - case <-p.quit: - return nil - default: - } return err } - if client != nil { - go func() { - if err := p.processRequests(client); err != nil { - log.Println("error processing request:", err) - } - }() + if closed != 0 { + return nil } } } @@ -149,14 +169,15 @@ func (p *TSimpleServer) Serve() error { return nil } -var once sync.Once - func (p *TSimpleServer) Stop() error { - q := func() { - p.quit <- struct{}{} - p.serverTransport.Interrupt() + p.mu.Lock() + defer p.mu.Unlock() + if atomic.LoadInt32(&p.closed) != 0 { + return nil } - once.Do(q) + atomic.StoreInt32(&p.closed, 1) + p.serverTransport.Interrupt() + p.wg.Wait() return nil } @@ -177,6 +198,7 @@ func (p *TSimpleServer) processRequests(client TTransport) error { log.Printf("panic in processor: %s: %s", e, debug.Stack()) } }() + if inputTransport != nil { defer inputTransport.Close() } @@ -184,17 +206,20 @@ func (p *TSimpleServer) processRequests(client TTransport) error { defer outputTransport.Close() } for { - ok, err := processor.Process(inputProtocol, outputProtocol) + if atomic.LoadInt32(&p.closed) != 0 { + return nil + } + + ok, err := processor.Process(defaultCtx, inputProtocol, outputProtocol) if err, ok := err.(TTransportException); ok && err.TypeId() == END_OF_FILE { return nil } else if err != nil { - log.Printf("error processing request: %s", err) return err } if err, ok := err.(TApplicationException); ok && err.TypeId() == UNKNOWN_METHOD { continue } - if !ok { + if !ok { break } } diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/simple_server_test.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/simple_server_test.go new file mode 100644 index 0000000..58149a8 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/simple_server_test.go @@ -0,0 +1,156 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +package thrift + +import ( + "testing" + "errors" + "runtime" +) + +type mockServerTransport struct { + ListenFunc func() error + AcceptFunc func() (TTransport, error) + CloseFunc func() error + InterruptFunc func() error +} + +func (m *mockServerTransport) Listen() error { + return m.ListenFunc() +} + +func (m *mockServerTransport) Accept() (TTransport, error) { + return m.AcceptFunc() +} + +func (m *mockServerTransport) Close() error { + return m.CloseFunc() +} + +func (m *mockServerTransport) Interrupt() error { + return m.InterruptFunc() +} + +type mockTTransport struct { + TTransport +} + +func (m *mockTTransport) Close() error { + return nil +} + +func TestMultipleStop(t *testing.T) { + proc := &mockProcessor{ + ProcessFunc: func(in, out TProtocol) (bool, TException) { + return false, nil + }, + } + + var interruptCalled bool + c := make(chan struct{}) + trans := &mockServerTransport{ + ListenFunc: func() error { + return nil + }, + AcceptFunc: func() (TTransport, error) { + <-c + return nil, nil + }, + CloseFunc: func() error { + c <- struct{}{} + return nil + }, + InterruptFunc: func() error { + interruptCalled = true + return nil + }, + } + + serv := NewTSimpleServer2(proc, trans) + go serv.Serve() + serv.Stop() + if !interruptCalled { + t.Error("first server transport should have been interrupted") + } + + serv = NewTSimpleServer2(proc, trans) + interruptCalled = false + go serv.Serve() + serv.Stop() + if !interruptCalled { + t.Error("second server transport should have been interrupted") + } +} + +func TestWaitRace(t *testing.T) { + proc := &mockProcessor{ + ProcessFunc: func(in, out TProtocol) (bool, TException) { + return false, nil + }, + } + + trans := &mockServerTransport{ + ListenFunc: func() error { + return nil + }, + AcceptFunc: func() (TTransport, error) { + return &mockTTransport{}, nil + }, + CloseFunc: func() error { + return nil + }, + InterruptFunc: func() error { + return nil + }, + } + + serv := NewTSimpleServer2(proc, trans) + go serv.Serve() + runtime.Gosched() + serv.Stop() +} + +func TestNoHangDuringStopFromDanglingLockAcquireDuringAcceptLoop(t *testing.T) { + proc := &mockProcessor{ + ProcessFunc: func(in, out TProtocol) (bool, TException) { + return false, nil + }, + } + + trans := &mockServerTransport{ + ListenFunc: func() error { + return nil + }, + AcceptFunc: func() (TTransport, error) { + return nil, errors.New("no sir") + }, + CloseFunc: func() error { + return nil + }, + InterruptFunc: func() error { + return nil + }, + } + + serv := NewTSimpleServer2(proc, trans) + go serv.Serve() + runtime.Gosched() + serv.Stop() +} diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/socket.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/socket.go index 383b1fe..8854279 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/socket.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/socket.go @@ -20,6 +20,7 @@ package thrift import ( + "context" "net" "time" ) @@ -148,7 +149,7 @@ func (p *TSocket) Write(buf []byte) (int, error) { return p.conn.Write(buf) } -func (p *TSocket) Flush() error { +func (p *TSocket) Flush(ctx context.Context) error { return nil } diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/ssl_server_socket.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/ssl_server_socket.go index 58f859b..907afca 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/ssl_server_socket.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/ssl_server_socket.go @@ -20,9 +20,9 @@ package thrift import ( + "crypto/tls" "net" "time" - "crypto/tls" ) type TSSLServerSocket struct { @@ -38,6 +38,9 @@ func NewTSSLServerSocket(listenAddr string, cfg *tls.Config) (*TSSLServerSocket, } func NewTSSLServerSocketTimeout(listenAddr string, cfg *tls.Config, clientTimeout time.Duration) (*TSSLServerSocket, error) { + if cfg.MinVersion == 0 { + cfg.MinVersion = tls.VersionTLS10 + } addr, err := net.ResolveTCPAddr("tcp", listenAddr) if err != nil { return nil, err diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/ssl_socket.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/ssl_socket.go index 86a68a3..ba63377 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/ssl_socket.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/ssl_socket.go @@ -20,6 +20,7 @@ package thrift import ( + "context" "crypto/tls" "net" "time" @@ -48,6 +49,9 @@ func NewTSSLSocket(hostPort string, cfg *tls.Config) (*TSSLSocket, error) { // NewTSSLSocketTimeout creates a net.Conn-backed TTransport, given a host and port // it also accepts a tls Configuration and a timeout as a time.Duration func NewTSSLSocketTimeout(hostPort string, cfg *tls.Config, timeout time.Duration) (*TSSLSocket, error) { + if cfg.MinVersion == 0 { + cfg.MinVersion = tls.VersionTLS10 + } return &TSSLSocket{hostPort: hostPort, timeout: timeout, cfg: cfg}, nil } @@ -87,7 +91,8 @@ func (p *TSSLSocket) Open() error { // If we have a hostname, we need to pass the hostname to tls.Dial for // certificate hostname checks. if p.hostPort != "" { - if p.conn, err = tls.Dial("tcp", p.hostPort, p.cfg); err != nil { + if p.conn, err = tls.DialWithDialer(&net.Dialer{ + Timeout: p.timeout}, "tcp", p.hostPort, p.cfg); err != nil { return NewTTransportException(NOT_OPEN, err.Error()) } } else { @@ -103,7 +108,8 @@ func (p *TSSLSocket) Open() error { if len(p.addr.String()) == 0 { return NewTTransportException(NOT_OPEN, "Cannot open bad address.") } - if p.conn, err = tls.Dial(p.addr.Network(), p.addr.String(), p.cfg); err != nil { + if p.conn, err = tls.DialWithDialer(&net.Dialer{ + Timeout: p.timeout}, p.addr.Network(), p.addr.String(), p.cfg); err != nil { return NewTTransportException(NOT_OPEN, err.Error()) } } @@ -153,7 +159,7 @@ func (p *TSSLSocket) Write(buf []byte) (int, error) { return p.conn.Write(buf) } -func (p *TSSLSocket) Flush() error { +func (p *TSSLSocket) Flush(ctx context.Context) error { return nil } diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/transport.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/transport.go index 70a85a8..ba2738a 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/transport.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/transport.go @@ -20,6 +20,7 @@ package thrift import ( + "context" "errors" "io" ) @@ -30,6 +31,10 @@ type Flusher interface { Flush() (err error) } +type ContextFlusher interface { + Flush(ctx context.Context) (err error) +} + type ReadSizeProvider interface { RemainingBytes() (num_bytes uint64) } @@ -37,7 +42,7 @@ type ReadSizeProvider interface { // Encapsulates the I/O layer type TTransport interface { io.ReadWriteCloser - Flusher + ContextFlusher ReadSizeProvider // Opens the transport for communication @@ -60,6 +65,6 @@ type TRichTransport interface { io.ByteReader io.ByteWriter stringWriter - Flusher + ContextFlusher ReadSizeProvider } diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/transport_test.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/transport_test.go index 864958a..0127803 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/transport_test.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/transport_test.go @@ -20,6 +20,7 @@ package thrift import ( + "context" "io" "net" "strconv" @@ -54,7 +55,7 @@ func TransportTest(t *testing.T, writeTrans TTransport, readTrans TTransport) { if err != nil { t.Fatalf("Transport %T cannot write binary data of length %d: %s", writeTrans, len(transport_bdata), err) } - err = writeTrans.Flush() + err = writeTrans.Flush(context.Background()) if err != nil { t.Fatalf("Transport %T cannot flush write of binary data: %s", writeTrans, err) } @@ -74,7 +75,7 @@ func TransportTest(t *testing.T, writeTrans TTransport, readTrans TTransport) { if err != nil { t.Fatalf("Transport %T cannot write binary data 2 of length %d: %s", writeTrans, len(transport_bdata), err) } - err = writeTrans.Flush() + err = writeTrans.Flush(context.Background()) if err != nil { t.Fatalf("Transport %T cannot flush write binary data 2: %s", writeTrans, err) } @@ -113,7 +114,7 @@ func TransportHeaderTest(t *testing.T, writeTrans TTransport, readTrans TTranspo if err != nil { t.Fatalf("Transport %T cannot write binary data of length %d: %s", writeTrans, len(transport_bdata), err) } - err = writeTrans.Flush() + err = writeTrans.Flush(context.Background()) if err != nil { t.Fatalf("Transport %T cannot flush write of binary data: %s", writeTrans, err) } diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/zlib_transport.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/zlib_transport.go index 6f477ca..f3d4267 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/zlib_transport.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/zlib_transport.go @@ -21,13 +21,15 @@ package thrift import ( "compress/zlib" + "context" "io" "log" ) // TZlibTransportFactory is a factory for TZlibTransport instances type TZlibTransportFactory struct { - level int + level int + factory TTransportFactory } // TZlibTransport is a TTransport implementation that makes use of zlib compression. @@ -39,12 +41,26 @@ type TZlibTransport struct { // GetTransport constructs a new instance of NewTZlibTransport func (p *TZlibTransportFactory) GetTransport(trans TTransport) (TTransport, error) { + if p.factory != nil { + // wrap other factory + var err error + trans, err = p.factory.GetTransport(trans) + if err != nil { + return nil, err + } + } return NewTZlibTransport(trans, p.level) } // NewTZlibTransportFactory constructs a new instance of NewTZlibTransportFactory func NewTZlibTransportFactory(level int) *TZlibTransportFactory { - return &TZlibTransportFactory{level: level} + return &TZlibTransportFactory{level: level, factory: nil} +} + +// NewTZlibTransportFactory constructs a new instance of TZlibTransportFactory +// as a wrapper over existing transport factory +func NewTZlibTransportFactoryWithFactory(level int, factory TTransportFactory) *TZlibTransportFactory { + return &TZlibTransportFactory{level: level, factory: factory} } // NewTZlibTransport constructs a new instance of TZlibTransport @@ -76,11 +92,11 @@ func (z *TZlibTransport) Close() error { } // Flush flushes the writer and its underlying transport. -func (z *TZlibTransport) Flush() error { +func (z *TZlibTransport) Flush(ctx context.Context) error { if err := z.writer.Flush(); err != nil { return err } - return z.transport.Flush() + return z.transport.Flush(ctx) } // IsOpen returns true if the transport is open diff --git a/vendor/git.apache.org/thrift.git/lib/go/thrift/zlib_transport_test.go b/vendor/git.apache.org/thrift.git/lib/go/thrift/zlib_transport_test.go index f57610c..3c6f11e 100644 --- a/vendor/git.apache.org/thrift.git/lib/go/thrift/zlib_transport_test.go +++ b/vendor/git.apache.org/thrift.git/lib/go/thrift/zlib_transport_test.go @@ -31,3 +31,32 @@ func TestZlibTransport(t *testing.T) { } TransportTest(t, trans, trans) } + +type DummyTransportFactory struct{} + +func (p *DummyTransportFactory) GetTransport(trans TTransport) (TTransport, error) { + return NewTMemoryBuffer(), nil +} + +func TestZlibFactoryTransportWithFactory(t *testing.T) { + factory := NewTZlibTransportFactoryWithFactory( + zlib.BestCompression, + &DummyTransportFactory{}, + ) + buffer := NewTMemoryBuffer() + trans, err := factory.GetTransport(buffer) + if err != nil { + t.Fatal(err) + } + TransportTest(t, trans, trans) +} + +func TestZlibFactoryTransportWithoutFactory(t *testing.T) { + factory := NewTZlibTransportFactoryWithFactory(zlib.BestCompression, nil) + buffer := NewTMemoryBuffer() + trans, err := factory.GetTransport(buffer) + if err != nil { + t.Fatal(err) + } + TransportTest(t, trans, trans) +} diff --git a/vendor/git.apache.org/thrift.git/lib/haxe/README.md b/vendor/git.apache.org/thrift.git/lib/haxe/README.md index c5ad680..02e6919 100644 --- a/vendor/git.apache.org/thrift.git/lib/haxe/README.md +++ b/vendor/git.apache.org/thrift.git/lib/haxe/README.md @@ -44,9 +44,9 @@ target libraries need to be installed and how to achieve this. Haxe on Linux --------------- -For Linux platforms it is recommended not to download the -binaries manually, instead use the Haxe installation shell -script which can be found at `http://www.openfl.org/download`. +For Linux platforms it is recommended to use the distro-specific package +manager, where possible. More detailed information can be found at the +Haxe Linux download section: http://haxe.org/download/linux If you run into the error message @@ -69,10 +69,10 @@ Thrift Haxe bindings Thrift Haxe bindings can be set up via the `haxelib` tool either from the official ASF repo, or via the github mirror. -- To set up any **stable version**, choose the appropriate branch (e.g. `0.9.3`): +- To set up any **stable version**, choose the appropriate branch (e.g. `0.10.0`): - - `haxelib git thrift https://git.apache.org/thrift.git 0.9.3 lib/haxe` - - `haxelib git thrift https://github.com/apache/thrift.git 0.9.3 lib/haxe` + - `haxelib git thrift https://git.apache.org/thrift.git 0.12.0 lib/haxe` + - `haxelib git thrift https://github.com/apache/thrift.git 0.12.0 lib/haxe` - To set up the current **development version**, use the `master` branch: diff --git a/vendor/git.apache.org/thrift.git/lib/haxe/haxelib.json b/vendor/git.apache.org/thrift.git/lib/haxe/haxelib.json index 4c27917..8d1bb11 100644 --- a/vendor/git.apache.org/thrift.git/lib/haxe/haxelib.json +++ b/vendor/git.apache.org/thrift.git/lib/haxe/haxelib.json @@ -4,7 +4,7 @@ "license": "Apache", "tags": ["thrift", "rpc", "serialization", "cross", "framework"], "description": "Haxe bindings for the Apache Thrift RPC and serialization framework", - "version": "0.10.0", + "version": "0.12.0", "releasenote": "Licensed under Apache License, Version 2.0. The Apache Thrift compiler needs to be installed separately.", "contributors": ["Apache Software Foundation (ASF)"], "dependencies": { }, diff --git a/vendor/git.apache.org/thrift.git/lib/haxe/src/org/apache/thrift/protocol/TProtocolUtil.hx b/vendor/git.apache.org/thrift.git/lib/haxe/src/org/apache/thrift/protocol/TProtocolUtil.hx index 1ec59d2..001e405 100644 --- a/vendor/git.apache.org/thrift.git/lib/haxe/src/org/apache/thrift/protocol/TProtocolUtil.hx +++ b/vendor/git.apache.org/thrift.git/lib/haxe/src/org/apache/thrift/protocol/TProtocolUtil.hx @@ -95,7 +95,7 @@ class TProtocolUtil { prot.readListEnd(); default: - trace("Unknown field type ",type," in skipMaxDepth()"); + throw new TProtocolException(TProtocolException.UNKNOWN, "Unknown field type ${type}"); } prot.DecrementRecursionDepth(); diff --git a/vendor/git.apache.org/thrift.git/lib/haxe/src/org/apache/thrift/server/TSimpleServer.hx b/vendor/git.apache.org/thrift.git/lib/haxe/src/org/apache/thrift/server/TSimpleServer.hx index c9856b4..0600744 100644 --- a/vendor/git.apache.org/thrift.git/lib/haxe/src/org/apache/thrift/server/TSimpleServer.hx +++ b/vendor/git.apache.org/thrift.git/lib/haxe/src/org/apache/thrift/server/TSimpleServer.hx @@ -121,6 +121,11 @@ class TSimpleServer extends TServer { logDelegate(e); // Unexpected } + if(client != null && !runOnce) + { + client.close(); + } + // Fire deleteContext server event after client disconnects if (serverEventHandler != null) { serverEventHandler.deleteContext(connectionContext, inputProtocol, outputProtocol); diff --git a/vendor/git.apache.org/thrift.git/lib/haxe/test/Makefile.am b/vendor/git.apache.org/thrift.git/lib/haxe/test/Makefile.am index 5c638d4..2b8b245 100644 --- a/vendor/git.apache.org/thrift.git/lib/haxe/test/Makefile.am +++ b/vendor/git.apache.org/thrift.git/lib/haxe/test/Makefile.am @@ -17,7 +17,6 @@ # under the License. # -THRIFT = $(top_builddir)/compiler/cpp/thrift THRIFTCMD = $(THRIFT) --gen haxe -r THRIFTTEST = $(top_srcdir)/test/ThriftTest.thrift AGGR = $(top_srcdir)/contrib/async-test/aggr.thrift diff --git a/vendor/git.apache.org/thrift.git/lib/hs/CMakeLists.txt b/vendor/git.apache.org/thrift.git/lib/hs/CMakeLists.txt index 7653ed6..a20a319 100644 --- a/vendor/git.apache.org/thrift.git/lib/hs/CMakeLists.txt +++ b/vendor/git.apache.org/thrift.git/lib/hs/CMakeLists.txt @@ -33,7 +33,7 @@ set(haskell_sources src/Thrift/Transport/HttpClient.hs src/Thrift/Transport/IOBuffer.hs src/Thrift/Types.hs - Thrift.cabal + thrift.cabal ) if(BUILD_TESTING) diff --git a/vendor/git.apache.org/thrift.git/lib/hs/Makefile.am b/vendor/git.apache.org/thrift.git/lib/hs/Makefile.am index 90d5e14..3cd8b57 100644 --- a/vendor/git.apache.org/thrift.git/lib/hs/Makefile.am +++ b/vendor/git.apache.org/thrift.git/lib/hs/Makefile.am @@ -24,7 +24,7 @@ EXTRA_DIST = \ README.md \ Setup.lhs \ TODO \ - Thrift.cabal \ + thrift.cabal \ src \ test diff --git a/vendor/git.apache.org/thrift.git/lib/hs/Thrift.cabal b/vendor/git.apache.org/thrift.git/lib/hs/Thrift.cabal index a604307..c136480 100644 --- a/vendor/git.apache.org/thrift.git/lib/hs/Thrift.cabal +++ b/vendor/git.apache.org/thrift.git/lib/hs/Thrift.cabal @@ -18,8 +18,8 @@ -- Name: thrift -Version: 0.10.0 -Cabal-Version: >= 1.8 +Version: 0.12.0 +Cabal-Version: 1.24 License: OtherLicense Category: Foreign Build-Type: Simple @@ -40,7 +40,7 @@ Library Hs-Source-Dirs: src Build-Depends: - base >= 4, base < 5, containers, ghc-prim, attoparsec, binary, bytestring >= 0.10, base64-bytestring, hashable, HTTP, text, unordered-containers >= 0.2.6, vector == 0.10.12.2, QuickCheck >= 2.8.2, split + base >= 4, base < 5, containers, ghc-prim, attoparsec, binary, bytestring >= 0.10, base64-bytestring, hashable, HTTP, text, hspec-core > 2.4.0, unordered-containers >= 0.2.6, vector >= 0.10.12.2, QuickCheck >= 2.8.2, split if flag(network-uri) build-depends: network-uri >= 2.6, network >= 2.6 else @@ -49,6 +49,7 @@ Library Thrift, Thrift.Arbitraries Thrift.Protocol, + Thrift.Protocol.Header, Thrift.Protocol.Binary, Thrift.Protocol.Compact, Thrift.Protocol.JSON, @@ -57,11 +58,13 @@ Library Thrift.Transport.Empty, Thrift.Transport.Framed, Thrift.Transport.Handle, + Thrift.Transport.Header, Thrift.Transport.HttpClient, Thrift.Transport.IOBuffer, Thrift.Transport.Memory, Thrift.Types - Extensions: + Default-Language: Haskell2010 + Default-Extensions: DeriveDataTypeable, ExistentialQuantification, FlexibleInstances, @@ -78,3 +81,4 @@ Test-Suite spec Ghc-Options: -Wall main-is: Spec.hs Build-Depends: base, thrift, hspec, QuickCheck >= 2.8.2, bytestring >= 0.10, unordered-containers >= 0.2.6 + Default-Language: Haskell2010 diff --git a/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift.hs b/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift.hs index 58a304b..6580209 100644 --- a/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift.hs +++ b/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift.hs @@ -90,13 +90,13 @@ data AppExn = AppExn { ae_type :: AppExnType, ae_message :: String } deriving ( Show, Typeable ) instance Exception AppExn -writeAppExn :: (Protocol p, Transport t) => p t -> AppExn -> IO () +writeAppExn :: Protocol p => p -> AppExn -> IO () writeAppExn pt ae = writeVal pt $ TStruct $ Map.fromList [ (1, ("message", TString $ encodeUtf8 $ pack $ ae_message ae)) , (2, ("type", TI32 $ fromIntegral $ fromEnum (ae_type ae))) ] -readAppExn :: (Protocol p, Transport t) => p t -> IO AppExn +readAppExn :: Protocol p => p -> IO AppExn readAppExn pt = do let typemap = Map.fromList [(1,("message",T_STRING)),(2,("type",T_I32))] TStruct fields <- readVal pt $ T_STRUCT typemap diff --git a/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Protocol.hs b/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Protocol.hs index ed779a2..67a9175 100644 --- a/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Protocol.hs +++ b/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Protocol.hs @@ -22,12 +22,11 @@ module Thrift.Protocol ( Protocol(..) + , StatelessProtocol(..) , ProtocolExn(..) , ProtocolExnType(..) , getTypeOf , runParser - , versionMask - , version1 , bsToDouble , bsToDoubleLE ) where @@ -35,7 +34,6 @@ module Thrift.Protocol import Control.Exception import Data.Attoparsec.ByteString import Data.Bits -import Data.ByteString.Lazy (ByteString, toStrict) import Data.ByteString.Unsafe import Data.Functor ((<$>)) import Data.Int @@ -44,37 +42,26 @@ import Data.Text.Lazy (Text) import Data.Typeable (Typeable) import Data.Word import Foreign.Ptr (castPtr) -import Foreign.Storable (Storable, peek, poke) +import Foreign.Storable (peek, poke) import System.IO.Unsafe import qualified Data.ByteString as BS import qualified Data.HashMap.Strict as Map +import qualified Data.ByteString.Lazy as LBS -import Thrift.Types import Thrift.Transport - -versionMask :: Int32 -versionMask = fromIntegral (0xffff0000 :: Word32) - -version1 :: Int32 -version1 = fromIntegral (0x80010000 :: Word32) +import Thrift.Types class Protocol a where - getTransport :: Transport t => a t -> t + readByte :: a -> IO LBS.ByteString + readVal :: a -> ThriftType -> IO ThriftVal + readMessage :: a -> ((Text, MessageType, Int32) -> IO b) -> IO b - writeMessageBegin :: Transport t => a t -> (Text, MessageType, Int32) -> IO () - writeMessageEnd :: Transport t => a t -> IO () - writeMessageEnd _ = return () - - readMessageBegin :: Transport t => a t -> IO (Text, MessageType, Int32) - readMessageEnd :: Transport t => a t -> IO () - readMessageEnd _ = return () + writeVal :: a -> ThriftVal -> IO () + writeMessage :: a -> (Text, MessageType, Int32) -> IO () -> IO () - serializeVal :: Transport t => a t -> ThriftVal -> ByteString - deserializeVal :: Transport t => a t -> ThriftType -> ByteString -> ThriftVal - - writeVal :: Transport t => a t -> ThriftVal -> IO () - writeVal p = tWrite (getTransport p) . serializeVal p - readVal :: Transport t => a t -> ThriftType -> IO ThriftVal +class Protocol a => StatelessProtocol a where + serializeVal :: a -> ThriftVal -> LBS.ByteString + deserializeVal :: a -> ThriftType -> LBS.ByteString -> ThriftVal data ProtocolExnType = PE_UNKNOWN @@ -105,10 +92,10 @@ getTypeOf v = case v of TBinary{} -> T_BINARY TDouble{} -> T_DOUBLE -runParser :: (Protocol p, Transport t, Show a) => p t -> Parser a -> IO a +runParser :: (Protocol p, Show a) => p -> Parser a -> IO a runParser prot p = refill >>= getResult . parse p where - refill = handle handleEOF $ toStrict <$> tReadAll (getTransport prot) 1 + refill = handle handleEOF $ LBS.toStrict <$> readByte prot getResult (Done _ a) = return a getResult (Partial k) = refill >>= getResult . k getResult f = throw $ ProtocolExn PE_INVALID_DATA (show f) diff --git a/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Protocol/Binary.hs b/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Protocol/Binary.hs index 2d35305..7b0acd9 100644 --- a/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Protocol/Binary.hs +++ b/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Protocol/Binary.hs @@ -25,6 +25,8 @@ module Thrift.Protocol.Binary ( module Thrift.Protocol , BinaryProtocol(..) + , versionMask + , version1 ) where import Control.Exception ( throw ) @@ -35,6 +37,7 @@ import Data.Functor import Data.Int import Data.Monoid import Data.Text.Lazy.Encoding ( decodeUtf8, encodeUtf8 ) +import Data.Word import Thrift.Protocol import Thrift.Transport @@ -47,37 +50,55 @@ import qualified Data.ByteString.Lazy as LBS import qualified Data.HashMap.Strict as Map import qualified Data.Text.Lazy as LT -data BinaryProtocol a = BinaryProtocol a +versionMask :: Int32 +versionMask = fromIntegral (0xffff0000 :: Word32) + +version1 :: Int32 +version1 = fromIntegral (0x80010000 :: Word32) + +data BinaryProtocol a = Transport a => BinaryProtocol a + +getTransport :: Transport t => BinaryProtocol t -> t +getTransport (BinaryProtocol t) = t -- NOTE: Reading and Writing functions rely on Builders and Data.Binary to -- encode and decode data. Data.Binary assumes that the binary values it is -- encoding to and decoding from are in BIG ENDIAN format, and converts the -- endianness as necessary to match the local machine. -instance Protocol BinaryProtocol where - getTransport (BinaryProtocol t) = t +instance Transport t => Protocol (BinaryProtocol t) where + readByte p = tReadAll (getTransport p) 1 + -- flushTransport p = tFlush (getTransport p) + writeMessage p (n, t, s) f = do + tWrite (getTransport p) messageBegin + f + tFlush $ getTransport p + where + messageBegin = toLazyByteString $ + buildBinaryValue (TI32 (version1 .|. fromIntegral (fromEnum t))) <> + buildBinaryValue (TString $ encodeUtf8 n) <> + buildBinaryValue (TI32 s) - writeMessageBegin p (n, t, s) = tWrite (getTransport p) $ toLazyByteString $ - buildBinaryValue (TI32 (version1 .|. fromIntegral (fromEnum t))) <> - buildBinaryValue (TString $ encodeUtf8 n) <> - buildBinaryValue (TI32 s) + readMessage p = (readMessageBegin p >>=) + where + readMessageBegin p = runParser p $ do + TI32 ver <- parseBinaryValue T_I32 + if ver .&. versionMask /= version1 + then throw $ ProtocolExn PE_BAD_VERSION "Missing version identifier" + else do + TString s <- parseBinaryValue T_STRING + TI32 sz <- parseBinaryValue T_I32 + return (decodeUtf8 s, toEnum $ fromIntegral $ ver .&. 0xFF, sz) - readMessageBegin p = runParser p $ do - TI32 ver <- parseBinaryValue T_I32 - if ver .&. versionMask /= version1 - then throw $ ProtocolExn PE_BAD_VERSION "Missing version identifier" - else do - TString s <- parseBinaryValue T_STRING - TI32 sz <- parseBinaryValue T_I32 - return (decodeUtf8 s, toEnum $ fromIntegral $ ver .&. 0xFF, sz) + writeVal p = tWrite (getTransport p) . toLazyByteString . buildBinaryValue + readVal p = runParser p . parseBinaryValue +instance Transport t => StatelessProtocol (BinaryProtocol t) where serializeVal _ = toLazyByteString . buildBinaryValue deserializeVal _ ty bs = case LP.eitherResult $ LP.parse (parseBinaryValue ty) bs of Left s -> error s Right val -> val - readVal p = runParser p . parseBinaryValue - -- | Writing Functions buildBinaryValue :: ThriftVal -> Builder buildBinaryValue (TStruct fields) = buildBinaryStruct fields <> buildType T_STOP diff --git a/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Protocol/Compact.hs b/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Protocol/Compact.hs index 07113df..f23970a 100644 --- a/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Protocol/Compact.hs +++ b/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Protocol/Compact.hs @@ -25,10 +25,11 @@ module Thrift.Protocol.Compact ( module Thrift.Protocol , CompactProtocol(..) + , parseVarint + , buildVarint ) where import Control.Applicative -import Control.Exception ( throw ) import Control.Monad import Data.Attoparsec.ByteString as P import Data.Attoparsec.ByteString.Lazy as LP @@ -40,7 +41,7 @@ import Data.Monoid import Data.Word import Data.Text.Lazy.Encoding ( decodeUtf8, encodeUtf8 ) -import Thrift.Protocol hiding (versionMask) +import Thrift.Protocol import Thrift.Transport import Thrift.Types @@ -64,38 +65,47 @@ typeBits = 0x07 -- 0000 0111 typeShiftAmount :: Int typeShiftAmount = 5 +getTransport :: Transport t => CompactProtocol t -> t +getTransport (CompactProtocol t) = t -instance Protocol CompactProtocol where - getTransport (CompactProtocol t) = t +instance Transport t => Protocol (CompactProtocol t) where + readByte p = tReadAll (getTransport p) 1 + writeMessage p (n, t, s) f = do + tWrite (getTransport p) messageBegin + f + tFlush $ getTransport p + where + messageBegin = toLazyByteString $ + B.word8 protocolID <> + B.word8 ((version .&. versionMask) .|. + (((fromIntegral $ fromEnum t) `shiftL` + typeShiftAmount) .&. typeMask)) <> + buildVarint (i32ToZigZag s) <> + buildCompactValue (TString $ encodeUtf8 n) - writeMessageBegin p (n, t, s) = tWrite (getTransport p) $ toLazyByteString $ - B.word8 protocolID <> - B.word8 ((version .&. versionMask) .|. - (((fromIntegral $ fromEnum t) `shiftL` - typeShiftAmount) .&. typeMask)) <> - buildVarint (i32ToZigZag s) <> - buildCompactValue (TString $ encodeUtf8 n) - - readMessageBegin p = runParser p $ do - pid <- fromIntegral <$> P.anyWord8 - when (pid /= protocolID) $ error "Bad Protocol ID" - w <- fromIntegral <$> P.anyWord8 - let ver = w .&. versionMask - when (ver /= version) $ error "Bad Protocol version" - let typ = (w `shiftR` typeShiftAmount) .&. typeBits - seqId <- parseVarint zigZagToI32 - TString name <- parseCompactValue T_STRING - return (decodeUtf8 name, toEnum $ fromIntegral $ typ, seqId) + readMessage p f = readMessageBegin >>= f + where + readMessageBegin = runParser p $ do + pid <- fromIntegral <$> P.anyWord8 + when (pid /= protocolID) $ error "Bad Protocol ID" + w <- fromIntegral <$> P.anyWord8 + let ver = w .&. versionMask + when (ver /= version) $ error "Bad Protocol version" + let typ = (w `shiftR` typeShiftAmount) .&. typeBits + seqId <- parseVarint zigZagToI32 + TString name <- parseCompactValue T_STRING + return (decodeUtf8 name, toEnum $ fromIntegral $ typ, seqId) + writeVal p = tWrite (getTransport p) . toLazyByteString . buildCompactValue + readVal p ty = runParser p $ parseCompactValue ty + +instance Transport t => StatelessProtocol (CompactProtocol t) where serializeVal _ = toLazyByteString . buildCompactValue deserializeVal _ ty bs = case LP.eitherResult $ LP.parse (parseCompactValue ty) bs of Left s -> error s Right val -> val - readVal p ty = runParser p $ parseCompactValue ty - - -- | Writing Functions buildCompactValue :: ThriftVal -> Builder buildCompactValue (TStruct fields) = buildCompactStruct fields @@ -283,7 +293,7 @@ typeOf v = case v of TSet{} -> 0x0A TMap{} -> 0x0B TStruct{} -> 0x0C - + typeFrom :: Word8 -> ThriftType typeFrom w = case w of 0x01 -> T_BOOL diff --git a/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Protocol/Header.hs b/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Protocol/Header.hs new file mode 100644 index 0000000..5f42db4 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Protocol/Header.hs @@ -0,0 +1,141 @@ +-- +-- Licensed to the Apache Software Foundation (ASF) under one +-- or more contributor license agreements. See the NOTICE file +-- distributed with this work for additional information +-- regarding copyright ownership. The ASF licenses this file +-- to you 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. +-- + + +module Thrift.Protocol.Header + ( module Thrift.Protocol + , HeaderProtocol(..) + , getProtocolType + , setProtocolType + , getHeaders + , getWriteHeaders + , setHeader + , setHeaders + , createHeaderProtocol + , createHeaderProtocol1 + ) where + +import Thrift.Protocol +import Thrift.Protocol.Binary +import Thrift.Protocol.JSON +import Thrift.Protocol.Compact +import Thrift.Transport +import Thrift.Transport.Header +import Data.IORef +import qualified Data.Map as Map + +data ProtocolWrap = forall a. (Protocol a) => ProtocolWrap(a) + +instance Protocol ProtocolWrap where + readByte (ProtocolWrap p) = readByte p + readVal (ProtocolWrap p) = readVal p + readMessage (ProtocolWrap p) = readMessage p + writeVal (ProtocolWrap p) = writeVal p + writeMessage (ProtocolWrap p) = writeMessage p + +data HeaderProtocol i o = (Transport i, Transport o) => HeaderProtocol { + trans :: HeaderTransport i o, + wrappedProto :: IORef ProtocolWrap + } + +createProtocolWrap :: Transport t => ProtocolType -> t -> ProtocolWrap +createProtocolWrap typ t = + case typ of + TBinary -> ProtocolWrap $ BinaryProtocol t + TCompact -> ProtocolWrap $ CompactProtocol t + TJSON -> ProtocolWrap $ JSONProtocol t + +createHeaderProtocol :: (Transport i, Transport o) => i -> o -> IO(HeaderProtocol i o) +createHeaderProtocol i o = do + t <- openHeaderTransport i o + pid <- readIORef $ protocolType t + proto <- newIORef $ createProtocolWrap pid t + return $ HeaderProtocol { trans = t, wrappedProto = proto } + +createHeaderProtocol1 :: Transport t => t -> IO(HeaderProtocol t t) +createHeaderProtocol1 t = createHeaderProtocol t t + +resetProtocol :: (Transport i, Transport o) => HeaderProtocol i o -> IO () +resetProtocol p = do + pid <- readIORef $ protocolType $ trans p + writeIORef (wrappedProto p) $ createProtocolWrap pid $ trans p + +getWrapped = readIORef . wrappedProto + +setTransport :: (Transport i, Transport o) => HeaderProtocol i o -> HeaderTransport i o -> HeaderProtocol i o +setTransport p t = p { trans = t } + +updateTransport :: (Transport i, Transport o) => HeaderProtocol i o -> (HeaderTransport i o -> HeaderTransport i o)-> HeaderProtocol i o +updateTransport p f = setTransport p (f $ trans p) + +type Headers = Map.Map String String + +-- TODO: we want to set headers without recreating client... +setHeader :: (Transport i, Transport o) => HeaderProtocol i o -> String -> String -> HeaderProtocol i o +setHeader p k v = updateTransport p $ \t -> t { writeHeaders = Map.insert k v $ writeHeaders t } + +setHeaders :: (Transport i, Transport o) => HeaderProtocol i o -> Headers -> HeaderProtocol i o +setHeaders p h = updateTransport p $ \t -> t { writeHeaders = h } + +-- TODO: make it public once we have first transform implementation for Haskell +setTransforms :: (Transport i, Transport o) => HeaderProtocol i o -> [TransformType] -> HeaderProtocol i o +setTransforms p trs = updateTransport p $ \t -> t { writeTransforms = trs } + +setTransform :: (Transport i, Transport o) => HeaderProtocol i o -> TransformType -> HeaderProtocol i o +setTransform p tr = updateTransport p $ \t -> t { writeTransforms = tr:(writeTransforms t) } + +getWriteHeaders :: (Transport i, Transport o) => HeaderProtocol i o -> Headers +getWriteHeaders = writeHeaders . trans + +getHeaders :: (Transport i, Transport o) => HeaderProtocol i o -> IO [(String, String)] +getHeaders = readIORef . headers . trans + +getProtocolType :: (Transport i, Transport o) => HeaderProtocol i o -> IO ProtocolType +getProtocolType p = readIORef $ protocolType $ trans p + +setProtocolType :: (Transport i, Transport o) => HeaderProtocol i o -> ProtocolType -> IO () +setProtocolType p typ = do + typ0 <- getProtocolType p + if typ == typ0 + then return () + else do + tSetProtocol (trans p) typ + resetProtocol p + +instance (Transport i, Transport o) => Protocol (HeaderProtocol i o) where + readByte p = tReadAll (trans p) 1 + + readVal p tp = do + proto <- getWrapped p + readVal proto tp + + readMessage p f = do + tResetProtocol (trans p) + resetProtocol p + proto <- getWrapped p + readMessage proto f + + writeVal p v = do + proto <- getWrapped p + writeVal proto v + + writeMessage p x f = do + proto <- getWrapped p + writeMessage proto x f + diff --git a/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Protocol/JSON.hs b/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Protocol/JSON.hs index 7f619e8..839eddc 100644 --- a/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Protocol/JSON.hs +++ b/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Protocol/JSON.hs @@ -29,12 +29,12 @@ module Thrift.Protocol.JSON ) where import Control.Applicative +import Control.Exception (bracket) import Control.Monad import Data.Attoparsec.ByteString as P import Data.Attoparsec.ByteString.Char8 as PC import Data.Attoparsec.ByteString.Lazy as LP import Data.ByteString.Base64.Lazy as B64C -import Data.ByteString.Base64 as B64 import Data.ByteString.Lazy.Builder as B import Data.ByteString.Internal (c2w, w2c) import Data.Functor @@ -58,38 +58,48 @@ import qualified Data.Text.Lazy as LT -- encoded as a JSON 'ByteString' data JSONProtocol t = JSONProtocol t -- ^ Construct a 'JSONProtocol' with a 'Transport' +getTransport :: Transport t => JSONProtocol t -> t +getTransport (JSONProtocol t) = t -instance Protocol JSONProtocol where - getTransport (JSONProtocol t) = t +instance Transport t => Protocol (JSONProtocol t) where + readByte p = tReadAll (getTransport p) 1 - writeMessageBegin (JSONProtocol t) (s, ty, sq) = tWrite t $ toLazyByteString $ - B.char8 '[' <> buildShowable (1 :: Int32) <> - B.string8 ",\"" <> escape (encodeUtf8 s) <> B.char8 '\"' <> - B.char8 ',' <> buildShowable (fromEnum ty) <> - B.char8 ',' <> buildShowable sq <> - B.char8 ',' - writeMessageEnd (JSONProtocol t) = tWrite t "]" - readMessageBegin p = runParser p $ skipSpace *> do - _ver :: Int32 <- lexeme (PC.char8 '[') *> lexeme (signed decimal) - bs <- lexeme (PC.char8 ',') *> lexeme escapedString - case decodeUtf8' bs of - Left _ -> fail "readMessage: invalid text encoding" - Right str -> do - ty <- toEnum <$> (lexeme (PC.char8 ',') *> lexeme (signed decimal)) - seqNum <- lexeme (PC.char8 ',') *> lexeme (signed decimal) - _ <- PC.char8 ',' - return (str, ty, seqNum) - readMessageEnd p = void $ runParser p (PC.char8 ']') + writeMessage (JSONProtocol t) (s, ty, sq) = bracket readMessageBegin readMessageEnd . const + where + readMessageBegin = tWrite t $ toLazyByteString $ + B.char8 '[' <> buildShowable (1 :: Int32) <> + B.string8 ",\"" <> escape (encodeUtf8 s) <> B.char8 '\"' <> + B.char8 ',' <> buildShowable (fromEnum ty) <> + B.char8 ',' <> buildShowable sq <> + B.char8 ',' + readMessageEnd _ = do + tWrite t "]" + tFlush t + readMessage p = bracket readMessageBegin readMessageEnd + where + readMessageBegin = runParser p $ skipSpace *> do + _ver :: Int32 <- lexeme (PC.char8 '[') *> lexeme (signed decimal) + bs <- lexeme (PC.char8 ',') *> lexeme escapedString + case decodeUtf8' bs of + Left _ -> fail "readMessage: invalid text encoding" + Right str -> do + ty <- toEnum <$> (lexeme (PC.char8 ',') *> lexeme (signed decimal)) + seqNum <- lexeme (PC.char8 ',') *> lexeme (signed decimal) + _ <- PC.char8 ',' + return (str, ty, seqNum) + readMessageEnd _ = void $ runParser p (PC.char8 ']') + + writeVal p = tWrite (getTransport p) . toLazyByteString . buildJSONValue + readVal p ty = runParser p $ skipSpace *> parseJSONValue ty + +instance Transport t => StatelessProtocol (JSONProtocol t) where serializeVal _ = toLazyByteString . buildJSONValue deserializeVal _ ty bs = case LP.eitherResult $ LP.parse (parseJSONValue ty) bs of Left s -> error s Right val -> val - readVal p ty = runParser p $ skipSpace *> parseJSONValue ty - - -- Writing Functions buildJSONValue :: ThriftVal -> Builder diff --git a/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Server.hs b/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Server.hs index ed74ceb..543f338 100644 --- a/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Server.hs +++ b/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Server.hs @@ -38,10 +38,10 @@ import Thrift.Protocol.Binary -- | A threaded sever that is capable of using any Transport or Protocol -- instances. -runThreadedServer :: (Transport t, Protocol i, Protocol o) - => (Socket -> IO (i t, o t)) +runThreadedServer :: (Protocol i, Protocol o) + => (Socket -> IO (i, o)) -> h - -> (h -> (i t, o t) -> IO Bool) + -> (h -> (i, o) -> IO Bool) -> PortID -> IO a runThreadedServer accepter hand proc_ port = do diff --git a/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Transport/Handle.hs b/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Transport/Handle.hs index b7d16e4..ff6295b 100644 --- a/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Transport/Handle.hs +++ b/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Transport/Handle.hs @@ -44,7 +44,13 @@ import Data.Monoid instance Transport Handle where tIsOpen = hIsOpen tClose = hClose - tRead h n = LBS.hGet h n `Control.Exception.catch` handleEOF mempty + tRead h n = read `Control.Exception.catch` handleEOF mempty + where + read = do + hLookAhead h + LBS.hGetNonBlocking h n + tReadAll _ 0 = return mempty + tReadAll h n = LBS.hGet h n `Control.Exception.catch` throwTransportExn tPeek h = (Just . c2w <$> hLookAhead h) `Control.Exception.catch` handleEOF Nothing tWrite = LBS.hPut tFlush = hFlush @@ -61,8 +67,12 @@ instance HandleSource FilePath where instance HandleSource (HostName, PortID) where hOpen = uncurry connectTo +throwTransportExn :: IOError -> IO a +throwTransportExn e = if isEOFError e + then throw $ TransportExn "Cannot read. Remote side has closed." TE_UNKNOWN + else throw $ TransportExn "Handle tReadAll: Could not read" TE_UNKNOWN handleEOF :: a -> IOError -> IO a handleEOF a e = if isEOFError e then return a - else throw $ TransportExn "TChannelTransport: Could not read" TE_UNKNOWN + else throw $ TransportExn "Handle: Could not read" TE_UNKNOWN diff --git a/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Transport/Header.hs b/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Transport/Header.hs new file mode 100644 index 0000000..2dacad2 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/hs/src/Thrift/Transport/Header.hs @@ -0,0 +1,354 @@ +-- +-- Licensed to the Apache Software Foundation (ASF) under one +-- or more contributor license agreements. See the NOTICE file +-- distributed with this work for additional information +-- regarding copyright ownership. The ASF licenses this file +-- to you 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. +-- + +module Thrift.Transport.Header + ( module Thrift.Transport + , HeaderTransport(..) + , openHeaderTransport + , ProtocolType(..) + , TransformType(..) + , ClientType(..) + , tResetProtocol + , tSetProtocol + ) where + +import Thrift.Transport +import Thrift.Protocol.Compact +import Control.Applicative +import Control.Exception ( throw ) +import Control.Monad +import Data.Bits +import Data.IORef +import Data.Int +import Data.Monoid +import Data.Word + +import qualified Data.Attoparsec.ByteString as P +import qualified Data.Binary as Binary +import qualified Data.ByteString as BS +import qualified Data.ByteString.Char8 as C +import qualified Data.ByteString.Lazy as LBS +import qualified Data.ByteString.Lazy.Builder as B +import qualified Data.Map as Map + +data ProtocolType = TBinary | TCompact | TJSON deriving (Enum, Eq) +data ClientType = HeaderClient | Framed | Unframed deriving (Enum, Eq) + +infoIdKeyValue = 1 + +type Headers = Map.Map String String + +data TransformType = ZlibTransform deriving (Enum, Eq) + +fromTransportType :: TransformType -> Int16 +fromTransportType ZlibTransform = 1 + +toTransportType :: Int16 -> TransformType +toTransportType 1 = ZlibTransform +toTransportType _ = throw $ TransportExn "HeaderTransport: Unknown transform ID" TE_UNKNOWN + +data HeaderTransport i o = (Transport i, Transport o) => HeaderTransport + { readBuffer :: IORef LBS.ByteString + , writeBuffer :: IORef B.Builder + , inTrans :: i + , outTrans :: o + , clientType :: IORef ClientType + , protocolType :: IORef ProtocolType + , headers :: IORef [(String, String)] + , writeHeaders :: Headers + , transforms :: IORef [TransformType] + , writeTransforms :: [TransformType] + } + +openHeaderTransport :: (Transport i, Transport o) => i -> o -> IO (HeaderTransport i o) +openHeaderTransport i o = do + pid <- newIORef TCompact + rBuf <- newIORef LBS.empty + wBuf <- newIORef mempty + cType <- newIORef HeaderClient + h <- newIORef [] + trans <- newIORef [] + return HeaderTransport + { readBuffer = rBuf + , writeBuffer = wBuf + , inTrans = i + , outTrans = o + , clientType = cType + , protocolType = pid + , headers = h + , writeHeaders = Map.empty + , transforms = trans + , writeTransforms = [] + } + +isFramed t = (/= Unframed) <$> readIORef (clientType t) + +readFrame :: (Transport i, Transport o) => HeaderTransport i o -> IO Bool +readFrame t = do + let input = inTrans t + let rBuf = readBuffer t + let cType = clientType t + lsz <- tRead input 4 + let sz = LBS.toStrict lsz + case P.parseOnly P.endOfInput sz of + Right _ -> do return False + Left _ -> do + case parseBinaryMagic sz of + Right _ -> do + writeIORef rBuf $ lsz + writeIORef cType Unframed + writeIORef (protocolType t) TBinary + return True + Left _ -> do + case parseCompactMagic sz of + Right _ -> do + writeIORef rBuf $ lsz + writeIORef cType Unframed + writeIORef (protocolType t) TCompact + return True + Left _ -> do + let len = Binary.decode lsz :: Int32 + lbuf <- tReadAll input $ fromIntegral len + let buf = LBS.toStrict lbuf + case parseBinaryMagic buf of + Right _ -> do + writeIORef cType Framed + writeIORef (protocolType t) TBinary + writeIORef rBuf lbuf + return True + Left _ -> do + case parseCompactMagic buf of + Right _ -> do + writeIORef cType Framed + writeIORef (protocolType t) TCompact + writeIORef rBuf lbuf + return True + Left _ -> do + case parseHeaderMagic buf of + Right flags -> do + let (flags, seqNum, header, body) = extractHeader buf + writeIORef cType HeaderClient + handleHeader t header + payload <- untransform t body + writeIORef rBuf $ LBS.fromStrict $ payload + return True + Left _ -> + throw $ TransportExn "HeaderTransport: unkonwn client type" TE_UNKNOWN + +parseBinaryMagic = P.parseOnly $ P.word8 0x80 *> P.word8 0x01 *> P.word8 0x00 *> P.anyWord8 +parseCompactMagic = P.parseOnly $ P.word8 0x82 *> P.satisfy (\b -> b .&. 0x1f == 0x01) +parseHeaderMagic = P.parseOnly $ P.word8 0x0f *> P.word8 0xff *> (P.count 2 P.anyWord8) + +parseI32 :: P.Parser Int32 +parseI32 = Binary.decode . LBS.fromStrict <$> P.take 4 +parseI16 :: P.Parser Int16 +parseI16 = Binary.decode . LBS.fromStrict <$> P.take 2 + +extractHeader :: BS.ByteString -> (Int16, Int32, BS.ByteString, BS.ByteString) +extractHeader bs = + case P.parse extractHeader_ bs of + P.Done remain (flags, seqNum, header) -> (flags, seqNum, header, remain) + _ -> throw $ TransportExn "HeaderTransport: Invalid header" TE_UNKNOWN + where + extractHeader_ = do + magic <- P.word8 0x0f *> P.word8 0xff + flags <- parseI16 + seqNum <- parseI32 + (headerSize :: Int) <- (* 4) . fromIntegral <$> parseI16 + header <- P.take headerSize + return (flags, seqNum, header) + +handleHeader t header = + case P.parseOnly parseHeader header of + Right (pType, trans, info) -> do + writeIORef (protocolType t) pType + writeIORef (transforms t) trans + writeIORef (headers t) info + _ -> throw $ TransportExn "HeaderTransport: Invalid header" TE_UNKNOWN + + +iw16 :: Int16 -> Word16 +iw16 = fromIntegral +iw32 :: Int32 -> Word32 +iw32 = fromIntegral +wi16 :: Word16 -> Int16 +wi16 = fromIntegral +wi32 :: Word32 -> Int32 +wi32 = fromIntegral + +parseHeader :: P.Parser (ProtocolType, [TransformType], [(String, String)]) +parseHeader = do + protocolType <- toProtocolType <$> parseVarint wi16 + numTrans <- fromIntegral <$> parseVarint wi16 + trans <- replicateM numTrans parseTransform + info <- parseInfo + return (protocolType, trans, info) + +toProtocolType :: Int16 -> ProtocolType +toProtocolType 0 = TBinary +toProtocolType 1 = TJSON +toProtocolType 2 = TCompact + +fromProtocolType :: ProtocolType -> Int16 +fromProtocolType TBinary = 0 +fromProtocolType TJSON = 1 +fromProtocolType TCompact = 2 + +parseTransform :: P.Parser TransformType +parseTransform = toTransportType <$> parseVarint wi16 + +parseInfo :: P.Parser [(String, String)] +parseInfo = do + n <- P.eitherP P.endOfInput (parseVarint wi32) + case n of + Left _ -> return [] + Right n0 -> + replicateM (fromIntegral n0) $ do + klen <- parseVarint wi16 + k <- P.take $ fromIntegral klen + vlen <- parseVarint wi16 + v <- P.take $ fromIntegral vlen + return (C.unpack k, C.unpack v) + +parseString :: P.Parser BS.ByteString +parseString = parseVarint wi32 >>= (P.take . fromIntegral) + +buildHeader :: HeaderTransport i o -> IO B.Builder +buildHeader t = do + pType <- readIORef $ protocolType t + let pId = buildVarint $ iw16 $ fromProtocolType pType + let headerContent = pId <> (buildTransforms t) <> (buildInfo t) + let len = fromIntegral $ LBS.length $ B.toLazyByteString headerContent + -- TODO: length limit check + let padding = mconcat $ replicate (mod len 4) $ B.word8 0 + let codedLen = B.int16BE (fromIntegral $ (quot (len - 1) 4) + 1) + let flags = 0 + let seqNum = 0 + return $ B.int16BE 0x0fff <> B.int16BE flags <> B.int32BE seqNum <> codedLen <> headerContent <> padding + +buildTransforms :: HeaderTransport i o -> B.Builder +-- TODO: check length limit +buildTransforms t = + let trans = writeTransforms t in + (buildVarint $ iw16 $ fromIntegral $ length trans) <> + (mconcat $ map (buildVarint . iw16 . fromTransportType) trans) + +buildInfo :: HeaderTransport i o -> B.Builder +buildInfo t = + let h = Map.assocs $ writeHeaders t in + -- TODO: check length limit + case length h of + 0 -> mempty + len -> (buildVarint $ iw16 $ fromIntegral $ len) <> (mconcat $ map buildInfoEntry h) + where + buildInfoEntry (k, v) = buildVarStr k <> buildVarStr v + -- TODO: check length limit + buildVarStr s = (buildVarint $ iw16 $ fromIntegral $ length s) <> B.string8 s + +tResetProtocol :: (Transport i, Transport o) => HeaderTransport i o -> IO Bool +tResetProtocol t = do + rBuf <- readIORef $ readBuffer t + writeIORef (clientType t) HeaderClient + readFrame t + +tSetProtocol :: (Transport i, Transport o) => HeaderTransport i o -> ProtocolType -> IO () +tSetProtocol t = writeIORef (protocolType t) + +transform :: HeaderTransport i o -> LBS.ByteString -> LBS.ByteString +transform t bs = + foldr applyTransform bs $ writeTransforms t + where + -- applyTransform bs ZlibTransform = + -- throw $ TransportExn "HeaderTransport: not implemented: ZlibTransform " TE_UNKNOWN + applyTransform bs _ = + throw $ TransportExn "HeaderTransport: Unknown transform" TE_UNKNOWN + +untransform :: HeaderTransport i o -> BS.ByteString -> IO BS.ByteString +untransform t bs = do + trans <- readIORef $ transforms t + return $ foldl unapplyTransform bs trans + where + -- unapplyTransform bs ZlibTransform = + -- throw $ TransportExn "HeaderTransport: not implemented: ZlibTransform " TE_UNKNOWN + unapplyTransform bs _ = + throw $ TransportExn "HeaderTransport: Unknown transform" TE_UNKNOWN + +instance (Transport i, Transport o) => Transport (HeaderTransport i o) where + tIsOpen t = do + tIsOpen (inTrans t) + tIsOpen (outTrans t) + + tClose t = do + tClose(outTrans t) + tClose(inTrans t) + + tRead t len = do + rBuf <- readIORef $ readBuffer t + if not $ LBS.null rBuf + then do + let (consumed, remain) = LBS.splitAt (fromIntegral len) rBuf + writeIORef (readBuffer t) remain + return consumed + else do + framed <- isFramed t + if not framed + then tRead (inTrans t) len + else do + ok <- readFrame t + if ok + then tRead t len + else return LBS.empty + + tPeek t = do + rBuf <- readIORef (readBuffer t) + if not $ LBS.null rBuf + then return $ Just $ LBS.head rBuf + else do + framed <- isFramed t + if not framed + then tPeek (inTrans t) + else do + ok <- readFrame t + if ok + then tPeek t + else return Nothing + + tWrite t buf = do + let wBuf = writeBuffer t + framed <- isFramed t + if framed + then modifyIORef wBuf (<> B.lazyByteString buf) + else + -- TODO: what should we do when switched to unframed in the middle ? + tWrite(outTrans t) buf + + tFlush t = do + cType <- readIORef $ clientType t + case cType of + Unframed -> tFlush $ outTrans t + Framed -> flushBuffer t id mempty + HeaderClient -> buildHeader t >>= flushBuffer t (transform t) + where + flushBuffer t f header = do + wBuf <- readIORef $ writeBuffer t + writeIORef (writeBuffer t) mempty + let payload = B.toLazyByteString (header <> wBuf) + tWrite (outTrans t) $ Binary.encode (fromIntegral $ LBS.length payload :: Int32) + tWrite (outTrans t) $ f payload + tFlush (outTrans t) diff --git a/vendor/git.apache.org/thrift.git/lib/java/CMakeLists.txt b/vendor/git.apache.org/thrift.git/lib/java/CMakeLists.txt index 57b97f1..46064e6 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/CMakeLists.txt +++ b/vendor/git.apache.org/thrift.git/lib/java/CMakeLists.txt @@ -17,19 +17,14 @@ # under the License. # -file(GLOB java_sources src/**/*.java) - if(ANDROID) - set(android_sources - android/build.gradle - android/settings.gradle - android/src/main/AndroidManifest.xml - ) set(THRIFT_AAR outputs/aar/thrift-debug.aar outputs/aar/thrift-release.aar) add_custom_command( OUTPUT ${THRIFT_AAR} - COMMAND ${GRADLE_EXECUTABLE} -p"${CMAKE_CURRENT_SOURCE_DIR}/android" -PbuildDir="${CMAKE_CURRENT_BINARY_DIR}" assemble - DEPENDS ${java_sources} ${android_sources}) + COMMAND ${GRADLE_EXECUTABLE} + -p "${CMAKE_CURRENT_SOURCE_DIR}/android" + "-PbuildDir=${CMAKE_CURRENT_BINARY_DIR}/android/build" assemble + ) add_custom_target(thrift_aar ALL DEPENDS ${THRIFT_AAR}) else(ANDROID) @@ -46,35 +41,47 @@ else(ANDROID) set(JAVA_DOC_INSTALL_DIR "${CMAKE_INSTALL_PREFIX}/${DOC_INSTALL_DIR}/java") endif() - file(GLOB_RECURSE ThriftJava_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src/*.java) - set(ThriftJava_ARTIFACTS - libthrift-${thrift_VERSION}.jar - libthrift-${thrift_VERSION}.pom - ) - add_custom_command( - OUTPUT ${ThriftJava_ARTIFACTS} - COMMAND ${Ant_EXECUTABLE} ${ANT_FLAGS} -Dbuild.dir="${CMAKE_CURRENT_BINARY_DIR}" -f build.xml - MAIN_DEPENDENCY ${CMAKE_CURRENT_SOURCE_DIR}/build.xml - DEPENDS ${ThriftJava_SOURCES} - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} - ) - add_custom_target(ThriftJava ALL - COMMENT "Building Java library using Ant" - DEPENDS ${ThriftJava_ARTIFACTS} + COMMENT "Building Java library using Gradle Wrapper" + COMMAND ${GRADLEW_EXECUTABLE} ${GRADLE_OPTS} assemble + --console=plain --no-daemon + -Prelease=true + -Pthrift.version=${thrift_VERSION} + "-Pbuild.dir=${CMAKE_CURRENT_BINARY_DIR}/build" + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} ) - # Hook the ant install task into CMake install - install(CODE "execute_process( - COMMAND ${Ant_EXECUTABLE} ${ANT_FLAGS} install - -Dbuild.dir=\"${CMAKE_CURRENT_BINARY_DIR}\" - -Dinstall.path=\"${JAVA_INSTALL_DIR}\" -Dinstall.javadoc.path=\"${JAVA_DOC_INSTALL_DIR}\" -f build.xml + # Enable publishing from CMake if the publishing information is provided + add_custom_target(MavenPublish + COMMENT "Publishing Java Library to Apache Maven staging" + COMMAND ${GRADLEW_EXECUTABLE} ${GRADLE_OPTS} clean uploadArchives + --console=plain --no-daemon + -Prelease=true + -Pthrift.version=${thrift_VERSION} + "-Pbuild.dir=${CMAKE_CURRENT_BINARY_DIR}/build" WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} - )") + ) + + # Hook the CMake install process to the results from make ALL. + # This works best when 'make all && sudo make install/fast' is used. + # Using slash to end the source location to avoid copying the directory path. + install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/build/libs/ + DESTINATION ${JAVA_INSTALL_DIR} + FILES_MATCHING PATTERN "libthrift-${thrift_VERSION}.jar") + install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/build/deps/ + DESTINATION ${JAVA_INSTALL_DIR} + FILES_MATCHING PATTERN "*.jar") + install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/build/docs/javadoc/ + DESTINATION ${JAVA_DOC_INSTALL_DIR}) if(BUILD_TESTING) add_test(NAME JavaTest - COMMAND ${Ant_EXECUTABLE} ${ANT_FLAGS} -Dbuild.dir="${CMAKE_CURRENT_BINARY_DIR}" -Dthrift.compiler="${THRIFT_COMPILER}" -f build.xml test - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) + COMMAND ${GRADLEW_EXECUTABLE} ${GRADLE_OPTS} test + --console=plain --no-daemon + -Prelease=true + -Pthrift.version=${thrift_VERSION} + "-Pbuild.dir=${CMAKE_CURRENT_BINARY_DIR}/build" + "-Pthrift.compiler=${THRIFT_COMPILER}" + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) endif() endif(ANDROID) diff --git a/vendor/git.apache.org/thrift.git/lib/java/Makefile.am b/vendor/git.apache.org/thrift.git/lib/java/Makefile.am index ab130f5..65981ca 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/Makefile.am +++ b/vendor/git.apache.org/thrift.git/lib/java/Makefile.am @@ -19,32 +19,54 @@ export CLASSPATH -THRIFT = $(top_builddir)/compiler/cpp/thrift - all-local: - $(ANT) $(ANT_FLAGS) + ./gradlew $(GRADLE_OPTS) assemble \ + -Prelease=true \ + -Pthrift.version=$(PACKAGE_VERSION) \ + --console=plain install-exec-hook: - $(ANT) $(ANT_FLAGS) install -Dinstall.path=$(DESTDIR)$(JAVA_PREFIX) \ - -Dinstall.javadoc.path=$(DESTDIR)$(docdir)/java + ./gradlew $(GRADLE_OPTS) install \ + -Prelease=true \ + -Pinstall.path=$(DESTDIR)$(JAVA_PREFIX) \ + -Pinstall.javadoc.path=$(DESTDIR)$(docdir)/java \ + -Pthrift.version=$(PACKAGE_VERSION) \ + --console=plain -# Make sure this doesn't fail if ant is not configured. clean-local: - ANT=$(ANT) ; if test -z "$$ANT" ; then ANT=: ; fi ; \ - $$ANT $(ANT_FLAGS) clean + ./gradlew $(GRADLE_OPTS) clean --console=plain precross: $(THRIFT) - $(ANT) $(ANT_FLAGS) compile-test + ./gradlew $(GRADLE_OPTS) shadowJar \ + -Prelease=true \ + -Pthrift.version=$(PACKAGE_VERSION) \ + -Pthrift.compiler=$(THRIFT) \ + --console=plain -check-local: all - $(ANT) $(ANT_FLAGS) test +check-local: $(THRIFT) + ./gradlew $(GRADLE_OPTS) test \ + -Prelease=true \ + -Pthrift.version=$(PACKAGE_VERSION) \ + -Pthrift.compiler=$(THRIFT) \ + --console=plain + +maven-publish: + ./gradlew $(GRADLE_OPTS) uploadArchives \ + -Prelease=true \ + -Pthrift.version=$(PACKAGE_VERSION) \ + --console=plain EXTRA_DIST = \ - build.xml \ - build.properties \ + build.gradle \ + gradle.properties \ + settings.gradle \ + gradle \ + gradlew \ + gradlew.bat \ CMakeLists.txt \ coding_standards.md \ android \ src \ test \ + code_quality_tools \ README.md diff --git a/vendor/git.apache.org/thrift.git/lib/java/README.md b/vendor/git.apache.org/thrift.git/lib/java/README.md index 66bcfa5..1e4aed2 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/README.md +++ b/vendor/git.apache.org/thrift.git/lib/java/README.md @@ -20,18 +20,59 @@ KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -Using Thrift with Java -====================== +Building and installing from source +=================================== + +When using a CMake build from the source distribution on Linux the +easiest way to build and install is this simple command line: + + make all && sudo make install/fast + +It is important to use the install/fast option to eliminate +the automatic rebuild by dependency that causes issues because +the build tooling is designed to work with cached files in the +user home directory during the build process. Instead this builds +the code in the expected local build tree and then uses CMake +install code to copy to the target destination. + +Building Thrift with Gradle without CMake/Autoconf +================================================== The Thrift Java source is not build using the GNU tools, but rather uses -the Apache Ant build system, which tends to be predominant amongst Java +the Gradle build system, which tends to be predominant amongst Java developers. To compile the Java Thrift libraries, simply do the following: - ant + ./gradlew -Yep, that's easy. Look for libthrift.jar in the base directory. +Yep, that's easy. Look for libthrift-.jar in the build/libs directory. + +The default build will run the unit tests which expect a usable +Thrift compiler to exist on the system. You have two choices for +that. + +* Build the Thrift executable from source at the default + location in the source tree. The project is configured + to look for it there. +* Install the published binary distribution to have Thrift + executable in a known location and add the path to the + ~/.gradle/gradle.properties file using the property name + "thrift.compiler". For example this would set the path in + a Windows box if Thrift was installed under C:\Thrift + + thrift.compiler=C:/Thrift/thrift.exe + +To just build the library without running unit tests you simply do this. + + ./gradlew assemble + +To install the library in the local Maven repository location +where other Maven or Gradle builds can reference it simply do this. + + ./gradlew install + +The library will be placed in your home directory under .m2/repository To include Thrift in your applications simply add libthrift.jar to your classpath, or install if in your default system classpath of choice. @@ -39,15 +80,84 @@ classpath, or install if in your default system classpath of choice. Build Thrift behind a proxy: - ant -Dproxy.enabled=1 -Dproxy.host=myproxyhost -Dproxy.user=thriftuser -Dproxy.pass=topsecret + ./gradlew -Dhttp.proxyHost=myproxyhost -Dhttp.proxyPort=8080 -Dhttp.proxyUser=thriftuser -Dhttp.proxyPassword=topsecret or via - ./configure --with-java ANT_FLAGS='-Dproxy.enabled=1 -Dproxy.host=myproxyhost -Dproxy.user=thriftuser -Dproxy.pass=topsecret' + ./configure --with-java GRADLE_OPTS='-Dhttp.proxyHost=myproxyhost -Dhttp.proxyPort=8080 -Dhttp.proxyUser=thriftuser -Dhttp.proxyPassword=topsecret' + + +Unit Test HTML Reports +====================== + +The build will automatically generate an HTML Unit Test report. This can be found +under build/reports/tests/test/index.html. It can be viewed with a browser +directly from that location. + + +Clover Code Coverage for Thrift +=============================== + +The build will optionally generate Clover Code coverage if the Gradle property +`cloverEnabled=true` is set in ~/.gradle/gradle.properties or on the command line +via `-PcloverEnabled=true`. The generated report can be found under the location +build/reports/clover/html/index.html. It can be viewed with a browser +directly from that location. Additionally, a PDF report is generated and is found +under the location build/reports/clover/clover.pdf. + +The following command will build, unit test, and generate Clover reports: + + ./gradlew -PcloverEnabled=true + + +Publishing Maven Artifacts to Maven Central +=========================================== + +The Automake build generates a Makefile that provides the correct parameters +when you run the build provided the configure.ac has been set with the correct +version number. The Gradle build will receive the correct value for the build. +The same applies to the CMake build, the value from the configure.ac file will +be used if you execute these commands: + + make maven-publish -- This is for an Automake Linux build + make MavenPublish -- This is for a CMake generated build + +The uploadArchives task in Gradle is preconfigured with all necessary details +to sign and publish the artifacts from the build to the Apache Maven staging +repository. The task requires the following externally provided properties to +authenticate to the repository and sign the artifacts. The preferred approach +is to create or edit the ~/.gradle/gradle.properties file and add the following +properties to it. + + # Signing key information for artifacts PGP signature (values are examples) + signing.keyId=24875D73 + signing.password=secret + signing.secretKeyRingFile=/Users/me/.gnupg/secring.gpg + + # Apache Maven staging repository user credentials + mavenUser=meMyselfAndI + mavenPassword=MySuperAwesomeSecretPassword + +It is also possible to manually publish using the Gradle build directly. +With the key information and credentials in place the following will generate +if needed the build artifacts and proceed to publish the results. + + ./gradlew -Prelease=true -Pthrift.version=0.11.0 uploadArchives + +It is also possible to override the target repository for the Maven Publication +by using a Gradle property, for example you can publish signed JAR files to your +company internal server if you add this to the command line or in the +~/.gradle/gradle.properties file. The URL below assumes a Nexus Repository. + + maven-repository-url=https://my.company.com/service/local/staging/deploy/maven2 + +Or the same on the command line: + + ./gradlew -Pmaven-repository-url=https://my.company.com/service/local/staging/deploy/maven2 -Prelease=true -Pthrift.version=0.11.0 uploadArchives Dependencies ============ -Apache Ant -http://ant.apache.org/ +Gradle +http://gradle.org/ diff --git a/vendor/git.apache.org/thrift.git/lib/java/android/build.gradle b/vendor/git.apache.org/thrift.git/lib/java/android/build.gradle index 4aa2864..c998423 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/android/build.gradle +++ b/vendor/git.apache.org/thrift.git/lib/java/android/build.gradle @@ -20,31 +20,31 @@ apply plugin: 'com.android.library' android { - compileSdkVersion 23 - buildToolsVersion "23.0.1" - useLibrary 'org.apache.http.legacy' - sourceSets.main.java { - srcDir '../src' - exclude 'org/apache/thrift/transport/TSaslClientTransport.java' - exclude 'org/apache/thrift/transport/TSaslServerTransport.java' - exclude 'org/apache/thrift/transport/TSaslTransport.java' - } + compileSdkVersion 23 + buildToolsVersion "23.0.1" + useLibrary 'org.apache.http.legacy' + sourceSets.main.java { + srcDir '../src' + exclude 'org/apache/thrift/transport/TSaslClientTransport.java' + exclude 'org/apache/thrift/transport/TSaslServerTransport.java' + exclude 'org/apache/thrift/transport/TSaslTransport.java' + } } repositories { - mavenCentral() + mavenCentral() } dependencies { - compile 'org.slf4j:slf4j-api:1.7.13' - compile 'javax.servlet:servlet-api:2.5' - compile 'org.apache.httpcomponents:httpcore:4.4.4' + compile 'org.slf4j:slf4j-api:1.7.13' + compile 'javax.servlet:servlet-api:2.5' + compile 'org.apache.httpcomponents:httpcore:4.4.4' } buildscript { - repositories { - mavenCentral() - } - dependencies { - classpath 'com.android.tools.build:gradle:1.5.0' - } + repositories { + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.5.0' + } } diff --git a/vendor/git.apache.org/thrift.git/lib/java/build.gradle b/vendor/git.apache.org/thrift.git/lib/java/build.gradle new file mode 100644 index 0000000..4302f77 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/build.gradle @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +// Using the legacy plugin classpath for Clover so it can be loaded optionally +buildscript { + repositories { + google() + jcenter() + gradlePluginPortal() + } + + dependencies { + classpath 'com.bmuschko:gradle-clover-plugin:2.2.0' + } +} + +plugins { + id 'java' + id 'maven' + id 'signing' + id 'com.github.johnrengelman.shadow' version '2.0.2' +} + +description = 'Apache Thrift Java Library' + +defaultTasks 'build' + +// Version components for this project +group = property('thrift.groupid') + +// Drop the -dev suffix, we use the SNAPSHOT suffix for non-release versions +def parsedVersion = property('thrift.version').toString().replace('-dev', '') +if (Boolean.parseBoolean(project.release)) { + version = parsedVersion +} else { + version = parsedVersion + '-SNAPSHOT' +} + +// Keeping the rest of the build logic in functional named scripts for clarity +apply from: 'gradle/environment.gradle' +apply from: 'gradle/sourceConfiguration.gradle' +apply from: 'gradle/additionalArtifacts.gradle' +apply from: 'gradle/generateTestThrift.gradle' +apply from: 'gradle/unitTests.gradle' +apply from: 'gradle/cloverCoverage.gradle' +apply from: 'gradle/functionalTests.gradle' +apply from: 'gradle/publishing.gradle' +apply from: 'gradle/codeQualityChecks.gradle' diff --git a/vendor/git.apache.org/thrift.git/lib/java/build.xml b/vendor/git.apache.org/thrift.git/lib/java/build.xml deleted file mode 100644 index 40e5284..0000000 --- a/vendor/git.apache.org/thrift.git/lib/java/build.xml +++ /dev/null @@ -1,414 +0,0 @@ - - - - - Thrift Build File - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Tests failed! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/vendor/git.apache.org/thrift.git/lib/java/code_quality_tools/findbugs-filter.xml b/vendor/git.apache.org/thrift.git/lib/java/code_quality_tools/findbugs-filter.xml new file mode 100644 index 0000000..8a93b0a --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/code_quality_tools/findbugs-filter.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vendor/git.apache.org/thrift.git/lib/java/build.properties b/vendor/git.apache.org/thrift.git/lib/java/gradle.properties similarity index 56% rename from vendor/git.apache.org/thrift.git/lib/java/build.properties rename to vendor/git.apache.org/thrift.git/lib/java/gradle.properties index a3f2de5..4955b4c 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/build.properties +++ b/vendor/git.apache.org/thrift.git/lib/java/gradle.properties @@ -1,31 +1,33 @@ -thrift.version=0.10.0 +# This file is shared currently between this Gradle build and the +# Ant builds for fd303 and JavaScript. Keep the dotted notation for +# the properties to minimize the changes in the dependencies. +thrift.version=0.12.0 thrift.groupid=org.apache.thrift -release=false - -# Jar Versions -mvn.ant.task.version=2.1.3 +release=true # Local Install paths install.path=/usr/local/lib -install.javadoc.path=${install.path} +install.javadoc.path=/usr/local/lib + +# Test execution properties +testPort=9090 + +# Test with Clover Code coverage (disabled by default) +cloverEnabled=false # Maven dependency download locations mvn.repo=http://repo1.maven.org/maven2 apache.repo=https://repository.apache.org/content/repositories/releases -mvn.ant.task.url=${mvn.repo}/org/apache/maven/maven-ant-tasks/${mvn.ant.task.version} -mvn.ant.task.jar=maven-ant-tasks-${mvn.ant.task.version}.jar # Apache Maven publish license=http://www.apache.org/licenses/LICENSE-2.0.txt maven-repository-url=https://repository.apache.org/service/local/staging/deploy/maven2 maven-repository-id=apache.releases.https -# Jar Versions -mvn.ant.task.version=2.1.3 - # Dependency versions httpclient.version=4.4.1 httpcore.version=4.4.1 slf4j.version=1.7.12 servlet.version=2.5 - +junit.version=4.12 +mockito.version=1.9.5 diff --git a/vendor/git.apache.org/thrift.git/lib/java/gradle/additionalArtifacts.gradle b/vendor/git.apache.org/thrift.git/lib/java/gradle/additionalArtifacts.gradle new file mode 100644 index 0000000..201469d --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/gradle/additionalArtifacts.gradle @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +// Following Gradle best practices to keep build logic organized + +task sourcesJar(type: Jar, group: 'Build') { + description = 'Assembles a jar archive containing the main Java sources.' + + classifier 'sources' + from sourceSets.main.allSource +} + +task javadocJar(type: Jar, dependsOn: javadoc, group: 'Build') { + description = 'Assembles a jar archive containing the JavaDoc.' + + classifier 'javadoc' + from javadoc.destinationDir +} + +artifacts { + archives sourcesJar + archives javadocJar +} + diff --git a/vendor/git.apache.org/thrift.git/lib/java/gradle/cloverCoverage.gradle b/vendor/git.apache.org/thrift.git/lib/java/gradle/cloverCoverage.gradle new file mode 100644 index 0000000..cef0e79 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/gradle/cloverCoverage.gradle @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +// Following Gradle best practices to keep build logic organized + +// Keep this as an optional feature for now, disabled by default +if (Boolean.parseBoolean(project.cloverEnabled)) { + apply plugin: 'com.bmuschko.clover' + + dependencies { + clover 'org.openclover:clover:4.2.+' + } + + clover { + + testIncludes = ['**/Test*.java'] + // Exclude the generated test code from code coverage + testExcludes = ['thrift/test/Test*.java'] + + compiler { + encoding = 'UTF-8' + debug = true + } + + report { + html = true + pdf = true + } + } + + build.dependsOn cloverGenerateReport +} diff --git a/vendor/git.apache.org/thrift.git/lib/java/gradle/codeQualityChecks.gradle b/vendor/git.apache.org/thrift.git/lib/java/gradle/codeQualityChecks.gradle new file mode 100644 index 0000000..9572ca1 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/gradle/codeQualityChecks.gradle @@ -0,0 +1,40 @@ + +// ================================================================= +// Configure the Gradle code quality plugins here. +// + +apply plugin: 'findbugs' + +findbugs { + ignoreFailures = true + toolVersion = '3.0.1' + sourceSets = [ sourceSets.main ] + effort = 'max' + reportLevel = 'low' + excludeFilter = file('code_quality_tools/findbugs-filter.xml') +} + +tasks.withType(FindBugs) { + reports { + text.enabled = false + html.enabled = true + xml.enabled = false + } +} + +apply plugin: 'pmd' + +pmd { + ignoreFailures = true + toolVersion = '6.0.0' + sourceSets = [ sourceSets.main ] + targetJdk = sourceCompatibility + ruleSets = [ 'java-basic' ] +} + +tasks.withType(Pmd) { + reports { + html.enabled = true + xml.enabled = false + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/java/gradle/environment.gradle b/vendor/git.apache.org/thrift.git/lib/java/gradle/environment.gradle new file mode 100644 index 0000000..9b7eb1e --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/gradle/environment.gradle @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +// Following Gradle best practices to keep build logic organized + +// Override the build directory if CMake is used (allows for out-of-tree-builds) +if (hasProperty('build.dir')) { + buildDir = file(property('build.dir')) +} + +// In order to remain compatible with other Ant based builds in the system +// we convert the gradle.properties into DSL friendly camelCased properties +ext.installPath = property('install.path') +ext.installJavadocPath = property('install.javadoc.path') + +ext.thriftRoot = file('../..') + +if (hasProperty('thrift.compiler')) { + ext.thriftCompiler = property('thrift.compiler') +} else { + ext.thriftCompiler = "$thriftRoot/compiler/cpp/thrift" +} + +ext.mvnRepo = property('mvn.repo') +ext.apacheRepo = property('apache.repo') +ext.mavenRepositoryUrl = property('maven-repository-url') + +// Versions used in this project +ext.httpclientVersion = property('httpclient.version') +ext.httpcoreVersion = property('httpcore.version') +ext.servletVersion = property('servlet.version') +ext.slf4jVersion = property('slf4j.version') +ext.junitVersion = property('junit.version') +ext.mockitoVersion = property('mockito.version') + +// In this section you declare where to find the dependencies of your project +repositories { + maven { + name 'Maven Central Repository' + url mvnRepo + } + maven { + name 'Apache Maven Repository' + url apacheRepo + } +} + +dependencies { + compile "org.slf4j:slf4j-api:${slf4jVersion}" + compile "org.apache.httpcomponents:httpclient:${httpclientVersion}" + compile "org.apache.httpcomponents:httpcore:${httpcoreVersion}" + compile "javax.servlet:servlet-api:${servletVersion}" + + testCompile "junit:junit:${junitVersion}" + testCompile "org.mockito:mockito-all:${mockitoVersion}" + testRuntime "org.slf4j:slf4j-log4j12:${slf4jVersion}" +} diff --git a/vendor/git.apache.org/thrift.git/lib/java/gradle/functionalTests.gradle b/vendor/git.apache.org/thrift.git/lib/java/gradle/functionalTests.gradle new file mode 100644 index 0000000..c420d12 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/gradle/functionalTests.gradle @@ -0,0 +1,155 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +// Following Gradle best practices to keep build logic organized + +// ---------------------------------------------------------------------------- +// Functional testing harness creation. This helps run the cross-check tests. +// The Makefile precross target invokes the shadowJar task and the tests.json +// code is changed to call runclient or runserver as needed. + +// ---------------------------------------------------------------------------- +// Cross Test sources are separated in their own sourceSet +// +sourceSets { + crossTest { + java { + srcDir 'test' + include '**/test/TestClient.java' + include '**/test/TestServer.java' + include '**/test/TestNonblockingServer.java' + } + } +} + +configurations { + crossTestCompile { extendsFrom testCompile } + crossTestRuntime { extendsFrom crossTestCompile, testRuntime } +} + +dependencies { + crossTestCompile sourceSets.main.output + crossTestCompile sourceSets.test.output +} + +// I am using shadow plugin to make a self contained functional test Uber JAR that +// eliminates startup problems with wrapping the cross-check harness in Gradle. +// This is used by the runner scripts as the single classpath entry which +// allows the process to be as lightweight as it can. +shadowJar { + description = 'Assemble a test JAR file for cross-check execution' + // make sure the runners are created when this runs + dependsOn 'generateRunnerScriptForClient', 'generateRunnerScriptForServer', 'generateRunnerScriptForNonblockingServer' + + baseName = 'functionalTest' + destinationDir = file("$buildDir/functionalTestJar") + classifier = null + + // We do not need a version number for this internal jar + version = null + + // Bundle the complete set of unit test classes including generated code + // and the runtime dependencies in one JAR to expedite execution. + from sourceSets.test.output + from sourceSets.crossTest.output + configurations = [project.configurations.testRuntime] +} + +// Common script runner configuration elements +def scriptExt = '' +def execExt = '' +def scriptHead = '#!/bin/bash' +def args = '$*' + +// Although this is marked internal it is an available and stable interface +if (org.gradle.internal.os.OperatingSystem.current().windows) { + scriptExt = '.bat' + execExt = '.exe' + scriptHead = '@echo off' + args = '%*' +} + +// The Java executable to use with the runner scripts +def javaExe = file("${System.getProperty('java.home')}/bin/java${execExt}").canonicalPath +// The common Uber jar path +def jarPath = shadowJar.archivePath.canonicalPath +def trustStore = file('test/.truststore').canonicalPath +def keyStore = file('test/.keystore').canonicalPath + +task generateRunnerScriptForClient(group: 'Build') { + description = 'Generate a runner script for cross-check tests with TestClient' + + def clientFile = file("$buildDir/runclient${scriptExt}") + + def runClientText = """\ +${scriptHead} + +"${javaExe}" -cp "$jarPath" "-Djavax.net.ssl.trustStore=$trustStore" -Djavax.net.ssl.trustStorePassword=thrift org.apache.thrift.test.TestClient $args +""" + inputs.property 'runClientText', runClientText + outputs.file clientFile + + doLast { + clientFile.parentFile.mkdirs() + clientFile.text = runClientText + clientFile.setExecutable(true, false) + } +} + +task generateRunnerScriptForServer(group: 'Build') { + description = 'Generate a runner script for cross-check tests with TestServer' + + def serverFile = file("$buildDir/runserver${scriptExt}") + + def runServerText = """\ +${scriptHead} + +"${javaExe}" -cp "$jarPath" "-Djavax.net.ssl.keyStore=$keyStore" -Djavax.net.ssl.keyStorePassword=thrift org.apache.thrift.test.TestServer $args +""" + + inputs.property 'runServerText', runServerText + outputs.file serverFile + + doLast { + serverFile.parentFile.mkdirs() + serverFile.text = runServerText + serverFile.setExecutable(true, false) + } +} + +task generateRunnerScriptForNonblockingServer(group: 'Build') { + description = 'Generate a runner script for cross-check tests with TestNonblockingServer' + + def serverFile = file("$buildDir/runnonblockingserver${scriptExt}") + + def runServerText = """\ +${scriptHead} + +"${javaExe}" -cp "$jarPath" "-Djavax.net.ssl.keyStore=$keyStore" -Djavax.net.ssl.keyStorePassword=thrift org.apache.thrift.test.TestNonblockingServer $args +""" + + inputs.property 'runServerText', runServerText + outputs.file serverFile + + doLast { + serverFile.parentFile.mkdirs() + serverFile.text = runServerText + serverFile.setExecutable(true, false) + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/java/gradle/generateTestThrift.gradle b/vendor/git.apache.org/thrift.git/lib/java/gradle/generateTestThrift.gradle new file mode 100644 index 0000000..2b53739 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/gradle/generateTestThrift.gradle @@ -0,0 +1,119 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +// Following Gradle best practices to keep build logic organized + +// Generated code locations for Unit tests +ext.genSrc = file("$buildDir/gen-java") +ext.genBeanSrc = file("$buildDir/gen-javabean") +ext.genReuseSrc = file("$buildDir/gen-javareuse") +ext.genFullCamelSrc = file("$buildDir/gen-fullcamel") +ext.genUnsafeSrc = file("$buildDir/gen-unsafe") + +// Add the generated code directories to the test source set +sourceSets { + test.java.srcDirs genSrc, genBeanSrc, genReuseSrc, genFullCamelSrc, genUnsafeSrc +} + +// ---------------------------------------------------------------------------- +// Code generation for Unit Testing + +// A callable closure to make this easier +ext.thriftCompile = { Task task, String thriftFileName, String generator = 'java', File outputDir = genSrc -> + def thriftFile = file("$thriftRoot/test/$thriftFileName") + assert thriftFile.exists() + + task.inputs.file thriftFile + task.outputs.dir outputDir + + task.doLast { + outputDir.mkdirs() + def result = exec { + executable file(thriftCompiler) + args '--gen', generator + args '-out', outputDir + args thriftFile + standardOutput = task.outputBuffer + errorOutput = task.outputBuffer + ignoreExitValue = true + } + if (result.exitValue != 0) { + // Only show the Thrift compiler output on failures, cuts down on noise! + println task.outputBuffer.toString() + result.rethrowFailure() + } + } +} + +task generate(group: 'Build') { + description = 'Generate all unit test Thrift sources' + compileTestJava.dependsOn it +} + +task generateJava(group: 'Build') { + description = 'Generate the thrift gen-java source' + generate.dependsOn it + + ext.outputBuffer = new ByteArrayOutputStream() + + thriftCompile(it, 'ThriftTest.thrift') + thriftCompile(it, 'JavaTypes.thrift') + thriftCompile(it, 'DebugProtoTest.thrift') + thriftCompile(it, 'DoubleConstantsTest.thrift') + thriftCompile(it, 'OptionalRequiredTest.thrift') + thriftCompile(it, 'ManyOptionals.thrift') + thriftCompile(it, 'JavaDeepCopyTest.thrift') + thriftCompile(it, 'EnumContainersTest.thrift') +} + +task generateBeanJava(group: 'Build') { + description = 'Generate the thrift gen-javabean source' + generate.dependsOn it + + ext.outputBuffer = new ByteArrayOutputStream() + + thriftCompile(it, 'JavaBeansTest.thrift', 'java:beans,nocamel', genBeanSrc) +} + +task generateReuseJava(group: 'Build') { + description = 'Generate the thrift gen-javareuse source' + generate.dependsOn it + + ext.outputBuffer = new ByteArrayOutputStream() + + thriftCompile(it, 'FullCamelTest.thrift', 'java:fullcamel', genFullCamelSrc) +} + +task generateFullCamelJava(group: 'Build') { + description = 'Generate the thrift gen-fullcamel source' + generate.dependsOn it + + ext.outputBuffer = new ByteArrayOutputStream() + + thriftCompile(it, 'ReuseObjects.thrift', 'java:reuse-objects', genReuseSrc) +} + +task generateUnsafeBinariesJava(group: 'Build') { + description = 'Generate the thrift gen-unsafebinaries source' + generate.dependsOn it + + ext.outputBuffer = new ByteArrayOutputStream() + + thriftCompile(it, 'UnsafeTypes.thrift', 'java:unsafe_binaries', genUnsafeSrc) +} diff --git a/vendor/git.apache.org/thrift.git/lib/java/gradle/publishing.gradle b/vendor/git.apache.org/thrift.git/lib/java/gradle/publishing.gradle new file mode 100644 index 0000000..961d58f --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/gradle/publishing.gradle @@ -0,0 +1,119 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +// Following Gradle best practices to keep build logic organized + +// ---------------------------------------------------------------------------- +// Installation subtasks, not used currently, we use "make install/fast" +task installDist(type: Copy, group: 'Install') { + description = "Copy Thrift JAR and dependencies into $installPath location" + + destinationDir = file(installPath) + + from jar + from configurations.compile +} + +task installJavadoc(type: Copy, group: 'Install', dependsOn: javadoc) { + description = "Install Thrift JavaDoc into $installJavadocPath location" + + destinationDir = file(installJavadocPath) + + from javadoc.destinationDir +} + +// This is not needed by Gradle builds but the remaining Ant builds seem to +// need access to the generated test classes for Thrift unit tests so we +// assist them to use it this way. +task copyDependencies(type: Copy, group: 'Build') { + description = 'Copy runtime dependencies in a common location for other Ant based projects' + project.assemble.dependsOn it + + destinationDir = file("$buildDir/deps") + from configurations.testRuntime + // exclude some very specific unit test dependencies + exclude '**/junit*.jar', '**/mockito*.jar', '**/hamcrest*.jar' +} + +// ---------------------------------------------------------------------------- +// Allow this configuration to be shared between install and uploadArchives tasks +def configurePom(pom) { + pom.project { + name 'Apache Thrift' + description 'Thrift is a software framework for scalable cross-language services development.' + packaging 'jar' + url 'http://thrift.apache.org' + + scm { + url 'https://git-wip-us.apache.org/repos/asf?p=thrift.git' + connection 'scm:git:https://git-wip-us.apache.org/repos/asf/thrift.git' + developerConnection 'scm:git:https://git-wip-us.apache.org/repos/asf/thrift.git' + } + + licenses { + license { + name 'The Apache Software License, Version 2.0' + url "${project.license}" + distribution 'repo' + } + } + + developers { + developer { + id 'dev' + name 'Apache Thrift Developers' + email 'dev@thrift.apache.org' + } + } + } + + pom.whenConfigured { + // Fixup the scope for servlet-api to be 'provided' instead of 'compile' + dependencies.find { dep -> dep.groupId == 'javax.servlet' && dep.artifactId == 'servlet-api' }.with { + // it.optional = true + it.scope = 'provided' + } + } +} + +install { + repositories.mavenInstaller { + configurePom(pom) + } +} + +uploadArchives { + dependsOn test // make sure we run unit tests when publishing + repositories.mavenDeployer { + // signPom will silently do nothing when no signing information is provided + beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } + repository(url: project.mavenRepositoryUrl) { + if (project.hasProperty('mavenUser') && project.hasProperty('mavenPassword')) { + authentication(userName: mavenUser, password: mavenPassword) + } + } + configurePom(pom) + } +} + +// Signing configuration, optional, only when release and uploadArchives is activated +signing { + required { !version.endsWith("SNAPSHOT") && gradle.taskGraph.hasTask("uploadArchives") } + sign configurations.archives +} diff --git a/vendor/git.apache.org/thrift.git/lib/java/gradle/sourceConfiguration.gradle b/vendor/git.apache.org/thrift.git/lib/java/gradle/sourceConfiguration.gradle new file mode 100644 index 0000000..decc6a2 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/gradle/sourceConfiguration.gradle @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +// Following Gradle best practices to keep build logic organized + +// ---------------------------------------------------------------------------- +// source sets for main and test sources +sourceSets { + main { + java { + srcDir 'src' + } + } + test { + java { + srcDir 'test' + // see functionalTests.gradle for these files + exclude '**/test/TestClient.java' + exclude '**/test/TestServer.java' + exclude '**/test/TestNonblockingServer.java' + } + resources { + srcDir 'test' + include 'log4j.properties' + } + } +} + +// ---------------------------------------------------------------------------- +// Compiler configuration details + +sourceCompatibility = '1.6' +targetCompatibility = '1.6' + +tasks.withType(JavaCompile) { + options.encoding = 'UTF-8' + options.debug = true + options.deprecation = true + // options.compilerArgs.addAll('-Xlint:unchecked') +} + +// ---------------------------------------------------------------------------- +// Jar packaging details +processResources { + into('META-INF') { + from "$thriftRoot/LICENSE" + from "$thriftRoot/NOTICE" + rename('(.+)', '$1.txt') + } +} + +jar { + project.test.dependsOn it + manifest { + attributes([ + "Implementation-Version": "${project.version}", + "Bundle-ManifestVersion": "2", + "Bundle-SymbolicName": "${project.group}", + "Bundle-Name": "Apache Thrift", + "Bundle-Version": "${project.version}", + "Bundle-Description": "Apache Thrift library", + "Bundle-License": "${project.license}", + "Bundle-ActivationPolicy": "lazy", + "Export-Package": "${project.group}.async;uses:=\"${project.group}.protocol,${project.group}.transport,org.slf4j,${project.group}\";version=\"${version}\",${project.group}.protocol;uses:=\"${project.group}.transport,${project.group},${project.group}.scheme\";version=\"${version}\",${project.group}.server;uses:=\"${project.group}.transport,${project.group}.protocol,${project.group},org.slf4j,javax.servlet,javax.servlet.http\";version=\"${version}\",${project.group}.transport;uses:=\"${project.group}.protocol,${project.group},org.apache.http.client,org.apache.http.params,org.apache.http.entity,org.apache.http.client.methods,org.apache.http,org.slf4j,javax.net.ssl,javax.net,javax.security.sasl,javax.security.auth.callback\";version=\"${version}\",${project.group};uses:=\"${project.group}.protocol,${project.group}.async,${project.group}.server,${project.group}.transport,org.slf4j,org.apache.log4j,${project.group}.scheme\";version=\"${version}\",${project.group}.meta_data;uses:=\"${project.group}\";version=\"${version}\",${project.group}.scheme;uses:=\"${project.group}.protocol,${project.group}\";version=\"${version}\"", + "Import-Package": "javax.net,javax.net.ssl,javax.security.auth.callback,javax.security.sasl,javax.servlet;resolution:=optional,javax.servlet.http;resolution:=optional,org.slf4j;resolution:=optional;version=\"[1.4,2)\",org.apache.http.client;resolution:=optional,org.apache.http.params;resolution:=optional,org.apache.http.entity;resolution:=optional,org.apache.http.client.methods;resolution:=optional,org.apache.http;resolution:=optional" + ]) + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/java/gradle/unitTests.gradle b/vendor/git.apache.org/thrift.git/lib/java/gradle/unitTests.gradle new file mode 100644 index 0000000..61f2fbd --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/gradle/unitTests.gradle @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +// Following Gradle best practices to keep build logic organized + +// Bundle the test classes in a JAR for other Ant based builds +task testJar(type: Jar, group: 'Build') { + description = 'Assembles a jar archive containing the test classes.' + project.test.dependsOn it + + classifier 'test' + from sourceSets.test.output +} + +// ---------------------------------------------------------------------------- +// Unit test tasks and configurations + +// Help the up to date algorithm to make these tests done +ext.markTaskDone = { task -> + def buildFile = file("$buildDir/${task.name}.flag") + task.inputs.files task.classpath + task.outputs.file buildFile + task.doLast { + buildFile.text = 'Passed!' + } +} + +task deprecatedEqualityTest(type: JavaExec, group: 'Verification') { + description = 'Run the non-JUnit test suite ' + classpath = sourceSets.test.runtimeClasspath + main 'org.apache.thrift.test.EqualityTest' + markTaskDone(it) +} + +task deprecatedJavaBeansTest(type: JavaExec, group: 'Verification') { + description = 'Run the non-JUnit test suite ' + classpath = sourceSets.test.runtimeClasspath + main 'org.apache.thrift.test.JavaBeansTest' + markTaskDone(it) +} + +// Main Unit Test task configuration +test { + description="Run the full test suite" + dependsOn deprecatedEqualityTest, deprecatedJavaBeansTest + + // Allow repeating tests even after successful execution + if (project.hasProperty('rerunTests')) { + outputs.upToDateWhen { false } + } + + include '**/Test*.class' + exclude '**/Test*\$*.class' + + maxHeapSize = '512m' + forkEvery = 1 + + systemProperties = [ + 'build.test': "${compileTestJava.destinationDir}", + 'test.port': "${testPort}", + 'javax.net.ssl.trustStore': "${projectDir}/test/.truststore", + 'javax.net.ssl.trustStorePassword': 'thrift', + 'javax.net.ssl.keyStore': "${projectDir}/test/.keystore", + 'javax.net.ssl.keyStorePassword': 'thrift' + ] +} diff --git a/vendor/git.apache.org/thrift.git/lib/java/gradle/wrapper/gradle-wrapper.properties b/vendor/git.apache.org/thrift.git/lib/java/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..2c2bbe5 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.4.1-bin.zip diff --git a/vendor/git.apache.org/thrift.git/lib/java/gradlew b/vendor/git.apache.org/thrift.git/lib/java/gradlew new file mode 100755 index 0000000..cccdd3d --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/vendor/git.apache.org/thrift.git/lib/java/gradlew.bat b/vendor/git.apache.org/thrift.git/lib/java/gradlew.bat new file mode 100644 index 0000000..f955316 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/vendor/git.apache.org/thrift.git/lib/java/settings.gradle b/vendor/git.apache.org/thrift.git/lib/java/settings.gradle new file mode 100644 index 0000000..c9bd8bc --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/settings.gradle @@ -0,0 +1,20 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +rootProject.name = 'libthrift' diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/AsyncProcessFunction.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/AsyncProcessFunction.java index 550ebd5..483c8d0 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/AsyncProcessFunction.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/AsyncProcessFunction.java @@ -20,7 +20,6 @@ package org.apache.thrift; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.protocol.TMessage; -import org.apache.thrift.protocol.TMessageType; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.server.AbstractNonblockingServer; diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/ProcessFunction.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/ProcessFunction.java index 992e859..e6213df 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/ProcessFunction.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/ProcessFunction.java @@ -1,12 +1,10 @@ -/** - * - */ package org.apache.thrift; import org.apache.thrift.protocol.TMessage; import org.apache.thrift.protocol.TMessageType; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TProtocolException; +import org.apache.thrift.transport.TTransportException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,31 +31,51 @@ public abstract class ProcessFunction { return; } iprot.readMessageEnd(); - TBase result = null; + TSerializable result = null; + byte msgType = TMessageType.REPLY; try { result = getResult(iface, args); - } catch(TException tex) { - LOGGER.error("Internal error processing " + getMethodName(), tex); - if (!isOneway()) { - TApplicationException x = new TApplicationException(TApplicationException.INTERNAL_ERROR, - "Internal error processing " + getMethodName()); - oprot.writeMessageBegin(new TMessage(getMethodName(), TMessageType.EXCEPTION, seqid)); - x.write(oprot); - oprot.writeMessageEnd(); - oprot.getTransport().flush(); + } catch (TTransportException ex) { + LOGGER.error("Transport error while processing " + getMethodName(), ex); + throw ex; + } catch (TApplicationException ex) { + LOGGER.error("Internal application error processing " + getMethodName(), ex); + result = ex; + msgType = TMessageType.EXCEPTION; + } catch (Exception ex) { + LOGGER.error("Internal error processing " + getMethodName(), ex); + if(rethrowUnhandledExceptions()) throw new RuntimeException(ex.getMessage(), ex); + if(!isOneway()) { + result = new TApplicationException(TApplicationException.INTERNAL_ERROR, + "Internal error processing " + getMethodName()); + msgType = TMessageType.EXCEPTION; } - return; } if(!isOneway()) { - oprot.writeMessageBegin(new TMessage(getMethodName(), TMessageType.REPLY, seqid)); + oprot.writeMessageBegin(new TMessage(getMethodName(), msgType, seqid)); result.write(oprot); oprot.writeMessageEnd(); oprot.getTransport().flush(); } } + private void handleException(int seqid, TProtocol oprot) throws TException { + if (!isOneway()) { + TApplicationException x = new TApplicationException(TApplicationException.INTERNAL_ERROR, + "Internal error processing " + getMethodName()); + oprot.writeMessageBegin(new TMessage(getMethodName(), TMessageType.EXCEPTION, seqid)); + x.write(oprot); + oprot.writeMessageEnd(); + oprot.getTransport().flush(); + } + } + + protected boolean rethrowUnhandledExceptions(){ + return false; + } + protected abstract boolean isOneway(); public abstract TBase getResult(I iface, T args) throws TException; diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/TAsyncProcessor.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/TAsyncProcessor.java index 0a069ea..533e74d 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/TAsyncProcessor.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/TAsyncProcessor.java @@ -18,14 +18,7 @@ */ package org.apache.thrift; -import org.apache.thrift.protocol.*; - -import org.apache.thrift.server.AbstractNonblockingServer.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Collections; -import java.util.Map; +import org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer; public interface TAsyncProcessor { /** diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/TEnumHelper.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/TEnumHelper.java index c17d661..fbc7787 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/TEnumHelper.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/TEnumHelper.java @@ -19,7 +19,6 @@ package org.apache.thrift; -import java.lang.InstantiationException; import java.lang.NoSuchMethodException; import java.lang.IllegalAccessException; import java.lang.reflect.InvocationTargetException; diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/TMultiplexedProcessor.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/TMultiplexedProcessor.java index f6547ac..d0c5603 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/TMultiplexedProcessor.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/TMultiplexedProcessor.java @@ -52,6 +52,7 @@ public class TMultiplexedProcessor implements TProcessor { private final Map SERVICE_PROCESSOR_MAP = new HashMap(); + private TProcessor defaultProcessor; /** * 'Register' a service with this TMultiplexedProcessor. This @@ -67,6 +68,14 @@ public class TMultiplexedProcessor implements TProcessor { SERVICE_PROCESSOR_MAP.put(serviceName, processor); } + /** + * Register a service to be called to process queries without service name + * @param processor + */ + public void registerDefault(TProcessor processor) { + defaultProcessor = processor; + } + /** * This implementation of process performs the following steps: * @@ -77,7 +86,7 @@ public class TMultiplexedProcessor implements TProcessor { *
  • Dispatch to the processor, with a decorated instance of TProtocol * that allows readMessageBegin() to return the original TMessage.
  • * - * + * * @throws TException If the message type is not CALL or ONEWAY, if * the service name was not found in the message, or if the service * name was not found in the service map. You called {@link #registerProcessor(String, TProcessor) registerProcessor} @@ -92,14 +101,16 @@ public class TMultiplexedProcessor implements TProcessor { TMessage message = iprot.readMessageBegin(); if (message.type != TMessageType.CALL && message.type != TMessageType.ONEWAY) { - // TODO Apache Guys - Can the server ever get an EXCEPTION or REPLY? - // TODO Should we check for this here? throw new TException("This should not have happened!?"); } // Extract the service name int index = message.name.indexOf(TMultiplexedProtocol.SEPARATOR); if (index < 0) { + if (defaultProcessor != null) { + // Dispatch processing to the stored processor + return defaultProcessor.process(new StoredMessageProtocol(iprot, message), oprot); + } throw new TException("Service name not found in message name: " + message.name + ". Did you " + "forget to use a TMultiplexProtocol in your client?"); } diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/TServiceClient.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/TServiceClient.java index 6619b9c..00a36ee 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/TServiceClient.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/TServiceClient.java @@ -81,7 +81,6 @@ public abstract class TServiceClient { iprot_.readMessageEnd(); throw x; } - System.out.format("Received %d%n", msg.seqid); if (msg.seqid != seqid_) { throw new TApplicationException(TApplicationException.BAD_SEQUENCE_ID, String.format("%s failed: out of sequence response: expected %d but got %d", methodName, seqid_, msg.seqid)); diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/annotation/Nullable.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/annotation/Nullable.java new file mode 100644 index 0000000..a34b01e --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/annotation/Nullable.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +package org.apache.thrift.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Annotation indicating a field, method return, or method parameter may be {@code null}. + * We package our own annotation to avoid a mandatory third-party dependency. + */ +@Retention(RetentionPolicy.CLASS) +public @interface Nullable { + +} diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/protocol/TBinaryProtocol.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/protocol/TBinaryProtocol.java index d7f8b83..aaa1fd8 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/protocol/TBinaryProtocol.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/protocol/TBinaryProtocol.java @@ -373,6 +373,7 @@ public class TBinaryProtocol extends TProtocol { } public String readStringBody(int size) throws TException { + checkStringReadLength(size); try { byte[] buf = new byte[size]; trans_.readAll(buf, 0, size); diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/protocol/TProtocolUtil.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/protocol/TProtocolUtil.java index b76f8ea..cdaa30b 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/protocol/TProtocolUtil.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/protocol/TProtocolUtil.java @@ -141,7 +141,8 @@ public class TProtocolUtil { break; default: - break; + throw new TProtocolException(TProtocolException.INVALID_DATA, + "Unrecognized type " + type); } } diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/server/AbstractNonblockingServer.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/server/AbstractNonblockingServer.java index 0c492cc..5c62b99 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/server/AbstractNonblockingServer.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/server/AbstractNonblockingServer.java @@ -19,15 +19,6 @@ package org.apache.thrift.server; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.spi.SelectorProvider; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.atomic.AtomicLong; - import org.apache.thrift.TAsyncProcessor; import org.apache.thrift.TByteArrayOutputStream; import org.apache.thrift.TException; @@ -42,6 +33,15 @@ import org.apache.thrift.transport.TTransportException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.spi.SelectorProvider; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.atomic.AtomicLong; + /** * Provides common methods and classes used by nonblocking TServer * implementations. @@ -50,7 +50,7 @@ public abstract class AbstractNonblockingServer extends TServer { protected final Logger LOGGER = LoggerFactory.getLogger(getClass().getName()); public static abstract class AbstractNonblockingServerArgs> extends AbstractServerArgs { - public long maxReadBufferBytes = Long.MAX_VALUE; + public long maxReadBufferBytes = 256 * 1024 * 1024; public AbstractNonblockingServerArgs(TNonblockingServerTransport transport) { super(transport); @@ -102,7 +102,7 @@ public abstract class AbstractNonblockingServer extends TServer { /** * Starts any threads required for serving. - * + * * @return true if everything went ok, false if threads could not be started. */ protected abstract boolean startThreads(); @@ -115,7 +115,7 @@ public abstract class AbstractNonblockingServer extends TServer { /** * Have the server transport start accepting connections. - * + * * @return true if we started listening successfully, false if something went * wrong. */ @@ -139,7 +139,7 @@ public abstract class AbstractNonblockingServer extends TServer { /** * Perform an invocation. This method could behave several different ways - * invoke immediately inline, queue for separate execution, etc. - * + * * @return true if invocation was successfully requested, which is not a * guarantee that invocation has completed. False if the request * failed. @@ -152,7 +152,7 @@ public abstract class AbstractNonblockingServer extends TServer { * corresponding to requests. */ protected abstract class AbstractSelectThread extends Thread { - protected final Selector selector; + protected Selector selector; // List of FrameBuffers that want to change their selection interests. protected final Set selectInterestChanges = new HashSet(); @@ -285,21 +285,21 @@ public abstract class AbstractNonblockingServer extends TServer { protected ByteBuffer buffer_; protected final TByteArrayOutputStream response_; - + // the frame that the TTransport should wrap. protected final TMemoryInputTransport frameTrans_; - + // the transport that should be used to connect to clients protected final TTransport inTrans_; - + protected final TTransport outTrans_; - + // the input protocol to use on frames protected final TProtocol inProt_; - + // the output protocol to use on frames protected final TProtocol outProt_; - + // context associated with this connection protected final ServerContext context_; @@ -328,7 +328,7 @@ public abstract class AbstractNonblockingServer extends TServer { /** * Give this FrameBuffer a chance to read. The selector loop should have * received a read event for this FrameBuffer. - * + * * @return true if the connection should live on, false if it should be * closed */ @@ -455,7 +455,7 @@ public abstract class AbstractNonblockingServer extends TServer { public void close() { // if we're being closed due to an error, we might have allocated a // buffer that we need to subtract for our memory accounting. - if (state_ == FrameBufferState.READING_FRAME || + if (state_ == FrameBufferState.READING_FRAME || state_ == FrameBufferState.READ_FRAME_COMPLETE || state_ == FrameBufferState.AWAITING_CLOSE) { readBufferBytesAllocated.addAndGet(-buffer_.array().length); @@ -510,7 +510,7 @@ public abstract class AbstractNonblockingServer extends TServer { public void invoke() { frameTrans_.reset(buffer_.array()); response_.reset(); - + try { if (eventHandler_ != null) { eventHandler_.processContext(context_, inTrans_, outTrans_); @@ -530,7 +530,7 @@ public abstract class AbstractNonblockingServer extends TServer { /** * Perform a read into buffer. - * + * * @return true if the read succeeded, false if there was an error or the * connection closed. */ diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/server/TExtensibleServlet.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/server/TExtensibleServlet.java index d328dd6..75082c0 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/server/TExtensibleServlet.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/server/TExtensibleServlet.java @@ -63,7 +63,7 @@ public abstract class TExtensibleServlet extends HttpServlet { * Returns the appropriate {@link TProcessor}. This will be called once just * after the {@link #init()} method * - * @return + * @return the appropriate {@link TProcessor} */ protected abstract TProcessor getProcessor(); @@ -71,7 +71,7 @@ public abstract class TExtensibleServlet extends HttpServlet { * Returns the appropriate in {@link TProtocolFactory}. This will be called * once just after the {@link #init()} method * - * @return + * @return the appropriate in {@link TProtocolFactory} */ protected abstract TProtocolFactory getInProtocolFactory(); @@ -79,7 +79,7 @@ public abstract class TExtensibleServlet extends HttpServlet { * Returns the appropriate out {@link TProtocolFactory}. This will be called * once just after the {@link #init()} method * - * @return + * @return the appropriate out {@link TProtocolFactory} */ protected abstract TProtocolFactory getOutProtocolFactory(); diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/server/THsHaServer.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/server/THsHaServer.java index 3b8fb35..4c5d7b5 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/server/THsHaServer.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/server/THsHaServer.java @@ -155,6 +155,9 @@ public class THsHaServer extends TNonblockingServer { return invoker; } + protected ExecutorService getInvoker() { + return invoker; + } protected void gracefullyShutdownInvokerPool() { // try to gracefully shut down the executor service diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/server/TThreadPoolServer.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/server/TThreadPoolServer.java index 0529d72..3b5f21e 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/server/TThreadPoolServer.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/server/TThreadPoolServer.java @@ -75,6 +75,11 @@ public class TThreadPoolServer extends TServer { return this; } + public Args stopTimeoutUnit(TimeUnit tu) { + stopTimeoutUnit = tu; + return this; + } + public Args requestTimeout(int n) { requestTimeout = n; return this; @@ -136,26 +141,44 @@ public class TThreadPoolServer extends TServer { return new ThreadPoolExecutor(args.minWorkerThreads, args.maxWorkerThreads, args.stopTimeoutVal, - TimeUnit.SECONDS, + args.stopTimeoutUnit, executorQueue); } - - public void serve() { - try { + protected ExecutorService getExecutorService() { + return executorService_; + } + + protected boolean preServe() { + try { serverTransport_.listen(); } catch (TTransportException ttx) { LOGGER.error("Error occurred during listening.", ttx); - return; + return false; } // Run the preServe event if (eventHandler_ != null) { eventHandler_.preServe(); } - stopped_ = false; setServing(true); + + return true; + } + + public void serve() { + if (!preServe()) { + return; + } + + execute(); + waitForShutdown(); + + setServing(false); + } + + protected void execute() { int failureCount = 0; while (!stopped_) { try { @@ -208,8 +231,10 @@ public class TThreadPoolServer extends TServer { } } } - - executorService_.shutdown(); + } + + protected void waitForShutdown() { + executorService_.shutdown(); // Loop until awaitTermination finally does return without a interrupted // exception. If we don't do this, then we'll shut down prematurely. We want @@ -227,7 +252,6 @@ public class TThreadPoolServer extends TServer { now = newnow; } } - setServing(false); } public void stop() { @@ -269,7 +293,7 @@ public class TThreadPoolServer extends TServer { inputTransport = inputTransportFactory_.getTransport(client_); outputTransport = outputTransportFactory_.getTransport(client_); inputProtocol = inputProtocolFactory_.getProtocol(inputTransport); - outputProtocol = outputProtocolFactory_.getProtocol(outputTransport); + outputProtocol = outputProtocolFactory_.getProtocol(outputTransport); eventHandler = getEventHandler(); if (eventHandler != null) { @@ -287,14 +311,24 @@ public class TThreadPoolServer extends TServer { break; } } - } catch (TSaslTransportException ttx) { - // Something thats not SASL was in the stream, continue silently - } catch (TTransportException ttx) { - // Assume the client died and continue silently } catch (TException tx) { LOGGER.error("Thrift error occurred during processing of message.", tx); } catch (Exception x) { - LOGGER.error("Error occurred during processing of message.", x); + // We'll usually receive RuntimeException types here + // Need to unwrap to ascertain real causing exception before we choose to ignore + Throwable realCause = x.getCause(); + // Ignore err-logging all transport-level/type exceptions + if ((realCause != null && realCause instanceof TTransportException) + || (x instanceof TTransportException)) { + if (LOGGER.isDebugEnabled()) { + // Write to debug, just in case the exception gets required + LOGGER + .debug("Received TTransportException during processing of message, ignoring: ", x); + } + } else { + // Log the exception at error level and continue + LOGGER.error("Error occurred during processing of message.", x); + } } finally { if (eventHandler != null) { eventHandler.deleteContext(connectionContext, inputProtocol, outputProtocol); diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/server/TThreadedSelectorServer.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/server/TThreadedSelectorServer.java index 353b8e0..038507e 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/server/TThreadedSelectorServer.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/server/TThreadedSelectorServer.java @@ -19,7 +19,15 @@ package org.apache.thrift.server; +import org.apache.thrift.transport.TNonblockingServerTransport; +import org.apache.thrift.transport.TNonblockingTransport; +import org.apache.thrift.transport.TTransportException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.IOException; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.spi.SelectorProvider; @@ -37,24 +45,18 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; -import org.apache.thrift.transport.TNonblockingServerTransport; -import org.apache.thrift.transport.TNonblockingTransport; -import org.apache.thrift.transport.TTransportException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * A Half-Sync/Half-Async server with a separate pool of threads to handle * non-blocking I/O. Accepts are handled on a single thread, and a configurable * number of nonblocking selector threads manage reading and writing of client * connections. A synchronous worker thread pool handles processing of requests. - * + * * Performs better than TNonblockingServer/THsHaServer in multi-core * environments when the the bottleneck is CPU on the single selector thread * handling I/O. In addition, because the accept handling is decoupled from * reads/writes and invocation, the server has better ability to handle back- * pressure from new connections (e.g. stop accepting when busy). - * + * * Like TNonblockingServer, it relies on the use of TFramedTransport. */ public class TThreadedSelectorServer extends AbstractNonblockingServer { @@ -205,7 +207,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { /** * Start the accept and selector threads running to deal with clients. - * + * * @return true if everything went ok, false if we couldn't start for some * reason. */ @@ -349,7 +351,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { /** * Set up the AcceptThead - * + * * @throws IOException */ public AcceptThread(TNonblockingServerTransport serverTransport, @@ -478,10 +480,13 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { // Accepted connections added by the accept thread. private final BlockingQueue acceptedQueue; + private int SELECTOR_AUTO_REBUILD_THRESHOLD = 512; + private long MONITOR_PERIOD = 1000L; + private int jvmBug = 0; /** * Set up the SelectorThread with an unbounded queue for incoming accepts. - * + * * @throws IOException * if a selector cannot be created */ @@ -491,7 +496,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { /** * Set up the SelectorThread with an bounded queue for incoming accepts. - * + * * @throws IOException * if a selector cannot be created */ @@ -501,7 +506,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { /** * Set up the SelectorThread with a specified queue for connections. - * + * * @param acceptedQueue * The BlockingQueue implementation for holding incoming accepted * connections. @@ -515,7 +520,7 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { /** * Hands off an accepted connection to be handled by this thread. This * method will block if the queue for new connections is at capacity. - * + * * @param accepted * The connection that has been accepted. * @return true if the connection has been successfully added. @@ -566,8 +571,8 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { */ private void select() { try { - // wait for io events. - selector.select(); + + doSelect(); // process the io events we received Iterator selectedKeys = selector.selectedKeys().iterator(); @@ -596,6 +601,77 @@ public class TThreadedSelectorServer extends AbstractNonblockingServer { } } + /** + * Do select and judge epoll bug happen. + * See : https://issues.apache.org/jira/browse/THRIFT-4251 + */ + private void doSelect() throws IOException { + long beforeSelect = System.currentTimeMillis(); + int selectedNums = selector.select(); + long afterSelect = System.currentTimeMillis(); + + if (selectedNums == 0) { + jvmBug++; + } else { + jvmBug = 0; + } + + long selectedTime = afterSelect - beforeSelect; + if (selectedTime >= MONITOR_PERIOD) { + jvmBug = 0; + } else if (jvmBug > SELECTOR_AUTO_REBUILD_THRESHOLD) { + LOGGER.warn("In {} ms happen {} times jvm bug; rebuilding selector.", MONITOR_PERIOD, jvmBug); + rebuildSelector(); + selector.selectNow(); + jvmBug = 0; + } + + } + + /** + * Replaces the current Selector of this SelectorThread with newly created Selector to work + * around the infamous epoll 100% CPU bug. + */ + private synchronized void rebuildSelector() { + final Selector oldSelector = selector; + if (oldSelector == null) { + return; + } + Selector newSelector = null; + try { + newSelector = Selector.open(); + LOGGER.warn("Created new Selector."); + } catch (IOException e) { + LOGGER.error("Create new Selector error.", e); + } + + for (SelectionKey key : oldSelector.selectedKeys()) { + if (!key.isValid() && key.readyOps() == 0) + continue; + SelectableChannel channel = key.channel(); + Object attachment = key.attachment(); + + try { + if (attachment == null) { + channel.register(newSelector, key.readyOps()); + } else { + channel.register(newSelector, key.readyOps(), attachment); + } + } catch (ClosedChannelException e) { + LOGGER.error("Register new selector key error.", e); + } + + } + + selector = newSelector; + try { + oldSelector.close(); + } catch (IOException e) { + LOGGER.error("Close old selector error.", e); + } + LOGGER.warn("Replace new selector success."); + } + private void processAcceptedConnections() { // Register accepted connections while (!stopped_) { diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TByteBuffer.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TByteBuffer.java index a09f33d..b6b0657 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TByteBuffer.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TByteBuffer.java @@ -35,7 +35,7 @@ public final class TByteBuffer extends TTransport { final int n = Math.min(byteBuffer.remaining(), len); if (n > 0) { try { - byteBuffer.get(buf, off, len); + byteBuffer.get(buf, off, n); } catch (BufferUnderflowException e) { throw new TTransportException("Unexpected end of input buffer", e); } diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TFastFramedTransport.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TFastFramedTransport.java index 0398ca7..d265600 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TFastFramedTransport.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TFastFramedTransport.java @@ -65,7 +65,8 @@ public class TFastFramedTransport extends TTransport { private final TTransport underlying; private final AutoExpandingBufferWriteTransport writeBuffer; - private final AutoExpandingBufferReadTransport readBuffer; + private AutoExpandingBufferReadTransport readBuffer; + private final int initialBufferCapacity; private final byte[] i32buf = new byte[4]; private final int maxLength; @@ -104,6 +105,7 @@ public class TFastFramedTransport extends TTransport { public TFastFramedTransport(TTransport underlying, int initialBufferCapacity, int maxLength) { this.underlying = underlying; this.maxLength = maxLength; + this.initialBufferCapacity = initialBufferCapacity; writeBuffer = new AutoExpandingBufferWriteTransport(initialBufferCapacity, 1.5); readBuffer = new AutoExpandingBufferReadTransport(initialBufferCapacity, 1.5); } @@ -164,6 +166,10 @@ public class TFastFramedTransport extends TTransport { readBuffer.consumeBuffer(len); } + public void clear() { + readBuffer = new AutoExpandingBufferReadTransport(initialBufferCapacity, 1.5); + } + @Override public void flush() throws TTransportException { int length = writeBuffer.getPos(); diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TFileTransport.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TFileTransport.java index 915fa73..c011c52 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TFileTransport.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TFileTransport.java @@ -366,7 +366,7 @@ public class TFileTransport extends TTransport { currentEvent_ = new Event(new byte [256]); if(!readOnly_) - outputStream_ = new BufferedOutputStream(inputFile_.getOutputStream(), 8192); + outputStream_ = new BufferedOutputStream(inputFile_.getOutputStream()); } catch (IOException iox) { throw new TTransportException(TTransportException.NOT_OPEN, iox); } diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TFramedTransport.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TFramedTransport.java index f7d220c..fa531ef 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TFramedTransport.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TFramedTransport.java @@ -45,7 +45,8 @@ public class TFramedTransport extends TTransport { /** * Buffer for input */ - private TMemoryInputTransport readBuffer_ = new TMemoryInputTransport(new byte[0]); + private final TMemoryInputTransport readBuffer_ = + new TMemoryInputTransport(new byte[0]); public static class Factory extends TTransportFactory { private int maxLength_; @@ -90,11 +91,9 @@ public class TFramedTransport extends TTransport { } public int read(byte[] buf, int off, int len) throws TTransportException { - if (readBuffer_ != null) { - int got = readBuffer_.read(buf, off, len); - if (got > 0) { - return got; - } + int got = readBuffer_.read(buf, off, len); + if (got > 0) { + return got; } // Read another frame of data @@ -123,6 +122,10 @@ public class TFramedTransport extends TTransport { readBuffer_.consumeBuffer(len); } + public void clear() { + readBuffer_.clear(); + } + private final byte[] i32buf = new byte[4]; private void readFrame() throws TTransportException { diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/THttpClient.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/THttpClient.java index 5a5b37c..c3063fe 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/THttpClient.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/THttpClient.java @@ -304,6 +304,9 @@ public class THttpClient extends TTransport { throw new TTransportException(ioe); } } + if (post != null) { + post.releaseConnection(); + } } } diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TNonblockingServerSocket.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TNonblockingServerSocket.java index 44fe273..ef82ac2 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TNonblockingServerSocket.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TNonblockingServerSocket.java @@ -93,7 +93,7 @@ public class TNonblockingServerSocket extends TNonblockingServerTransport { serverSocket_.bind(args.bindAddr, args.backlog); } catch (IOException ioe) { serverSocket_ = null; - throw new TTransportException("Could not create ServerSocket on address " + args.bindAddr.toString() + "."); + throw new TTransportException("Could not create ServerSocket on address " + args.bindAddr.toString() + ".", ioe); } } diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TSSLTransportFactory.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TSSLTransportFactory.java index 9c60ed1..2232a31 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TSSLTransportFactory.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TSSLTransportFactory.java @@ -186,7 +186,11 @@ public class TSSLTransportFactory { if (params.isTrustStoreSet) { tmf = TrustManagerFactory.getInstance(params.trustManagerType); KeyStore ts = KeyStore.getInstance(params.trustStoreType); - in = getStoreAsStream(params.trustStore); + if (params.trustStoreStream != null) { + in = params.trustStoreStream; + } else { + in = getStoreAsStream(params.trustStore); + } ts.load(in, (params.trustPass != null ? params.trustPass.toCharArray() : null)); tmf.init(ts); @@ -195,7 +199,11 @@ public class TSSLTransportFactory { if (params.isKeyStoreSet) { kmf = KeyManagerFactory.getInstance(params.keyManagerType); KeyStore ks = KeyStore.getInstance(params.keyStoreType); - is = getStoreAsStream(params.keyStore); + if (params.keyStoreStream != null) { + is = params.keyStoreStream; + } else { + is = getStoreAsStream(params.keyStore); + } ks.load(is, params.keyPass.toCharArray()); kmf.init(ks, params.keyPass.toCharArray()); } @@ -273,10 +281,12 @@ public class TSSLTransportFactory { public static class TSSLTransportParameters { protected String protocol = "TLS"; protected String keyStore; + protected InputStream keyStoreStream; protected String keyPass; protected String keyManagerType = KeyManagerFactory.getDefaultAlgorithm(); protected String keyStoreType = "JKS"; protected String trustStore; + protected InputStream trustStoreStream; protected String trustPass; protected String trustManagerType = TrustManagerFactory.getDefaultAlgorithm(); protected String trustStoreType = "JKS"; @@ -332,7 +342,20 @@ public class TSSLTransportFactory { } isKeyStoreSet = true; } - + + /** + * Set the keystore, password, certificate type and the store type + * + * @param keyStoreStream Keystore content input stream + * @param keyPass Keystore password + * @param keyManagerType The default is X509 + * @param keyStoreType The default is JKS + */ + public void setKeyStore(InputStream keyStoreStream, String keyPass, String keyManagerType, String keyStoreType) { + this.keyStoreStream = keyStoreStream; + setKeyStore("", keyPass, keyManagerType, keyStoreType); + } + /** * Set the keystore and password * @@ -342,7 +365,17 @@ public class TSSLTransportFactory { public void setKeyStore(String keyStore, String keyPass) { setKeyStore(keyStore, keyPass, null, null); } - + + /** + * Set the keystore and password + * + * @param keyStoreStream Keystore content input stream + * @param keyPass Keystore password + */ + public void setKeyStore(InputStream keyStoreStream, String keyPass) { + setKeyStore(keyStoreStream, keyPass, null, null); + } + /** * Set the truststore, password, certificate type and the store type * @@ -362,6 +395,19 @@ public class TSSLTransportFactory { } isTrustStoreSet = true; } + + /** + * Set the truststore, password, certificate type and the store type + * + * @param trustStoreStream Truststore content input stream + * @param trustPass Truststore password + * @param trustManagerType The default is X509 + * @param trustStoreType The default is JKS + */ + public void setTrustStore(InputStream trustStoreStream, String trustPass, String trustManagerType, String trustStoreType) { + this.trustStoreStream = trustStoreStream; + setTrustStore("", trustPass, trustManagerType, trustStoreType); + } /** * Set the truststore and password @@ -372,6 +418,16 @@ public class TSSLTransportFactory { public void setTrustStore(String trustStore, String trustPass) { setTrustStore(trustStore, trustPass, null, null); } + + /** + * Set the truststore and password + * + * @param trustStoreStream Truststore content input stream + * @param trustPass Truststore password + */ + public void setTrustStore(InputStream trustStoreStream, String trustPass) { + setTrustStore(trustStoreStream, trustPass, null, null); + } /** * Set if client authentication is required @@ -380,6 +436,6 @@ public class TSSLTransportFactory { */ public void requireClientAuth(boolean clientAuth) { this.clientAuth = clientAuth; - } - } + } + } } diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TSaslTransport.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TSaslTransport.java index a94d9a7..bbd3f9a 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TSaslTransport.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TSaslTransport.java @@ -287,7 +287,7 @@ abstract class TSaslTransport extends TTransport { if (message.status == NegotiationStatus.COMPLETE && getRole() == SaslRole.CLIENT) { LOGGER.debug("{}: All done!", getRole()); - break; + continue; } sendSaslMessage(sasl.isComplete() ? NegotiationStatus.COMPLETE : NegotiationStatus.OK, @@ -295,8 +295,6 @@ abstract class TSaslTransport extends TTransport { } LOGGER.debug("{}: Main negotiation loop complete", getRole()); - assert sasl.isComplete(); - // If we're the client, and we're complete, but the server isn't // complete yet, we need to wait for its response. This will occur // with ANONYMOUS auth, for example, where we send an initial response diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TServerSocket.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TServerSocket.java index 7bd87f4..79f7b7f 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TServerSocket.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TServerSocket.java @@ -111,7 +111,7 @@ public class TServerSocket extends TServerTransport { } public void listen() throws TTransportException { - // Make sure not to block on accept + // Make sure to block on accept if (serverSocket_ != null) { try { serverSocket_.setSoTimeout(0); diff --git a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TSocket.java b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TSocket.java index 148122f..b20b32b 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TSocket.java +++ b/vendor/git.apache.org/thrift.git/lib/java/src/org/apache/thrift/transport/TSocket.java @@ -80,8 +80,8 @@ public class TSocket extends TIOStreamTransport { if (isOpen()) { try { - inputStream_ = new BufferedInputStream(socket_.getInputStream(), 1024); - outputStream_ = new BufferedOutputStream(socket_.getOutputStream(), 1024); + inputStream_ = new BufferedInputStream(socket_.getInputStream()); + outputStream_ = new BufferedOutputStream(socket_.getOutputStream()); } catch (IOException iox) { close(); throw new TTransportException(TTransportException.NOT_OPEN, iox); @@ -219,8 +219,8 @@ public class TSocket extends TIOStreamTransport { try { socket_.connect(new InetSocketAddress(host_, port_), connectTimeout_); - inputStream_ = new BufferedInputStream(socket_.getInputStream(), 1024); - outputStream_ = new BufferedOutputStream(socket_.getOutputStream(), 1024); + inputStream_ = new BufferedInputStream(socket_.getInputStream()); + outputStream_ = new BufferedOutputStream(socket_.getOutputStream()); } catch (IOException iox) { close(); throw new TTransportException(TTransportException.NOT_OPEN, iox); diff --git a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/Fixtures.java b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/Fixtures.java index 9f28124..81671d8 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/Fixtures.java +++ b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/Fixtures.java @@ -277,7 +277,7 @@ public class Fixtures { nesting = new Nesting(bonk, oneOfEach); holyMoley = new HolyMoley(); - ArrayList big = new ArrayList(); + List big = new ArrayList(); big.add(new OneOfEach(oneOfEach)); big.add(nesting.my_ooe); holyMoley.setBig(big); diff --git a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestDeepCopy.java b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestDeepCopy.java new file mode 100644 index 0000000..acafaef --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestDeepCopy.java @@ -0,0 +1,34 @@ +package org.apache.thrift; + +import junit.framework.TestCase; +import thrift.test.DeepCopyBar; +import thrift.test.DeepCopyFoo; + +public class TestDeepCopy extends TestCase { + + public void testDeepCopy() throws Exception { + final DeepCopyFoo foo = new DeepCopyFoo(); + + foo.addToL(new DeepCopyBar()); + foo.addToS(new DeepCopyBar()); + foo.putToM("test 3", new DeepCopyBar()); + + foo.addToLi(new thrift.test.Object()); + foo.addToSi(new thrift.test.Object()); + foo.putToMi("test 3", new thrift.test.Object()); + + foo.setBar(new DeepCopyBar()); + + final DeepCopyFoo deepCopyFoo = foo.deepCopy(); + + assertNotSame(foo.getBar(), deepCopyFoo.getBar()); + + assertNotSame(foo.getL().get(0), deepCopyFoo.getL().get(0)); + assertNotSame(foo.getS().toArray(new DeepCopyBar[0])[0], deepCopyFoo.getS().toArray(new DeepCopyBar[0])[0]); + assertNotSame(foo.getM().get("test 3"), deepCopyFoo.getM().get("test 3")); + + assertNotSame(foo.getLi().get(0), deepCopyFoo.getLi().get(0)); + assertNotSame(foo.getSi().toArray(new thrift.test.Object[0])[0], deepCopyFoo.getSi().toArray(new thrift.test.Object[0])[0]); + assertNotSame(foo.getMi().get("test 3"), deepCopyFoo.getMi().get("test 3")); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestEnumContainers.java b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestEnumContainers.java new file mode 100644 index 0000000..683246b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestEnumContainers.java @@ -0,0 +1,81 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +package org.apache.thrift; + +import junit.framework.TestCase; +import thrift.test.enumcontainers.EnumContainersTestConstants; +import thrift.test.enumcontainers.GodBean; +import thrift.test.enumcontainers.GreekGodGoddess; + +import java.util.EnumMap; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; + +public class TestEnumContainers extends TestCase { + + public void testEnumContainers() throws Exception { + final GodBean b1 = new GodBean(); + b1.addToGoddess(GreekGodGoddess.HERA); + b1.getGoddess().add(GreekGodGoddess.APHRODITE); + b1.putToPower(GreekGodGoddess.ZEUS, 1000); + b1.getPower().put(GreekGodGoddess.HERA, 333); + b1.putToByAlias("Mr. Z", GreekGodGoddess.ZEUS); + b1.addToImages("Baths of Aphrodite 01.jpeg"); + + final GodBean b2 = new GodBean(b1); + + final GodBean b3 = new GodBean(); + { + final TSerializer serializer = new TSerializer(); + final TDeserializer deserializer = new TDeserializer(); + + final byte[] bytes = serializer.serialize(b1); + deserializer.deserialize(b3, bytes); + } + + assertTrue(b1.getGoddess() != b2.getGoddess()); + assertTrue(b1.getPower() != b2.getPower()); + + assertTrue(b1.getGoddess() != b3.getGoddess()); + assertTrue(b1.getPower() != b3.getPower()); + + for (GodBean each : new GodBean[]{b1, b2, b3}) { + assertTrue(each.getGoddess().contains(GreekGodGoddess.HERA)); + assertFalse(each.getGoddess().contains(GreekGodGoddess.POSEIDON)); + assertTrue(each.getGoddess() instanceof EnumSet); + + assertEquals(Integer.valueOf(1000), each.getPower().get(GreekGodGoddess.ZEUS)); + assertEquals(Integer.valueOf(333), each.getPower().get(GreekGodGoddess.HERA)); + assertTrue(each.getPower() instanceof EnumMap); + + assertTrue(each.getByAlias() instanceof HashMap); + assertTrue(each.getImages() instanceof HashSet); + } + } + + public void testEnumConstants() { + assertEquals("lightning bolt", EnumContainersTestConstants.ATTRIBUTES.get(GreekGodGoddess.ZEUS)); + assertTrue(EnumContainersTestConstants.ATTRIBUTES instanceof EnumMap); + + assertTrue(EnumContainersTestConstants.BEAUTY.contains(GreekGodGoddess.APHRODITE)); + assertTrue(EnumContainersTestConstants.BEAUTY instanceof EnumSet); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestMultiplexedProcessor.java b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestMultiplexedProcessor.java new file mode 100644 index 0000000..01776ca --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestMultiplexedProcessor.java @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +package org.apache.thrift; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.apache.thrift.protocol.TMessage; +import org.apache.thrift.protocol.TMessageType; +import org.apache.thrift.protocol.TProtocol; +import org.junit.Before; +import org.junit.Test; + +public class TestMultiplexedProcessor { + private TMultiplexedProcessor mp; + private TProtocol iprot; + private TProtocol oprot; + + @Before + public void setUp() throws Exception { + mp = new TMultiplexedProcessor(); + iprot = mock(TProtocol.class); + oprot = mock(TProtocol.class); + } + + @Test(expected = TException.class) + public void testWrongMessageType() throws TException { + when (iprot.readMessageBegin()).thenReturn(new TMessage("service:func", TMessageType.REPLY, 42)); + mp.process(iprot, oprot); + } + + @Test(expected = TException.class) + public void testNoSuchService() throws TException { + when(iprot.readMessageBegin()).thenReturn(new TMessage("service:func", TMessageType.CALL, 42)); + + mp.process(iprot, oprot); + } + + static class StubProcessor implements TProcessor { + @Override + public boolean process(TProtocol in, TProtocol out) throws TException { + TMessage msg = in.readMessageBegin(); + if (!"func".equals(msg.name) || msg.type!=TMessageType.CALL || msg.seqid!=42) { + throw new TException("incorrect parameters"); + } + out.writeMessageBegin(new TMessage("func", TMessageType.REPLY, 42)); + return true; + } + } + + @Test + public void testExistingService() throws TException { + when(iprot.readMessageBegin()).thenReturn(new TMessage("service:func", TMessageType.CALL, 42)); + mp.registerProcessor("service", new StubProcessor()); + mp.process(iprot, oprot); + verify(oprot).writeMessageBegin(any(TMessage.class)); + } + + @Test + public void testDefaultService() throws TException { + when(iprot.readMessageBegin()).thenReturn(new TMessage("func", TMessageType.CALL, 42)); + mp.registerDefault(new StubProcessor()); + mp.process(iprot, oprot); + verify(oprot).writeMessageBegin(any(TMessage.class)); + } + +} diff --git a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestRenderedDoubleConstants.java b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestRenderedDoubleConstants.java new file mode 100644 index 0000000..d691fe3 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestRenderedDoubleConstants.java @@ -0,0 +1,179 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +package org.apache.thrift; + +import java.util.List; +import junit.framework.TestCase; +import static org.junit.Assert.*; +import org.junit.Test; +import thrift.test.DoubleConstantsTestConstants; + +public class TestRenderedDoubleConstants extends TestCase { + private static final double EPSILON = 0.0000001; + private static final String ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST = + "failed to verify a double constant generated by Thrift (expected = %f, got = %f)"; + private static final String ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_LIST_TEST = + "failed to verify a list item by Thrift (expected = %f, got = %f)"; + private static final String ASSERTION_MESSAGE_FOR_TYPE_CHECKS = + "the rendered variable with name %s is not of double type"; + + // to make sure lists containing doubles are generated correctly + public void testRenderedDoubleList() throws Exception { + final double[] EXPECTED_LIST = + {1d,-100d,100d,9223372036854775807d,-9223372036854775807d,3.14159265359,1000000.1,-1000000.1,1.7e+308, + -1.7e+308,9223372036854775816.43,-9223372036854775816.43}; + assertEquals(EXPECTED_LIST.length, DoubleConstantsTestConstants.DOUBLE_LIST_TEST.size()); + for (int i = 0; i < EXPECTED_LIST.length; ++i) { + assertEquals( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_LIST_TEST, + EXPECTED_LIST[i], + DoubleConstantsTestConstants.DOUBLE_LIST_TEST.get(i)), + EXPECTED_LIST[i], DoubleConstantsTestConstants.DOUBLE_LIST_TEST.get(i), EPSILON); + } + } + + // to make sure the variables inside Thrift files are generated correctly + public void testRenderedDoubleConstants() throws Exception { + final double EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT = 1.0; + final double EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT = -100.0; + final double EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT = 9223372036854775807.0; + final double EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT = -9223372036854775807.0; + final double EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS = 3.14159265359; + final double EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE = 1000000.1; + final double EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE = -1000000.1; + final double EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE = 1.7e+308; + final double EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE = 9223372036854775816.43; + final double EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE = -1.7e+308; + final double EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE = -9223372036854775816.43; + assertEquals( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST), + EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST, EPSILON); + assertEquals( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST), + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST, EPSILON); + assertEquals( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST), + EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST, EPSILON); + assertEquals( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST), + EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST, EPSILON); + assertEquals( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST), + EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST, EPSILON); + assertEquals( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST), + EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST, EPSILON); + assertEquals( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST), + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST, EPSILON); + assertEquals( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST), + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST, EPSILON); + assertEquals( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST), + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST, EPSILON); + assertEquals( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST), + EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST, EPSILON); + assertEquals( + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST), + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST, EPSILON); + assertTrue( + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST"), + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST)); + assertTrue( + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST"), + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST)); + assertTrue( + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST"), + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST)); + assertTrue( + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST"), + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST)); + assertTrue( + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST"), + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST)); + assertTrue( + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST"), + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST)); + assertTrue( + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST"), + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST)); + //assertTrue( + // String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST"), + // Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST)); + assertTrue( + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST"), + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST)); + //assertTrue( + // String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST"), + // Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST)); + assertTrue( + String.format( + ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST"), + Double.class.isInstance( + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST)); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestReuse.java b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestReuse.java index db16c74..b44abd0 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestReuse.java +++ b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestReuse.java @@ -21,10 +21,7 @@ package org.apache.thrift; import java.util.HashSet; -import junit.framework.TestCase; - import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.protocol.TType; import thrift.test.Reuse; diff --git a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestUnsafeBinaries.java b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestUnsafeBinaries.java new file mode 100644 index 0000000..d1fc213 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/TestUnsafeBinaries.java @@ -0,0 +1,146 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +package org.apache.thrift; + +import java.nio.ByteBuffer; +import java.util.Arrays; + +import thrift.test.SafeBytes; +import thrift.test.UnsafeBytes; + +// test generating types with un-copied byte[]/ByteBuffer input/output +// +public class TestUnsafeBinaries extends TestStruct { + + private static byte[] input() { + return new byte[]{1, 1}; + } + + // + // verify that the unsafe_binaries option modifies behavior + // + + // constructor doesn't copy + public void testUnsafeConstructor() throws Exception { + + byte[] input = input(); + UnsafeBytes struct = new UnsafeBytes(ByteBuffer.wrap(input)); + + input[0] = 2; + + assertTrue(Arrays.equals( + new byte[]{2, 1}, + struct.getBytes()) + ); + + } + + // getter doesn't copy + // note: this behavior is the same with/without the flag, but if this default ever changes, the current behavior + // should be retained when using this flag + public void testUnsafeGetter(){ + UnsafeBytes struct = new UnsafeBytes(ByteBuffer.wrap(input())); + + byte[] val = struct.getBytes(); + val[0] = 2; + + assertTrue(Arrays.equals( + new byte[]{2, 1}, + struct.getBytes()) + ); + + } + + // setter doesn't copy + public void testUnsafeSetter(){ + UnsafeBytes struct = new UnsafeBytes(); + + byte[] val = input(); + struct.setBytes(val); + + val[0] = 2; + + assertTrue(Arrays.equals( + new byte[]{2, 1}, + struct.getBytes()) + ); + + } + + // buffer doens't copy + public void testUnsafeBufferFor(){ + UnsafeBytes struct = new UnsafeBytes(ByteBuffer.wrap(input())); + + ByteBuffer val = struct.bufferForBytes(); + val.array()[0] = 2; + + assertTrue(Arrays.equals( + new byte[]{2, 1}, + struct.getBytes()) + ); + + } + + // + // verify that the default generator does not change behavior + // + + public void testSafeConstructor() { + + byte[] input = input(); + SafeBytes struct = new SafeBytes(ByteBuffer.wrap(input)); + + input[0] = 2; + + assertTrue(Arrays.equals( + new byte[]{1, 1}, + struct.getBytes()) + ); + + } + + public void testSafeSetter() { + + byte[] input = input(); + SafeBytes struct = new SafeBytes(ByteBuffer.wrap(input)); + + input[0] = 2; + + assertTrue(Arrays.equals( + new byte[]{1, 1}, + struct.getBytes()) + ); + + } + + public void testSafeBufferFor(){ + SafeBytes struct = new SafeBytes(ByteBuffer.wrap(input())); + + ByteBuffer val = struct.bufferForBytes(); + val.array()[0] = 2; + + assertTrue(Arrays.equals( + new byte[]{1, 1}, + struct.getBytes()) + ); + + } + +} diff --git a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/protocol/TestTProtocolUtil.java b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/protocol/TestTProtocolUtil.java index 199c707..89cf536 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/protocol/TestTProtocolUtil.java +++ b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/protocol/TestTProtocolUtil.java @@ -18,24 +18,10 @@ */ package org.apache.thrift.protocol; -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.List; - import junit.framework.TestCase; -import org.apache.thrift.Fixtures; -import org.apache.thrift.TBase; -import org.apache.thrift.TDeserializer; -import org.apache.thrift.TException; import org.apache.thrift.TSerializer; -import org.apache.thrift.transport.TMemoryBuffer; -import thrift.test.CompactProtoTestStruct; -import thrift.test.HolyMoley; -import thrift.test.Nesting; -import thrift.test.OneOfEach; -import thrift.test.Srv; import thrift.test.GuessProtocolStruct; public class TestTProtocolUtil extends TestCase { diff --git a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/protocol/TestTSimpleJSONProtocol.java b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/protocol/TestTSimpleJSONProtocol.java index 0b9c732..b8c4657 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/protocol/TestTSimpleJSONProtocol.java +++ b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/protocol/TestTSimpleJSONProtocol.java @@ -84,7 +84,7 @@ public class TestTSimpleJSONProtocol extends TestCase { struct.unsetDouble_byte_map(); struct.unsetString_byte_map(); struct.write(proto); - assertEquals("{\"a_byte\":127,\"a_i16\":32000,\"a_i32\":1000000000,\"a_i64\":1099511627775,\"a_double\":5.6789,\"a_string\":\"my string\",\"a_binary\":\"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\",\"true_field\":1,\"false_field\":0,\"empty_struct_field\":{},\"byte_list\":[-127,-1,0,1,127],\"i16_list\":[-1,0,1,32767],\"i32_list\":[-1,0,255,65535,16777215,2147483647],\"i64_list\":[-1,0,255,65535,16777215,4294967295,1099511627775,281474976710655,72057594037927935,9223372036854775807],\"double_list\":[0.1,0.2,0.3],\"string_list\":[\"first\",\"second\",\"third\"],\"boolean_list\":[1,1,1,0,0,0],\"struct_list\":[{},{}],\"i32_set\":[1,2,3],\"boolean_set\":[0,1],\"struct_set\":[{}],\"byte_byte_map\":{\"1\":2},\"boolean_byte_map\":{\"0\":0,\"1\":1},\"byte_i16_map\":{\"1\":1,\"2\":-1,\"3\":32767},\"byte_i32_map\":{\"1\":1,\"2\":-1,\"3\":2147483647},\"byte_i64_map\":{\"1\":1,\"2\":-1,\"3\":9223372036854775807},\"byte_double_map\":{\"1\":0.1,\"2\":-0.1,\"3\":1000000.0},\"byte_string_map\":{\"1\":\"\",\"2\":\"blah\",\"3\":\"loooooooooooooong string\"},\"byte_boolean_map\":{\"1\":1,\"2\":0},\"byte_map_map\":{\"0\":{},\"1\":{\"1\":1},\"2\":{\"1\":1,\"2\":2}},\"byte_set_map\":{\"0\":[],\"1\":[1],\"2\":[1,2]},\"byte_list_map\":{\"0\":[],\"1\":[1],\"2\":[1,2]}}", bufToString()); + assertEquals("{\"a_byte\":127,\"a_i16\":32000,\"a_i32\":1000000000,\"a_i64\":1099511627775,\"a_double\":5.6789,\"a_string\":\"my string\",\"a_binary\":\"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\",\"true_field\":1,\"false_field\":0,\"empty_struct_field\":{},\"byte_list\":[-127,-1,0,1,127],\"i16_list\":[-1,0,1,32767],\"i32_list\":[-1,0,255,65535,16777215,2147483647],\"i64_list\":[-1,0,255,65535,16777215,4294967295,1099511627775,281474976710655,72057594037927935,9223372036854775807],\"double_list\":[0.1,0.2,0.3],\"string_list\":[\"first\",\"second\",\"third\"],\"boolean_list\":[1,1,1,0,0,0],\"struct_list\":[{},{}],\"i32_set\":[1,2,3],\"boolean_set\":[0,1],\"struct_set\":[{}],\"byte_byte_map\":{\"1\":2},\"boolean_byte_map\":{\"0\":0,\"1\":1},\"byte_i16_map\":{\"1\":1,\"2\":-1,\"3\":32767},\"byte_i32_map\":{\"1\":1,\"2\":-1,\"3\":2147483647},\"byte_i64_map\":{\"1\":1,\"2\":-1,\"3\":9223372036854775807},\"byte_double_map\":{\"1\":0.1,\"2\":-0.1,\"3\":1000000.1},\"byte_string_map\":{\"1\":\"\",\"2\":\"blah\",\"3\":\"loooooooooooooong string\"},\"byte_boolean_map\":{\"1\":1,\"2\":0},\"byte_map_map\":{\"0\":{},\"1\":{\"1\":1},\"2\":{\"1\":1,\"2\":2}},\"byte_set_map\":{\"0\":[],\"1\":[1],\"2\":[1,2]},\"byte_list_map\":{\"0\":[],\"1\":[1],\"2\":[1,2]}}", bufToString()); } public void testThrowsOnCollectionKeys() throws TException { diff --git a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/server/ServerTestBase.java b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/server/ServerTestBase.java index c2d2952..1dee22d 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/server/ServerTestBase.java +++ b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/server/ServerTestBase.java @@ -54,13 +54,13 @@ import thrift.test.Xtruct2; public abstract class ServerTestBase extends TestCase { public static class TestHandler implements ThriftTest.Iface { - + public TestHandler() {} - + public void testVoid() { System.out.print("testVoid()\n"); } - + public String testString(String thing) { System.out.print("testString(\"" + thing + "\")\n"); return thing; @@ -70,22 +70,22 @@ public abstract class ServerTestBase extends TestCase { System.out.print("testBool(" + thing + ")\n"); return thing; } - + public byte testByte(byte thing) { System.out.print("testByte(" + thing + ")\n"); return thing; } - + public int testI32(int thing) { System.out.print("testI32(" + thing + ")\n"); return thing; } - + public long testI64(long thing) { System.out.print("testI64(" + thing + ")\n"); return thing; } - + public double testDouble(double thing) { System.out.print("testDouble(" + thing + ")\n"); return thing; @@ -110,7 +110,7 @@ public abstract class ServerTestBase extends TestCase { thing.i64_thing + "})\n"); return thing; } - + public Xtruct2 testNest(Xtruct2 nest) { Xtruct thing = nest.struct_thing; System.out.print("testNest({" + @@ -122,7 +122,7 @@ public abstract class ServerTestBase extends TestCase { nest.i32_thing + "})\n"); return nest; } - + public Map testMap(Map thing) { System.out.print("testMap({"); System.out.print(thing); @@ -136,7 +136,7 @@ public abstract class ServerTestBase extends TestCase { System.out.print("})\n"); return thing; } - + public Set testSet(Set thing) { System.out.print("testSet({"); boolean first = true; @@ -151,7 +151,7 @@ public abstract class ServerTestBase extends TestCase { System.out.print("})\n"); return thing; } - + public List testList(List thing) { System.out.print("testList({"); boolean first = true; @@ -166,58 +166,58 @@ public abstract class ServerTestBase extends TestCase { System.out.print("})\n"); return thing; } - + public Numberz testEnum(Numberz thing) { System.out.print("testEnum(" + thing + ")\n"); return thing; } - + public long testTypedef(long thing) { System.out.print("testTypedef(" + thing + ")\n"); return thing; } - + public Map> testMapMap(int hello) { System.out.print("testMapMap(" + hello + ")\n"); Map> mapmap = new HashMap>(); - + HashMap pos = new HashMap(); HashMap neg = new HashMap(); for (int i = 1; i < 5; i++) { pos.put(i, i); neg.put(-i, -i); } - + mapmap.put(4, pos); mapmap.put(-4, neg); - + return mapmap; } - + public Map> testInsanity(Insanity argument) { System.out.print("testInsanity()\n"); - + HashMap first_map = new HashMap(); HashMap second_map = new HashMap();; - + first_map.put(Numberz.TWO, argument); first_map.put(Numberz.THREE, argument); - + Insanity looney = new Insanity(); second_map.put(Numberz.SIX, looney); - + Map> insane = new HashMap>(); insane.put((long)1, first_map); insane.put((long)2, second_map); - + return insane; } - + public Xtruct testMulti(byte arg0, int arg1, long arg2, Map arg3, Numberz arg4, long arg5) { System.out.print("testMulti()\n"); - + Xtruct hello = new Xtruct();; hello.string_thing = "Hello2"; hello.byte_thing = arg0; @@ -225,7 +225,7 @@ public abstract class ServerTestBase extends TestCase { hello.i64_thing = arg2; return hello; } - + public void testException(String arg) throws Xception, TException { System.out.print("testException("+arg+")\n"); if ("Xception".equals(arg)) { @@ -234,14 +234,15 @@ public abstract class ServerTestBase extends TestCase { x.message = arg; throw x; } else if ("TException".equals(arg)) { - throw new TException(arg); + // Unspecified exception should yield a TApplicationException on client side + throw new RuntimeException(arg); } else { Xtruct result = new Xtruct(); result.string_thing = arg; } return; } - + public Xtruct testMultiException(String arg0, String arg1) throws Xception, Xception2 { System.out.print("testMultiException(" + arg0 + ", " + arg1 + ")\n"); if (arg0.equals("Xception")) { @@ -256,17 +257,17 @@ public abstract class ServerTestBase extends TestCase { x.struct_thing.string_thing = "This is an Xception2"; throw x; } - + Xtruct result = new Xtruct(); result.string_thing = arg1; return result; } - + public void testOneway(int sleepFor) { System.out.println("testOneway(" + Integer.toString(sleepFor) + ") => sleeping..."); try { - Thread.sleep(sleepFor * 1000); + Thread.sleep(sleepFor * SLEEP_DELAY); System.out.println("Done sleeping!"); } catch (InterruptedException ie) { throw new RuntimeException(ie); @@ -281,6 +282,7 @@ public abstract class ServerTestBase extends TestCase { public static final String HOST = "localhost"; public static final int PORT = Integer.valueOf( System.getProperty("test.port", "9090")); + protected static final int SLEEP_DELAY = 1000; protected static final int SOCKET_TIMEOUT = 1500; private static final Xtruct XSTRUCT = new Xtruct("Zero", (byte) 1, -3, -5); private static final Xtruct2 XSTRUCT2 = new Xtruct2((byte)1, XSTRUCT, 5); @@ -333,7 +335,7 @@ public abstract class ServerTestBase extends TestCase { // todo: add assertions private void testInsanity(ThriftTest.Client testClient) throws TException { Insanity insane; - + insane = new Insanity(); insane.userMap = new HashMap(); insane.userMap.put(Numberz.FIVE, (long)5000); @@ -351,7 +353,7 @@ public abstract class ServerTestBase extends TestCase { for (long key : whoa.keySet()) { Map val = whoa.get(key); System.out.print(key + " => {"); - + for (Numberz k2 : val.keySet()) { Insanity v2 = val.get(k2); System.out.print(k2 + " => {"); @@ -363,7 +365,7 @@ public abstract class ServerTestBase extends TestCase { } } System.out.print("}, "); - + List xtructs = v2.xtructs; System.out.print("{"); if (xtructs != null) { @@ -372,7 +374,7 @@ public abstract class ServerTestBase extends TestCase { } } System.out.print("}"); - + System.out.print("}, "); } System.out.print("}, "); @@ -387,7 +389,7 @@ public abstract class ServerTestBase extends TestCase { public void testIt() throws Exception { for (TProtocolFactory protoFactory : getProtocols()) { - TProcessor processor = useAsyncProcessor() ? new ThriftTest.AsyncProcessor(new AsyncTestHandler()) : new ThriftTest.Processor(new TestHandler()); + TProcessor processor = useAsyncProcessor() ? new ThriftTest.AsyncProcessor(new AsyncTestHandler()) : new ThriftTest.Processor(new TestHandler()); startServer(processor, protoFactory); @@ -420,6 +422,7 @@ public abstract class ServerTestBase extends TestCase { testOneway(testClient); testI32(testClient); transport.close(); + socket.close(); stopServer(); } @@ -430,7 +433,7 @@ public abstract class ServerTestBase extends TestCase { } public List getProtocols() { - return PROTOCOLS; + return PROTOCOLS; } private void testList(ThriftTest.Client testClient) throws TException { @@ -466,14 +469,14 @@ public abstract class ServerTestBase extends TestCase { testClient.testMapMap(1); Map> mapmap = new HashMap>(); - + HashMap pos = new HashMap(); HashMap neg = new HashMap(); for (int i = 1; i < 5; i++) { pos.put(i, i); neg.put(-i, -i); } - + mapmap.put(4, pos); mapmap.put(-4, neg); assertEquals(mapmap, mm); @@ -535,7 +538,7 @@ public abstract class ServerTestBase extends TestCase { public void testTransportFactory() throws Exception { for (TProtocolFactory protoFactory : getProtocols()) { TestHandler handler = new TestHandler(); - ThriftTest.Processor processor = new ThriftTest.Processor(handler); + ThriftTest.Processor processor = new ThriftTest.Processor(handler); final CallCountingTransportFactory factory = new CallCountingTransportFactory(new TFramedTransport.Factory()); @@ -551,6 +554,7 @@ public abstract class ServerTestBase extends TestCase { ThriftTest.Client testClient = new ThriftTest.Client(protocol); assertEquals(0, testClient.testByte((byte) 0)); assertEquals(2, factory.count); + socket.close(); stopServer(); } } @@ -679,13 +683,15 @@ public abstract class ServerTestBase extends TestCase { x.errorCode = 1001; x.message = arg; // throw and onError yield the same result. - // resultHandler.onError(x); - // return; - throw x; - } else if ("TException".equals(arg)) { - // throw new TException(arg); - resultHandler.onError(new TException(arg)); + // throw x; + resultHandler.onError(x); return; + } else if ("TException".equals(arg)) { + // throw and onError yield the same result. + // resultHandler.onError(new TException(arg)); + // return; + // Unspecified exception should yield a TApplicationException on client side + throw new RuntimeException(arg); } resultHandler.onComplete(null); } diff --git a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/test/TestClient.java b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/test/TestClient.java index b2ce1e6..feaa972 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/test/TestClient.java +++ b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/test/TestClient.java @@ -33,6 +33,7 @@ import org.apache.thrift.TSerializer; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TCompactProtocol; import org.apache.thrift.protocol.TJSONProtocol; +import org.apache.thrift.protocol.TMultiplexedProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TSimpleJSONProtocol; import org.apache.thrift.transport.TFastFramedTransport; @@ -46,6 +47,7 @@ import org.apache.thrift.transport.TTransportException; // Generated code import thrift.test.Insanity; import thrift.test.Numberz; +import thrift.test.SecondService; import thrift.test.ThriftTest; import thrift.test.Xception; import thrift.test.Xception2; @@ -64,6 +66,7 @@ public class TestClient { private static int ERR_STRUCTS = 2; private static int ERR_CONTAINERS = 4; private static int ERR_EXCEPTIONS = 8; + private static int ERR_PROTOCOLS = 16; private static int ERR_UNKNOWN = 64; public static void main(String [] args) { @@ -102,7 +105,7 @@ public class TestClient { System.out.println(" --host=arg (=" + host + ")\tHost to connect"); System.out.println(" --port=arg (=" + port + ")\tPort number to connect"); System.out.println(" --transport=arg (=" + transport_type + ")\n\t\t\t\tTransport: buffered, framed, fastframed, http"); - System.out.println(" --protocol=arg (=" + protocol_type + ")\tProtocol: binary, json, compact"); + System.out.println(" --protocol=arg (=" + protocol_type + ")\tProtocol: binary, compact, json, multi, multic, multij"); System.out.println(" --ssl\t\t\tEncrypted Transport using SSL"); System.out.println(" --testloops[--n]=arg (=" + numTests + ")\tNumber of Tests"); System.exit(0); @@ -117,6 +120,9 @@ public class TestClient { if (protocol_type.equals("binary")) { } else if (protocol_type.equals("compact")) { } else if (protocol_type.equals("json")) { + } else if (protocol_type.equals("multi")) { + } else if (protocol_type.equals("multic")) { + } else if (protocol_type.equals("multij")) { } else { throw new Exception("Unknown protocol type! " + protocol_type); } @@ -163,16 +169,21 @@ public class TestClient { } TProtocol tProtocol = null; - if (protocol_type.equals("json")) { + TProtocol tProtocol2 = null; + if (protocol_type.equals("json") || protocol_type.equals("multij")) { tProtocol = new TJSONProtocol(transport); - } else if (protocol_type.equals("compact")) { + } else if (protocol_type.equals("compact") || protocol_type.equals("multic")) { tProtocol = new TCompactProtocol(transport); } else { tProtocol = new TBinaryProtocol(transport); } - ThriftTest.Client testClient = - new ThriftTest.Client(tProtocol); + if (protocol_type.startsWith("multi")) { + tProtocol2 = new TMultiplexedProtocol(tProtocol, "SecondService"); + tProtocol = new TMultiplexedProtocol(tProtocol, "ThriftTest"); + } + + ThriftTest.Client testClient = new ThriftTest.Client(tProtocol); Insanity insane = new Insanity(); long timeMin = 0; @@ -222,6 +233,19 @@ public class TestClient { System.out.println("*** FAILURE ***\n"); } + /** + * Multiplexed test + */ + if (protocol_type.startsWith("multi")) { + SecondService.Client secondClient = new SecondService.Client(tProtocol2); + System.out.print("secondtestString(\"Test2\")"); + s = secondClient.secondtestString("Test2"); + System.out.print(" = \"" + s + "\"\n"); + if (!s.equals("testString(\"Test2\")")) { + returnCode |= ERR_PROTOCOLS; + System.out.println("*** FAILURE ***\n"); + } + } /** * BYTE TEST */ diff --git a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/test/TestServer.java b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/test/TestServer.java index 14cd2ab..1f3e555 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/test/TestServer.java +++ b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/test/TestServer.java @@ -30,6 +30,7 @@ import org.apache.thrift.protocol.TCompactProtocol; import org.apache.thrift.protocol.TJSONProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TProtocolFactory; +import org.apache.thrift.protocol.TMultiplexedProtocol; import org.apache.thrift.server.ServerContext; import org.apache.thrift.server.TServer; import org.apache.thrift.server.TServer.Args; @@ -46,10 +47,11 @@ import org.apache.thrift.transport.TSSLTransportFactory; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportFactory; import org.apache.thrift.transport.TNonblockingServerSocket; - +import org.apache.thrift.TMultiplexedProcessor; import thrift.test.Insanity; import thrift.test.Numberz; +import thrift.test.SecondService; import thrift.test.ThriftTest; import thrift.test.Xception; import thrift.test.Xception2; @@ -58,6 +60,24 @@ import thrift.test.Xtruct2; public class TestServer { + // Multiplexed Protocol Support Details: + // + // For multiplexed testing we always use binary protocol underneath. + // + // "ThriftTest" named service implements "ThriftTest" from ThriftTest.thrift + // "SecondService" named service implements "SecondService" from ThriftTest.thrift + // In addition, to support older non-multiplexed clients using the same concrete protocol + // the multiplexed processor is taught to use "ThriftTest" if the incoming request has no + // multiplexed call name decoration. + + static class SecondHandler implements thrift.test.SecondService.Iface { + + @Override + public java.lang.String secondtestString(java.lang.String thing) throws org.apache.thrift.TException + { return "testString(\"" + thing + "\")"; } + + } + static class TestServerContext implements ServerContext { int connectionId; @@ -139,7 +159,7 @@ public class TestServer { System.out.println(" --help\t\t\tProduce help message"); System.out.println(" --port=arg (=" + port + ")\tPort number to connect"); System.out.println(" --transport=arg (=" + transport_type + ")\n\t\t\t\tTransport: buffered, framed, fastframed"); - System.out.println(" --protocol=arg (=" + protocol_type + ")\tProtocol: binary, json, compact"); + System.out.println(" --protocol=arg (=" + protocol_type + ")\tProtocol: binary, compact, json, multi, multic, multij"); System.out.println(" --ssl\t\t\tEncrypted Transport using SSL"); System.out.println(" --server-type=arg (=" + server_type +")\n\t\t\t\tType of server: simple, thread-pool, nonblocking, threaded-selector"); System.out.println(" --string-limit=arg (=" + string_limit + ")\tString read length limit"); @@ -167,8 +187,11 @@ public class TestServer { throw new Exception("Unknown server type! " + server_type); } if (protocol_type.equals("binary")) { - } else if (protocol_type.equals("json")) { } else if (protocol_type.equals("compact")) { + } else if (protocol_type.equals("json")) { + } else if (protocol_type.equals("multi")) { + } else if (protocol_type.equals("multic")) { + } else if (protocol_type.equals("multij")) { } else { throw new Exception("Unknown protocol type! " + protocol_type); } @@ -183,19 +206,20 @@ public class TestServer { System.exit(1); } - // Processor - TestHandler testHandler = - new TestHandler(); - ThriftTest.Processor testProcessor = - new ThriftTest.Processor(testHandler); + // Processors + TestHandler testHandler = new TestHandler(); + ThriftTest.Processor testProcessor = new ThriftTest.Processor(testHandler); + + SecondHandler secondHandler = new SecondHandler(); + SecondService.Processor secondProcessor = new SecondService.Processor(secondHandler); // Protocol factory TProtocolFactory tProtocolFactory = null; - if (protocol_type.equals("json")) { + if (protocol_type.equals("json") || protocol_type.equals("multij")) { tProtocolFactory = new TJSONProtocol.Factory(); - } else if (protocol_type.equals("compact")) { + } else if (protocol_type.equals("compact") || protocol_type.equals("multic")) { tProtocolFactory = new TCompactProtocol.Factory(string_limit, container_limit); - } else { + } else { // also covers multi tProtocolFactory = new TBinaryProtocol.Factory(string_limit, container_limit); } @@ -211,6 +235,11 @@ public class TestServer { TServer serverEngine = null; + // If we are multiplexing services in one server... + TMultiplexedProcessor multiplexedProcessor = new TMultiplexedProcessor(); + multiplexedProcessor.registerDefault (testProcessor); + multiplexedProcessor.registerProcessor("ThriftTest", testProcessor); + multiplexedProcessor.registerProcessor("SecondService", secondProcessor); if (server_type.equals("nonblocking") || server_type.equals("threaded-selector")) { @@ -218,23 +247,21 @@ public class TestServer { TNonblockingServerSocket tNonblockingServerSocket = new TNonblockingServerSocket(new TNonblockingServerSocket.NonblockingAbstractServerSocketArgs().port(port)); - if (server_type.equals("nonblocking")) { + if (server_type.contains("nonblocking")) { // Nonblocking Server TNonblockingServer.Args tNonblockingServerArgs = new TNonblockingServer.Args(tNonblockingServerSocket); - tNonblockingServerArgs.processor(testProcessor); + tNonblockingServerArgs.processor(protocol_type.startsWith("multi") ? multiplexedProcessor : testProcessor); tNonblockingServerArgs.protocolFactory(tProtocolFactory); tNonblockingServerArgs.transportFactory(tTransportFactory); - serverEngine = new TNonblockingServer(tNonblockingServerArgs); } else { // server_type.equals("threaded-selector") // ThreadedSelector Server TThreadedSelectorServer.Args tThreadedSelectorServerArgs = new TThreadedSelectorServer.Args(tNonblockingServerSocket); - tThreadedSelectorServerArgs.processor(testProcessor); + tThreadedSelectorServerArgs.processor(protocol_type.startsWith("multi") ? multiplexedProcessor : testProcessor); tThreadedSelectorServerArgs.protocolFactory(tProtocolFactory); tThreadedSelectorServerArgs.transportFactory(tTransportFactory); - serverEngine = new TThreadedSelectorServer(tThreadedSelectorServerArgs); } } else { @@ -251,29 +278,28 @@ public class TestServer { if (server_type.equals("simple")) { // Simple Server TServer.Args tServerArgs = new TServer.Args(tServerSocket); - tServerArgs.processor(testProcessor); + tServerArgs.processor(protocol_type.startsWith("multi") ? multiplexedProcessor : testProcessor); tServerArgs.protocolFactory(tProtocolFactory); tServerArgs.transportFactory(tTransportFactory); - serverEngine = new TSimpleServer(tServerArgs); } else { // server_type.equals("threadpool") // ThreadPool Server TThreadPoolServer.Args tThreadPoolServerArgs = new TThreadPoolServer.Args(tServerSocket); - tThreadPoolServerArgs.processor(testProcessor); + tThreadPoolServerArgs.processor(protocol_type.startsWith("multi") ? multiplexedProcessor : testProcessor); tThreadPoolServerArgs.protocolFactory(tProtocolFactory); tThreadPoolServerArgs.transportFactory(tTransportFactory); - serverEngine = new TThreadPoolServer(tThreadPoolServerArgs); } } - - //Set server event handler + // Set server event handler serverEngine.setServerEventHandler(new TestServerEventHandler()); // Run it - System.out.println("Starting the server on port " + port + "..."); + System.out.println("Starting the " + (ssl ? "ssl server" : "server") + + " [" + protocol_type + "/" + transport_type + "/" + server_type + "] on " + + ((domain_socket == "") ? ("port " + port) : ("unix socket " + domain_socket))); serverEngine.serve(); } catch (Exception x) { diff --git a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/transport/TestTFastFramedTransport.java b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/transport/TestTFastFramedTransport.java index 11fbdf4..06ee206 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/transport/TestTFastFramedTransport.java +++ b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/transport/TestTFastFramedTransport.java @@ -19,13 +19,15 @@ package org.apache.thrift.transport; public class TestTFastFramedTransport extends TestTFramedTransport { + protected final static int INITIAL_CAPACITY = 50; + @Override protected TTransport getTransport(TTransport underlying) { - return new TFastFramedTransport(underlying, 50, 10 * 1024 * 1024); + return new TFastFramedTransport(underlying, INITIAL_CAPACITY, 10 * 1024 * 1024); } @Override protected TTransport getTransport(TTransport underlying, int maxLength) { - return new TFastFramedTransport(underlying, 50, maxLength); + return new TFastFramedTransport(underlying, INITIAL_CAPACITY, maxLength); } } diff --git a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/transport/TestTFramedTransport.java b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/transport/TestTFramedTransport.java index 6cebd3c..7e889d6 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/transport/TestTFramedTransport.java +++ b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/transport/TestTFramedTransport.java @@ -183,4 +183,32 @@ public class TestTFramedTransport extends TestCase { assertEquals(65, trans.getBytesRemainingInBuffer()); assertEquals(10, trans.getBufferPosition()); } + + public void testClear() throws IOException, TTransportException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + dos.writeInt(220); + dos.write(byteSequence(0, 219)); + + TMemoryBuffer membuf = new TMemoryBuffer(0); + membuf.write(baos.toByteArray()); + + ReadCountingTransport countTrans = new ReadCountingTransport(membuf); + TTransport trans = getTransport(countTrans); + + byte[] readBuf = new byte[220]; + trans.read(readBuf, 0, 220); + assertTrue(Arrays.equals(readBuf, byteSequence(0,219))); + + assertTrue(trans instanceof TFramedTransport || trans instanceof TFastFramedTransport); + if (trans instanceof TFramedTransport) { + assertTrue(trans.getBuffer() != null && trans.getBuffer().length > 0); + ((TFramedTransport) trans).clear(); + assertTrue(trans.getBuffer() == null); + } else if (trans instanceof TFastFramedTransport) { + assertTrue(trans.getBuffer().length > TestTFastFramedTransport.INITIAL_CAPACITY); + ((TFastFramedTransport) trans).clear(); + assertTrue(trans.getBuffer().length == TestTFastFramedTransport.INITIAL_CAPACITY); + } + } } diff --git a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/transport/TestTSSLTransportFactory.java b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/transport/TestTSSLTransportFactory.java index 478407a..032c2eb 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/transport/TestTSSLTransportFactory.java +++ b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/transport/TestTSSLTransportFactory.java @@ -45,6 +45,10 @@ public class TestTSSLTransportFactory extends ServerTestBase { throws Exception { return TSSLTransportFactory.getClientSocket(HOST, PORT); } + + protected TServerSocket getServerTransport() throws Exception { + return TSSLTransportFactory.getServerSocket(PORT); + } @Override public void startServer(final TProcessor processor, final TProtocolFactory protoFactory, final TTransportFactory factory) @@ -52,11 +56,11 @@ public class TestTSSLTransportFactory extends ServerTestBase { serverThread = new Thread() { public void run() { try { - TServerTransport serverTransport = TSSLTransportFactory.getServerSocket(PORT); + TServerTransport serverTransport = getServerTransport(); final Args args = new Args(serverTransport).processor(processor); server = new TSimpleServer(args); server.serve(); - } catch (TTransportException e) { + } catch (Exception e) { e.printStackTrace(); assert false; } @@ -64,7 +68,7 @@ public class TestTSSLTransportFactory extends ServerTestBase { }; serverThread.start(); - Thread.sleep(1000); + Thread.sleep(SLEEP_DELAY); } @Override diff --git a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/transport/TestTSSLTransportFactoryStreamedStore.java b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/transport/TestTSSLTransportFactoryStreamedStore.java new file mode 100644 index 0000000..25bf5ce --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/transport/TestTSSLTransportFactoryStreamedStore.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +package org.apache.thrift.transport; + +import java.io.FileInputStream; +import java.net.InetAddress; + +public class TestTSSLTransportFactoryStreamedStore extends TestTSSLTransportFactory { + private static String keyStoreLocation = System.getProperty("javax.net.ssl.keyStore"); + private static String trustStoreLocation = System.getProperty("javax.net.ssl.trustStore"); + + public TestTSSLTransportFactoryStreamedStore() { + super(); + + /** + * Override system properties to be able to test passing + * the trustStore and keyStore as input stream + */ + System.setProperty("javax.net.ssl.trustStore", ""); + System.setProperty("javax.net.ssl.keyStore", ""); + } + + @Override + public TTransport getClientTransport(TTransport underlyingTransport) + throws Exception { + TSSLTransportFactory.TSSLTransportParameters params = new + TSSLTransportFactory.TSSLTransportParameters(); + + params.setTrustStore(new FileInputStream(trustStoreLocation), + System.getProperty("javax.net.ssl.trustStorePassword")); + + return TSSLTransportFactory.getClientSocket(HOST, PORT, 0/*timeout*/, params); + } + + @Override + protected TServerSocket getServerTransport() throws Exception { + TSSLTransportFactory.TSSLTransportParameters params = new + TSSLTransportFactory.TSSLTransportParameters(); + + params.setKeyStore(new FileInputStream(keyStoreLocation), + System.getProperty("javax.net.ssl.keyStorePassword")); + + return TSSLTransportFactory.getServerSocket(PORT, 0/*timeout*/, InetAddress.getByName(HOST), params); + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/transport/TestTSimpleFileTransport.java b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/transport/TestTSimpleFileTransport.java index 5d2fb45..7b880f4 100644 --- a/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/transport/TestTSimpleFileTransport.java +++ b/vendor/git.apache.org/thrift.git/lib/java/test/org/apache/thrift/transport/TestTSimpleFileTransport.java @@ -27,21 +27,21 @@ public class TestTSimpleFileTransport extends TestCase { public void testFresh() throws Exception { //Test write side Path tempFilePathName = Files.createTempFile("TSimpleFileTransportTest", null); - Files.delete(tempFilePathName); + Files.delete(tempFilePathName); byte[] input_buf = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; TSimpleFileTransport trans_write = new TSimpleFileTransport(tempFilePathName.toString(),false, true, false); assert (!trans_write.isOpen()); trans_write.open(); assert(trans_write.isOpen()); trans_write.write(input_buf); - trans_write.write(input_buf,2,2); + trans_write.write(input_buf,2,2); trans_write.flush(); trans_write.close(); - + //Test read side TSimpleFileTransport trans = new TSimpleFileTransport(tempFilePathName.toString(),true, false); - assert(trans_write.isOpen()); - + assert(trans.isOpen()); + //Simple file trans provides no buffer access assert(0 == trans.getBufferPosition()); assert(null == trans.getBuffer()); @@ -56,19 +56,19 @@ public class TestTSimpleFileTransport extends TestCase { trans.readAll(buf1, 0, BUFSIZ); assert(BUFSIZ == trans.getFilePointer()); assert(Arrays.equals(new byte[]{1, 2, 3, 4}, buf1)); - + int bytesRead = trans.read(buf1, 0, BUFSIZ); assert(bytesRead > 0); for (int i = 0; i < bytesRead; ++i) { - assert(buf1[i] == i+5); + assert(buf1[i] == i+5); } - + trans.seek(0); assert(0 == trans.getFilePointer()); trans.readAll(buf1, 0, BUFSIZ); assert(Arrays.equals(new byte[]{1, 2, 3, 4}, buf1)); assert(BUFSIZ == trans.getFilePointer()); trans.close(); - Files.delete(tempFilePathName); + Files.delete(tempFilePathName); } } diff --git a/vendor/git.apache.org/thrift.git/lib/js/Gruntfile.js b/vendor/git.apache.org/thrift.git/lib/js/Gruntfile.js index bff250f..bb7691a 100644 --- a/vendor/git.apache.org/thrift.git/lib/js/Gruntfile.js +++ b/vendor/git.apache.org/thrift.git/lib/js/Gruntfile.js @@ -3,6 +3,7 @@ //Prerequisites: // Node Setup - nodejs.org // Grunt Setup - npm install //reads the ./package.json and installs project dependencies +// Run grunt - npx grunt // uses project-local installed version of grunt (from package.json) module.exports = function(grunt) { 'use strict'; @@ -38,112 +39,216 @@ module.exports = function(grunt) { }, shell: { InstallThriftJS: { - command: 'mkdir test/build; mkdir test/build/js; cp src/thrift.js test/build/js/thrift.js' + command: 'mkdir -p test/build/js/lib; cp src/thrift.js test/build/js/thrift.js' }, InstallThriftNodeJSDep: { command: 'cd ../..; npm install' }, + InstallTestLibs: { + command: 'cd test; ant download_jslibs' + }, ThriftGen: { - command: '../../compiler/cpp/thrift -gen js -gen js:node -o test ../../test/ThriftTest.thrift' + command: [ + 'mkdir -p test/gen-js', + '../../compiler/cpp/thrift -gen js --out test/gen-js ../../test/ThriftTest.thrift', + '../../compiler/cpp/thrift -gen js --out test/gen-js ../../test/JsDeepConstructorTest.thrift', + 'mkdir -p test/gen-js-jquery', + '../../compiler/cpp/thrift -gen js:jquery --out test/gen-js-jquery ../../test/ThriftTest.thrift', + 'mkdir -p test/gen-nodejs', + '../../compiler/cpp/thrift -gen js:node --out test/gen-nodejs ../../test/ThriftTest.thrift', + 'mkdir -p test/gen-js-es6', + '../../compiler/cpp/thrift -gen js:es6 --out test/gen-js-es6 ../../test/ThriftTest.thrift', + 'mkdir -p test/gen-nodejs-es6', + '../../compiler/cpp/thrift -gen js:node,es6 --out ./test/gen-nodejs-es6 ../../test/ThriftTest.thrift', + ].join(' && ') }, ThriftGenJQ: { command: '../../compiler/cpp/thrift -gen js:jquery -gen js:node -o test ../../test/ThriftTest.thrift' }, ThriftGenDeepConstructor: { command: '../../compiler/cpp/thrift -gen js -o test ../../test/JsDeepConstructorTest.thrift' - } - }, - external_daemon: { + }, + ThriftGenDoubleConstants: { + command: '../../compiler/cpp/thrift -gen js -o test ../../test/DoubleConstantsTest.thrift' + }, ThriftTestServer: { options: { - startCheck: function(stdout, stderr) { - return (/Thrift Server running on port/).test(stdout); - }, - nodeSpawnOptions: { - cwd: "test", - env: {NODE_PATH: "../../nodejs/lib:../../../node_modules"} - } + async: true, + execOptions: { + cwd: "./test", + env: {NODE_PATH: "../../nodejs/lib:../../../node_modules"} + } }, - cmd: "node", - args: ["server_http.js"] + command: "node server_http.js", + }, + ThriftTestServerES6: { + options: { + async: true, + execOptions: { + cwd: "./test", + env: {NODE_PATH: "../../nodejs/lib:../../../node_modules"} + } + }, + command: "node server_http.js --es6", }, ThriftTestServer_TLS: { options: { - startCheck: function(stdout, stderr) { - return (/Thrift Server running on port/).test(stdout); - }, - nodeSpawnOptions: { - cwd: "test", - env: {NODE_PATH: "../../nodejs/lib:../../../node_modules"} - } + async: true, + execOptions: { + cwd: "./test", + env: {NODE_PATH: "../../nodejs/lib:../../../node_modules"} + } }, - cmd: "node", - args: ["server_https.js"] - } + command: "node server_https.js", + }, + ThriftTestServerES6_TLS: { + options: { + async: true, + execOptions: { + cwd: "./test", + env: {NODE_PATH: "../../nodejs/lib:../../../node_modules"} + } + }, + command: "node server_https.js --es6", + }, }, qunit: { ThriftJS: { options: { urls: [ - 'http://localhost:8088/test-nojq.html' - ] + 'http://localhost:8089/test-nojq.html' + ], + puppeteer: { + headless: true, + args: ['--no-sandbox'], + }, } }, ThriftJSJQ: { options: { urls: [ - 'http://localhost:8088/test.html' - ] + 'http://localhost:8089/test.html' + ], + puppeteer: { + headless: true, + args: ['--no-sandbox'], + }, + } + }, + ThriftJS_DoubleRendering: { + options: { + urls: [ + 'http://localhost:8089/test-double-rendering.html' + ], + puppeteer: { + headless: true, + args: ['--no-sandbox'], + ignoreHTTPSErrors: true, + }, } }, ThriftWS: { options: { urls: [ - 'http://localhost:8088/testws.html' - ] + 'http://localhost:8089/testws.html' + ], + puppeteer: { + headless: true, + args: ['--no-sandbox'], + }, } }, ThriftJS_TLS: { options: { - '--ignore-ssl-errors': true, urls: [ - 'https://localhost:8089/test-nojq.html' - ] + 'https://localhost:8091/test-nojq.html' + ], + puppeteer: { + headless: true, + args: ['--no-sandbox'], + ignoreHTTPSErrors: true, + }, } }, ThriftJSJQ_TLS: { options: { - '--ignore-ssl-errors': true, urls: [ - 'https://localhost:8089/test.html' - ] + 'https://localhost:8091/test.html' + ], + puppeteer: { + headless: true, + args: ['--no-sandbox'], + ignoreHTTPSErrors: true, + }, } }, ThriftWS_TLS: { options: { - '--ignore-ssl-errors': true, urls: [ - 'https://localhost:8089/testws.html' - ] + 'https://localhost:8091/testws.html' + ], + puppeteer: { + headless: true, + args: ['--no-sandbox'], + ignoreHTTPSErrors: true, + }, } }, ThriftDeepConstructor: { options: { urls: [ - 'http://localhost:8088/test-deep-constructor.html' - ] + 'http://localhost:8089/test-deep-constructor.html' + ], + puppeteer: { + headless: true, + args: ['--no-sandbox'], + }, + } + }, + ThriftWSES6: { + options: { + urls: [ + 'http://localhost:8088/test-es6.html' + ], + puppeteer: { + headless: true, + args: ['--no-sandbox'], + }, } } }, jshint: { - files: ['Gruntfile.js', 'src/**/*.js', 'test/*.js'], - options: { - // options here to override JSHint defaults - globals: { - jQuery: true, - console: true, - module: true, - document: true + // The main thrift library file. not es6 yet :( + lib: { + src: ['src/**/*.js'], + }, + // The test files use es6 + test: { + src: ['Gruntfile.js', 'test/*.js'], + options: { + esversion: 6, + } + }, + gen_js_code: { + src: ['test/gen-js/*.js', 'test/gen-js-jquery/*.js'], + }, + gen_es6_code: { + src: ['test/gen-js-es6/*.js'], + options: { + esversion: 6, + } + }, + gen_node_code: { + src: ['test/gen-nodejs/*.js'], + options: { + node: true, + } + }, + gen_node_es6_code: { + src: ['test/gen-nodejs-es6/*.js'], + options: { + node: true, + esversion: 6, } } }, @@ -154,19 +259,34 @@ module.exports = function(grunt) { grunt.loadNpmTasks('grunt-contrib-qunit'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-jsdoc'); - grunt.loadNpmTasks('grunt-external-daemon'); - grunt.loadNpmTasks('grunt-shell'); + grunt.loadNpmTasks('grunt-shell-spawn'); - grunt.registerTask('test', ['jshint', 'shell:InstallThriftJS', 'shell:InstallThriftNodeJSDep', 'shell:ThriftGen', - 'external_daemon:ThriftTestServer', 'external_daemon:ThriftTestServer_TLS', - 'shell:ThriftGenDeepConstructor', 'qunit:ThriftDeepConstructor', - 'qunit:ThriftJS', 'qunit:ThriftJS_TLS', - 'shell:ThriftGenJQ', 'qunit:ThriftJSJQ', 'qunit:ThriftJSJQ_TLS' - ]); - grunt.registerTask('default', ['jshint', 'shell:InstallThriftJS', 'shell:InstallThriftNodeJSDep', 'shell:ThriftGen', - 'external_daemon:ThriftTestServer', 'external_daemon:ThriftTestServer_TLS', - 'qunit:ThriftJS', 'qunit:ThriftJS_TLS', - 'shell:ThriftGenJQ', 'qunit:ThriftJSJQ', 'qunit:ThriftJSJQ_TLS', - 'concat', 'uglify', 'jsdoc' - ]); + grunt.registerTask('wait', 'Wait just one second for server to start', function () { + var done = this.async(); + setTimeout(function() { + done(true); + }, 1000); + }); + + grunt.registerTask('installAndGenerate', [ + 'shell:InstallThriftJS', 'shell:InstallThriftNodeJSDep', 'shell:ThriftGen', + 'shell:ThriftGenDeepConstructor', + 'shell:InstallTestLibs', + ]); + + grunt.registerTask('test', [ + 'installAndGenerate', + 'jshint', + 'shell:ThriftTestServer', 'shell:ThriftTestServer_TLS', + 'shell:ThriftTestServerES6', 'shell:ThriftTestServerES6_TLS', + 'wait', + 'qunit:ThriftDeepConstructor', + 'qunit:ThriftJS', 'qunit:ThriftJS_TLS', + 'qunit:ThriftWS', + 'qunit:ThriftJSJQ', 'qunit:ThriftJSJQ_TLS', + 'qunit:ThriftWSES6', + 'shell:ThriftTestServer:kill', 'shell:ThriftTestServer_TLS:kill', + 'shell:ThriftTestServerES6:kill', 'shell:ThriftTestServerES6_TLS:kill', + ]); + grunt.registerTask('default', ['test', 'concat', 'uglify', 'jsdoc']); }; diff --git a/vendor/git.apache.org/thrift.git/lib/js/Makefile.am b/vendor/git.apache.org/thrift.git/lib/js/Makefile.am index 9a27e9d..9ea20a4 100644 --- a/vendor/git.apache.org/thrift.git/lib/js/Makefile.am +++ b/vendor/git.apache.org/thrift.git/lib/js/Makefile.am @@ -18,10 +18,13 @@ # # Make sure this doesn't fail if ant is not configured. - +# We call install twice to work around npm issues +# +if HAVE_NPM SUBDIRS = test check-local: all - npm install + $(NPM) install || $(NPM) install + $(NPM) list ./node_modules/.bin/grunt - +endif diff --git a/vendor/git.apache.org/thrift.git/lib/js/README.md b/vendor/git.apache.org/thrift.git/lib/js/README.md index dfa6e82..9d51e2a 100644 --- a/vendor/git.apache.org/thrift.git/lib/js/README.md +++ b/vendor/git.apache.org/thrift.git/lib/js/README.md @@ -38,19 +38,12 @@ This reads the package.json and pulls in the appropriate sources from the internet. To build the JavaScript branch of Apache Thrift execute the command: - grunt + npx grunt -This runs the grunt build tool, linting all of the source -files, setting up and running the tests, concatenating and -minifying the main libraries and generating the html -documentation. - -If grunt is not installed you can install it with npm -like this: - - sudo npm install -g grunt-cli - npm install grunt --save-dev - +This runs the grunt build tool (from within `./node_modules/.bin/`), +linting all of the source files, setting up and running the +tests, concatenating and minifying the main libraries and +generating the html documentation. Tree ---- diff --git a/vendor/git.apache.org/thrift.git/lib/js/package-lock.json b/vendor/git.apache.org/thrift.git/lib/js/package-lock.json new file mode 100644 index 0000000..63d81c3 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/js/package-lock.json @@ -0,0 +1,3777 @@ +{ + "name": "thrift", + "version": "1.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==" + }, + "agent-base": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-4.2.1.tgz", + "integrity": "sha512-JVwXMr9nHYTUXsBFKUqhJwvlcYU/blreOEUkhNR2eXZIvwd+c+o5V4MgDPKWnMS/56awN3TRzIP+KoPn+roQtg==", + "dev": true, + "requires": { + "es6-promisify": "^5.0.0" + } + }, + "ajv": { + "version": "5.5.2", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-5.5.2.tgz", + "integrity": "sha1-c7Xuyj+rZT49P5Qis0GtQiBdyWU=", + "dev": true, + "optional": true, + "requires": { + "co": "^4.6.0", + "fast-deep-equal": "^1.0.0", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.3.0" + } + }, + "align-text": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/align-text/-/align-text-0.1.4.tgz", + "integrity": "sha1-DNkKVhCT810KmSVsIrcGlDP60Rc=", + "dev": true, + "requires": { + "kind-of": "^3.0.2", + "longest": "^1.0.1", + "repeat-string": "^1.5.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "requires": { + "sprintf-js": "~1.0.2" + }, + "dependencies": { + "sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", + "dev": true + } + } + }, + "arr-diff": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz", + "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", + "dev": true + }, + "arr-flatten": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/arr-flatten/-/arr-flatten-1.1.0.tgz", + "integrity": "sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==", + "dev": true + }, + "arr-union": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-3.1.0.tgz", + "integrity": "sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=", + "dev": true + }, + "array-each": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/array-each/-/array-each-1.0.1.tgz", + "integrity": "sha1-p5SvDAWrF1KEbudTofIRoFugxE8=", + "dev": true + }, + "array-find-index": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-find-index/-/array-find-index-1.0.2.tgz", + "integrity": "sha1-3wEKoSh+Fku9pvlyOwqWoexBh6E=", + "dev": true + }, + "array-slice": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/array-slice/-/array-slice-1.1.0.tgz", + "integrity": "sha512-B1qMD3RBP7O8o0H2KbrXDyB0IccejMF15+87Lvlor12ONPRHP6gTjXMNkt/d3ZuOGbAe66hFmaCfECI24Ufp6w==", + "dev": true + }, + "array-unique": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz", + "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", + "dev": true + }, + "asn1": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.4.tgz", + "integrity": "sha512-jxwzQpLQjSmWXgwaCZE9Nz+glAG01yF1QnWgbhGwHI5A6FRIEY6IVqtHhIepHqI7/kyEyQEagBC5mBEFlIYvdg==", + "dev": true, + "optional": true, + "requires": { + "safer-buffer": "~2.1.0" + } + }, + "assert-plus": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", + "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=", + "dev": true + }, + "assign-symbols": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assign-symbols/-/assign-symbols-1.0.0.tgz", + "integrity": "sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=", + "dev": true + }, + "async": { + "version": "1.5.2", + "resolved": "http://registry.npmjs.org/async/-/async-1.5.2.tgz", + "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=", + "dev": true + }, + "async-limiter": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz", + "integrity": "sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg==", + "dev": true + }, + "asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=", + "dev": true, + "optional": true + }, + "atob": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/atob/-/atob-2.1.2.tgz", + "integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==", + "dev": true + }, + "aws-sign2": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", + "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=", + "dev": true, + "optional": true + }, + "aws4": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.8.0.tgz", + "integrity": "sha512-ReZxvNHIOv88FlT7rxcXIIC0fPt4KZqZbOlivyWtXLt8ESx84zd3kMC6iK5jVeS2qt+g7ftS7ye4fi06X5rtRQ==", + "dev": true, + "optional": true + }, + "babylon": { + "version": "7.0.0-beta.19", + "resolved": "https://registry.npmjs.org/babylon/-/babylon-7.0.0-beta.19.tgz", + "integrity": "sha512-Vg0C9s/REX6/WIXN37UKpv5ZhRi6A4pjHlpkE34+8/a6c2W1Q692n3hmc+SZG5lKRnaExLUbxtJ1SVT+KaCQ/A==" + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "base": { + "version": "0.11.2", + "resolved": "https://registry.npmjs.org/base/-/base-0.11.2.tgz", + "integrity": "sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg==", + "dev": true, + "requires": { + "cache-base": "^1.0.1", + "class-utils": "^0.3.5", + "component-emitter": "^1.2.1", + "define-property": "^1.0.0", + "isobject": "^3.0.1", + "mixin-deep": "^1.2.0", + "pascalcase": "^0.1.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "bcrypt-pbkdf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", + "dev": true, + "optional": true, + "requires": { + "tweetnacl": "^0.14.3" + } + }, + "bluebird": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.2.tgz", + "integrity": "sha512-dhHTWMI7kMx5whMQntl7Vr9C6BvV10lFXDAasnqnrMYhXVCzzk6IO9Fo2L75jXHT07WrOngL1WDXOp+yYS91Yg==" + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "braces": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-2.3.2.tgz", + "integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==", + "dev": true, + "requires": { + "arr-flatten": "^1.1.0", + "array-unique": "^0.3.2", + "extend-shallow": "^2.0.1", + "fill-range": "^4.0.0", + "isobject": "^3.0.1", + "repeat-element": "^1.1.2", + "snapdragon": "^0.8.1", + "snapdragon-node": "^2.0.1", + "split-string": "^3.0.2", + "to-regex": "^3.0.1" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "browserify-zlib": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/browserify-zlib/-/browserify-zlib-0.1.4.tgz", + "integrity": "sha1-uzX4pRn2AOD6a4SFJByXnQFB+y0=", + "dev": true, + "requires": { + "pako": "~0.2.0" + } + }, + "buffer-from": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", + "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==", + "dev": true + }, + "buffer-shims": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/buffer-shims/-/buffer-shims-1.0.0.tgz", + "integrity": "sha1-mXjOMXOIxkmth5MCjDR37wRKi1E=", + "dev": true + }, + "builtin-modules": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-1.1.1.tgz", + "integrity": "sha1-Jw8HbFpywC9bZaR9+Uxf46J4iS8=", + "dev": true + }, + "cache-base": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/cache-base/-/cache-base-1.0.1.tgz", + "integrity": "sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ==", + "dev": true, + "requires": { + "collection-visit": "^1.0.0", + "component-emitter": "^1.2.1", + "get-value": "^2.0.6", + "has-value": "^1.0.0", + "isobject": "^3.0.1", + "set-value": "^2.0.0", + "to-object-path": "^0.3.0", + "union-value": "^1.0.0", + "unset-value": "^1.0.0" + } + }, + "camelcase": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-2.1.1.tgz", + "integrity": "sha1-fB0W1nmhu+WcoCys7PsBHiAfWh8=", + "dev": true + }, + "camelcase-keys": { + "version": "2.1.0", + "resolved": "http://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz", + "integrity": "sha1-MIvur/3ygRkFHvodkyITyRuPkuc=", + "dev": true, + "requires": { + "camelcase": "^2.0.0", + "map-obj": "^1.0.0" + } + }, + "caseless": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", + "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=", + "dev": true, + "optional": true + }, + "catharsis": { + "version": "0.8.9", + "resolved": "https://registry.npmjs.org/catharsis/-/catharsis-0.8.9.tgz", + "integrity": "sha1-mMyJDKZS3S7w5ws3klMQ/56Q/Is=", + "requires": { + "underscore-contrib": "~0.3.0" + } + }, + "center-align": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/center-align/-/center-align-0.1.3.tgz", + "integrity": "sha1-qg0yYptu6XIgBBHL1EYckHvCt60=", + "dev": true, + "requires": { + "align-text": "^0.1.3", + "lazy-cache": "^1.0.3" + } + }, + "chalk": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", + "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "class-utils": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz", + "integrity": "sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg==", + "dev": true, + "requires": { + "arr-union": "^3.1.0", + "define-property": "^0.2.5", + "isobject": "^3.0.0", + "static-extend": "^0.1.1" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + } + } + }, + "cli": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/cli/-/cli-1.0.1.tgz", + "integrity": "sha1-IoF1NPJL+klQw01TLUjsvGIbjBQ=", + "dev": true, + "requires": { + "exit": "0.1.2", + "glob": "^7.1.1" + }, + "dependencies": { + "glob": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.3.tgz", + "integrity": "sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + } + } + }, + "cliui": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-2.1.0.tgz", + "integrity": "sha1-S0dXYP+AJkx2LDoXGQMukcf+oNE=", + "dev": true, + "requires": { + "center-align": "^0.1.1", + "right-align": "^0.1.1", + "wordwrap": "0.0.2" + } + }, + "co": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", + "integrity": "sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ=", + "dev": true, + "optional": true + }, + "coffeescript": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/coffeescript/-/coffeescript-1.10.0.tgz", + "integrity": "sha1-56qDAZF+9iGzXYo580jc3R234z4=", + "dev": true + }, + "collection-visit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/collection-visit/-/collection-visit-1.0.0.tgz", + "integrity": "sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA=", + "dev": true, + "requires": { + "map-visit": "^1.0.0", + "object-visit": "^1.0.0" + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", + "dev": true + }, + "colors": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.1.2.tgz", + "integrity": "sha1-FopHAXVran9RoSzgyXv6KMCE7WM=", + "dev": true + }, + "combined-stream": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.7.tgz", + "integrity": "sha512-brWl9y6vOB1xYPZcpZde3N9zDByXTosAeMDo4p1wzo6UMOX4vumB+TP1RZ76sfE6Md68Q0NJSrE/gbezd4Ul+w==", + "dev": true, + "requires": { + "delayed-stream": "~1.0.0" + } + }, + "component-emitter": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.2.1.tgz", + "integrity": "sha1-E3kY1teCg/ffemt8WmPhQOaUJeY=", + "dev": true + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "concat-stream": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.6", + "resolved": "http://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", + "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } + } + }, + "console-browserify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.1.0.tgz", + "integrity": "sha1-8CQcRXMKn8YyOyBtvzjtx0HQuxA=", + "dev": true, + "requires": { + "date-now": "^0.1.4" + } + }, + "copy-descriptor": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz", + "integrity": "sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=", + "dev": true + }, + "core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", + "dev": true + }, + "cross-spawn": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", + "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", + "dev": true, + "requires": { + "nice-try": "^1.0.4", + "path-key": "^2.0.1", + "semver": "^5.5.0", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + } + }, + "currently-unhandled": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/currently-unhandled/-/currently-unhandled-0.4.1.tgz", + "integrity": "sha1-mI3zP+qxke95mmE2nddsF635V+o=", + "dev": true, + "requires": { + "array-find-index": "^1.0.1" + } + }, + "cycle": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz", + "integrity": "sha1-IegLK+hYD5i0aPN5QwZisEbDStI=", + "dev": true, + "optional": true + }, + "dashdash": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", + "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", + "dev": true, + "optional": true, + "requires": { + "assert-plus": "^1.0.0" + } + }, + "date-now": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/date-now/-/date-now-0.1.4.tgz", + "integrity": "sha1-6vQ5/U1ISK105cx9vvIAZyueNFs=", + "dev": true + }, + "dateformat": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-1.0.12.tgz", + "integrity": "sha1-nxJLZ1lMk3/3BpMuSmQsyo27/uk=", + "dev": true, + "requires": { + "get-stdin": "^4.0.1", + "meow": "^3.3.0" + } + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", + "dev": true + }, + "decode-uri-component": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz", + "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=", + "dev": true + }, + "define-property": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-2.0.2.tgz", + "integrity": "sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ==", + "dev": true, + "requires": { + "is-descriptor": "^1.0.2", + "isobject": "^3.0.1" + }, + "dependencies": { + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=", + "dev": true + }, + "detect-file": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/detect-file/-/detect-file-1.0.0.tgz", + "integrity": "sha1-8NZtA2cqglyxtzvbP+YjEMjlUrc=", + "dev": true + }, + "dom-serializer": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-0.1.0.tgz", + "integrity": "sha1-BzxpdUbOB4DOI75KKOKT5AvDDII=", + "dev": true, + "requires": { + "domelementtype": "~1.1.1", + "entities": "~1.1.1" + }, + "dependencies": { + "domelementtype": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.1.3.tgz", + "integrity": "sha1-vSh3PiZCiBrsUVRJJCmcXNgiGFs=", + "dev": true + }, + "entities": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-1.1.1.tgz", + "integrity": "sha1-blwtClYhtdra7O+AuQ7ftc13cvA=", + "dev": true + } + } + }, + "domelementtype": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.3.0.tgz", + "integrity": "sha1-sXrtguirWeUt2cGbF1bg/BhyBMI=", + "dev": true + }, + "domhandler": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-2.3.0.tgz", + "integrity": "sha1-LeWaCCLVAn+r/28DLCsloqir5zg=", + "dev": true, + "requires": { + "domelementtype": "1" + } + }, + "domutils": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.5.1.tgz", + "integrity": "sha1-3NhIiib1Y9YQeeSMn3t+Mjc2gs8=", + "dev": true, + "requires": { + "dom-serializer": "0", + "domelementtype": "1" + } + }, + "ecc-jsbn": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", + "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=", + "dev": true, + "optional": true, + "requires": { + "jsbn": "~0.1.0", + "safer-buffer": "^2.1.0" + } + }, + "entities": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-1.0.0.tgz", + "integrity": "sha1-sph6o4ITR/zeZCsk/fyeT7cSvyY=", + "dev": true + }, + "error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dev": true, + "requires": { + "is-arrayish": "^0.2.1" + } + }, + "es6-promise": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.5.tgz", + "integrity": "sha512-n6wvpdE43VFtJq+lUDYDBFUwV8TZbuGXLV4D6wKafg13ldznKsyEvatubnmUe31zcvelSzOHF+XbaT+Bl9ObDg==", + "dev": true + }, + "es6-promisify": { + "version": "5.0.0", + "resolved": "http://registry.npmjs.org/es6-promisify/-/es6-promisify-5.0.0.tgz", + "integrity": "sha1-UQnWLz5W6pZ8S2NQWu8IKRyKUgM=", + "dev": true, + "requires": { + "es6-promise": "^4.0.3" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" + }, + "esprima": { + "version": "2.7.3", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-2.7.3.tgz", + "integrity": "sha1-luO3DVd59q1JzQMmc9HDEnZ7pYE=", + "dev": true + }, + "eventemitter2": { + "version": "0.4.14", + "resolved": "http://registry.npmjs.org/eventemitter2/-/eventemitter2-0.4.14.tgz", + "integrity": "sha1-j2G3XN4BKy6esoTUVFWDtWQ7Yas=", + "dev": true + }, + "exit": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", + "integrity": "sha1-BjJjj42HfMghB9MKD/8aF8uhzQw=", + "dev": true + }, + "expand-brackets": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz", + "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=", + "dev": true, + "requires": { + "debug": "^2.3.3", + "define-property": "^0.2.5", + "extend-shallow": "^2.0.1", + "posix-character-classes": "^0.1.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "expand-tilde": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/expand-tilde/-/expand-tilde-2.0.2.tgz", + "integrity": "sha1-l+gBqgUt8CRU3kawK/YhZCzchQI=", + "dev": true, + "requires": { + "homedir-polyfill": "^1.0.1" + } + }, + "extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "dev": true + }, + "extend-shallow": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-3.0.2.tgz", + "integrity": "sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=", + "dev": true, + "requires": { + "assign-symbols": "^1.0.0", + "is-extendable": "^1.0.1" + }, + "dependencies": { + "is-extendable": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", + "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", + "dev": true, + "requires": { + "is-plain-object": "^2.0.4" + } + } + } + }, + "extglob": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.4.tgz", + "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==", + "dev": true, + "requires": { + "array-unique": "^0.3.2", + "define-property": "^1.0.0", + "expand-brackets": "^2.1.4", + "extend-shallow": "^2.0.1", + "fragment-cache": "^0.2.1", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "extract-zip": { + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-1.6.7.tgz", + "integrity": "sha1-qEC0uK9kAyZMjbV/Txp0Mz74H+k=", + "dev": true, + "requires": { + "concat-stream": "1.6.2", + "debug": "2.6.9", + "mkdirp": "0.5.1", + "yauzl": "2.4.1" + } + }, + "extsprintf": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", + "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=", + "dev": true + }, + "eyes": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/eyes/-/eyes-0.1.8.tgz", + "integrity": "sha1-Ys8SAjTGg3hdkCNIqADvPgzCC8A=", + "dev": true, + "optional": true + }, + "fast-deep-equal": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-1.1.0.tgz", + "integrity": "sha1-wFNHeBfIa1HaqFPIHgWbcz0CNhQ=", + "dev": true, + "optional": true + }, + "fast-json-stable-stringify": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz", + "integrity": "sha1-1RQsDK7msRifh9OnYREGT4bIu/I=", + "dev": true, + "optional": true + }, + "fd-slicer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.0.1.tgz", + "integrity": "sha1-i1vL2ewyfFBBv5qwI/1nUPEXfmU=", + "dev": true, + "requires": { + "pend": "~1.2.0" + } + }, + "figures": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-1.7.0.tgz", + "integrity": "sha1-y+Hjr/zxzUS4DK3+0o3Hk6lwHS4=", + "dev": true, + "requires": { + "escape-string-regexp": "^1.0.5", + "object-assign": "^4.1.0" + } + }, + "fill-range": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz", + "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=", + "dev": true, + "requires": { + "extend-shallow": "^2.0.1", + "is-number": "^3.0.0", + "repeat-string": "^1.6.1", + "to-regex-range": "^2.1.0" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "find-up": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-1.1.2.tgz", + "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=", + "dev": true, + "requires": { + "path-exists": "^2.0.0", + "pinkie-promise": "^2.0.0" + } + }, + "findup-sync": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-0.3.0.tgz", + "integrity": "sha1-N5MKpdgWt3fANEXhlmzGeQpMCxY=", + "dev": true, + "requires": { + "glob": "~5.0.0" + }, + "dependencies": { + "glob": { + "version": "5.0.15", + "resolved": "https://registry.npmjs.org/glob/-/glob-5.0.15.tgz", + "integrity": "sha1-G8k2ueAvSmA/zCIuz3Yz0wuLk7E=", + "dev": true, + "requires": { + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "2 || 3", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + } + } + }, + "fined": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fined/-/fined-1.1.0.tgz", + "integrity": "sha1-s33IRLdqL15wgeiE98CuNE8VNHY=", + "dev": true, + "requires": { + "expand-tilde": "^2.0.2", + "is-plain-object": "^2.0.3", + "object.defaults": "^1.1.0", + "object.pick": "^1.2.0", + "parse-filepath": "^1.0.1" + } + }, + "flagged-respawn": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/flagged-respawn/-/flagged-respawn-1.0.0.tgz", + "integrity": "sha1-Tnmumy6zi/hrO7Vr8+ClaqX8q9c=", + "dev": true + }, + "for-in": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", + "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=", + "dev": true + }, + "for-own": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/for-own/-/for-own-1.0.0.tgz", + "integrity": "sha1-xjMy9BXO3EsE2/5wz4NklMU8tEs=", + "dev": true, + "requires": { + "for-in": "^1.0.1" + } + }, + "forever-agent": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", + "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=", + "dev": true, + "optional": true + }, + "form-data": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz", + "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", + "dev": true, + "optional": true, + "requires": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.6", + "mime-types": "^2.1.12" + } + }, + "fragment-cache": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/fragment-cache/-/fragment-cache-0.2.1.tgz", + "integrity": "sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk=", + "dev": true, + "requires": { + "map-cache": "^0.2.2" + } + }, + "fs-extra": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-1.0.0.tgz", + "integrity": "sha1-zTzl9+fLYUWIP8rjGR6Yd/hYeVA=", + "dev": true, + "optional": true, + "requires": { + "graceful-fs": "^4.1.2", + "jsonfile": "^2.1.0", + "klaw": "^1.0.0" + }, + "dependencies": { + "klaw": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/klaw/-/klaw-1.3.1.tgz", + "integrity": "sha1-QIhDO0azsbolnXh4XY6W9zugJDk=", + "dev": true, + "optional": true, + "requires": { + "graceful-fs": "^4.1.9" + } + } + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "get-stdin": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-4.0.1.tgz", + "integrity": "sha1-uWjGsKBDhDJJAui/Gl3zJXmkUP4=", + "dev": true + }, + "get-value": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/get-value/-/get-value-2.0.6.tgz", + "integrity": "sha1-3BXKHGcjh8p2vTesCjlbogQqLCg=", + "dev": true + }, + "getobject": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/getobject/-/getobject-0.1.0.tgz", + "integrity": "sha1-BHpEl4n6Fg0Bj1SG7ZEyC27HiFw=", + "dev": true + }, + "getpass": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", + "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", + "dev": true, + "optional": true, + "requires": { + "assert-plus": "^1.0.0" + } + }, + "glob": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.0.6.tgz", + "integrity": "sha1-IRuvr0nlJbjNkyYNFKsTYVKz9Xo=", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.2", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "global-modules": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-1.0.0.tgz", + "integrity": "sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg==", + "dev": true, + "requires": { + "global-prefix": "^1.0.1", + "is-windows": "^1.0.1", + "resolve-dir": "^1.0.0" + } + }, + "global-prefix": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/global-prefix/-/global-prefix-1.0.2.tgz", + "integrity": "sha1-2/dDxsFJklk8ZVVoy2btMsASLr4=", + "dev": true, + "requires": { + "expand-tilde": "^2.0.2", + "homedir-polyfill": "^1.0.1", + "ini": "^1.3.4", + "is-windows": "^1.0.1", + "which": "^1.2.14" + } + }, + "graceful-fs": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", + "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=" + }, + "grunt": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/grunt/-/grunt-1.0.3.tgz", + "integrity": "sha512-/JzmZNPfKorlCrrmxWqQO4JVodO+DVd5XX4DkocL/1WlLlKVLE9+SdEIempOAxDhWPysLle6afvn/hg7Ck2k9g==", + "dev": true, + "requires": { + "coffeescript": "~1.10.0", + "dateformat": "~1.0.12", + "eventemitter2": "~0.4.13", + "exit": "~0.1.1", + "findup-sync": "~0.3.0", + "glob": "~7.0.0", + "grunt-cli": "~1.2.0", + "grunt-known-options": "~1.1.0", + "grunt-legacy-log": "~2.0.0", + "grunt-legacy-util": "~1.1.1", + "iconv-lite": "~0.4.13", + "js-yaml": "~3.5.2", + "minimatch": "~3.0.2", + "mkdirp": "~0.5.1", + "nopt": "~3.0.6", + "path-is-absolute": "~1.0.0", + "rimraf": "~2.6.2" + }, + "dependencies": { + "grunt-cli": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/grunt-cli/-/grunt-cli-1.2.0.tgz", + "integrity": "sha1-VisRnrsGndtGSs4oRVAb6Xs1tqg=", + "dev": true, + "requires": { + "findup-sync": "~0.3.0", + "grunt-known-options": "~1.1.0", + "nopt": "~3.0.6", + "resolve": "~1.1.0" + } + }, + "nopt": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-3.0.6.tgz", + "integrity": "sha1-xkZdvwirzU2zWTF/eaxopkayj/k=", + "dev": true, + "requires": { + "abbrev": "1" + } + } + } + }, + "grunt-cli": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/grunt-cli/-/grunt-cli-1.3.1.tgz", + "integrity": "sha512-UwBRu/QpAjDc53DRLEkyilFdL0zenpxu+fddTIlsF/KJqdNcHaQmvyu1W3cDesZ9rqqZdKK5A8+QDIyLUEWoZQ==", + "dev": true, + "requires": { + "grunt-known-options": "~1.1.0", + "interpret": "~1.1.0", + "liftoff": "~2.5.0", + "nopt": "~4.0.1", + "v8flags": "~3.0.2" + } + }, + "grunt-contrib-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/grunt-contrib-concat/-/grunt-contrib-concat-1.0.1.tgz", + "integrity": "sha1-YVCYYwhOhx1+ht5IwBUlntl3Rb0=", + "dev": true, + "requires": { + "chalk": "^1.0.0", + "source-map": "^0.5.3" + }, + "dependencies": { + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "chalk": { + "version": "1.1.3", + "resolved": "http://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + } + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + } + } + }, + "grunt-contrib-jshint": { + "version": "1.1.0", + "resolved": "http://registry.npmjs.org/grunt-contrib-jshint/-/grunt-contrib-jshint-1.1.0.tgz", + "integrity": "sha1-Np2QmyWTxA6L55lAshNAhQx5Oaw=", + "dev": true, + "requires": { + "chalk": "^1.1.1", + "hooker": "^0.2.3", + "jshint": "~2.9.4" + }, + "dependencies": { + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "chalk": { + "version": "1.1.3", + "resolved": "http://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + } + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + } + } + }, + "grunt-contrib-qunit": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/grunt-contrib-qunit/-/grunt-contrib-qunit-3.0.1.tgz", + "integrity": "sha512-s994+ipKwc+oUUIWaGIw1soyID4pExSGMd/cHQN5h0p8KbIjR1Le3ZC3giSDDKXtZFE0i+Obf0uIjNvjftX2Cw==", + "dev": true, + "requires": { + "eventemitter2": "^5.0.1", + "p-each-series": "^1.0.0", + "puppeteer": "1.7.0" + }, + "dependencies": { + "eventemitter2": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eventemitter2/-/eventemitter2-5.0.1.tgz", + "integrity": "sha1-YZegldX7a1folC9v1+qtY6CclFI=", + "dev": true + } + } + }, + "grunt-contrib-uglify": { + "version": "1.0.2", + "resolved": "http://registry.npmjs.org/grunt-contrib-uglify/-/grunt-contrib-uglify-1.0.2.tgz", + "integrity": "sha1-rmekb5FT7dTLEYE6Vetpxw19svs=", + "dev": true, + "requires": { + "chalk": "^1.0.0", + "lodash": "^4.0.1", + "maxmin": "^1.1.0", + "uglify-js": "~2.6.2", + "uri-path": "^1.0.0" + }, + "dependencies": { + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "chalk": { + "version": "1.1.3", + "resolved": "http://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + } + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + } + } + }, + "grunt-jsdoc": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/grunt-jsdoc/-/grunt-jsdoc-2.3.0.tgz", + "integrity": "sha512-gC66TCRXeQMj3HIyqVSBJm8zdUz43e5vaG/PLO/627A1edbJnzxhJV7nF0KqLwMM0RDNu1istC6fvfnYqFKi3w==", + "dev": true, + "requires": { + "cross-spawn": "^6.0.5", + "jsdoc": "~3.5.5", + "marked": "^0.5.0" + }, + "dependencies": { + "marked": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/marked/-/marked-0.5.1.tgz", + "integrity": "sha512-iUkBZegCZou4AdwbKTwSW/lNDcz5OuRSl3qdcl31Ia0B2QPG0Jn+tKblh/9/eP9/6+4h27vpoh8wel/vQOV0vw==", + "dev": true + } + } + }, + "grunt-known-options": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/grunt-known-options/-/grunt-known-options-1.1.1.tgz", + "integrity": "sha512-cHwsLqoighpu7TuYj5RonnEuxGVFnztcUqTqp5rXFGYL4OuPFofwC4Ycg7n9fYwvK6F5WbYgeVOwph9Crs2fsQ==", + "dev": true + }, + "grunt-legacy-log": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/grunt-legacy-log/-/grunt-legacy-log-2.0.0.tgz", + "integrity": "sha512-1m3+5QvDYfR1ltr8hjiaiNjddxGdQWcH0rw1iKKiQnF0+xtgTazirSTGu68RchPyh1OBng1bBUjLmX8q9NpoCw==", + "dev": true, + "requires": { + "colors": "~1.1.2", + "grunt-legacy-log-utils": "~2.0.0", + "hooker": "~0.2.3", + "lodash": "~4.17.5" + } + }, + "grunt-legacy-log-utils": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/grunt-legacy-log-utils/-/grunt-legacy-log-utils-2.0.1.tgz", + "integrity": "sha512-o7uHyO/J+i2tXG8r2bZNlVk20vlIFJ9IEYyHMCQGfWYru8Jv3wTqKZzvV30YW9rWEjq0eP3cflQ1qWojIe9VFA==", + "dev": true, + "requires": { + "chalk": "~2.4.1", + "lodash": "~4.17.10" + } + }, + "grunt-legacy-util": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/grunt-legacy-util/-/grunt-legacy-util-1.1.1.tgz", + "integrity": "sha512-9zyA29w/fBe6BIfjGENndwoe1Uy31BIXxTH3s8mga0Z5Bz2Sp4UCjkeyv2tI449ymkx3x26B+46FV4fXEddl5A==", + "dev": true, + "requires": { + "async": "~1.5.2", + "exit": "~0.1.1", + "getobject": "~0.1.0", + "hooker": "~0.2.3", + "lodash": "~4.17.10", + "underscore.string": "~3.3.4", + "which": "~1.3.0" + } + }, + "grunt-shell-spawn": { + "version": "0.3.10", + "resolved": "https://registry.npmjs.org/grunt-shell-spawn/-/grunt-shell-spawn-0.3.10.tgz", + "integrity": "sha1-gbuNRX7EfTGCqH1jCO+EXd+5SI8=", + "dev": true, + "requires": { + "grunt": ">=0.4.x", + "sync-exec": "~0.6.2" + } + }, + "gzip-size": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gzip-size/-/gzip-size-1.0.0.tgz", + "integrity": "sha1-Zs+LEBBHInuVus5uodoMF37Vwi8=", + "dev": true, + "requires": { + "browserify-zlib": "^0.1.4", + "concat-stream": "^1.4.1" + } + }, + "har-schema": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", + "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=", + "dev": true, + "optional": true + }, + "har-validator": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.0.tgz", + "integrity": "sha512-+qnmNjI4OfH2ipQ9VQOw23bBd/ibtfbVdK2fYbY4acTDqKTW/YDp9McimZdDbG8iV9fZizUqQMD5xvriB146TA==", + "dev": true, + "optional": true, + "requires": { + "ajv": "^5.3.0", + "har-schema": "^2.0.0" + } + }, + "has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "dev": true + }, + "has-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-value/-/has-value-1.0.0.tgz", + "integrity": "sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc=", + "dev": true, + "requires": { + "get-value": "^2.0.6", + "has-values": "^1.0.0", + "isobject": "^3.0.0" + } + }, + "has-values": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-values/-/has-values-1.0.0.tgz", + "integrity": "sha1-lbC2P+whRmGab+V/51Yo1aOe/k8=", + "dev": true, + "requires": { + "is-number": "^3.0.0", + "kind-of": "^4.0.0" + }, + "dependencies": { + "kind-of": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-4.0.0.tgz", + "integrity": "sha1-IIE989cSkosgc3hpGkUGb65y3Vc=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "hasha": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/hasha/-/hasha-2.2.0.tgz", + "integrity": "sha1-eNfL/B5tZjA/55g3NlmEUXsvbuE=", + "dev": true, + "optional": true, + "requires": { + "is-stream": "^1.0.1", + "pinkie-promise": "^2.0.0" + } + }, + "homedir-polyfill": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/homedir-polyfill/-/homedir-polyfill-1.0.1.tgz", + "integrity": "sha1-TCu8inWJmP7r9e1oWA921GdotLw=", + "dev": true, + "requires": { + "parse-passwd": "^1.0.0" + } + }, + "hooker": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/hooker/-/hooker-0.2.3.tgz", + "integrity": "sha1-uDT3I8xKJCqmWWNFnfbZhMXT2Vk=", + "dev": true + }, + "hosted-git-info": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.7.1.tgz", + "integrity": "sha512-7T/BxH19zbcCTa8XkMlbK5lTo1WtgkFi3GvdWEyNuc4Vex7/9Dqbnpsf4JMydcfj9HCg4zUWFTL3Za6lapg5/w==", + "dev": true + }, + "htmlparser2": { + "version": "3.8.3", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.8.3.tgz", + "integrity": "sha1-mWwosZFRaovoZQGn15dX5ccMEGg=", + "dev": true, + "requires": { + "domelementtype": "1", + "domhandler": "2.3", + "domutils": "1.5", + "entities": "1.0", + "readable-stream": "1.1" + } + }, + "http-signature": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", + "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=", + "dev": true, + "optional": true, + "requires": { + "assert-plus": "^1.0.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" + } + }, + "https-proxy-agent": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-2.2.1.tgz", + "integrity": "sha512-HPCTS1LW51bcyMYbxUIOO4HEOlQ1/1qRaFWcyxvwaqUS9TY88aoEuHUY33kuAh1YhVVaDQhLZsnPd+XNARWZlQ==", + "dev": true, + "requires": { + "agent-base": "^4.1.0", + "debug": "^3.1.0" + }, + "dependencies": { + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", + "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", + "dev": true + } + } + }, + "iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dev": true, + "requires": { + "safer-buffer": ">= 2.1.2 < 3" + } + }, + "indent-string": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-2.1.0.tgz", + "integrity": "sha1-ji1INIdCEhtKghi3oTfppSBJ3IA=", + "dev": true, + "requires": { + "repeating": "^2.0.0" + } + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "ini": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.5.tgz", + "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==", + "dev": true + }, + "interpret": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.1.0.tgz", + "integrity": "sha1-ftGxQQxqDg94z5XTuEQMY/eLhhQ=", + "dev": true + }, + "is-absolute": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-absolute/-/is-absolute-1.0.0.tgz", + "integrity": "sha512-dOWoqflvcydARa360Gvv18DZ/gRuHKi2NU/wU5X1ZFzdYfH29nkiNZsF3mp4OJ3H4yo9Mx8A/uAGNzpzPN3yBA==", + "dev": true, + "requires": { + "is-relative": "^1.0.0", + "is-windows": "^1.0.1" + } + }, + "is-accessor-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", + "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", + "dev": true + }, + "is-buffer": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", + "dev": true + }, + "is-builtin-module": { + "version": "1.0.0", + "resolved": "http://registry.npmjs.org/is-builtin-module/-/is-builtin-module-1.0.0.tgz", + "integrity": "sha1-VAVy0096wxGfj3bDDLwbHgN6/74=", + "dev": true, + "requires": { + "builtin-modules": "^1.0.0" + } + }, + "is-data-descriptor": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", + "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "is-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", + "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^0.1.6", + "is-data-descriptor": "^0.1.4", + "kind-of": "^5.0.0" + }, + "dependencies": { + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } + } + }, + "is-extendable": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", + "integrity": "sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=", + "dev": true + }, + "is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", + "dev": true + }, + "is-finite": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.0.2.tgz", + "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", + "dev": true, + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "is-glob": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz", + "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", + "dev": true, + "requires": { + "is-extglob": "^2.1.0" + } + }, + "is-number": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", + "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "dev": true, + "requires": { + "isobject": "^3.0.1" + } + }, + "is-relative": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-relative/-/is-relative-1.0.0.tgz", + "integrity": "sha512-Kw/ReK0iqwKeu0MITLFuj0jbPAmEiOsIwyIXvvbfa6QfmN9pkD1M+8pdk7Rl/dTKbH34/XBFMbgD4iMJhLQbGA==", + "dev": true, + "requires": { + "is-unc-path": "^1.0.0" + } + }, + "is-stream": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", + "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=", + "dev": true, + "optional": true + }, + "is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=", + "dev": true, + "optional": true + }, + "is-unc-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-unc-path/-/is-unc-path-1.0.0.tgz", + "integrity": "sha512-mrGpVd0fs7WWLfVsStvgF6iEJnbjDFZh9/emhRDcGWTduTfNHd9CHeUwH3gYIjdbwo4On6hunkztwOaAw0yllQ==", + "dev": true, + "requires": { + "unc-path-regex": "^0.1.2" + } + }, + "is-utf8": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz", + "integrity": "sha1-Sw2hRCEE0bM2NA6AeX6GXPOffXI=", + "dev": true + }, + "is-windows": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", + "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==", + "dev": true + }, + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", + "dev": true + }, + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", + "dev": true + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", + "dev": true + }, + "js-yaml": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.5.5.tgz", + "integrity": "sha1-A3fDgBfKvHMisNH7zSWkkWQfL74=", + "dev": true, + "requires": { + "argparse": "^1.0.2", + "esprima": "^2.6.0" + } + }, + "js2xmlparser": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/js2xmlparser/-/js2xmlparser-3.0.0.tgz", + "integrity": "sha1-P7YOqgicVED5MZ9RdgzNB+JJlzM=", + "requires": { + "xmlcreate": "^1.0.1" + } + }, + "jsbn": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", + "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=", + "dev": true + }, + "jsdoc": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/jsdoc/-/jsdoc-3.5.5.tgz", + "integrity": "sha512-6PxB65TAU4WO0Wzyr/4/YhlGovXl0EVYfpKbpSroSj0qBxT4/xod/l40Opkm38dRHRdQgdeY836M0uVnJQG7kg==", + "requires": { + "babylon": "7.0.0-beta.19", + "bluebird": "~3.5.0", + "catharsis": "~0.8.9", + "escape-string-regexp": "~1.0.5", + "js2xmlparser": "~3.0.0", + "klaw": "~2.0.0", + "marked": "~0.3.6", + "mkdirp": "~0.5.1", + "requizzle": "~0.2.1", + "strip-json-comments": "~2.0.1", + "taffydb": "2.6.2", + "underscore": "~1.8.3" + } + }, + "jshint": { + "version": "2.9.6", + "resolved": "https://registry.npmjs.org/jshint/-/jshint-2.9.6.tgz", + "integrity": "sha512-KO9SIAKTlJQOM4lE64GQUtGBRpTOuvbrRrSZw3AhUxMNG266nX9hK2cKA4SBhXOj0irJGyNyGSLT62HGOVDEOA==", + "dev": true, + "requires": { + "cli": "~1.0.0", + "console-browserify": "1.1.x", + "exit": "0.1.x", + "htmlparser2": "3.8.x", + "lodash": "~4.17.10", + "minimatch": "~3.0.2", + "phantom": "~4.0.1", + "phantomjs-prebuilt": "~2.1.7", + "shelljs": "0.3.x", + "strip-json-comments": "1.0.x", + "unicode-5.2.0": "^0.7.5" + }, + "dependencies": { + "strip-json-comments": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-1.0.4.tgz", + "integrity": "sha1-HhX7ysl9Pumb8tc7TGVrCCu6+5E=", + "dev": true + } + } + }, + "jslint": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/jslint/-/jslint-0.12.0.tgz", + "integrity": "sha512-RoCsyICcKA+6TFsbys9DpKTfPVaC71Mm5QSjvrWA0lDVN+LIvx6apa42FFisMqmCTvJ8DxkcoQGJ0j7m3kTVow==", + "dev": true, + "requires": { + "exit": "~0.1.2", + "glob": "~7.1.2", + "nopt": "~3.0.1", + "readable-stream": "~2.1.5" + }, + "dependencies": { + "glob": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.3.tgz", + "integrity": "sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "nopt": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-3.0.6.tgz", + "integrity": "sha1-xkZdvwirzU2zWTF/eaxopkayj/k=", + "dev": true, + "requires": { + "abbrev": "1" + } + }, + "process-nextick-args": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.7.tgz", + "integrity": "sha1-FQ4gt1ZZCtP5EJPyWk8q2L/zC6M=", + "dev": true + }, + "readable-stream": { + "version": "2.1.5", + "resolved": "http://registry.npmjs.org/readable-stream/-/readable-stream-2.1.5.tgz", + "integrity": "sha1-ZvqLcg4UOLNkaB8q0aY8YYRIydA=", + "dev": true, + "requires": { + "buffer-shims": "^1.0.0", + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "~1.0.0", + "process-nextick-args": "~1.0.6", + "string_decoder": "~0.10.x", + "util-deprecate": "~1.0.1" + } + } + } + }, + "json-schema": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", + "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=", + "dev": true, + "optional": true + }, + "json-schema-traverse": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz", + "integrity": "sha1-NJptRMU6Ud6JtAgFxdXlm0F9M0A=", + "dev": true, + "optional": true + }, + "json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=", + "dev": true, + "optional": true + }, + "jsonfile": { + "version": "2.4.0", + "resolved": "http://registry.npmjs.org/jsonfile/-/jsonfile-2.4.0.tgz", + "integrity": "sha1-NzaitCi4e72gzIO1P6PWM6NcKug=", + "dev": true, + "optional": true, + "requires": { + "graceful-fs": "^4.1.6" + } + }, + "jsprim": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz", + "integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=", + "dev": true, + "optional": true, + "requires": { + "assert-plus": "1.0.0", + "extsprintf": "1.3.0", + "json-schema": "0.2.3", + "verror": "1.10.0" + } + }, + "kew": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/kew/-/kew-0.7.0.tgz", + "integrity": "sha1-edk9LTM2PW/dKXCzNdkUGtWR15s=", + "dev": true, + "optional": true + }, + "kind-of": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", + "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", + "dev": true + }, + "klaw": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/klaw/-/klaw-2.0.0.tgz", + "integrity": "sha1-WcEo4Nxc5BAgEVEZTuucv4WGUPY=", + "requires": { + "graceful-fs": "^4.1.9" + } + }, + "lazy-cache": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/lazy-cache/-/lazy-cache-1.0.4.tgz", + "integrity": "sha1-odePw6UEdMuAhF07O24dpJpEbo4=", + "dev": true + }, + "liftoff": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/liftoff/-/liftoff-2.5.0.tgz", + "integrity": "sha1-IAkpG7Mc6oYbvxCnwVooyvdcMew=", + "dev": true, + "requires": { + "extend": "^3.0.0", + "findup-sync": "^2.0.0", + "fined": "^1.0.1", + "flagged-respawn": "^1.0.0", + "is-plain-object": "^2.0.4", + "object.map": "^1.0.0", + "rechoir": "^0.6.2", + "resolve": "^1.1.7" + }, + "dependencies": { + "findup-sync": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-2.0.0.tgz", + "integrity": "sha1-kyaxSIwi0aYIhlCoaQGy2akKLLw=", + "dev": true, + "requires": { + "detect-file": "^1.0.0", + "is-glob": "^3.1.0", + "micromatch": "^3.0.4", + "resolve-dir": "^1.0.1" + } + } + } + }, + "load-json-file": { + "version": "1.1.0", + "resolved": "http://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", + "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "parse-json": "^2.2.0", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0", + "strip-bom": "^2.0.0" + } + }, + "lodash": { + "version": "4.17.11", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", + "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==", + "dev": true + }, + "longest": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/longest/-/longest-1.0.1.tgz", + "integrity": "sha1-MKCy2jj3N3DoKUoNIuZiXtd9AJc=", + "dev": true + }, + "loud-rejection": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/loud-rejection/-/loud-rejection-1.6.0.tgz", + "integrity": "sha1-W0b4AUft7leIcPCG0Eghz5mOVR8=", + "dev": true, + "requires": { + "currently-unhandled": "^0.4.1", + "signal-exit": "^3.0.0" + } + }, + "make-iterator": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/make-iterator/-/make-iterator-1.0.1.tgz", + "integrity": "sha512-pxiuXh0iVEq7VM7KMIhs5gxsfxCux2URptUQaXo4iZZJxBAzTPOLE2BumO5dbfVYq/hBJFBR/a1mFDmOx5AGmw==", + "dev": true, + "requires": { + "kind-of": "^6.0.2" + } + }, + "map-cache": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/map-cache/-/map-cache-0.2.2.tgz", + "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=", + "dev": true + }, + "map-obj": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz", + "integrity": "sha1-2TPOuSBdgr3PSIb2dCvcK03qFG0=", + "dev": true + }, + "map-visit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/map-visit/-/map-visit-1.0.0.tgz", + "integrity": "sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=", + "dev": true, + "requires": { + "object-visit": "^1.0.0" + } + }, + "marked": { + "version": "0.3.19", + "resolved": "http://registry.npmjs.org/marked/-/marked-0.3.19.tgz", + "integrity": "sha512-ea2eGWOqNxPcXv8dyERdSr/6FmzvWwzjMxpfGB/sbMccXoct+xY+YukPD+QTUZwyvK7BZwcr4m21WBOW41pAkg==" + }, + "maxmin": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/maxmin/-/maxmin-1.1.0.tgz", + "integrity": "sha1-cTZehKmd2Piz99X94vANHn9zvmE=", + "dev": true, + "requires": { + "chalk": "^1.0.0", + "figures": "^1.0.1", + "gzip-size": "^1.0.0", + "pretty-bytes": "^1.0.0" + }, + "dependencies": { + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "chalk": { + "version": "1.1.3", + "resolved": "http://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + } + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + } + } + }, + "meow": { + "version": "3.7.0", + "resolved": "http://registry.npmjs.org/meow/-/meow-3.7.0.tgz", + "integrity": "sha1-cstmi0JSKCkKu/qFaJJYcwioAfs=", + "dev": true, + "requires": { + "camelcase-keys": "^2.0.0", + "decamelize": "^1.1.2", + "loud-rejection": "^1.0.0", + "map-obj": "^1.0.1", + "minimist": "^1.1.3", + "normalize-package-data": "^2.3.4", + "object-assign": "^4.0.1", + "read-pkg-up": "^1.0.1", + "redent": "^1.0.0", + "trim-newlines": "^1.0.0" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "resolved": "http://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", + "dev": true + } + } + }, + "micromatch": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.10.tgz", + "integrity": "sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==", + "dev": true, + "requires": { + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "braces": "^2.3.1", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "extglob": "^2.0.4", + "fragment-cache": "^0.2.1", + "kind-of": "^6.0.2", + "nanomatch": "^1.2.9", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.2" + } + }, + "mime": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.3.1.tgz", + "integrity": "sha512-OEUllcVoydBHGN1z84yfQDimn58pZNNNXgZlHXSboxMlFvgI6MXSWpWKpFRra7H1HxpVhHTkrghfRW49k6yjeg==", + "dev": true + }, + "mime-db": { + "version": "1.37.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.37.0.tgz", + "integrity": "sha512-R3C4db6bgQhlIhPU48fUtdVmKnflq+hRdad7IyKhtFj06VPNVdk2RhiYL3UjQIlso8L+YxAtFkobT0VK+S/ybg==", + "dev": true + }, + "mime-types": { + "version": "2.1.21", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.21.tgz", + "integrity": "sha512-3iL6DbwpyLzjR3xHSFNFeb9Nz/M8WDkX33t1GFQnFOllWk8pOrh/LSrB5OXlnlW5P9LH73X6loW/eogc+F5lJg==", + "dev": true, + "requires": { + "mime-db": "~1.37.0" + } + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "0.0.8", + "resolved": "http://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=" + }, + "mixin-deep": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.1.tgz", + "integrity": "sha512-8ZItLHeEgaqEvd5lYBXfm4EZSFCX29Jb9K+lAHhDKzReKBQKj3R+7NOF6tjqYi9t4oI8VUfaWITJQm86wnXGNQ==", + "dev": true, + "requires": { + "for-in": "^1.0.2", + "is-extendable": "^1.0.1" + }, + "dependencies": { + "is-extendable": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", + "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", + "dev": true, + "requires": { + "is-plain-object": "^2.0.4" + } + } + } + }, + "mkdirp": { + "version": "0.5.1", + "resolved": "http://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "requires": { + "minimist": "0.0.8" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "nanomatch": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.13.tgz", + "integrity": "sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA==", + "dev": true, + "requires": { + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "fragment-cache": "^0.2.1", + "is-windows": "^1.0.2", + "kind-of": "^6.0.2", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + } + }, + "nice-try": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", + "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==", + "dev": true + }, + "nopt": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-4.0.1.tgz", + "integrity": "sha1-0NRoWv1UFRk8jHUFYC0NF81kR00=", + "requires": { + "abbrev": "1", + "osenv": "^0.1.4" + } + }, + "normalize-package-data": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.4.0.tgz", + "integrity": "sha512-9jjUFbTPfEy3R/ad/2oNbKtW9Hgovl5O1FvFWKkKblNXoN/Oou6+9+KKohPK13Yc3/TyunyWhJp6gvRNR/PPAw==", + "dev": true, + "requires": { + "hosted-git-info": "^2.1.4", + "is-builtin-module": "^1.0.0", + "semver": "2 || 3 || 4 || 5", + "validate-npm-package-license": "^3.0.1" + } + }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", + "dev": true + }, + "oauth-sign": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", + "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==", + "dev": true, + "optional": true + }, + "object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", + "dev": true + }, + "object-copy": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/object-copy/-/object-copy-0.1.0.tgz", + "integrity": "sha1-fn2Fi3gb18mRpBupde04EnVOmYw=", + "dev": true, + "requires": { + "copy-descriptor": "^0.1.0", + "define-property": "^0.2.5", + "kind-of": "^3.0.3" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "object-visit": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/object-visit/-/object-visit-1.0.1.tgz", + "integrity": "sha1-95xEk68MU3e1n+OdOV5BBC3QRbs=", + "dev": true, + "requires": { + "isobject": "^3.0.0" + } + }, + "object.defaults": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/object.defaults/-/object.defaults-1.1.0.tgz", + "integrity": "sha1-On+GgzS0B96gbaFtiNXNKeQ1/s8=", + "dev": true, + "requires": { + "array-each": "^1.0.1", + "array-slice": "^1.0.0", + "for-own": "^1.0.0", + "isobject": "^3.0.0" + } + }, + "object.map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/object.map/-/object.map-1.0.1.tgz", + "integrity": "sha1-z4Plncj8wK1fQlDh94s7gb2AHTc=", + "dev": true, + "requires": { + "for-own": "^1.0.0", + "make-iterator": "^1.0.0" + } + }, + "object.pick": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/object.pick/-/object.pick-1.3.0.tgz", + "integrity": "sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=", + "dev": true, + "requires": { + "isobject": "^3.0.1" + } + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "os-homedir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", + "integrity": "sha1-/7xJiDNuDoM94MFox+8VISGqf7M=" + }, + "os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=" + }, + "osenv": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/osenv/-/osenv-0.1.5.tgz", + "integrity": "sha512-0CWcCECdMVc2Rw3U5w9ZjqX6ga6ubk1xDVKxtBQPK7wis/0F2r9T6k4ydGYhecl7YUBxBVxhL5oisPsNxAPe2g==", + "requires": { + "os-homedir": "^1.0.0", + "os-tmpdir": "^1.0.0" + } + }, + "p-each-series": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-each-series/-/p-each-series-1.0.0.tgz", + "integrity": "sha1-kw89Et0fUOdDRFeiLNbwSsatf3E=", + "dev": true, + "requires": { + "p-reduce": "^1.0.0" + } + }, + "p-reduce": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-reduce/-/p-reduce-1.0.0.tgz", + "integrity": "sha1-GMKw3ZNqRpClKfgjH1ig/bakffo=", + "dev": true + }, + "pako": { + "version": "0.2.9", + "resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz", + "integrity": "sha1-8/dSL073gjSNqBYbrZ7P1Rv4OnU=", + "dev": true + }, + "parse-filepath": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/parse-filepath/-/parse-filepath-1.0.2.tgz", + "integrity": "sha1-pjISf1Oq89FYdvWHLz/6x2PWyJE=", + "dev": true, + "requires": { + "is-absolute": "^1.0.0", + "map-cache": "^0.2.0", + "path-root": "^0.1.1" + } + }, + "parse-json": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-2.2.0.tgz", + "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", + "dev": true, + "requires": { + "error-ex": "^1.2.0" + } + }, + "parse-passwd": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/parse-passwd/-/parse-passwd-1.0.0.tgz", + "integrity": "sha1-bVuTSkVpk7I9N/QKOC1vFmao5cY=", + "dev": true + }, + "pascalcase": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/pascalcase/-/pascalcase-0.1.1.tgz", + "integrity": "sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=", + "dev": true + }, + "path-exists": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-2.1.0.tgz", + "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", + "dev": true, + "requires": { + "pinkie-promise": "^2.0.0" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "path-key": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", + "dev": true + }, + "path-root": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/path-root/-/path-root-0.1.1.tgz", + "integrity": "sha1-mkpoFMrBwM1zNgqV8yCDyOpHRbc=", + "dev": true, + "requires": { + "path-root-regex": "^0.1.0" + } + }, + "path-root-regex": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/path-root-regex/-/path-root-regex-0.1.2.tgz", + "integrity": "sha1-v8zcjfWxLcUsi0PsONGNcsBLqW0=", + "dev": true + }, + "path-type": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-1.1.0.tgz", + "integrity": "sha1-WcRPfuSR2nBNpBXaWkBwuk+P5EE=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0" + } + }, + "pend": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", + "integrity": "sha1-elfrVQpng/kRUzH89GY9XI4AelA=", + "dev": true + }, + "performance-now": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", + "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=", + "dev": true, + "optional": true + }, + "phantom": { + "version": "4.0.12", + "resolved": "https://registry.npmjs.org/phantom/-/phantom-4.0.12.tgz", + "integrity": "sha512-Tz82XhtPmwCk1FFPmecy7yRGZG2btpzY2KI9fcoPT7zT9det0CcMyfBFPp1S8DqzsnQnm8ZYEfdy528mwVtksA==", + "dev": true, + "optional": true, + "requires": { + "phantomjs-prebuilt": "^2.1.16", + "split": "^1.0.1", + "winston": "^2.4.0" + } + }, + "phantomjs-prebuilt": { + "version": "2.1.16", + "resolved": "https://registry.npmjs.org/phantomjs-prebuilt/-/phantomjs-prebuilt-2.1.16.tgz", + "integrity": "sha1-79ISpKOWbTZHaE6ouniFSb4q7+8=", + "dev": true, + "optional": true, + "requires": { + "es6-promise": "^4.0.3", + "extract-zip": "^1.6.5", + "fs-extra": "^1.0.0", + "hasha": "^2.2.0", + "kew": "^0.7.0", + "progress": "^1.1.8", + "request": "^2.81.0", + "request-progress": "^2.0.1", + "which": "^1.2.10" + } + }, + "pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", + "dev": true + }, + "pinkie": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", + "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=", + "dev": true + }, + "pinkie-promise": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", + "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", + "dev": true, + "requires": { + "pinkie": "^2.0.0" + } + }, + "posix-character-classes": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/posix-character-classes/-/posix-character-classes-0.1.1.tgz", + "integrity": "sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=", + "dev": true + }, + "pretty-bytes": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/pretty-bytes/-/pretty-bytes-1.0.4.tgz", + "integrity": "sha1-CiLoIQYJrTVUL4yNXSFZr/B1HIQ=", + "dev": true, + "requires": { + "get-stdin": "^4.0.1", + "meow": "^3.1.0" + } + }, + "process-nextick-args": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.0.tgz", + "integrity": "sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==", + "dev": true + }, + "progress": { + "version": "1.1.8", + "resolved": "http://registry.npmjs.org/progress/-/progress-1.1.8.tgz", + "integrity": "sha1-4mDHj2Fhzdmw5WzD4Khd4Xx6V74=", + "dev": true, + "optional": true + }, + "proxy-from-env": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.0.0.tgz", + "integrity": "sha1-M8UDmPcOp+uW0h97gXYwpVeRx+4=", + "dev": true + }, + "psl": { + "version": "1.1.29", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.1.29.tgz", + "integrity": "sha512-AeUmQ0oLN02flVHXWh9sSJF7mcdFq0ppid/JkErufc3hGIV/AMa8Fo9VgDo/cT2jFdOWoFvHp90qqBH54W+gjQ==", + "dev": true, + "optional": true + }, + "punycode": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", + "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=", + "dev": true, + "optional": true + }, + "puppeteer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/puppeteer/-/puppeteer-1.7.0.tgz", + "integrity": "sha512-f+1DxKHPqce6CXUBz2eVO2WcATeVeQSOPG9GYaGObEZDCiCEUwG+gogjMsrvn7he2wHTqNVb5p6RUrwmr8XFBA==", + "dev": true, + "requires": { + "debug": "^3.1.0", + "extract-zip": "^1.6.6", + "https-proxy-agent": "^2.2.1", + "mime": "^2.0.3", + "progress": "^2.0.0", + "proxy-from-env": "^1.0.0", + "rimraf": "^2.6.1", + "ws": "^5.1.1" + }, + "dependencies": { + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", + "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", + "dev": true + }, + "progress": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.1.tgz", + "integrity": "sha512-OE+a6vzqazc+K6LxJrX5UPyKFvGnL5CYmq2jFGNIBWHpc4QyE49/YOumcrpQFJpfejmvRtbJzgO1zPmMCqlbBg==", + "dev": true + } + } + }, + "qs": { + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz", + "integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==", + "dev": true, + "optional": true + }, + "read-pkg": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-1.1.0.tgz", + "integrity": "sha1-9f+qXs0pyzHAR0vKfXVra7KePyg=", + "dev": true, + "requires": { + "load-json-file": "^1.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^1.0.0" + } + }, + "read-pkg-up": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-1.0.1.tgz", + "integrity": "sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI=", + "dev": true, + "requires": { + "find-up": "^1.0.0", + "read-pkg": "^1.0.0" + } + }, + "readable-stream": { + "version": "1.1.14", + "resolved": "http://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", + "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + }, + "dependencies": { + "isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", + "dev": true + } + } + }, + "rechoir": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.6.2.tgz", + "integrity": "sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q=", + "dev": true, + "requires": { + "resolve": "^1.1.6" + } + }, + "redent": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/redent/-/redent-1.0.0.tgz", + "integrity": "sha1-z5Fqsf1fHxbfsggi3W7H9zDCr94=", + "dev": true, + "requires": { + "indent-string": "^2.1.0", + "strip-indent": "^1.0.1" + } + }, + "regex-not": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/regex-not/-/regex-not-1.0.2.tgz", + "integrity": "sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A==", + "dev": true, + "requires": { + "extend-shallow": "^3.0.2", + "safe-regex": "^1.1.0" + } + }, + "repeat-element": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/repeat-element/-/repeat-element-1.1.3.tgz", + "integrity": "sha512-ahGq0ZnV5m5XtZLMb+vP76kcAM5nkLqk0lpqAuojSKGgQtn4eRi4ZZGm2olo2zKFH+sMsWaqOCW1dqAnOru72g==", + "dev": true + }, + "repeat-string": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", + "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=", + "dev": true + }, + "repeating": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz", + "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", + "dev": true, + "requires": { + "is-finite": "^1.0.0" + } + }, + "request": { + "version": "2.88.0", + "resolved": "https://registry.npmjs.org/request/-/request-2.88.0.tgz", + "integrity": "sha512-NAqBSrijGLZdM0WZNsInLJpkJokL72XYjUpnB0iwsRgxh7dB6COrHnTBNwN0E+lHDAJzu7kLAkDeY08z2/A0hg==", + "dev": true, + "optional": true, + "requires": { + "aws-sign2": "~0.7.0", + "aws4": "^1.8.0", + "caseless": "~0.12.0", + "combined-stream": "~1.0.6", + "extend": "~3.0.2", + "forever-agent": "~0.6.1", + "form-data": "~2.3.2", + "har-validator": "~5.1.0", + "http-signature": "~1.2.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.19", + "oauth-sign": "~0.9.0", + "performance-now": "^2.1.0", + "qs": "~6.5.2", + "safe-buffer": "^5.1.2", + "tough-cookie": "~2.4.3", + "tunnel-agent": "^0.6.0", + "uuid": "^3.3.2" + } + }, + "request-progress": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/request-progress/-/request-progress-2.0.1.tgz", + "integrity": "sha1-XTa7V5YcZzqlt4jbyBQf3yO0Tgg=", + "dev": true, + "optional": true, + "requires": { + "throttleit": "^1.0.0" + } + }, + "requizzle": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/requizzle/-/requizzle-0.2.1.tgz", + "integrity": "sha1-aUPDUwxNmn5G8c3dUcFY/GcM294=", + "requires": { + "underscore": "~1.6.0" + }, + "dependencies": { + "underscore": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.6.0.tgz", + "integrity": "sha1-izixDKze9jM3uLJOT/htRa6lKag=" + } + } + }, + "resolve": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.1.7.tgz", + "integrity": "sha1-IDEU2CrSxe2ejgQRs5ModeiJ6Xs=", + "dev": true + }, + "resolve-dir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/resolve-dir/-/resolve-dir-1.0.1.tgz", + "integrity": "sha1-eaQGRMNivoLybv/nOcm7U4IEb0M=", + "dev": true, + "requires": { + "expand-tilde": "^2.0.0", + "global-modules": "^1.0.0" + } + }, + "resolve-url": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz", + "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=", + "dev": true + }, + "ret": { + "version": "0.1.15", + "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", + "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==", + "dev": true + }, + "right-align": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/right-align/-/right-align-0.1.3.tgz", + "integrity": "sha1-YTObci/mo1FWiSENJOFMlhSGE+8=", + "dev": true, + "requires": { + "align-text": "^0.1.1" + } + }, + "rimraf": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.2.tgz", + "integrity": "sha512-lreewLK/BlghmxtfH36YYVg1i8IAce4TI7oao75I1g245+6BctqTVQiBP3YUJ9C6DQOXJmkYR9X9fCLtCOJc5w==", + "dev": true, + "requires": { + "glob": "^7.0.5" + } + }, + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true + }, + "safe-regex": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", + "integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=", + "dev": true, + "requires": { + "ret": "~0.1.10" + } + }, + "safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true + }, + "semver": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.6.0.tgz", + "integrity": "sha512-RS9R6R35NYgQn++fkDWaOmqGoj4Ek9gGs+DPxNUZKuwE183xjJroKvyo1IzVFeXvUrvmALy6FWD5xrdJT25gMg==", + "dev": true + }, + "set-value": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.0.tgz", + "integrity": "sha512-hw0yxk9GT/Hr5yJEYnHNKYXkIA8mVJgd9ditYZCe16ZczcaELYYcfvaXesNACk2O8O0nTiPQcQhGUQj8JLzeeg==", + "dev": true, + "requires": { + "extend-shallow": "^2.0.1", + "is-extendable": "^0.1.1", + "is-plain-object": "^2.0.3", + "split-string": "^3.0.1" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "shebang-command": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", + "dev": true, + "requires": { + "shebang-regex": "^1.0.0" + } + }, + "shebang-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", + "dev": true + }, + "shelljs": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.3.0.tgz", + "integrity": "sha1-NZbmMHp4FUT1kfN9phg2DzHbV7E=", + "dev": true + }, + "signal-exit": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", + "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=", + "dev": true + }, + "snapdragon": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.2.tgz", + "integrity": "sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg==", + "dev": true, + "requires": { + "base": "^0.11.1", + "debug": "^2.2.0", + "define-property": "^0.2.5", + "extend-shallow": "^2.0.1", + "map-cache": "^0.2.2", + "source-map": "^0.5.6", + "source-map-resolve": "^0.5.0", + "use": "^3.1.0" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "snapdragon-node": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/snapdragon-node/-/snapdragon-node-2.1.1.tgz", + "integrity": "sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw==", + "dev": true, + "requires": { + "define-property": "^1.0.0", + "isobject": "^3.0.0", + "snapdragon-util": "^3.0.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "snapdragon-util": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/snapdragon-util/-/snapdragon-util-3.0.1.tgz", + "integrity": "sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ==", + "dev": true, + "requires": { + "kind-of": "^3.2.0" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + }, + "source-map-resolve": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.5.2.tgz", + "integrity": "sha512-MjqsvNwyz1s0k81Goz/9vRBe9SZdB09Bdw+/zYyO+3CuPk6fouTaxscHkgtE8jKvf01kVfl8riHzERQ/kefaSA==", + "dev": true, + "requires": { + "atob": "^2.1.1", + "decode-uri-component": "^0.2.0", + "resolve-url": "^0.2.1", + "source-map-url": "^0.4.0", + "urix": "^0.1.0" + } + }, + "source-map-url": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/source-map-url/-/source-map-url-0.4.0.tgz", + "integrity": "sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM=", + "dev": true + }, + "spdx-correct": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.0.2.tgz", + "integrity": "sha512-q9hedtzyXHr5S0A1vEPoK/7l8NpfkFYTq6iCY+Pno2ZbdZR6WexZFtqeVGkGxW3TEJMN914Z55EnAGMmenlIQQ==", + "dev": true, + "requires": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-exceptions": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.2.0.tgz", + "integrity": "sha512-2XQACfElKi9SlVb1CYadKDXvoajPgBVPn/gOQLrTvHdElaVhr7ZEbqJaRnJLVNeaI4cMEAgVCeBMKF6MWRDCRA==", + "dev": true + }, + "spdx-expression-parse": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.0.tgz", + "integrity": "sha512-Yg6D3XpRD4kkOmTpdgbUiEJFKghJH03fiC1OPll5h/0sO6neh2jqRDVHOQ4o/LMea0tgCkbMgea5ip/e+MkWyg==", + "dev": true, + "requires": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-license-ids": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.1.tgz", + "integrity": "sha512-TfOfPcYGBB5sDuPn3deByxPhmfegAhpDYKSOXZQN81Oyrrif8ZCodOLzK3AesELnCx03kikhyDwh0pfvvQvF8w==", + "dev": true + }, + "split": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/split/-/split-1.0.1.tgz", + "integrity": "sha512-mTyOoPbrivtXnwnIxZRFYRrPNtEFKlpB2fvjSnCQUiAA6qAZzqwna5envK4uk6OIeP17CsdF3rSBGYVBsU0Tkg==", + "dev": true, + "optional": true, + "requires": { + "through": "2" + } + }, + "split-string": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/split-string/-/split-string-3.1.0.tgz", + "integrity": "sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw==", + "dev": true, + "requires": { + "extend-shallow": "^3.0.0" + } + }, + "sprintf-js": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.1.tgz", + "integrity": "sha1-Nr54Mgr+WAH2zqPueLblqrlA6gw=", + "dev": true + }, + "sshpk": { + "version": "1.15.1", + "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.15.1.tgz", + "integrity": "sha512-mSdgNUaidk+dRU5MhYtN9zebdzF2iG0cNPWy8HG+W8y+fT1JnSkh0fzzpjOa0L7P8i1Rscz38t0h4gPcKz43xA==", + "dev": true, + "optional": true, + "requires": { + "asn1": "~0.2.3", + "assert-plus": "^1.0.0", + "bcrypt-pbkdf": "^1.0.0", + "dashdash": "^1.12.0", + "ecc-jsbn": "~0.1.1", + "getpass": "^0.1.1", + "jsbn": "~0.1.0", + "safer-buffer": "^2.0.2", + "tweetnacl": "~0.14.0" + } + }, + "stack-trace": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=", + "dev": true, + "optional": true + }, + "static-extend": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/static-extend/-/static-extend-0.1.2.tgz", + "integrity": "sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY=", + "dev": true, + "requires": { + "define-property": "^0.2.5", + "object-copy": "^0.1.0" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + } + } + }, + "string_decoder": { + "version": "0.10.31", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", + "dev": true + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "strip-bom": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-2.0.0.tgz", + "integrity": "sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4=", + "dev": true, + "requires": { + "is-utf8": "^0.2.0" + } + }, + "strip-indent": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-1.0.1.tgz", + "integrity": "sha1-DHlipq3vp7vUrDZkYKY4VSrhoKI=", + "dev": true, + "requires": { + "get-stdin": "^4.0.1" + } + }, + "strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=" + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + }, + "sync-exec": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/sync-exec/-/sync-exec-0.6.2.tgz", + "integrity": "sha1-cX0izFPwzh3vVZQ2LzqJouu5EQU=", + "dev": true + }, + "taffydb": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/taffydb/-/taffydb-2.6.2.tgz", + "integrity": "sha1-fLy2S1oUG2ou/CxdLGe04VCyomg=" + }, + "throttleit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/throttleit/-/throttleit-1.0.0.tgz", + "integrity": "sha1-nnhYNtr0Z0MUWlmEtiaNgoUorGw=", + "dev": true, + "optional": true + }, + "through": { + "version": "2.3.8", + "resolved": "http://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=", + "dev": true, + "optional": true + }, + "to-object-path": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/to-object-path/-/to-object-path-0.3.0.tgz", + "integrity": "sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "to-regex": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/to-regex/-/to-regex-3.0.2.tgz", + "integrity": "sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw==", + "dev": true, + "requires": { + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "regex-not": "^1.0.2", + "safe-regex": "^1.1.0" + } + }, + "to-regex-range": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-2.1.1.tgz", + "integrity": "sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg=", + "dev": true, + "requires": { + "is-number": "^3.0.0", + "repeat-string": "^1.6.1" + } + }, + "tough-cookie": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.4.3.tgz", + "integrity": "sha512-Q5srk/4vDM54WJsJio3XNn6K2sCG+CQ8G5Wz6bZhRZoAe/+TxjWB/GlFAnYEbkYVlON9FMk/fE3h2RLpPXo4lQ==", + "dev": true, + "optional": true, + "requires": { + "psl": "^1.1.24", + "punycode": "^1.4.1" + } + }, + "trim-newlines": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/trim-newlines/-/trim-newlines-1.0.0.tgz", + "integrity": "sha1-WIeWa7WCpFA6QetST301ARgVphM=", + "dev": true + }, + "tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", + "dev": true, + "optional": true, + "requires": { + "safe-buffer": "^5.0.1" + } + }, + "tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=", + "dev": true + }, + "typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=", + "dev": true + }, + "uglify-js": { + "version": "2.6.4", + "resolved": "http://registry.npmjs.org/uglify-js/-/uglify-js-2.6.4.tgz", + "integrity": "sha1-ZeovswWck5RpLxX+2HwrNsFrmt8=", + "dev": true, + "requires": { + "async": "~0.2.6", + "source-map": "~0.5.1", + "uglify-to-browserify": "~1.0.0", + "yargs": "~3.10.0" + }, + "dependencies": { + "async": { + "version": "0.2.10", + "resolved": "http://registry.npmjs.org/async/-/async-0.2.10.tgz", + "integrity": "sha1-trvgsGdLnXGXCMo43owjfLUmw9E=", + "dev": true + } + } + }, + "uglify-to-browserify": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz", + "integrity": "sha1-bgkk1r2mta/jSeOabWMoUKD4grc=", + "dev": true + }, + "unc-path-regex": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/unc-path-regex/-/unc-path-regex-0.1.2.tgz", + "integrity": "sha1-5z3T17DXxe2G+6xrCufYxqadUPo=", + "dev": true + }, + "underscore": { + "version": "1.8.3", + "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.8.3.tgz", + "integrity": "sha1-Tz+1OxBuYJf8+ctBCfKl6b36UCI=" + }, + "underscore-contrib": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/underscore-contrib/-/underscore-contrib-0.3.0.tgz", + "integrity": "sha1-ZltmwkeD+PorGMn4y7Dix9SMJsc=", + "requires": { + "underscore": "1.6.0" + }, + "dependencies": { + "underscore": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.6.0.tgz", + "integrity": "sha1-izixDKze9jM3uLJOT/htRa6lKag=" + } + } + }, + "underscore.string": { + "version": "3.3.5", + "resolved": "https://registry.npmjs.org/underscore.string/-/underscore.string-3.3.5.tgz", + "integrity": "sha512-g+dpmgn+XBneLmXXo+sGlW5xQEt4ErkS3mgeN2GFbremYeMBSJKr9Wf2KJplQVaiPY/f7FN6atosWYNm9ovrYg==", + "dev": true, + "requires": { + "sprintf-js": "^1.0.3", + "util-deprecate": "^1.0.2" + } + }, + "unicode-5.2.0": { + "version": "0.7.5", + "resolved": "https://registry.npmjs.org/unicode-5.2.0/-/unicode-5.2.0-0.7.5.tgz", + "integrity": "sha512-KVGLW1Bri30x00yv4HNM8kBxoqFXr0Sbo55735nvrlsx4PYBZol3UtoWgO492fSwmsetzPEZzy73rbU8OGXJcA==", + "dev": true + }, + "union-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.0.tgz", + "integrity": "sha1-XHHDTLW61dzr4+oM0IIHulqhrqQ=", + "dev": true, + "requires": { + "arr-union": "^3.1.0", + "get-value": "^2.0.6", + "is-extendable": "^0.1.1", + "set-value": "^0.4.3" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + }, + "set-value": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/set-value/-/set-value-0.4.3.tgz", + "integrity": "sha1-fbCPnT0i3H945Trzw79GZuzfzPE=", + "dev": true, + "requires": { + "extend-shallow": "^2.0.1", + "is-extendable": "^0.1.1", + "is-plain-object": "^2.0.1", + "to-object-path": "^0.3.0" + } + } + } + }, + "unset-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unset-value/-/unset-value-1.0.0.tgz", + "integrity": "sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=", + "dev": true, + "requires": { + "has-value": "^0.3.1", + "isobject": "^3.0.0" + }, + "dependencies": { + "has-value": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/has-value/-/has-value-0.3.1.tgz", + "integrity": "sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8=", + "dev": true, + "requires": { + "get-value": "^2.0.3", + "has-values": "^0.1.4", + "isobject": "^2.0.0" + }, + "dependencies": { + "isobject": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", + "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", + "dev": true, + "requires": { + "isarray": "1.0.0" + } + } + } + }, + "has-values": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/has-values/-/has-values-0.1.4.tgz", + "integrity": "sha1-bWHeldkd/Km5oCCJrThL/49it3E=", + "dev": true + } + } + }, + "uri-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/uri-path/-/uri-path-1.0.0.tgz", + "integrity": "sha1-l0fwGDWJM8Md4PzP2C0TjmcmLjI=", + "dev": true + }, + "urix": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/urix/-/urix-0.1.0.tgz", + "integrity": "sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=", + "dev": true + }, + "use": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/use/-/use-3.1.1.tgz", + "integrity": "sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ==", + "dev": true + }, + "util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", + "dev": true + }, + "uuid": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.2.tgz", + "integrity": "sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA==", + "dev": true, + "optional": true + }, + "v8flags": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/v8flags/-/v8flags-3.0.2.tgz", + "integrity": "sha512-6sgSKoFw1UpUPd3cFdF7QGnrH6tDeBgW1F3v9gy8gLY0mlbiBXq8soy8aQpY6xeeCjH5K+JvC62Acp7gtl7wWA==", + "dev": true, + "requires": { + "homedir-polyfill": "^1.0.1" + } + }, + "validate-npm-package-license": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", + "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", + "dev": true, + "requires": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "verror": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", + "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", + "dev": true, + "optional": true, + "requires": { + "assert-plus": "^1.0.0", + "core-util-is": "1.0.2", + "extsprintf": "^1.2.0" + } + }, + "which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + }, + "window-size": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/window-size/-/window-size-0.1.0.tgz", + "integrity": "sha1-VDjNLqk7IC76Ohn+iIeu58lPnJ0=", + "dev": true + }, + "winston": { + "version": "2.4.4", + "resolved": "https://registry.npmjs.org/winston/-/winston-2.4.4.tgz", + "integrity": "sha512-NBo2Pepn4hK4V01UfcWcDlmiVTs7VTB1h7bgnB0rgP146bYhMxX0ypCz3lBOfNxCO4Zuek7yeT+y/zM1OfMw4Q==", + "dev": true, + "optional": true, + "requires": { + "async": "~1.0.0", + "colors": "1.0.x", + "cycle": "1.0.x", + "eyes": "0.1.x", + "isstream": "0.1.x", + "stack-trace": "0.0.x" + }, + "dependencies": { + "async": { + "version": "1.0.0", + "resolved": "http://registry.npmjs.org/async/-/async-1.0.0.tgz", + "integrity": "sha1-+PwEyjoTeErenhZBr5hXjPvWR6k=", + "dev": true, + "optional": true + }, + "colors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz", + "integrity": "sha1-BDP0TYCWgP3rYO0mDxsMJi6CpAs=", + "dev": true, + "optional": true + } + } + }, + "wordwrap": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.2.tgz", + "integrity": "sha1-t5Zpu0LstAn4PVg8rVLKF+qhZD8=", + "dev": true + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + }, + "ws": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-5.2.2.tgz", + "integrity": "sha512-jaHFD6PFv6UgoIVda6qZllptQsMlDEJkTQcybzzXDYM1XO9Y8em691FGMPmM46WGyLU4z9KMgQN+qrux/nhlHA==", + "dev": true, + "requires": { + "async-limiter": "~1.0.0" + } + }, + "xmlcreate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/xmlcreate/-/xmlcreate-1.0.2.tgz", + "integrity": "sha1-+mv3YqYKQT+z3Y9LA8WyaSONMI8=" + }, + "yargs": { + "version": "3.10.0", + "resolved": "http://registry.npmjs.org/yargs/-/yargs-3.10.0.tgz", + "integrity": "sha1-9+572FfdfB0tOMDnTvvWgdFDH9E=", + "dev": true, + "requires": { + "camelcase": "^1.0.2", + "cliui": "^2.1.0", + "decamelize": "^1.0.0", + "window-size": "0.1.0" + }, + "dependencies": { + "camelcase": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-1.2.1.tgz", + "integrity": "sha1-m7UwTS4LVmmLLHWLCKPqqdqlijk=", + "dev": true + } + } + }, + "yauzl": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.4.1.tgz", + "integrity": "sha1-lSj0QtqxsihOWLQ3m7GU4i4MQAU=", + "dev": true, + "requires": { + "fd-slicer": "~1.0.1" + } + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/js/package.json b/vendor/git.apache.org/thrift.git/lib/js/package.json index 9491970..2ddd238 100644 --- a/vendor/git.apache.org/thrift.git/lib/js/package.json +++ b/vendor/git.apache.org/thrift.git/lib/js/package.json @@ -1,15 +1,19 @@ { "name": "thrift", - "version": "0.10.0", + "version": "0.12.0", "devDependencies": { - "grunt": "^0.4.5", + "grunt": "^1.0.2", "grunt-cli": "^1.2.0", - "grunt-contrib-uglify": "^1.0.1", - "grunt-contrib-jshint": "^1.0.0", - "grunt-contrib-qunit": "^1.2.0", "grunt-contrib-concat": "^1.0.1", - "grunt-jsdoc": "^2.0.0", - "grunt-external-daemon": "^1.1.0", - "grunt-shell": "^1.3.0" + "grunt-contrib-jshint": "^1.0.0", + "grunt-contrib-qunit": "^3.0.1", + "grunt-contrib-uglify": "^1.0.1", + "grunt-jsdoc": "^2.2.1", + "grunt-shell-spawn": "^0.3.10", + "jslint": "^0.12.0" + }, + "dependencies": { + "jsdoc": "^3.5.5", + "nopt": "^4.0.1" } } diff --git a/vendor/git.apache.org/thrift.git/lib/js/src/thrift.js b/vendor/git.apache.org/thrift.git/lib/js/src/thrift.js index 41935c4..9418ca3 100644 --- a/vendor/git.apache.org/thrift.git/lib/js/src/thrift.js +++ b/vendor/git.apache.org/thrift.git/lib/js/src/thrift.js @@ -34,7 +34,7 @@ * all features must be scoped within the Thrift namespace. * @namespace * @example - * var transport = new Thrift.Transport("http://localhost:8585"); + * var transport = new Thrift.Transport('http://localhost:8585'); * var protocol = new Thrift.Protocol(transport); * var client = new MyThriftSvcClient(protocol); * var result = client.MyMethod(); @@ -46,7 +46,7 @@ var Thrift = { * @const {string} Version * @memberof Thrift */ - Version: '0.10.0', + Version: '0.12.0', /** * Thrift IDL type string to Id mapping. @@ -70,23 +70,23 @@ var Thrift = { * @property {number} UTF16 - Array of bytes representing a string of UTF16 encoded characters. */ Type: { - 'STOP' : 0, - 'VOID' : 1, - 'BOOL' : 2, - 'BYTE' : 3, - 'I08' : 3, - 'DOUBLE' : 4, - 'I16' : 6, - 'I32' : 8, - 'I64' : 10, - 'STRING' : 11, - 'UTF7' : 11, - 'STRUCT' : 12, - 'MAP' : 13, - 'SET' : 14, - 'LIST' : 15, - 'UTF8' : 16, - 'UTF16' : 17 + STOP: 0, + VOID: 1, + BOOL: 2, + BYTE: 3, + I08: 3, + DOUBLE: 4, + I16: 6, + I32: 8, + I64: 10, + STRING: 11, + UTF7: 11, + STRUCT: 12, + MAP: 13, + SET: 14, + LIST: 15, + UTF8: 16, + UTF16: 17 }, /** @@ -98,10 +98,10 @@ var Thrift = { * @property {number} ONEWAY - Oneway RPC call from client to server with no response. */ MessageType: { - 'CALL' : 1, - 'REPLY' : 2, - 'EXCEPTION' : 3, - 'ONEWAY' : 4 + CALL: 1, + REPLY: 2, + EXCEPTION: 3, + ONEWAY: 4 }, /** @@ -130,7 +130,7 @@ var Thrift = { function F() {} F.prototype = superConstructor.prototype; constructor.prototype = new F(); - constructor.prototype.name = name || ""; + constructor.prototype.name = name || ''; } }; @@ -171,17 +171,17 @@ Thrift.TException.prototype.getMessage = function() { * @property {number} UNSUPPORTED_CLIENT_TYPE - Unused. */ Thrift.TApplicationExceptionType = { - 'UNKNOWN' : 0, - 'UNKNOWN_METHOD' : 1, - 'INVALID_MESSAGE_TYPE' : 2, - 'WRONG_METHOD_NAME' : 3, - 'BAD_SEQUENCE_ID' : 4, - 'MISSING_RESULT' : 5, - 'INTERNAL_ERROR' : 6, - 'PROTOCOL_ERROR' : 7, - 'INVALID_TRANSFORM' : 8, - 'INVALID_PROTOCOL' : 9, - 'UNSUPPORTED_CLIENT_TYPE' : 10 + UNKNOWN: 0, + UNKNOWN_METHOD: 1, + INVALID_MESSAGE_TYPE: 2, + WRONG_METHOD_NAME: 3, + BAD_SEQUENCE_ID: 4, + MISSING_RESULT: 5, + INTERNAL_ERROR: 6, + PROTOCOL_ERROR: 7, + INVALID_TRANSFORM: 8, + INVALID_PROTOCOL: 9, + UNSUPPORTED_CLIENT_TYPE: 10 }; /** @@ -194,7 +194,7 @@ Thrift.TApplicationExceptionType = { */ Thrift.TApplicationException = function(message, code) { this.message = message; - this.code = typeof code === "number" ? code : 0; + this.code = typeof code === 'number' ? code : 0; }; Thrift.inherits(Thrift.TApplicationException, Thrift.TException, 'TApplicationException'); @@ -572,14 +572,16 @@ Thrift.TWebSocketTransport.prototype = { var clientCallback = callback; return function(msg) { self.setRecvBuffer(msg); - clientCallback(); + if (clientCallback) { + clientCallback(); + } }; }())); } else { //Queue the send to go out __onOpen this.send_pending.push({ buf: this.send_buf, - cb: callback + cb: callback }); } }, @@ -590,8 +592,8 @@ Thrift.TWebSocketTransport.prototype = { //If the user made calls before the connection was fully //open, send them now this.send_pending.forEach(function(elem) { - this.socket.send(elem.buf); - this.callbacks.push((function() { + self.socket.send(elem.buf); + self.callbacks.push((function() { var clientCallback = elem.cb; return function(msg) { self.setRecvBuffer(msg); @@ -614,7 +616,7 @@ Thrift.TWebSocketTransport.prototype = { }, __onError: function(evt) { - console.log("Thrift WebSocket Error: " + evt.toString()); + console.log('Thrift WebSocket Error: ' + evt.toString()); this.socket.close(); }, @@ -1256,7 +1258,12 @@ Thrift.Protocol.prototype = { /** Deserializes the end of a list. */ readListEnd: function() { - this.readFieldEnd(); + var pos = this.rpos.pop() - 2; + var st = this.rstack; + st.pop(); + if (st instanceof Array && st.length > pos && st[pos].length > 0) { + st.push(st[pos].shift()); + } }, /** @@ -1312,7 +1319,11 @@ Thrift.Protocol.prototype = { if (f.length === 0) { r.value = undefined; } else { - r.value = f.shift(); + if (!f.isReversed) { + f.reverse(); + f.isReversed = true; + } + r.value = f.pop(); } } else if (f instanceof Object) { for (var i in f) { @@ -1431,6 +1442,9 @@ Thrift.Protocol.prototype = { } this.readListEnd(); return null; + + default: + throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.INVALID_DATA); } } }; @@ -1440,23 +1454,23 @@ Thrift.Protocol.prototype = { * Initializes a MutilplexProtocol Implementation as a Wrapper for Thrift.Protocol * @constructor */ -Thrift.MultiplexProtocol = function (srvName, trans, strictRead, strictWrite) { +Thrift.MultiplexProtocol = function(srvName, trans, strictRead, strictWrite) { Thrift.Protocol.call(this, trans, strictRead, strictWrite); this.serviceName = srvName; }; Thrift.inherits(Thrift.MultiplexProtocol, Thrift.Protocol, 'multiplexProtocol'); /** Override writeMessageBegin method of prototype*/ -Thrift.MultiplexProtocol.prototype.writeMessageBegin = function (name, type, seqid) { +Thrift.MultiplexProtocol.prototype.writeMessageBegin = function(name, type, seqid) { if (type === Thrift.MessageType.CALL || type === Thrift.MessageType.ONEWAY) { - Thrift.Protocol.prototype.writeMessageBegin.call(this, this.serviceName + ":" + name, type, seqid); + Thrift.Protocol.prototype.writeMessageBegin.call(this, this.serviceName + ':' + name, type, seqid); } else { Thrift.Protocol.prototype.writeMessageBegin.call(this, name, type, seqid); } }; -Thrift.Multiplexer = function () { +Thrift.Multiplexer = function() { this.seqid = 0; }; @@ -1471,12 +1485,12 @@ Thrift.Multiplexer = function () { * var protocol = new Thrift.Protocol(transport); * var client = mp.createClient('AuthService', AuthServiceClient, transport); */ -Thrift.Multiplexer.prototype.createClient = function (serviceName, SCl, transport) { +Thrift.Multiplexer.prototype.createClient = function(serviceName, SCl, transport) { if (SCl.Client) { SCl = SCl.Client; } var self = this; - SCl.prototype.new_seqid = function () { + SCl.prototype.new_seqid = function() { self.seqid += 1; return self.seqid; }; @@ -1519,7 +1533,7 @@ copyList = function(lst, types) { return result; }; -copyMap = function(obj, types){ +copyMap = function(obj, types) { if (!obj) {return obj; } @@ -1534,8 +1548,8 @@ copyMap = function(obj, types){ var Type = type; var result = {}, val; - for(var prop in obj) { - if(obj.hasOwnProperty(prop)) { + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) { val = obj[prop]; if (type === null) { result[prop] = val; diff --git a/vendor/git.apache.org/thrift.git/lib/js/test/build.properties b/vendor/git.apache.org/thrift.git/lib/js/test/build.properties new file mode 100644 index 0000000..8463668 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/js/test/build.properties @@ -0,0 +1,5 @@ +# Maven Ant tasks Jar details +mvn.ant.task.version=2.1.3 +mvn.repo=http://repo1.maven.org/maven2 +mvn.ant.task.url=${mvn.repo}/org/apache/maven/maven-ant-tasks/${mvn.ant.task.version} +mvn.ant.task.jar=maven-ant-tasks-${mvn.ant.task.version}.jar diff --git a/vendor/git.apache.org/thrift.git/lib/js/test/build.xml b/vendor/git.apache.org/thrift.git/lib/js/test/build.xml index b3a6b3e..04c1360 100755 --- a/vendor/git.apache.org/thrift.git/lib/js/test/build.xml +++ b/vendor/git.apache.org/thrift.git/lib/js/test/build.xml @@ -31,17 +31,21 @@ + + - + - - + + + + - + @@ -59,15 +63,16 @@ - + + You need libthrift*.jar and libthrift*test.jar located at - ${thrift.java.dir}/build + ${thrift.java.dir}/build/libs Did you compile Thrift Java library and its test suite by "ant compile-test"? @@ -84,6 +89,7 @@ + @@ -92,16 +98,19 @@ - + - - + + + + + - - + + @@ -161,6 +170,9 @@ + + + @@ -207,7 +219,17 @@ - + + + + + + + + + + + diff --git a/vendor/git.apache.org/thrift.git/lib/js/test/deep-constructor.test.js b/vendor/git.apache.org/thrift.git/lib/js/test/deep-constructor.test.js index 9a19809..82d3a1e 100644 --- a/vendor/git.apache.org/thrift.git/lib/js/test/deep-constructor.test.js +++ b/vendor/git.apache.org/thrift.git/lib/js/test/deep-constructor.test.js @@ -1,18 +1,18 @@ function serialize(data) { - var transport = new Thrift.Transport("/service"); - var protocol = new Thrift.Protocol(transport); - protocol.writeMessageBegin("", 0, 0); + const transport = new Thrift.Transport('/service'); + const protocol = new Thrift.Protocol(transport); + protocol.writeMessageBegin('', 0, 0); data.write(protocol); protocol.writeMessageEnd(); return transport.send_buf; } function deserialize(serialized, type) { - var transport = new Thrift.Transport("/service"); + const transport = new Thrift.Transport('/service'); transport.setRecvBuffer(serialized); - var protocol = new Thrift.Protocol(transport); + const protocol = new Thrift.Protocol(transport); protocol.readMessageBegin(); - var data = new type(); + const data = new type(); data.read(protocol); protocol.readMessageEnd(); return data; @@ -27,12 +27,12 @@ function createThriftObj() { struct_list_field: [ new Simple({value: 'b'}), - new Simple({value: 'c'}), + new Simple({value: 'c'}) ], struct_set_field: [ new Simple({value: 'd'}), - new Simple({value: 'e'}), + new Simple({value: 'e'}) ], struct_map_field: { @@ -61,7 +61,13 @@ function createThriftObj() { DB: new Simple({value: 'k'}) } ] - } + }, + + list_of_list_field: [ + ['one', 'two'], + ['three', 'four'], + ['five', 'six'] + ] } ); } @@ -75,12 +81,12 @@ function createJsObj() { struct_list_field: [ {value: 'b'}, - {value: 'c'}, + {value: 'c'} ], struct_set_field: [ {value: 'd'}, - {value: 'e'}, + {value: 'e'} ], struct_map_field: { @@ -108,7 +114,13 @@ function createJsObj() { DB: {value: 'k'} } ] - } + }, + + list_of_list_field: [ + ['one', 'two'], + ['three', 'four'], + ['five', 'six'] + ] }; } @@ -125,38 +137,44 @@ function assertValues(obj, assert) { assert.equal(obj.struct_nested_containers_field[0][0].C[1].value, 'i'); assert.equal(obj.struct_nested_containers_field2.D[0].DA.value, 'j'); assert.equal(obj.struct_nested_containers_field2.D[1].DB.value, 'k'); + assert.equal(obj.list_of_list_field[0][0], 'one'); + assert.equal(obj.list_of_list_field[0][1], 'two'); + assert.equal(obj.list_of_list_field[1][0], 'three'); + assert.equal(obj.list_of_list_field[1][1], 'four'); + assert.equal(obj.list_of_list_field[2][0], 'five'); + assert.equal(obj.list_of_list_field[2][1], 'six'); } -var cases = { +const cases = { - "Serialize/deserialize simple struct should return equal object": function(assert){ - var tObj = new Simple({value: 'a'}); - var received = deserialize(serialize(tObj), Simple); + 'Serialize/deserialize simple struct should return equal object': function(assert) { + const tObj = new Simple({value: 'a'}); + const received = deserialize(serialize(tObj), Simple); assert.ok(tObj !== received); assert.deepEqual(received, tObj); }, - "Serialize/deserialize should return equal object": function(assert){ - var tObj = createThriftObj(); - var received = deserialize(serialize(tObj), Complex); + 'Serialize/deserialize should return equal object': function(assert) { + const tObj = createThriftObj(); + const received = deserialize(serialize(tObj), Complex); assert.ok(tObj !== received); assert.deepEqual(received, tObj); }, - "Nested structs and containers initialized from plain js objects should serialize same as if initialized from thrift objects": function(assert) { - var tObj1 = createThriftObj(); - var tObj2 = new Complex(createJsObj()); + 'Nested structs and containers initialized from plain js objects should serialize same as if initialized from thrift objects': function(assert) { + const tObj1 = createThriftObj(); + const tObj2 = new Complex(createJsObj()); assertValues(tObj2, assert); assert.equal(serialize(tObj2), serialize(tObj1)); }, - "Modifications to args object should not affect constructed Thrift object": function (assert) { + 'Modifications to args object should not affect constructed Thrift object': function(assert) { - var args = createJsObj(); + const args = createJsObj(); assertValues(args, assert); - var tObj = new Complex(args); + const tObj = new Complex(args); assertValues(tObj, assert); args.struct_field.value = 'ZZZ'; @@ -174,8 +192,8 @@ var cases = { assertValues(tObj, assert); }, - "nulls are ok": function(assert) { - var tObj = new Complex({ + 'nulls are ok': function(assert) { + const tObj = new Complex({ struct_field: null, struct_list_field: null, struct_set_field: null, @@ -183,7 +201,7 @@ var cases = { struct_nested_containers_field: null, struct_nested_containers_field2: null }); - var received = deserialize(serialize(tObj), Complex); + const received = deserialize(serialize(tObj), Complex); assert.ok(tObj !== received); assert.deepEqual(tObj, received); } @@ -191,5 +209,5 @@ var cases = { }; Object.keys(cases).forEach(function(caseName) { - test(caseName, cases[caseName]); + QUnit.test(caseName, cases[caseName]); }); diff --git a/vendor/git.apache.org/thrift.git/lib/js/test/jsTestDriver.conf b/vendor/git.apache.org/thrift.git/lib/js/test/jsTestDriver.conf index b9702cd..eb1588c 100755 --- a/vendor/git.apache.org/thrift.git/lib/js/test/jsTestDriver.conf +++ b/vendor/git.apache.org/thrift.git/lib/js/test/jsTestDriver.conf @@ -7,6 +7,7 @@ load: # dependencies - build/js/lib/jquery.js - build/js/thrift.js + - gen-js/DoubleConstantsTest_constants.js - gen-js/ThriftTest_types.js - gen-js/ThriftTest.js # the test suite diff --git a/vendor/git.apache.org/thrift.git/lib/js/test/phantom-client.js b/vendor/git.apache.org/thrift.git/lib/js/test/phantom-client.js index f75b256..d517e71 100644 --- a/vendor/git.apache.org/thrift.git/lib/js/test/phantom-client.js +++ b/vendor/git.apache.org/thrift.git/lib/js/test/phantom-client.js @@ -44,10 +44,10 @@ var parseArgs = function(args) { var skips = [ '--transport=http', - '--protocol=json', + '--protocol=json' ]; var opts = { - port: '9090', + port: '9090' // protocol: 'json', }; var keys = {}; @@ -90,8 +90,8 @@ var opts = parseArgs(system.args.slice(1)); var port = opts.port; var transport = new Thrift.Transport('http://localhost:' + port + '/service'); - var protocol = new Thrift.Protocol(transport); - var client = new ThriftTest.ThriftTestClient(protocol); + var protocol = new Thrift.Protocol(transport); + var client = new ThriftTest.ThriftTestClient(protocol); // TODO: Remove duplicate code with test.js. @@ -110,17 +110,17 @@ } } - test("Void", function() { + test('Void', function() { equal(client.testVoid(), undefined); }); - test("Binary (String)", function() { + test('Binary (String)', function() { var binary = ''; for (var v = 255; v >= 0; --v) { binary += String.fromCharCode(v); } equal(client.testBinary(binary), binary); }); - test("Binary (Uint8Array)", function() { + test('Binary (Uint8Array)', function() { var binary = ''; for (var v = 255; v >= 0; --v) { binary += String.fromCharCode(v); @@ -131,7 +131,7 @@ } equal(client.testBinary(arr), binary); }); - test("String", function() { + test('String', function() { equal(client.testString(''), ''); equal(client.testString(stringTest), stringTest); @@ -140,41 +140,41 @@ ' backspace: \b formfeed: \f newline: \n return: \r tab: ' + ' now-all-of-them-together: "\\\/\b\n\r\t' + ' now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><'; - equal(client.testString(specialCharacters),specialCharacters); + equal(client.testString(specialCharacters), specialCharacters); }); - test("Double", function() { + test('Double', function() { equal(client.testDouble(0), 0); equal(client.testDouble(-1), -1); equal(client.testDouble(3.14), 3.14); - equal(client.testDouble(Math.pow(2,60)), Math.pow(2,60)); + equal(client.testDouble(Math.pow(2, 60)), Math.pow(2, 60)); }); - test("Bool", function() { + test('Bool', function() { equal(client.testBool(true), true); equal(client.testBool(false), false); }); - test("I8", function() { + test('I8', function() { equal(client.testByte(0), 0); equal(client.testByte(0x01), 0x01); }); - test("I32", function() { + test('I32', function() { equal(client.testI32(0), 0); - equal(client.testI32(Math.pow(2,30)), Math.pow(2,30)); - equal(client.testI32(-Math.pow(2,30)), -Math.pow(2,30)); + equal(client.testI32(Math.pow(2, 30)), Math.pow(2, 30)); + equal(client.testI32(-Math.pow(2, 30)), -Math.pow(2, 30)); }); - test("I64", function() { + test('I64', function() { equal(client.testI64(0), 0); //This is usually 2^60 but JS cannot represent anything over 2^52 accurately - equal(client.testI64(Math.pow(2,52)), Math.pow(2,52)); - equal(client.testI64(-Math.pow(2,52)), -Math.pow(2,52)); + equal(client.testI64(Math.pow(2, 52)), Math.pow(2, 52)); + equal(client.testI64(-Math.pow(2, 52)), -Math.pow(2, 52)); }); - test("Struct", function() { + test('Struct', function() { var structTestInput = new ThriftTest.Xtruct(); structTestInput.string_thing = 'worked'; structTestInput.byte_thing = 0x01; - structTestInput.i32_thing = Math.pow(2,30); + structTestInput.i32_thing = Math.pow(2, 30); //This is usually 2^60 but JS cannot represent anything over 2^52 accurately - structTestInput.i64_thing = Math.pow(2,52); + structTestInput.i64_thing = Math.pow(2, 52); var structTestOutput = client.testStruct(structTestInput); @@ -186,18 +186,18 @@ equal(JSON.stringify(structTestOutput), JSON.stringify(structTestInput)); }); - test("Nest", function() { + test('Nest', function() { var xtrTestInput = new ThriftTest.Xtruct(); xtrTestInput.string_thing = 'worked'; xtrTestInput.byte_thing = 0x01; - xtrTestInput.i32_thing = Math.pow(2,30); + xtrTestInput.i32_thing = Math.pow(2, 30); //This is usually 2^60 but JS cannot represent anything over 2^52 accurately - xtrTestInput.i64_thing = Math.pow(2,52); + xtrTestInput.i64_thing = Math.pow(2, 52); var nestTestInput = new ThriftTest.Xtruct2(); nestTestInput.byte_thing = 0x02; nestTestInput.struct_thing = xtrTestInput; - nestTestInput.i32_thing = Math.pow(2,15); + nestTestInput.i32_thing = Math.pow(2, 15); var nestTestOutput = client.testNest(nestTestInput); @@ -211,8 +211,8 @@ equal(JSON.stringify(nestTestOutput), JSON.stringify(nestTestInput)); }); - test("Map", function() { - var mapTestInput = {7:77, 8:88, 9:99}; + test('Map', function() { + var mapTestInput = {7: 77, 8: 88, 9: 99}; var mapTestOutput = client.testMap(mapTestInput); @@ -221,10 +221,10 @@ } }); - test("StringMap", function() { + test('StringMap', function() { var mapTestInput = { - "a":"123", "a b":"with spaces ", "same":"same", "0":"numeric key", - "longValue":stringTest, stringTest:"long key" + 'a': '123', 'a b': 'with spaces ', 'same': 'same', '0': 'numeric key', + 'longValue': stringTest, stringTest: 'long key' }; var mapTestOutput = client.testStringMap(mapTestInput); @@ -234,30 +234,30 @@ } }); - test("Set", function() { - var setTestInput = [1,2,3]; + test('Set', function() { + var setTestInput = [1, 2, 3]; ok(client.testSet(setTestInput), setTestInput); }); - test("List", function() { - var listTestInput = [1,2,3]; + test('List', function() { + var listTestInput = [1, 2, 3]; ok(client.testList(listTestInput), listTestInput); }); - test("Enum", function() { + test('Enum', function() { equal(client.testEnum(ThriftTest.Numberz.ONE), ThriftTest.Numberz.ONE); }); - test("TypeDef", function() { + test('TypeDef', function() { equal(client.testTypedef(69), 69); }); - test("Skip", function() { + test('Skip', function() { var structTestInput = new ThriftTest.Xtruct(); var modifiedClient = new ThriftTest.ThriftTestClient(protocol); modifiedClient.recv_testStruct = function() { - var input = modifiedClient.input; + var input = modifiedClient.input; var xtruct3 = new ThriftTest.Xtruct3(); input.readMessageBegin(); @@ -278,9 +278,9 @@ }; structTestInput.string_thing = 'worked'; - structTestInput.byte_thing = 0x01; - structTestInput.i32_thing = Math.pow(2,30); - structTestInput.i64_thing = Math.pow(2,52); + structTestInput.byte_thing = 0x01; + structTestInput.i32_thing = Math.pow(2, 30); + structTestInput.i64_thing = Math.pow(2, 52); var structTestOutput = modifiedClient.testStruct(structTestInput); @@ -291,10 +291,10 @@ equal(structTestOutput.i64_thing, structTestInput.i64_thing); }); - test("MapMap", function() { + test('MapMap', function() { var mapMapTestExpectedResult = { - "4":{"1":1,"2":2,"3":3,"4":4}, - "-4":{"-4":-4, "-3":-3, "-2":-2, "-1":-1} + '4': {'1': 1, '2': 2, '3': 3, '4': 4}, + '-4': {'-4': -4, '-3': -3, '-2': -2, '-1': -1} }; var mapMapTestOutput = client.testMapMap(1); @@ -309,55 +309,55 @@ checkRecursively(mapMapTestOutput, mapMapTestExpectedResult); }); - test("Xception", function() { + test('Xception', function() { try { - client.testException("Xception"); + client.testException('Xception'); ok(false); } catch (e) { equal(e.errorCode, 1001); - equal(e.message, "Xception"); + equal(e.message, 'Xception'); } }); - test("no Exception", function() { + test('no Exception', function() { try { - client.testException("no Exception"); + client.testException('no Exception'); } catch (e) { ok(false); } }); - test("TException", function() { + test('TException', function() { try { - client.testException("TException"); + client.testException('TException'); ok(false); - } catch(e) { + } catch (e) { ok(ok); } }); var crazy = { - "userMap":{ "5":5, "8":8 }, - "xtructs":[{ - "string_thing":"Goodbye4", - "byte_thing":4, - "i32_thing":4, - "i64_thing":4 + 'userMap': { '5': 5, '8': 8 }, + 'xtructs': [{ + 'string_thing': 'Goodbye4', + 'byte_thing': 4, + 'i32_thing': 4, + 'i64_thing': 4 }, { - "string_thing":"Hello2", - "byte_thing":2, - "i32_thing":2, - "i64_thing":2 + 'string_thing': 'Hello2', + 'byte_thing': 2, + 'i32_thing': 2, + 'i64_thing': 2 }] }; - test("Insanity", function() { + test('Insanity', function() { var insanity = { - "1":{ - "2":crazy, - "3":crazy + '1': { + '2': crazy, + '3': crazy }, - "2":{ "6":{ "userMap":null, "xtructs":null } } + '2': { '6': { 'userMap': null, 'xtructs': null } } }; var res = client.testInsanity(new ThriftTest.Insanity(crazy)); ok(res, JSON.stringify(res)); diff --git a/vendor/git.apache.org/thrift.git/lib/js/test/phantomjs-qunit.js b/vendor/git.apache.org/thrift.git/lib/js/test/phantomjs-qunit.js index a840db6..c1d7a5b 100755 --- a/vendor/git.apache.org/thrift.git/lib/js/test/phantomjs-qunit.js +++ b/vendor/git.apache.org/thrift.git/lib/js/test/phantomjs-qunit.js @@ -28,18 +28,18 @@ function waitFor(testFx, onReady, timeOutMillis) { start = new Date().getTime(), condition = false, interval = setInterval(function() { - if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) { + if ((new Date().getTime() - start < maxtimeOutMillis) && !condition) { // If not time-out yet and condition not yet fulfilled - condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code + condition = (typeof(testFx) === 'string' ? eval(testFx) : testFx()); //< defensive code } else { - if(!condition) { + if (!condition) { // If condition still not fulfilled (timeout but condition is 'false') console.log("'waitFor()' timeout"); phantom.exit(1); } else { // Condition fulfilled (timeout and/or condition is 'true') - console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms."); - if (typeof(onReady) === "string") { + console.log("'waitFor()' finished in " + (new Date().getTime() - start) + 'ms.'); + if (typeof(onReady) === 'string') { eval(onReady); } else { onReady(); //< Do what it's supposed to do once the condition is fulfilled @@ -63,21 +63,21 @@ page.onConsoleMessage = function(msg) { console.log(msg); }; -page.open(system.args[1], function(status){ - if (status !== "success") { - console.log("Unable to access network"); +page.open(system.args[1], function(status) { + if (status !== 'success') { + console.log('Unable to access network'); phantom.exit(1); } else { - waitFor(function(){ - return page.evaluate(function(){ + waitFor(function() { + return page.evaluate(function() { var el = document.getElementById('qunit-testresult'); if (el && el.innerText.match('completed')) { return true; } return false; }); - }, function(){ - var failedNum = page.evaluate(function(){ + }, function() { + var failedNum = page.evaluate(function() { var el = document.getElementById('qunit-testresult'); console.log(el.innerText); try { diff --git a/vendor/git.apache.org/thrift.git/lib/js/test/server_http.js b/vendor/git.apache.org/thrift.git/lib/js/test/server_http.js index e195e80..8380c3a 100644 --- a/vendor/git.apache.org/thrift.git/lib/js/test/server_http.js +++ b/vendor/git.apache.org/thrift.git/lib/js/test/server_http.js @@ -17,33 +17,39 @@ * under the License. */ -//This HTTP server is designed to serve the test.html browser -// based JavaScript test page (which must be in the current directory). +// This HTTP server is designed to serve the test.html browser +// based JavaScript test page (which must be in the current directory). // This server also supplies the Thrift based test service, which depends // on the standard ThriftTest.thrift IDL service (which must be compiled // for Node and browser based JavaScript in ./gen-nodejs and ./gen-js -// respectively). +// respectively). +// +// Using the command flag --es6, this server can be run using nodejs code built +// for the es6 environment or for pre-es6 environment. +// -var thrift = require('../../nodejs/lib/thrift'); -var ThriftTestSvc = require('./gen-nodejs/ThriftTest.js'); -var ThriftTestHandler = require('./test_handler').ThriftTestHandler; +const thrift = require('../../nodejs/lib/thrift'); +const es6Mode = process.argv.includes('--es6'); +const genFolder = es6Mode ? 'gen-nodejs-es6' : 'gen-nodejs'; +const ThriftTestSvc = require(`./${genFolder}/ThriftTest.js`); +const ThriftTestHandler = require('./test_handler').ThriftTestHandler; -var ThriftTestSvcOpt = { +const ThriftTestSvcOpt = { transport: thrift.TBufferedTransport, protocol: thrift.TJSONProtocol, processor: ThriftTestSvc, handler: ThriftTestHandler }; -var ThriftWebServerOptions = { - files: ".", +const ThriftWebServerOptions = { + files: __dirname, services: { - "/service": ThriftTestSvcOpt + '/service': ThriftTestSvcOpt } }; -var server = thrift.createWebServer(ThriftWebServerOptions); -var port = 8088; +const server = thrift.createWebServer(ThriftWebServerOptions); +const port = es6Mode ? 8088 : 8089; server.listen(port); -console.log("Serving files from: " + __dirname); -console.log("Http/Thrift Server running on port: " + port); +console.log(`Serving files from: ${__dirname}`); +console.log(`Http/Thrift Server (ES6 mode ${es6Mode}) running on port: ${port}`); diff --git a/vendor/git.apache.org/thrift.git/lib/js/test/server_https.js b/vendor/git.apache.org/thrift.git/lib/js/test/server_https.js index af1745b..1a171dd 100644 --- a/vendor/git.apache.org/thrift.git/lib/js/test/server_https.js +++ b/vendor/git.apache.org/thrift.git/lib/js/test/server_https.js @@ -18,7 +18,7 @@ */ //This HTTP server is designed to server the test.html browser -// based JavaScript test page (which must be in the current directory). +// based JavaScript test page (which must be in the current directory). // This server also supplies the Thrift based test service, which depends // on the standard ThriftTest.thrift IDL service (which must be compiled // for Node and browser based JavaScript in ./gen-nodejs and ./gen-js @@ -26,32 +26,34 @@ // support libraries for test.html (jquery.js, qunit.js and qunit.css // in ./build/js/lib). -var fs = require("fs"); -var thrift = require('../../nodejs/lib/thrift'); -var ThriftTestSvc = require('./gen-nodejs/ThriftTest.js'); -var ThriftTestHandler = require('./test_handler').ThriftTestHandler; +const fs = require('fs'); +const thrift = require('../../nodejs/lib/thrift'); +const es6Mode = process.argv.includes('--es6'); +const genFolder = es6Mode ? 'gen-nodejs-es6' : 'gen-nodejs'; +const ThriftTestSvc = require(`./${genFolder}/ThriftTest.js`); +const ThriftTestHandler = require('./test_handler').ThriftTestHandler; //Setup the I/O stack options for the ThriftTest service -var ThriftTestSvcOpt = { +const ThriftTestSvcOpt = { transport: thrift.TBufferedTransport, protocol: thrift.TJSONProtocol, processor: ThriftTestSvc, handler: ThriftTestHandler }; -var ThriftWebServerOptions = { - files: ".", +const ThriftWebServerOptions = { + files: __dirname, tls: { - key: fs.readFileSync("../../../test/keys/server.key"), - cert: fs.readFileSync("../../../test/keys/server.crt") - }, + key: fs.readFileSync('../../../test/keys/server.key'), + cert: fs.readFileSync('../../../test/keys/server.crt') + }, services: { - "/service": ThriftTestSvcOpt + '/service': ThriftTestSvcOpt } }; -var server = thrift.createWebServer(ThriftWebServerOptions); -var port = 8089; +const server = thrift.createWebServer(ThriftWebServerOptions); +const port = es6Mode ? 8090 : 8091; server.listen(port); -console.log("Serving files from: " + __dirname); -console.log("Http/Thrift Server running on port: " + port); +console.log(`Serving files from: ${__dirname}`); +console.log(`Http/Thrift Server (ES6 mode ${es6Mode}) running on port: ${port}`); diff --git a/vendor/git.apache.org/thrift.git/lib/js/test/test-async.js b/vendor/git.apache.org/thrift.git/lib/js/test/test-async.js index 336e2bc..8c6b13e 100644 --- a/vendor/git.apache.org/thrift.git/lib/js/test/test-async.js +++ b/vendor/git.apache.org/thrift.git/lib/js/test/test-async.js @@ -17,9 +17,9 @@ * under the License. */ /* jshint -W100 */ - + /* - * Fully Async JavaScript test suite for ThriftTest.thrift. + * Fully Async JavaScript test suite for ThriftTest.thrift. * These tests are designed to exercise the WebSocket transport * (which is exclusively async). * @@ -30,319 +30,341 @@ // all Languages in UTF-8 -var stringTest = "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, Asturianu, Aymar aru, AzÉ™rbaycan, Башҡорт, Boarisch, ŽemaitÄ—Å¡ka, БеларуÑкаÑ, БеларуÑÐºÐ°Ñ (тарашкевіца), БългарÑки, Bamanankan, বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Ðохчийн, Cebuano, á£áŽ³áŽ©, ÄŒesky, СловѣÌньÑкъ / ⰔⰎⰑⰂⰡâ°â° â°”â°â°Ÿ, Чӑвашла, Cymraeg, Dansk, Zazaki, Þ‹Þ¨ÞˆÞ¬Þ€Þ¨Þ„Þ¦ÞÞ°, Ελληνικά, Emiliàn e rumagnòl, English, Esperanto, Español, Eesti, Euskara, ÙØ§Ø±Ø³ÛŒ, Suomi, Võro, Føroyskt, Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, Avañe'ẽ, ગà«àªœàª°àª¾àª¤à«€, Gaelg, עברית, हिनà¥à¤¦à¥€, Fiji Hindi, Hrvatski, Kreyòl ayisyen, Magyar, Õ€Õ¡ÕµÕ¥Ö€Õ¥Õ¶, Interlingua, Bahasa Indonesia, Ilokano, Ido, Ãslenska, Italiano, 日本語, Lojban, Basa Jawa, ქáƒáƒ áƒ—ული, Kongo, Kalaallisut, ಕನà³à²¨à²¡, 한국어, Къарачай-Малкъар, Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, LatvieÅ¡u, Basa Banyumasan, Malagasy, МакедонÑки, മലയാളം, मराठी, Bahasa Melayu, Ù…Ø§Ø²ÙØ±ÙˆÙ†ÛŒ, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, ‪Norsk (nynorsk)‬, ‪Norsk (bokmÃ¥l)‬, Nouormand, Diné bizaad, Occitan, Иронау, Papiamentu, Deitsch, Norfuk / Pitkern, Polski, پنجابی, پښتو, Português, Runa Simi, Rumantsch, Romani, Română, РуÑÑкий, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple English, SlovenÄina, SlovenÅ¡Äina, СрпÑки / Srpski, Seeltersk, Svenska, Kiswahili, தமிழà¯, తెలà±à°—à±, Тоҷикӣ, ไทย, Türkmençe, Tagalog, Türkçe, Татарча/Tatarça, УкраїнÑька, اردو, Tiếng Việt, Volapük, Walon, Winaray, å´è¯­, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, Bân-lâm-gú, 粵語"; - -function checkRecursively(map1, map2) { +const stringTest = "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, Asturianu, Aymar aru, AzÉ™rbaycan, Башҡорт, Boarisch, ŽemaitÄ—Å¡ka, БеларуÑкаÑ, БеларуÑÐºÐ°Ñ (тарашкевіца), БългарÑки, Bamanankan, বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Ðохчийн, Cebuano, á£áŽ³áŽ©, ÄŒesky, СловѣÌньÑкъ / ⰔⰎⰑⰂⰡâ°â° â°”â°â°Ÿ, Чӑвашла, Cymraeg, Dansk, Zazaki, Þ‹Þ¨ÞˆÞ¬Þ€Þ¨Þ„Þ¦ÞÞ°, Ελληνικά, Emiliàn e rumagnòl, English, Esperanto, Español, Eesti, Euskara, ÙØ§Ø±Ø³ÛŒ, Suomi, Võro, Føroyskt, Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, Avañe'ẽ, ગà«àªœàª°àª¾àª¤à«€, Gaelg, עברית, हिनà¥à¤¦à¥€, Fiji Hindi, Hrvatski, Kreyòl ayisyen, Magyar, Õ€Õ¡ÕµÕ¥Ö€Õ¥Õ¶, Interlingua, Bahasa Indonesia, Ilokano, Ido, Ãslenska, Italiano, 日本語, Lojban, Basa Jawa, ქáƒáƒ áƒ—ული, Kongo, Kalaallisut, ಕನà³à²¨à²¡, 한국어, Къарачай-Малкъар, Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, LatvieÅ¡u, Basa Banyumasan, Malagasy, МакедонÑки, മലയാളം, मराठी, Bahasa Melayu, Ù…Ø§Ø²ÙØ±ÙˆÙ†ÛŒ, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, ‪Norsk (nynorsk)‬, ‪Norsk (bokmÃ¥l)‬, Nouormand, Diné bizaad, Occitan, Иронау, Papiamentu, Deitsch, Norfuk / Pitkern, Polski, پنجابی, پښتو, Português, Runa Simi, Rumantsch, Romani, Română, РуÑÑкий, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple English, SlovenÄina, SlovenÅ¡Äina, СрпÑки / Srpski, Seeltersk, Svenska, Kiswahili, தமிழà¯, తెలà±à°—à±, Тоҷикӣ, ไทย, Türkmençe, Tagalog, Türkçe, Татарча/Tatarça, УкраїнÑька, اردو, Tiếng Việt, Volapük, Walon, Winaray, å´è¯­, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, Bân-lâm-gú, 粵語"; + +function checkRecursively(assert, map1, map2) { if (typeof map1 !== 'function' && typeof map2 !== 'function') { if (!map1 || typeof map1 !== 'object') { - equal(map1, map2); + assert.equal(map1, map2); } else { - for (var key in map1) { - checkRecursively(map1[key], map2[key]); + for (let key in map1) { + checkRecursively(assert, map1[key], map2[key]); } } } } -module("Base Types"); +QUnit.module('Base Types'); - asyncTest("Void", function() { - expect( 1 ); + QUnit.test('Void', function(assert) { + assert.expect(1); + const done = assert.async(); client.testVoid(function(result) { - equal(result, undefined); - QUnit.start(); + assert.equal(result, undefined); + done(); }); }); - - - asyncTest("String", function() { - expect( 3 ); - QUnit.stop(2); - client.testString('', function(result){ - equal(result, ''); - QUnit.start(); + + + QUnit.test('String', function(assert) { + assert.expect(3); + const done = assert.async(3); + client.testString('', function(result) { + assert.equal(result, ''); + done(); }); - client.testString(stringTest, function(result){ - equal(result, stringTest); - QUnit.start(); + client.testString(stringTest, function(result) { + assert.equal(result, stringTest); + done(); }); - var specialCharacters = 'quote: \" backslash:' + + const specialCharacters = 'quote: \" backslash:' + ' forwardslash-escaped: \/ ' + ' backspace: \b formfeed: \f newline: \n return: \r tab: ' + ' now-all-of-them-together: "\\\/\b\n\r\t' + ' now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><'; - client.testString(specialCharacters, function(result){ - equal(result, specialCharacters); - QUnit.start(); + client.testString(specialCharacters, function(result) { + assert.equal(result, specialCharacters); + done(); }); }); - asyncTest("Double", function() { - expect( 4 ); - QUnit.stop(3); - client.testDouble(0, function(result){ - equal(result, 0); - QUnit.start(); + QUnit.test('Double', function(assert) { + assert.expect(4); + const done = assert.async(4); + client.testDouble(0, function(result) { + assert.equal(result, 0); + done(); }); - client.testDouble(-1, function(result){ - equal(result, -1); - QUnit.start(); + client.testDouble(-1, function(result) { + assert.equal(result, -1); + done(); }); - client.testDouble(3.14, function(result){ - equal(result, 3.14); - QUnit.start(); + client.testDouble(3.14, function(result) { + assert.equal(result, 3.14); + done(); }); - client.testDouble(Math.pow(2,60), function(result){ - equal(result, Math.pow(2,60)); - QUnit.start(); + client.testDouble(Math.pow(2, 60), function(result) { + assert.equal(result, Math.pow(2, 60)); + done(); }); }); - // TODO: add testBinary() - asyncTest("Byte", function() { - expect( 2 ); - QUnit.stop(); + // TODO: add testBinary() + QUnit.test('Byte', function(assert) { + assert.expect(2); + const done = assert.async(2); client.testByte(0, function(result) { - equal(result, 0); - QUnit.start(); + assert.equal(result, 0); + done(); }); client.testByte(0x01, function(result) { - equal(result, 0x01); - QUnit.start(); + assert.equal(result, 0x01); + done(); }); }); - asyncTest("I32", function() { - expect( 3 ); - QUnit.stop(2); - client.testI32(0, function(result){ - equal(result, 0); - QUnit.start(); + QUnit.test('I32', function(assert) { + assert.expect(3); + const done = assert.async(3); + client.testI32(0, function(result) { + assert.equal(result, 0); + done(); }); - client.testI32(Math.pow(2,30), function(result){ - equal(result, Math.pow(2,30)); - QUnit.start(); + client.testI32(Math.pow(2, 30), function(result) { + assert.equal(result, Math.pow(2, 30)); + done(); }); - client.testI32(-Math.pow(2,30), function(result){ - equal(result, -Math.pow(2,30)); - QUnit.start(); + client.testI32(-Math.pow(2, 30), function(result) { + assert.equal(result, -Math.pow(2, 30)); + done(); }); }); - asyncTest("I64", function() { - expect( 3 ); - QUnit.stop(2); - client.testI64(0, function(result){ - equal(result, 0); - QUnit.start(); + QUnit.test('I64', function(assert) { + assert.expect(3); + const done = assert.async(3); + client.testI64(0, function(result) { + assert.equal(result, 0); + done(); }); //This is usually 2^60 but JS cannot represent anything over 2^52 accurately - client.testI64(Math.pow(2,52), function(result){ - equal(result, Math.pow(2,52)); - QUnit.start(); + client.testI64(Math.pow(2, 52), function(result) { + assert.equal(result, Math.pow(2, 52)); + done(); }); - client.testI64(-Math.pow(2,52), function(result){ - equal(result, -Math.pow(2,52)); - QUnit.start(); + client.testI64(-Math.pow(2, 52), function(result) { + assert.equal(result, -Math.pow(2, 52)); + done(); }); }); - - -module("Structured Types"); - asyncTest("Struct", function() { - expect( 5 ); - var structTestInput = new ThriftTest.Xtruct(); + +QUnit.module('Structured Types'); + + QUnit.test('Struct', function(assert) { + assert.expect(5); + const done = assert.async(); + const structTestInput = new ThriftTest.Xtruct(); structTestInput.string_thing = 'worked'; structTestInput.byte_thing = 0x01; - structTestInput.i32_thing = Math.pow(2,30); + structTestInput.i32_thing = Math.pow(2, 30); //This is usually 2^60 but JS cannot represent anything over 2^52 accurately - structTestInput.i64_thing = Math.pow(2,52); + structTestInput.i64_thing = Math.pow(2, 52); - client.testStruct(structTestInput, function(result){ - equal(result.string_thing, structTestInput.string_thing); - equal(result.byte_thing, structTestInput.byte_thing); - equal(result.i32_thing, structTestInput.i32_thing); - equal(result.i64_thing, structTestInput.i64_thing); - equal(JSON.stringify(result), JSON.stringify(structTestInput)); - QUnit.start(); + client.testStruct(structTestInput, function(result) { + assert.equal(result.string_thing, structTestInput.string_thing); + assert.equal(result.byte_thing, structTestInput.byte_thing); + assert.equal(result.i32_thing, structTestInput.i32_thing); + assert.equal(result.i64_thing, structTestInput.i64_thing); + assert.equal(JSON.stringify(result), JSON.stringify(structTestInput)); + done(); }); }); - asyncTest("Nest", function() { - expect( 7 ); - var xtrTestInput = new ThriftTest.Xtruct(); + QUnit.test('Nest', function(assert) { + assert.expect(7); + const done = assert.async(); + const xtrTestInput = new ThriftTest.Xtruct(); xtrTestInput.string_thing = 'worked'; xtrTestInput.byte_thing = 0x01; - xtrTestInput.i32_thing = Math.pow(2,30); + xtrTestInput.i32_thing = Math.pow(2, 30); //This is usually 2^60 but JS cannot represent anything over 2^52 accurately - xtrTestInput.i64_thing = Math.pow(2,52); - - var nestTestInput = new ThriftTest.Xtruct2(); + xtrTestInput.i64_thing = Math.pow(2, 52); + + const nestTestInput = new ThriftTest.Xtruct2(); nestTestInput.byte_thing = 0x02; nestTestInput.struct_thing = xtrTestInput; - nestTestInput.i32_thing = Math.pow(2,15); - - client.testNest(nestTestInput, function(result){ - equal(result.byte_thing, nestTestInput.byte_thing); - equal(result.struct_thing.string_thing, nestTestInput.struct_thing.string_thing); - equal(result.struct_thing.byte_thing, nestTestInput.struct_thing.byte_thing); - equal(result.struct_thing.i32_thing, nestTestInput.struct_thing.i32_thing); - equal(result.struct_thing.i64_thing, nestTestInput.struct_thing.i64_thing); - equal(result.i32_thing, nestTestInput.i32_thing); - equal(JSON.stringify(result), JSON.stringify(nestTestInput)); - QUnit.start(); + nestTestInput.i32_thing = Math.pow(2, 15); + + client.testNest(nestTestInput, function(result) { + assert.equal(result.byte_thing, nestTestInput.byte_thing); + assert.equal(result.struct_thing.string_thing, nestTestInput.struct_thing.string_thing); + assert.equal(result.struct_thing.byte_thing, nestTestInput.struct_thing.byte_thing); + assert.equal(result.struct_thing.i32_thing, nestTestInput.struct_thing.i32_thing); + assert.equal(result.struct_thing.i64_thing, nestTestInput.struct_thing.i64_thing); + assert.equal(result.i32_thing, nestTestInput.i32_thing); + assert.equal(JSON.stringify(result), JSON.stringify(nestTestInput)); + done(); }); }); - asyncTest("Map", function() { - expect( 3 ); - var mapTestInput = {7:77, 8:88, 9:99}; + QUnit.test('Map', function(assert) { + assert.expect(3); + const done = assert.async(); + const mapTestInput = {7: 77, 8: 88, 9: 99}; - client.testMap(mapTestInput, function(result){ - for (var key in result) { - equal(result[key], mapTestInput[key]); + client.testMap(mapTestInput, function(result) { + for (let key in result) { + assert.equal(result[key], mapTestInput[key]); } - QUnit.start(); + done(); }); }); - asyncTest("StringMap", function() { - expect( 6 ); - var mapTestInput = { - "a":"123", "a b":"with spaces ", "same":"same", "0":"numeric key", - "longValue":stringTest, stringTest:"long key" + QUnit.test('StringMap', function(assert) { + assert.expect(6); + const done = assert.async(); + const mapTestInput = { + 'a': '123', 'a b': 'with spaces ', 'same': 'same', '0': 'numeric key', + 'longValue': stringTest, stringTest: 'long key' }; - client.testStringMap(mapTestInput, function(result){ - for (var key in result) { - equal(result[key], mapTestInput[key]); + client.testStringMap(mapTestInput, function(result) { + for (let key in result) { + assert.equal(result[key], mapTestInput[key]); } - QUnit.start(); + done(); }); }); - asyncTest("Set", function() { - expect( 1 ); - var setTestInput = [1,2,3]; - client.testSet(setTestInput, function(result){ - ok(result, setTestInput); - QUnit.start(); + QUnit.test('Set', function(assert) { + assert.expect(1); + const done = assert.async(); + const setTestInput = [1, 2, 3]; + client.testSet(setTestInput, function(result) { + assert.ok(result, setTestInput); + done(); }); }); - asyncTest("List", function() { - expect( 1 ); - var listTestInput = [1,2,3]; - client.testList(listTestInput, function(result){ - ok(result, listTestInput); - QUnit.start(); + QUnit.test('List', function(assert) { + assert.expect(1); + const done = assert.async(); + const listTestInput = [1, 2, 3]; + client.testList(listTestInput, function(result) { + assert.ok(result, listTestInput); + done(); }); }); - asyncTest("Enum", function() { - expect( 1 ); - client.testEnum(ThriftTest.Numberz.ONE, function(result){ - equal(result, ThriftTest.Numberz.ONE); - QUnit.start(); + QUnit.test('Enum', function(assert) { + assert.expect(1); + const done = assert.async(); + client.testEnum(ThriftTest.Numberz.ONE, function(result) { + assert.equal(result, ThriftTest.Numberz.ONE); + done(); }); }); - asyncTest("TypeDef", function() { - expect( 1 ); - client.testTypedef(69, function(result){ - equal(result, 69); - QUnit.start(); + QUnit.test('TypeDef', function(assert) { + assert.expect(1); + const done = assert.async(); + client.testTypedef(69, function(result) { + assert.equal(result, 69); + done(); }); }); -module("deeper!"); +QUnit.module('deeper!'); - asyncTest("MapMap", function() { - expect( 16 ); - var mapMapTestExpectedResult = { - "4":{"1":1,"2":2,"3":3,"4":4}, - "-4":{"-4":-4, "-3":-3, "-2":-2, "-1":-1} + QUnit.test('MapMap', function(assert) { + assert.expect(16); + const done = assert.async(); + const mapMapTestExpectedResult = { + '4': {'1': 1, '2': 2, '3': 3, '4': 4}, + '-4': {'-4': -4, '-3': -3, '-2': -2, '-1': -1} }; - client.testMapMap(1, function(result){ - for (var key in result) { - for (var key2 in result[key]) { - equal(result[key][key2], mapMapTestExpectedResult[key][key2]); + client.testMapMap(1, function(result) { + for (let key in result) { + for (let key2 in result[key]) { + assert.equal(result[key][key2], mapMapTestExpectedResult[key][key2]); } } - checkRecursively(result, mapMapTestExpectedResult); - QUnit.start(); + checkRecursively(assert, result, mapMapTestExpectedResult); + done(); }); }); -module("Exception"); +QUnit.module('Exception'); - asyncTest("Xception", function() { - expect(2); - client.testException("Xception", function(e){ - equal(e.errorCode, 1001); - equal(e.message, "Xception"); - QUnit.start(); + QUnit.test('Xception', function(assert) { + assert.expect(2); + const done = assert.async(); + client.testException('Xception', function(e) { + assert.equal(e.errorCode, 1001); + assert.equal(e.message, 'Xception'); + done(); }); }); - asyncTest("no Exception", 0, function() { - expect( 1 ); - client.testException("no Exception", function(e){ - ok(!e); - QUnit.start(); + QUnit.test('no Exception', function(assert) { + assert.expect(1); + const done = assert.async(); + client.testException('no Exception', function(e) { + assert.ok(!e); + done(); }); }); -module("Insanity"); +QUnit.module('Insanity'); - asyncTest("testInsanity", function() { - expect( 24 ); - var insanity = { - "1":{ - "2":{ - "userMap":{ "5":5, "8":8 }, - "xtructs":[{ - "string_thing":"Goodbye4", - "byte_thing":4, - "i32_thing":4, - "i64_thing":4 + QUnit.test('testInsanity', function(assert) { + assert.expect(24); + const done = assert.async(); + const insanity = { + '1': { + '2': { + 'userMap': { '5': 5, '8': 8 }, + 'xtructs': [{ + 'string_thing': 'Goodbye4', + 'byte_thing': 4, + 'i32_thing': 4, + 'i64_thing': 4 }, { - "string_thing":"Hello2", - "byte_thing":2, - "i32_thing":2, - "i64_thing":2 + 'string_thing': 'Hello2', + 'byte_thing': 2, + 'i32_thing': 2, + 'i64_thing': 2 } ] }, - "3":{ - "userMap":{ "5":5, "8":8 }, - "xtructs":[{ - "string_thing":"Goodbye4", - "byte_thing":4, - "i32_thing":4, - "i64_thing":4 + '3': { + 'userMap': { '5': 5, '8': 8 }, + 'xtructs': [{ + 'string_thing': 'Goodbye4', + 'byte_thing': 4, + 'i32_thing': 4, + 'i64_thing': 4 }, { - "string_thing":"Hello2", - "byte_thing":2, - "i32_thing":2, - "i64_thing":2 + 'string_thing': 'Hello2', + 'byte_thing': 2, + 'i32_thing': 2, + 'i64_thing': 2 } ] } }, - "2":{ "6":{ "userMap":null, "xtructs":null } } + '2': { '6': { 'userMap': null, 'xtructs': null } } }; - client.testInsanity(new ThriftTest.Insanity(), function(res){ - ok(res, JSON.stringify(res)); - ok(insanity, JSON.stringify(insanity)); - checkRecursively(res, insanity); - QUnit.start(); + client.testInsanity(new ThriftTest.Insanity(), function(res) { + assert.ok(res, JSON.stringify(res)); + assert.ok(insanity, JSON.stringify(insanity)); + checkRecursively(assert, res, insanity); + done(); }); }); +QUnit.module('Oneway'); + QUnit.test('testOneway', function(assert) { + assert.expect(1); + const done = assert.async(); + client.testOneway(1, function(result) { + assert.equal(result, undefined); + done(); + }); + }); diff --git a/vendor/git.apache.org/thrift.git/lib/js/test/test-deep-constructor.html b/vendor/git.apache.org/thrift.git/lib/js/test/test-deep-constructor.html index 5835dc8..4c5fb02 100755 --- a/vendor/git.apache.org/thrift.git/lib/js/test/test-deep-constructor.html +++ b/vendor/git.apache.org/thrift.git/lib/js/test/test-deep-constructor.html @@ -25,11 +25,11 @@ - + - - + + diff --git a/vendor/git.apache.org/thrift.git/lib/js/test/test-double-rendering.html b/vendor/git.apache.org/thrift.git/lib/js/test/test-double-rendering.html new file mode 100644 index 0000000..240cb39 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/js/test/test-double-rendering.html @@ -0,0 +1,55 @@ ++ + + + + + Rendering Double Constants in JS: Unit Test + + + + + + + + + + + + + + + + + + +

    Rendering Double Constants in JS: Unit Test

    +

    +
    +

    +
    + + + diff --git a/vendor/git.apache.org/thrift.git/lib/js/test/test-double-rendering.js b/vendor/git.apache.org/thrift.git/lib/js/test/test-double-rendering.js new file mode 100644 index 0000000..b4b79b8 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/js/test/test-double-rendering.js @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + /* jshint -W100 */ + +/* + * JavaScript test suite for double constants inside + * DebugProtoTest.thrift. These tests will run against Normal (-gen js) + * Apache Thrift interfaces. + * + * Synchronous blocking calls should be identical in both + * Normal and jQuery interfaces. All synchronous tests belong + * here. + * + * Asynchronous success callbacks passed as the last parameter + * of an RPC call should be identical in both Normal and jQuery + * interfaces. Async success tests belong here. + * + * Asynchronous exception processing is different in Normal + * and jQuery interfaces. Such tests belong in the test-nojq.js + * or test-jq.js files respectively. jQuery specific XHR object + * tests also belong in test-jq.js. Do not create any jQuery + * dependencies in this file or in test-nojq.js + * + * To compile client code for this test use: + * $ thrift -gen js ThriftTest.thrift + * $ thrift -gen js DebugProtoTest.thrift + * + * See also: + * ++ test-nojq.js for "-gen js" only tests + */ + +// double assertion threshold +const EPSILON = 0.0000001; + +// Work around for old API used by QUnitAdapter of jsTestDriver +if (typeof QUnit.log == 'function') { + // When using real QUnit (fron PhantomJS) log failures to console + QUnit.log(function(details) { + if (!details.result) { + console.log('======== FAIL ========'); + console.log('TestName: ' + details.name); + if (details.message) console.log(details.message); + console.log('Expected: ' + details.expected); + console.log('Actual : ' + details.actual); + console.log('======================'); + } + }); +} + +QUnit.module('Double rendering'); + + QUnit.test('Double (rendering)', function(assert) { + console.log('Double rendering test -- starts'); + const EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT = 1; + const EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT = -100; + const EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT = 9223372036854775807; + const EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT = -9223372036854775807; + const EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS = 3.14159265359; + const EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE = 1000000.1; + const EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE = -1000000.1; + const EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE = 1.7e+308; + const EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE = 9223372036854775816.43; + const EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE = -1.7e+308; + const EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE = -9223372036854775816.43; + assert.ok( + Math.abs(EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT - DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST) <= EPSILON); + assert.ok( + Math.abs( + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT - + DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST) <= EPSILON); + assert.ok( + Math.abs( + EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT - + DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST) <= EPSILON); + assert.ok( + Math.abs( + EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT - + DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST) <= EPSILON); + assert.ok( + Math.abs( + EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS - + DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST) <= EPSILON); + assert.ok( + Math.abs( + EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE - + DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST) <= EPSILON); + assert.ok( + Math.abs( + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE - + DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST) <= EPSILON); + assert.ok( + Math.abs( + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE - + DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST) <= EPSILON); + assert.ok( + Math.abs( + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE - + DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST) <= EPSILON); + assert.ok( + Math.abs( + EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE - + DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST) <= EPSILON); + assert.ok( + Math.abs( + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE - + DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST) <= EPSILON); + assert.equal(typeof DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST, 'number'); + assert.equal(typeof DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST, 'number'); + assert.equal(typeof DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST, 'number'); + assert.equal(typeof DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST, 'number'); + assert.equal(typeof DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST, 'number'); + assert.equal(typeof DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST, 'number'); + assert.equal(typeof DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST, 'number'); + assert.equal(typeof DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST, 'number'); + assert.equal(typeof DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST, 'number'); + assert.equal(typeof DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST, 'number'); + assert.equal(typeof DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST, 'number'); + const EXPECTED_DOUBLE_LIST = + [1,-100,100,9223372036854775807,-9223372036854775807,3.14159265359,1000000.1,-1000000.1,1.7e+308,-1.7e+308, + 9223372036854775816.43,-9223372036854775816.43]; + assert.equal(DOUBLE_LIST_TEST.length, EXPECTED_DOUBLE_LIST.length); + for (let i = 0; i < EXPECTED_DOUBLE_LIST.length; ++i) { + assert.ok(Math.abs(EXPECTED_DOUBLE_LIST[i] - DOUBLE_LIST_TEST[i]) <= EPSILON); + } + console.log('Double rendering test -- ends'); + }); + diff --git a/vendor/git.apache.org/thrift.git/lib/js/test/test-es6.html b/vendor/git.apache.org/thrift.git/lib/js/test/test-es6.html new file mode 100644 index 0000000..5f55da7 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/js/test/test-es6.html @@ -0,0 +1,62 @@ + + + + + + Thrift Javascript Bindings: Unit Test + + + + + + + + + + + + + + + + + +

    Thrift Javascript Bindings: Unit Test (ThriftTest.thrift)

    +

    +
    +

    +
    + + + diff --git a/vendor/git.apache.org/thrift.git/lib/js/test/test-es6.js b/vendor/git.apache.org/thrift.git/lib/js/test/test-es6.js new file mode 100644 index 0000000..845171b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/js/test/test-es6.js @@ -0,0 +1,374 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + /* jshint -W100 */ + +/* + * Fully Async JavaScript test suite for ThriftTest.thrift. + * These tests are designed to exercise the WebSocket transport + * (which is exclusively async). + * + * To compile client code for this test use: + * $ thrift -gen js:es6 ThriftTest.thrift + */ + + + +// all Languages in UTF-8 + +const stringTest = "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, Asturianu, Aymar aru, AzÉ™rbaycan, Башҡорт, Boarisch, ŽemaitÄ—Å¡ka, БеларуÑкаÑ, БеларуÑÐºÐ°Ñ (тарашкевіца), БългарÑки, Bamanankan, বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Ðохчийн, Cebuano, á£áŽ³áŽ©, ÄŒesky, СловѣÌньÑкъ / ⰔⰎⰑⰂⰡâ°â° â°”â°â°Ÿ, Чӑвашла, Cymraeg, Dansk, Zazaki, Þ‹Þ¨ÞˆÞ¬Þ€Þ¨Þ„Þ¦ÞÞ°, Ελληνικά, Emiliàn e rumagnòl, English, Esperanto, Español, Eesti, Euskara, ÙØ§Ø±Ø³ÛŒ, Suomi, Võro, Føroyskt, Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, Avañe'ẽ, ગà«àªœàª°àª¾àª¤à«€, Gaelg, עברית, हिनà¥à¤¦à¥€, Fiji Hindi, Hrvatski, Kreyòl ayisyen, Magyar, Õ€Õ¡ÕµÕ¥Ö€Õ¥Õ¶, Interlingua, Bahasa Indonesia, Ilokano, Ido, Ãslenska, Italiano, 日本語, Lojban, Basa Jawa, ქáƒáƒ áƒ—ული, Kongo, Kalaallisut, ಕನà³à²¨à²¡, 한국어, Къарачай-Малкъар, Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, LatvieÅ¡u, Basa Banyumasan, Malagasy, МакедонÑки, മലയാളം, मराठी, Bahasa Melayu, Ù…Ø§Ø²ÙØ±ÙˆÙ†ÛŒ, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, ‪Norsk (nynorsk)‬, ‪Norsk (bokmÃ¥l)‬, Nouormand, Diné bizaad, Occitan, Иронау, Papiamentu, Deitsch, Norfuk / Pitkern, Polski, پنجابی, پښتو, Português, Runa Simi, Rumantsch, Romani, Română, РуÑÑкий, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple English, SlovenÄina, SlovenÅ¡Äina, СрпÑки / Srpski, Seeltersk, Svenska, Kiswahili, தமிழà¯, తెలà±à°—à±, Тоҷикӣ, ไทย, Türkmençe, Tagalog, Türkçe, Татарча/Tatarça, УкраїнÑька, اردو, Tiếng Việt, Volapük, Walon, Winaray, å´è¯­, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, Bân-lâm-gú, 粵語"; + +function checkRecursively(assert, map1, map2) { + if (typeof map1 !== 'function' && typeof map2 !== 'function') { + if (!map1 || typeof map1 !== 'object') { + assert.equal(map1, map2); + } else { + for (var key in map1) { + checkRecursively(assert, map1[key], map2[key]); + } + } + } +} + +QUnit.module('Base Types'); + + QUnit.test('Void', function( assert ) { + assert.expect(1); + const done = assert.async(); + client.testVoid().then(function(result) { + assert.equal(result, undefined); + done(); + }); + }); + + QUnit.test('String', function( assert ) { + assert.expect(3); + const done = assert.async(3); + client.testString('').then(function(result) { + assert.equal(result, ''); + done(); + }); + client.testString(stringTest).then(function(result) { + assert.equal(result, stringTest); + done(); + }); + var specialCharacters = 'quote: \" backslash:' + + ' forwardslash-escaped: \/ ' + + ' backspace: \b formfeed: \f newline: \n return: \r tab: ' + + ' now-all-of-them-together: "\\\/\b\n\r\t' + + ' now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><'; + client.testString(specialCharacters).then(function(result) { + assert.equal(result, specialCharacters); + done(); + }); + }); + + QUnit.test('Double', function( assert ) { + assert.expect(4); + const done = assert.async(4); + client.testDouble(0).then(function(result) { + assert.equal(result, 0); + done(); + }); + client.testDouble(-1).then(function(result) { + assert.equal(result, -1); + done(); + }); + client.testDouble(3.14).then(function(result) { + assert.equal(result, 3.14); + done(); + }); + client.testDouble(Math.pow(2, 60)).then(function(result) { + assert.equal(result, Math.pow(2, 60)); + done(); + }); + }); + // TODO: add testBinary() + QUnit.test('Byte', function( assert ) { + assert.expect(2); + const done = assert.async(2); + client.testByte(0).then(function(result) { + assert.equal(result, 0); + done(); + }); + client.testByte(0x01).then(function(result) { + assert.equal(result, 0x01); + done(); + }); + }); + QUnit.test('I32', function( assert ) { + assert.expect(3); + const done = assert.async(3); + client.testI32(0).then(function(result) { + assert.equal(result, 0); + done(); + }); + client.testI32(Math.pow(2, 30)).then(function(result) { + assert.equal(result, Math.pow(2, 30)); + done(); + }); + client.testI32(-Math.pow(2, 30)).then(function(result) { + assert.equal(result, -Math.pow(2, 30)); + done(); + }); + }); + QUnit.test('I64', function( assert ) { + assert.expect(3); + const done = assert.async(3); + client.testI64(0).then(function(result) { + assert.equal(result, 0); + done(); + }); + //This is usually 2^60 but JS cannot represent anything over 2^52 accurately + client.testI64(Math.pow(2, 52)).then(function(result) { + assert.equal(result, Math.pow(2, 52)); + done(); + }); + client.testI64(-Math.pow(2, 52)).then(function(result) { + assert.equal(result, -Math.pow(2, 52)); + done(); + }); + }); + + +QUnit.module('Structured Types'); + + QUnit.test('Struct', function( assert ) { + assert.expect(5); + const done = assert.async(); + var structTestInput = new ThriftTest.Xtruct(); + structTestInput.string_thing = 'worked'; + structTestInput.byte_thing = 0x01; + structTestInput.i32_thing = Math.pow(2, 30); + //This is usually 2^60 but JS cannot represent anything over 2^52 accurately + structTestInput.i64_thing = Math.pow(2, 52); + + client.testStruct(structTestInput).then(function(result) { + assert.equal(result.string_thing, structTestInput.string_thing); + assert.equal(result.byte_thing, structTestInput.byte_thing); + assert.equal(result.i32_thing, structTestInput.i32_thing); + assert.equal(result.i64_thing, structTestInput.i64_thing); + assert.equal(JSON.stringify(result), JSON.stringify(structTestInput)); + done(); + }); + }); + + QUnit.test('Nest', function( assert ) { + assert.expect(7); + const done = assert.async(); + var xtrTestInput = new ThriftTest.Xtruct(); + xtrTestInput.string_thing = 'worked'; + xtrTestInput.byte_thing = 0x01; + xtrTestInput.i32_thing = Math.pow(2, 30); + //This is usually 2^60 but JS cannot represent anything over 2^52 accurately + xtrTestInput.i64_thing = Math.pow(2, 52); + + var nestTestInput = new ThriftTest.Xtruct2(); + nestTestInput.byte_thing = 0x02; + nestTestInput.struct_thing = xtrTestInput; + nestTestInput.i32_thing = Math.pow(2, 15); + + client.testNest(nestTestInput).then(function(result) { + assert.equal(result.byte_thing, nestTestInput.byte_thing); + assert.equal(result.struct_thing.string_thing, nestTestInput.struct_thing.string_thing); + assert.equal(result.struct_thing.byte_thing, nestTestInput.struct_thing.byte_thing); + assert.equal(result.struct_thing.i32_thing, nestTestInput.struct_thing.i32_thing); + assert.equal(result.struct_thing.i64_thing, nestTestInput.struct_thing.i64_thing); + assert.equal(result.i32_thing, nestTestInput.i32_thing); + assert.equal(JSON.stringify(result), JSON.stringify(nestTestInput)); + done(); + }); + }); + + QUnit.test('Map', function( assert ) { + assert.expect(3); + const done = assert.async(); + var mapTestInput = {7: 77, 8: 88, 9: 99}; + + client.testMap(mapTestInput).then(function(result) { + for (var key in result) { + assert.equal(result[key], mapTestInput[key]); + } + done(); + }); + }); + + QUnit.test('StringMap', function( assert ) { + assert.expect(6); + const done = assert.async(); + var mapTestInput = { + 'a': '123', 'a b': 'with spaces ', 'same': 'same', '0': 'numeric key', + 'longValue': stringTest, stringTest: 'long key' + }; + + client.testStringMap(mapTestInput).then(function(result) { + for (var key in result) { + assert.equal(result[key], mapTestInput[key]); + } + done(); + }); + }); + + QUnit.test('Set', function( assert ) { + assert.expect(1); + const done = assert.async(); + var setTestInput = [1, 2, 3]; + client.testSet(setTestInput).then(function(result) { + assert.ok(result, setTestInput); + done(); + }); + }); + + QUnit.test('List', function( assert ) { + assert.expect(1); + const done = assert.async(); + var listTestInput = [1, 2, 3]; + client.testList(listTestInput).then(function(result) { + assert.ok(result, listTestInput); + done(); + }); + }); + + QUnit.test('Enum', function( assert ) { + assert.expect(1); + const done = assert.async(); + client.testEnum(ThriftTest.Numberz.ONE).then(function(result) { + assert.equal(result, ThriftTest.Numberz.ONE); + done(); + }); + }); + + QUnit.test('TypeDef', function( assert ) { + assert.expect(1); + const done = assert.async(); + client.testTypedef(69).then(function(result) { + assert.equal(result, 69); + done(); + }); + }); + + +QUnit.module('deeper!'); + + QUnit.test('MapMap', function( assert ) { + assert.expect(16); + const done = assert.async(); + var mapMapTestExpectedResult = { + '4': {'1': 1, '2': 2, '3': 3, '4': 4}, + '-4': {'-4': -4, '-3': -3, '-2': -2, '-1': -1} + }; + + client.testMapMap(1).then(function(result) { + for (var key in result) { + for (var key2 in result[key]) { + assert.equal(result[key][key2], mapMapTestExpectedResult[key][key2]); + } + } + checkRecursively(assert, result, mapMapTestExpectedResult); + done(); + }); + }); + + +QUnit.module('Exception'); + + QUnit.test('Xception', function( assert ) { + assert.expect(2); + const done = assert.async(); + client.testException('Xception').then(function(res) { + assert.ok(false); + }).catch(function(e) { + + console.log(`Exception exception e`); + console.log(e); + console.log(JSON.stringify(e, null, 2)); + + assert.equal(e.errorCode, 1001); + assert.equal(e.message, 'Xception'); + done(); + }); + }); + + QUnit.test('no Exception', function( assert ) { + assert.expect(1); + const done = assert.async(); + client.testException('no Exception').then(function(e) { + assert.ok(!e); + done(); + }); + }); + +QUnit.module('Insanity'); + + QUnit.test('testInsanity', function( assert ) { + assert.expect(24); + const done = assert.async(); + var insanity = { + '1': { + '2': { + 'userMap': { '5': 5, '8': 8 }, + 'xtructs': [{ + 'string_thing': 'Goodbye4', + 'byte_thing': 4, + 'i32_thing': 4, + 'i64_thing': 4 + }, + { + 'string_thing': 'Hello2', + 'byte_thing': 2, + 'i32_thing': 2, + 'i64_thing': 2 + } + ] + }, + '3': { + 'userMap': { '5': 5, '8': 8 }, + 'xtructs': [{ + 'string_thing': 'Goodbye4', + 'byte_thing': 4, + 'i32_thing': 4, + 'i64_thing': 4 + }, + { + 'string_thing': 'Hello2', + 'byte_thing': 2, + 'i32_thing': 2, + 'i64_thing': 2 + } + ] + } + }, + '2': { '6': { 'userMap': null, 'xtructs': null } } + }; + client.testInsanity(new ThriftTest.Insanity()).then(function(res) { + assert.ok(res, JSON.stringify(res)); + assert.ok(insanity, JSON.stringify(insanity)); + checkRecursively(assert, res, insanity); + done(); + }); + }); + +QUnit.module('Oneway'); + QUnit.test('testOneway', function( assert ) { + assert.expect(1); + const done = assert.async(); + client.testOneway(1).then(function(result) { + assert.equal(result, undefined); + done(); + }); + }); diff --git a/vendor/git.apache.org/thrift.git/lib/js/test/test-jq.js b/vendor/git.apache.org/thrift.git/lib/js/test/test-jq.js index 23ed60f..f62bb95 100644 --- a/vendor/git.apache.org/thrift.git/lib/js/test/test-jq.js +++ b/vendor/git.apache.org/thrift.git/lib/js/test/test-jq.js @@ -33,126 +33,127 @@ ////////////////////////////////// //jQuery asynchronous tests jQuery.ajaxSetup({ timeout: 0 }); -$(document).ajaxError( function() { QUnit.start(); } ); -module("jQ Async Manual"); +QUnit.module('jQ Async Manual'); - test("testI32", function() { - expect( 2 ); - QUnit.stop(); + QUnit.test('testI32', function(assert) { + assert.expect(2); + const done = assert.async(2); - var transport = new Thrift.Transport(); - var protocol = new Thrift.Protocol(transport); - var client = new ThriftTest.ThriftTestClient(protocol); + const transport = new Thrift.Transport(); + const protocol = new Thrift.Protocol(transport); + const client = new ThriftTest.ThriftTestClient(protocol); - var jqxhr = jQuery.ajax({ - url: "/service", - data: client.send_testI32(Math.pow(-2,31)), - type: "POST", + const jqxhr = jQuery.ajax({ + url: '/service', + data: client.send_testI32(Math.pow(-2, 31)), + type: 'POST', cache: false, - dataType: "text", - success: function(res){ - transport.setRecvBuffer( res ); - equal(client.recv_testI32(), Math.pow(-2,31)); + dataType: 'text', + success: function(res) { + transport.setRecvBuffer(res); + assert.equal(client.recv_testI32(), Math.pow(-2, 31)); + done(); }, - error: function() { ok(false); }, + error: function() { assert.ok(false); }, complete: function() { - ok(true); - QUnit.start(); + assert.ok(true); + done(); } }); }); - test("testI64", function() { - expect( 2 ); - QUnit.stop(); + QUnit.test('testI64', function(assert) { + assert.expect(2); + const done = assert.async(2); - var transport = new Thrift.Transport(); - var protocol = new Thrift.Protocol(transport); - var client = new ThriftTest.ThriftTestClient(protocol); + const transport = new Thrift.Transport(); + const protocol = new Thrift.Protocol(transport); + const client = new ThriftTest.ThriftTestClient(protocol); jQuery.ajax({ - url: "/service", + url: '/service', //This is usually 2^61 but JS cannot represent anything over 2^52 accurately - data: client.send_testI64(Math.pow(-2,52)), - type: "POST", + data: client.send_testI64(Math.pow(-2, 52)), + type: 'POST', cache: false, - dataType: "text", - success: function(res){ - transport.setRecvBuffer( res ); + dataType: 'text', + success: function(res) { + transport.setRecvBuffer(res); //This is usually 2^61 but JS cannot represent anything over 2^52 accurately - equal(client.recv_testI64(), Math.pow(-2,52)); + assert.equal(client.recv_testI64(), Math.pow(-2, 52)); + done(); }, - error: function() { ok(false); }, + error: function() { assert.ok(false); }, complete: function() { - ok(true); - QUnit.start(); + assert.ok(true); + done(); } }); }); -module("jQ Async"); - test("I32", function() { - expect( 3 ); +QUnit.module('jQ Async'); + QUnit.test('I32', function(assert) { + assert.expect(3); - QUnit.stop(); - client.testI32(Math.pow(2,30), function(result) { - equal(result, Math.pow(2,30)); - QUnit.start(); + const done = assert.async(3); + client.testI32(Math.pow(2, 30), function(result) { + assert.equal(result, Math.pow(2, 30)); + done(); }); - QUnit.stop(); - var jqxhr = client.testI32(Math.pow(-2,31), function(result) { - equal(result, Math.pow(-2,31)); + const jqxhr = client.testI32(Math.pow(-2, 31), function(result) { + assert.equal(result, Math.pow(-2, 31)); + done(); }); jqxhr.success(function(result) { - equal(result, Math.pow(-2,31)); - QUnit.start(); + assert.equal(result, Math.pow(-2, 31)); + done(); }); }); - test("I64", function() { - expect( 4 ); + QUnit.test('I64', function(assert) { + assert.expect(4); - QUnit.stop(); + const done = assert.async(4); //This is usually 2^60 but JS cannot represent anything over 2^52 accurately - client.testI64(Math.pow(2,52), function(result) { - equal(result, Math.pow(2,52)); - QUnit.start(); + client.testI64(Math.pow(2, 52), function(result) { + assert.equal(result, Math.pow(2, 52)); + done(); }); - QUnit.stop(); //This is usually 2^60 but JS cannot represent anything over 2^52 accurately - client.testI64(Math.pow(-2,52), function(result) { - equal(result, Math.pow(-2,52)); + client.testI64(Math.pow(-2, 52), function(result) { + assert.equal(result, Math.pow(-2, 52)); + done(); }) - .error( function(xhr, status, e) { ok(false, e.message); } ) + .error(function(xhr, status, e) { assert.ok(false, e.message); }) .success(function(result) { //This is usually 2^60 but JS cannot represent anything over 2^52 accurately - equal(result, Math.pow(-2,52)); + assert.equal(result, Math.pow(-2, 52)); + done(); }) .complete(function() { - ok(true); - QUnit.start(); + assert.ok(true); + done(); }); }); - test("Xception", function() { - expect( 2 ); + QUnit.test('Xception', function(assert) { + assert.expect(2); - QUnit.stop(); + const done = assert.async(2); - var dfd = client.testException("Xception", function(result) { - ok(false); - QUnit.start(); + const dfd = client.testException('Xception', function(result) { + assert.ok(false); + done(); }) - .error(function(xhr, status, e){ - equal(e.errorCode, 1001); - equal(e.message, "Xception"); - //QUnit.start(); - //Note start is not required here because: - //$(document).ajaxError( function() { QUnit.start(); } ); + .error(function(xhr, status, e) { + assert.equal(e.errorCode, 1001); + assert.equal(e.message, 'Xception'); + done(); + $(document).ajaxError( function() { done(); } ); }); }); diff --git a/vendor/git.apache.org/thrift.git/lib/js/test/test-nojq.html b/vendor/git.apache.org/thrift.git/lib/js/test/test-nojq.html index 541bffe..9eec7fc 100644 --- a/vendor/git.apache.org/thrift.git/lib/js/test/test-nojq.html +++ b/vendor/git.apache.org/thrift.git/lib/js/test/test-nojq.html @@ -29,7 +29,7 @@ - + @@ -37,7 +37,7 @@

    Thrift Javascript Bindings: Unit Test (ThriftTest.thrift)

    -
    +

    @@ -34,11 +34,6 @@ - diff --git a/vendor/git.apache.org/thrift.git/lib/js/test/test.js b/vendor/git.apache.org/thrift.git/lib/js/test/test.js index 2d8ec9b..a86a509 100755 --- a/vendor/git.apache.org/thrift.git/lib/js/test/test.js +++ b/vendor/git.apache.org/thrift.git/lib/js/test/test.js @@ -23,7 +23,7 @@ * will run against Normal (-gen js) and jQuery (-gen js:jquery) * Apache Thrift interfaces. * - * Synchronous blocking calls should be identical in both + * Synchronous blocking calls should be identical in both * Normal and jQuery interfaces. All synchronous tests belong * here. * @@ -47,9 +47,9 @@ * ++ test-jq.js for "-gen js:jquery" only tests */ -var transport = new Thrift.Transport("/service"); -var protocol = new Thrift.Protocol(transport); -var client = new ThriftTest.ThriftTestClient(protocol); +const transport = new Thrift.Transport('/service'); +const protocol = new Thrift.Protocol(transport); +const client = new ThriftTest.ThriftTestClient(protocol); // Work around for old API used by QUnitAdapter of jsTestDriver if (typeof QUnit.log == 'function') { @@ -67,170 +67,170 @@ if (typeof QUnit.log == 'function') { } // all Languages in UTF-8 -var stringTest = "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, Asturianu, Aymar aru, AzÉ™rbaycan, Башҡорт, Boarisch, ŽemaitÄ—Å¡ka, БеларуÑкаÑ, БеларуÑÐºÐ°Ñ (тарашкевіца), БългарÑки, Bamanankan, বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Ðохчийн, Cebuano, á£áŽ³áŽ©, ÄŒesky, СловѣÌньÑкъ / ⰔⰎⰑⰂⰡâ°â° â°”â°â°Ÿ, Чӑвашла, Cymraeg, Dansk, Zazaki, Þ‹Þ¨ÞˆÞ¬Þ€Þ¨Þ„Þ¦ÞÞ°, Ελληνικά, Emiliàn e rumagnòl, English, Esperanto, Español, Eesti, Euskara, ÙØ§Ø±Ø³ÛŒ, Suomi, Võro, Føroyskt, Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, Avañe'ẽ, ગà«àªœàª°àª¾àª¤à«€, Gaelg, עברית, हिनà¥à¤¦à¥€, Fiji Hindi, Hrvatski, Kreyòl ayisyen, Magyar, Õ€Õ¡ÕµÕ¥Ö€Õ¥Õ¶, Interlingua, Bahasa Indonesia, Ilokano, Ido, Ãslenska, Italiano, 日本語, Lojban, Basa Jawa, ქáƒáƒ áƒ—ული, Kongo, Kalaallisut, ಕನà³à²¨à²¡, 한국어, Къарачай-Малкъар, Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, LatvieÅ¡u, Basa Banyumasan, Malagasy, МакедонÑки, മലയാളം, मराठी, Bahasa Melayu, Ù…Ø§Ø²ÙØ±ÙˆÙ†ÛŒ, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, ‪Norsk (nynorsk)‬, ‪Norsk (bokmÃ¥l)‬, Nouormand, Diné bizaad, Occitan, Иронау, Papiamentu, Deitsch, Norfuk / Pitkern, Polski, پنجابی, پښتو, Português, Runa Simi, Rumantsch, Romani, Română, РуÑÑкий, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple English, SlovenÄina, SlovenÅ¡Äina, СрпÑки / Srpski, Seeltersk, Svenska, Kiswahili, தமிழà¯, తెలà±à°—à±, Тоҷикӣ, ไทย, Türkmençe, Tagalog, Türkçe, Татарча/Tatarça, УкраїнÑька, اردو, Tiếng Việt, Volapük, Walon, Winaray, å´è¯­, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, Bân-lâm-gú, 粵語"; +const stringTest = "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, Asturianu, Aymar aru, AzÉ™rbaycan, Башҡорт, Boarisch, ŽemaitÄ—Å¡ka, БеларуÑкаÑ, БеларуÑÐºÐ°Ñ (тарашкевіца), БългарÑки, Bamanankan, বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Ðохчийн, Cebuano, á£áŽ³áŽ©, ÄŒesky, СловѣÌньÑкъ / ⰔⰎⰑⰂⰡâ°â° â°”â°â°Ÿ, Чӑвашла, Cymraeg, Dansk, Zazaki, Þ‹Þ¨ÞˆÞ¬Þ€Þ¨Þ„Þ¦ÞÞ°, Ελληνικά, Emiliàn e rumagnòl, English, Esperanto, Español, Eesti, Euskara, ÙØ§Ø±Ø³ÛŒ, Suomi, Võro, Føroyskt, Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, Avañe'ẽ, ગà«àªœàª°àª¾àª¤à«€, Gaelg, עברית, हिनà¥à¤¦à¥€, Fiji Hindi, Hrvatski, Kreyòl ayisyen, Magyar, Õ€Õ¡ÕµÕ¥Ö€Õ¥Õ¶, Interlingua, Bahasa Indonesia, Ilokano, Ido, Ãslenska, Italiano, 日本語, Lojban, Basa Jawa, ქáƒáƒ áƒ—ული, Kongo, Kalaallisut, ಕನà³à²¨à²¡, 한국어, Къарачай-Малкъар, Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, LatvieÅ¡u, Basa Banyumasan, Malagasy, МакедонÑки, മലയാളം, मराठी, Bahasa Melayu, Ù…Ø§Ø²ÙØ±ÙˆÙ†ÛŒ, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, ‪Norsk (nynorsk)‬, ‪Norsk (bokmÃ¥l)‬, Nouormand, Diné bizaad, Occitan, Иронау, Papiamentu, Deitsch, Norfuk / Pitkern, Polski, پنجابی, پښتو, Português, Runa Simi, Rumantsch, Romani, Română, РуÑÑкий, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple English, SlovenÄina, SlovenÅ¡Äina, СрпÑки / Srpski, Seeltersk, Svenska, Kiswahili, தமிழà¯, తెలà±à°—à±, Тоҷикӣ, ไทย, Türkmençe, Tagalog, Türkçe, Татарча/Tatarça, УкраїнÑька, اردو, Tiếng Việt, Volapük, Walon, Winaray, å´è¯­, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, Bân-lâm-gú, 粵語"; -function checkRecursively(map1, map2) { +function checkRecursively(assert, map1, map2) { if (typeof map1 !== 'function' && typeof map2 !== 'function') { if (!map1 || typeof map1 !== 'object') { - equal(map1, map2); + assert.equal(map1, map2); } else { - for (var key in map1) { - checkRecursively(map1[key], map2[key]); + for (let key in map1) { + checkRecursively(assert, map1[key], map2[key]); } } } } -module("Base Types"); +QUnit.module('Base Types'); - test("Void", function() { - equal(client.testVoid(), undefined); + QUnit.test('Void', function(assert) { + assert.equal(client.testVoid(), undefined); }); - test("Binary (String)", function() { - var binary = ''; - for (var v = 255; v >= 0; --v) { + QUnit.test('Binary (String)', function(assert) { + let binary = ''; + for (let v = 255; v >= 0; --v) { binary += String.fromCharCode(v); } - equal(client.testBinary(binary), binary); + assert.equal(client.testBinary(binary), binary); }); - test("Binary (Uint8Array)", function() { - var binary = ''; - for (var v = 255; v >= 0; --v) { + QUnit.test('Binary (Uint8Array)', function(assert) { + let binary = ''; + for (let v = 255; v >= 0; --v) { binary += String.fromCharCode(v); } - var arr = new Uint8Array(binary.length); - for (var i = 0; i < binary.length; ++i) { + const arr = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; ++i) { arr[i] = binary[i].charCodeAt(); } - equal(client.testBinary(arr), binary); + assert.equal(client.testBinary(arr), binary); }); - test("String", function() { - equal(client.testString(''), ''); - equal(client.testString(stringTest), stringTest); + QUnit.test('String', function(assert) { + assert.equal(client.testString(''), ''); + assert.equal(client.testString(stringTest), stringTest); - var specialCharacters = 'quote: \" backslash:' + + const specialCharacters = 'quote: \" backslash:' + ' forwardslash-escaped: \/ ' + ' backspace: \b formfeed: \f newline: \n return: \r tab: ' + ' now-all-of-them-together: "\\\/\b\n\r\t' + ' now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><'; - equal(client.testString(specialCharacters),specialCharacters); + assert.equal(client.testString(specialCharacters), specialCharacters); }); - test("Double", function() { - equal(client.testDouble(0), 0); - equal(client.testDouble(-1), -1); - equal(client.testDouble(3.14), 3.14); - equal(client.testDouble(Math.pow(2,60)), Math.pow(2,60)); + QUnit.test('Double', function(assert) { + assert.equal(client.testDouble(0), 0); + assert.equal(client.testDouble(-1), -1); + assert.equal(client.testDouble(3.14), 3.14); + assert.equal(client.testDouble(Math.pow(2, 60)), Math.pow(2, 60)); }); - test("Byte", function() { - equal(client.testByte(0), 0); - equal(client.testByte(0x01), 0x01); + QUnit.test('Byte', function(assert) { + assert.equal(client.testByte(0), 0); + assert.equal(client.testByte(0x01), 0x01); }); - test("I32", function() { - equal(client.testI32(0), 0); - equal(client.testI32(Math.pow(2,30)), Math.pow(2,30)); - equal(client.testI32(-Math.pow(2,30)), -Math.pow(2,30)); + QUnit.test('I32', function(assert) { + assert.equal(client.testI32(0), 0); + assert.equal(client.testI32(Math.pow(2, 30)), Math.pow(2, 30)); + assert.equal(client.testI32(-Math.pow(2, 30)), -Math.pow(2, 30)); }); - test("I64", function() { - equal(client.testI64(0), 0); + QUnit.test('I64', function(assert) { + assert.equal(client.testI64(0), 0); //This is usually 2^60 but JS cannot represent anything over 2^52 accurately - equal(client.testI64(Math.pow(2,52)), Math.pow(2,52)); - equal(client.testI64(-Math.pow(2,52)), -Math.pow(2,52)); + assert.equal(client.testI64(Math.pow(2, 52)), Math.pow(2, 52)); + assert.equal(client.testI64(-Math.pow(2, 52)), -Math.pow(2, 52)); }); -module("Structured Types"); +QUnit.module('Structured Types'); - test("Struct", function() { - var structTestInput = new ThriftTest.Xtruct(); + QUnit.test('Struct', function(assert) { + const structTestInput = new ThriftTest.Xtruct(); structTestInput.string_thing = 'worked'; structTestInput.byte_thing = 0x01; - structTestInput.i32_thing = Math.pow(2,30); + structTestInput.i32_thing = Math.pow(2, 30); //This is usually 2^60 but JS cannot represent anything over 2^52 accurately - structTestInput.i64_thing = Math.pow(2,52); + structTestInput.i64_thing = Math.pow(2, 52); - var structTestOutput = client.testStruct(structTestInput); + const structTestOutput = client.testStruct(structTestInput); - equal(structTestOutput.string_thing, structTestInput.string_thing); - equal(structTestOutput.byte_thing, structTestInput.byte_thing); - equal(structTestOutput.i32_thing, structTestInput.i32_thing); - equal(structTestOutput.i64_thing, structTestInput.i64_thing); + assert.equal(structTestOutput.string_thing, structTestInput.string_thing); + assert.equal(structTestOutput.byte_thing, structTestInput.byte_thing); + assert.equal(structTestOutput.i32_thing, structTestInput.i32_thing); + assert.equal(structTestOutput.i64_thing, structTestInput.i64_thing); - equal(JSON.stringify(structTestOutput), JSON.stringify(structTestInput)); + assert.equal(JSON.stringify(structTestOutput), JSON.stringify(structTestInput)); }); - test("Nest", function() { - var xtrTestInput = new ThriftTest.Xtruct(); + QUnit.test('Nest', function(assert) { + const xtrTestInput = new ThriftTest.Xtruct(); xtrTestInput.string_thing = 'worked'; xtrTestInput.byte_thing = 0x01; - xtrTestInput.i32_thing = Math.pow(2,30); + xtrTestInput.i32_thing = Math.pow(2, 30); //This is usually 2^60 but JS cannot represent anything over 2^52 accurately - xtrTestInput.i64_thing = Math.pow(2,52); + xtrTestInput.i64_thing = Math.pow(2, 52); - var nestTestInput = new ThriftTest.Xtruct2(); + const nestTestInput = new ThriftTest.Xtruct2(); nestTestInput.byte_thing = 0x02; nestTestInput.struct_thing = xtrTestInput; - nestTestInput.i32_thing = Math.pow(2,15); + nestTestInput.i32_thing = Math.pow(2, 15); - var nestTestOutput = client.testNest(nestTestInput); + const nestTestOutput = client.testNest(nestTestInput); - equal(nestTestOutput.byte_thing, nestTestInput.byte_thing); - equal(nestTestOutput.struct_thing.string_thing, nestTestInput.struct_thing.string_thing); - equal(nestTestOutput.struct_thing.byte_thing, nestTestInput.struct_thing.byte_thing); - equal(nestTestOutput.struct_thing.i32_thing, nestTestInput.struct_thing.i32_thing); - equal(nestTestOutput.struct_thing.i64_thing, nestTestInput.struct_thing.i64_thing); - equal(nestTestOutput.i32_thing, nestTestInput.i32_thing); + assert.equal(nestTestOutput.byte_thing, nestTestInput.byte_thing); + assert.equal(nestTestOutput.struct_thing.string_thing, nestTestInput.struct_thing.string_thing); + assert.equal(nestTestOutput.struct_thing.byte_thing, nestTestInput.struct_thing.byte_thing); + assert.equal(nestTestOutput.struct_thing.i32_thing, nestTestInput.struct_thing.i32_thing); + assert.equal(nestTestOutput.struct_thing.i64_thing, nestTestInput.struct_thing.i64_thing); + assert.equal(nestTestOutput.i32_thing, nestTestInput.i32_thing); - equal(JSON.stringify(nestTestOutput), JSON.stringify(nestTestInput)); + assert.equal(JSON.stringify(nestTestOutput), JSON.stringify(nestTestInput)); }); - test("Map", function() { - var mapTestInput = {7:77, 8:88, 9:99}; + QUnit.test('Map', function(assert) { + const mapTestInput = {7: 77, 8: 88, 9: 99}; - var mapTestOutput = client.testMap(mapTestInput); + const mapTestOutput = client.testMap(mapTestInput); - for (var key in mapTestOutput) { - equal(mapTestOutput[key], mapTestInput[key]); + for (let key in mapTestOutput) { + assert.equal(mapTestOutput[key], mapTestInput[key]); } }); - test("StringMap", function() { - var mapTestInput = { - "a":"123", "a b":"with spaces ", "same":"same", "0":"numeric key", - "longValue":stringTest, stringTest:"long key" + QUnit.test('StringMap', function(assert) { + const mapTestInput = { + 'a': '123', 'a b': 'with spaces ', 'same': 'same', '0': 'numeric key', + 'longValue': stringTest, stringTest: 'long key' }; - var mapTestOutput = client.testStringMap(mapTestInput); + const mapTestOutput = client.testStringMap(mapTestInput); - for (var key in mapTestOutput) { - equal(mapTestOutput[key], mapTestInput[key]); + for (let key in mapTestOutput) { + assert.equal(mapTestOutput[key], mapTestInput[key]); } }); - test("Set", function() { - var setTestInput = [1,2,3]; - ok(client.testSet(setTestInput), setTestInput); + QUnit.test('Set', function(assert) { + const setTestInput = [1, 2, 3]; + assert.ok(client.testSet(setTestInput), setTestInput); }); - test("List", function() { - var listTestInput = [1,2,3]; - ok(client.testList(listTestInput), listTestInput); + QUnit.test('List', function(assert) { + const listTestInput = [1, 2, 3]; + assert.ok(client.testList(listTestInput), listTestInput); }); - test("Enum", function() { - equal(client.testEnum(ThriftTest.Numberz.ONE), ThriftTest.Numberz.ONE); + QUnit.test('Enum', function(assert) { + assert.equal(client.testEnum(ThriftTest.Numberz.ONE), ThriftTest.Numberz.ONE); }); - test("TypeDef", function() { - equal(client.testTypedef(69), 69); + QUnit.test('TypeDef', function(assert) { + assert.equal(client.testTypedef(69), 69); }); - test("Skip", function() { - var structTestInput = new ThriftTest.Xtruct(); - var modifiedClient = new ThriftTest.ThriftTestClient(protocol); + QUnit.test('Skip', function(assert) { + const structTestInput = new ThriftTest.Xtruct(); + const modifiedClient = new ThriftTest.ThriftTestClient(protocol); modifiedClient.recv_testStruct = function() { - var input = modifiedClient.input; - var xtruct3 = new ThriftTest.Xtruct3(); + const input = modifiedClient.input; + const xtruct3 = new ThriftTest.Xtruct3(); input.readMessageBegin(); input.readStructBegin(); @@ -250,163 +250,166 @@ module("Structured Types"); }; structTestInput.string_thing = 'worked'; - structTestInput.byte_thing = 0x01; - structTestInput.i32_thing = Math.pow(2,30); - structTestInput.i64_thing = Math.pow(2,52); + structTestInput.byte_thing = 0x01; + structTestInput.i32_thing = Math.pow(2, 30); + structTestInput.i64_thing = Math.pow(2, 52); - var structTestOutput = modifiedClient.testStruct(structTestInput); + const structTestOutput = modifiedClient.testStruct(structTestInput); - equal(structTestOutput instanceof ThriftTest.Xtruct3, true); - equal(structTestOutput.string_thing, structTestInput.string_thing); - equal(structTestOutput.changed, null); - equal(structTestOutput.i32_thing, structTestInput.i32_thing); - equal(structTestOutput.i64_thing, structTestInput.i64_thing); + assert.equal(structTestOutput instanceof ThriftTest.Xtruct3, true); + assert.equal(structTestOutput.string_thing, structTestInput.string_thing); + assert.equal(structTestOutput.changed, null); + assert.equal(structTestOutput.i32_thing, structTestInput.i32_thing); + assert.equal(structTestOutput.i64_thing, structTestInput.i64_thing); }); -module("deeper!"); +QUnit.module('deeper!'); - test("MapMap", function() { - var mapMapTestExpectedResult = { - "4":{"1":1,"2":2,"3":3,"4":4}, - "-4":{"-4":-4, "-3":-3, "-2":-2, "-1":-1} + QUnit.test('MapMap', function(assert) { + const mapMapTestExpectedResult = { + '4': {'1': 1, '2': 2, '3': 3, '4': 4}, + '-4': {'-4': -4, '-3': -3, '-2': -2, '-1': -1} }; - var mapMapTestOutput = client.testMapMap(1); + const mapMapTestOutput = client.testMapMap(1); - for (var key in mapMapTestOutput) { - for (var key2 in mapMapTestOutput[key]) { - equal(mapMapTestOutput[key][key2], mapMapTestExpectedResult[key][key2]); + for (let key in mapMapTestOutput) { + for (let key2 in mapMapTestOutput[key]) { + assert.equal(mapMapTestOutput[key][key2], mapMapTestExpectedResult[key][key2]); } } - checkRecursively(mapMapTestOutput, mapMapTestExpectedResult); + checkRecursively(assert, mapMapTestOutput, mapMapTestExpectedResult); }); -module("Exception"); +QUnit.module('Exception'); - test("Xception", function() { - expect(2); - try{ - client.testException("Xception"); - }catch(e){ - equal(e.errorCode, 1001); - equal(e.message, "Xception"); + QUnit.test('Xception', function(assert) { + assert.expect(2); + const done = assert.async(); + try { + client.testException('Xception'); + assert.ok(false); + }catch (e) { + assert.equal(e.errorCode, 1001); + assert.equal(e.message, 'Xception'); + done(); } }); - test("no Exception", 0, function() { - try{ - client.testException("no Exception"); - }catch(e){ - ok(false); + QUnit.test('no Exception', function(assert) { + assert.expect(1); + try { + client.testException('no Exception'); + assert.ok(true); + }catch (e) { + assert.ok(false); } }); - test("TException", function() { + QUnit.test('TException', function(assert) { //ThriftTest does not list TException as a legal exception so it will // generate an exception on the server that does not propagate back to // the client. This test has been modified to equate to "no exception" - expect(1); - try{ - client.testException("TException"); - } catch(e) { - //ok(false); + assert.expect(1); + try { + client.testException('TException'); + } catch (e) { + //assert.ok(false); } - ok(true); + assert.ok(true); }); -module("Insanity"); +QUnit.module('Insanity'); - var crazy = { - "userMap":{ "5":5, "8":8 }, - "xtructs":[{ - "string_thing":"Goodbye4", - "byte_thing":4, - "i32_thing":4, - "i64_thing":4 + const crazy = { + 'userMap': { '5': 5, '8': 8 }, + 'xtructs': [{ + 'string_thing': 'Goodbye4', + 'byte_thing': 4, + 'i32_thing': 4, + 'i64_thing': 4 }, { - "string_thing":"Hello2", - "byte_thing":2, - "i32_thing":2, - "i64_thing":2 + 'string_thing': 'Hello2', + 'byte_thing': 2, + 'i32_thing': 2, + 'i64_thing': 2 }] }; - test("testInsanity", function() { - var insanity = { - "1":{ - "2":crazy, - "3":crazy + QUnit.test('testInsanity', function(assert) { + const insanity = { + '1': { + '2': crazy, + '3': crazy }, - "2":{ "6":{ "userMap":null, "xtructs":null } } + '2': { '6': { 'userMap': null, 'xtructs': null } } }; - var res = client.testInsanity(new ThriftTest.Insanity(crazy)); - ok(res, JSON.stringify(res)); - ok(insanity, JSON.stringify(insanity)); + const res = client.testInsanity(new ThriftTest.Insanity(crazy)); + assert.ok(res, JSON.stringify(res)); + assert.ok(insanity, JSON.stringify(insanity)); - checkRecursively(res, insanity); + checkRecursively(assert, res, insanity); }); ////////////////////////////////// //Run same tests asynchronously -module("Async"); +QUnit.module('Async'); - test("Double", function() { - expect( 1 ); + QUnit.test('Double', function(assert) { + assert.expect(1); - QUnit.stop(); + const done = assert.async(); client.testDouble(3.14159265, function(result) { - equal(result, 3.14159265); - QUnit.start(); + assert.equal(result, 3.14159265); + done(); }); }); - test("Byte", function() { - expect( 1 ); + QUnit.test('Byte', function(assert) { + assert.expect(1); - QUnit.stop(); + const done = assert.async(); client.testByte(0x01, function(result) { - equal(result, 0x01); - QUnit.start(); + assert.equal(result, 0x01); + done(); }); }); - test("I32", function() { - expect( 2 ); + QUnit.test('I32', function(assert) { + assert.expect(2); - QUnit.stop(); - client.testI32(Math.pow(2,30), function(result) { - equal(result, Math.pow(2,30)); - QUnit.start(); + const done = assert.async(2); + client.testI32(Math.pow(2, 30), function(result) { + assert.equal(result, Math.pow(2, 30)); + done(); }); - QUnit.stop(); - client.testI32(Math.pow(-2,31), function(result) { - equal(result, Math.pow(-2,31)); - QUnit.start(); + client.testI32(Math.pow(-2, 31), function(result) { + assert.equal(result, Math.pow(-2, 31)); + done(); }); }); - test("I64", function() { - expect( 2 ); + QUnit.test('I64', function(assert) { + assert.expect(2); - QUnit.stop(); + const done = assert.async(2); //This is usually 2^60 but JS cannot represent anything over 2^52 accurately - client.testI64(Math.pow(2,52), function(result) { - equal(result, Math.pow(2,52)); - QUnit.start(); + client.testI64(Math.pow(2, 52), function(result) { + assert.equal(result, Math.pow(2, 52)); + done(); }); - QUnit.stop(); //This is usually 2^60 but JS cannot represent anything over 2^52 accurately - client.testI64(Math.pow(-2,52), function(result) { - equal(result, Math.pow(-2,52)); - QUnit.start(); + client.testI64(Math.pow(-2, 52), function(result) { + assert.equal(result, Math.pow(-2, 52)); + done(); }); }); diff --git a/vendor/git.apache.org/thrift.git/lib/js/test/test_handler.js b/vendor/git.apache.org/thrift.git/lib/js/test/test_handler.js index e1fa74f..af5f7bd 100644 --- a/vendor/git.apache.org/thrift.git/lib/js/test/test_handler.js +++ b/vendor/git.apache.org/thrift.git/lib/js/test/test_handler.js @@ -17,13 +17,15 @@ * under the License. */ -//This is the server side Node test handler for the standard +//This is the server side Node test handler for the standard // Apache Thrift test service. -var ttypes = require('./gen-nodejs/ThriftTest_types'); -var TException = require('../../nodejs/lib/thrift').TException; +const es6Mode = process.argv.includes('--es6'); +const genFolder = es6Mode ? 'gen-nodejs-es6' : 'gen-nodejs'; +const ttypes = require(`./${genFolder}/ThriftTest_types`); +const TException = require('../../nodejs/lib/thrift').TException; -var ThriftTestHandler = exports.ThriftTestHandler = { +exports.ThriftTestHandler = { testVoid: function(result) { console.log('testVoid()'); result(null); @@ -99,10 +101,10 @@ var ThriftTestHandler = exports.ThriftTestHandler = { testMapMap: function(hello, result) { console.log('testMapMap(' + hello + ')'); - var mapmap = []; - var pos = []; - var neg = []; - for (var i = 1; i < 5; i++) { + const mapmap = []; + const pos = []; + const neg = []; + for (let i = 1; i < 5; i++) { pos[i] = i; neg[-i] = -i; } @@ -116,34 +118,34 @@ var ThriftTestHandler = exports.ThriftTestHandler = { console.log(argument); console.log(')'); - var hello = new ttypes.Xtruct(); + const hello = new ttypes.Xtruct(); hello.string_thing = 'Hello2'; hello.byte_thing = 2; hello.i32_thing = 2; hello.i64_thing = 2; - var goodbye = new ttypes.Xtruct(); + const goodbye = new ttypes.Xtruct(); goodbye.string_thing = 'Goodbye4'; goodbye.byte_thing = 4; goodbye.i32_thing = 4; goodbye.i64_thing = 4; - var crazy = new ttypes.Insanity(); + const crazy = new ttypes.Insanity(); crazy.userMap = []; crazy.userMap[ttypes.Numberz.EIGHT] = 8; crazy.userMap[ttypes.Numberz.FIVE] = 5; crazy.xtructs = [goodbye, hello]; - var first_map = []; - var second_map = []; + const first_map = []; + const second_map = []; first_map[ttypes.Numberz.TWO] = crazy; first_map[ttypes.Numberz.THREE] = crazy; - var looney = new ttypes.Insanity(); + const looney = new ttypes.Insanity(); second_map[ttypes.Numberz.SIX] = looney; - var insane = []; + const insane = []; insane[1] = first_map; insane[2] = second_map; @@ -154,7 +156,7 @@ var ThriftTestHandler = exports.ThriftTestHandler = { testMulti: function(arg0, arg1, arg2, arg3, arg4, arg5, result) { console.log('testMulti()'); - var hello = new ttypes.Xtruct(); + const hello = new ttypes.Xtruct(); hello.string_thing = 'Hello2'; hello.byte_thing = arg0; hello.i32_thing = arg1; @@ -162,9 +164,9 @@ var ThriftTestHandler = exports.ThriftTestHandler = { result(null, hello); }, testException: function(arg, result) { - console.log('testException('+arg+')'); + console.log('testException(' + arg + ')'); if (arg === 'Xception') { - var x = new ttypes.Xception(); + const x = new ttypes.Xception(); x.errorCode = 1001; x.message = arg; result(x); @@ -177,19 +179,19 @@ var ThriftTestHandler = exports.ThriftTestHandler = { testMultiException: function(arg0, arg1, result) { console.log('testMultiException(' + arg0 + ', ' + arg1 + ')'); if (arg0 === ('Xception')) { - var x = new ttypes.Xception(); + const x = new ttypes.Xception(); x.errorCode = 1001; x.message = 'This is an Xception'; result(x); } else if (arg0 === ('Xception2')) { - var x2 = new ttypes.Xception2(); + const x2 = new ttypes.Xception2(); x2.errorCode = 2002; x2.struct_thing = new ttypes.Xtruct(); x2.struct_thing.string_thing = 'This is an Xception2'; result(x2); } - var res = new ttypes.Xtruct(); + const res = new ttypes.Xtruct(); res.string_thing = arg1; result(null, res); }, diff --git a/vendor/git.apache.org/thrift.git/lib/js/test/testws.html b/vendor/git.apache.org/thrift.git/lib/js/test/testws.html index f99a146..1edf0e0 100644 --- a/vendor/git.apache.org/thrift.git/lib/js/test/testws.html +++ b/vendor/git.apache.org/thrift.git/lib/js/test/testws.html @@ -35,12 +35,12 @@ diff --git a/vendor/git.apache.org/thrift.git/lib/json/schema.json b/vendor/git.apache.org/thrift.git/lib/json/schema.json index 011b4d3..d058a7c 100644 --- a/vendor/git.apache.org/thrift.git/lib/json/schema.json +++ b/vendor/git.apache.org/thrift.git/lib/json/schema.json @@ -273,6 +273,13 @@ "required": [ "functions" ] } ] + }, + "annotations": { + "title": "Map of annotation names to values", + "type": "object", + "additionalProperties": { + "type": "string" + } } }, @@ -296,6 +303,12 @@ }, "uniqueItems": true }, + "namespaces": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, "enums": { "type": "array", "items": { @@ -326,5 +339,6 @@ "$ref": "#/definitions/service" } } - } + }, + "additionalProperties": false } diff --git a/vendor/git.apache.org/thrift.git/lib/lua/Makefile.am b/vendor/git.apache.org/thrift.git/lib/lua/Makefile.am index 3dfc27c..5b0f17a 100644 --- a/vendor/git.apache.org/thrift.git/lib/lua/Makefile.am +++ b/vendor/git.apache.org/thrift.git/lib/lua/Makefile.am @@ -23,9 +23,9 @@ SUBDIRS = . lib_LTLIBRARIES = \ libluasocket.la \ + liblualongnumber.la \ libluabpack.la \ - libluabitwise.la \ - liblualongnumber.la + libluabitwise.la libluasocket_la_SOURCES = \ src/luasocket.c \ diff --git a/vendor/git.apache.org/thrift.git/lib/lua/TFramedTransport.lua b/vendor/git.apache.org/thrift.git/lib/lua/TFramedTransport.lua index 437b701..768e2d9 100644 --- a/vendor/git.apache.org/thrift.git/lib/lua/TFramedTransport.lua +++ b/vendor/git.apache.org/thrift.git/lib/lua/TFramedTransport.lua @@ -100,7 +100,7 @@ function TFramedTransport:flush() local tmp = self.wBuf self.wBuf = '' local frame_len_buf = libluabpack.bpack("i", string.len(tmp)) - self.trans:write(frame_len_buf) + tmp = frame_len_buf .. tmp self.trans:write(tmp) self.trans:flush() end diff --git a/vendor/git.apache.org/thrift.git/lib/lua/THttpTransport.lua b/vendor/git.apache.org/thrift.git/lib/lua/THttpTransport.lua index 19b7705..060a8ab 100644 --- a/vendor/git.apache.org/thrift.git/lib/lua/THttpTransport.lua +++ b/vendor/git.apache.org/thrift.git/lib/lua/THttpTransport.lua @@ -25,7 +25,7 @@ THttpTransport = TTransportBase:new{ wBuf = '', rBuf = '', CRLF = '\r\n', - VERSION = '0.10.0', + VERSION = '0.12.0', isServer = true } diff --git a/vendor/git.apache.org/thrift.git/lib/lua/Thrift.lua b/vendor/git.apache.org/thrift.git/lib/lua/Thrift.lua index 3eddb64..d495729 100644 --- a/vendor/git.apache.org/thrift.git/lib/lua/Thrift.lua +++ b/vendor/git.apache.org/thrift.git/lib/lua/Thrift.lua @@ -48,7 +48,7 @@ function ttable_size(t) return count end -version = 0.10 +version = '0.12.0' TType = { STOP = 0, diff --git a/vendor/git.apache.org/thrift.git/lib/lua/src/luabpack.c b/vendor/git.apache.org/thrift.git/lib/lua/src/luabpack.c index a86fc3e..077b6aa 100644 --- a/vendor/git.apache.org/thrift.git/lib/lua/src/luabpack.c +++ b/vendor/git.apache.org/thrift.git/lib/lua/src/luabpack.c @@ -104,10 +104,10 @@ static int l_bunpack(lua_State *L) { const char *code = luaL_checkstring(L, 1); luaL_argcheck(L, code[1] == '\0', 0, "Format code must be one character."); const char *data = luaL_checkstring(L, 2); -#ifdef _LUA51_ - size_t len = lua_objlen(L, 2); -#else +#if LUA_VERSION_NUM >= 502 size_t len = lua_rawlen(L, 2); +#else + size_t len = lua_objlen(L, 2); #endif switch (code[0]) { diff --git a/vendor/git.apache.org/thrift.git/lib/lua/src/socket.h b/vendor/git.apache.org/thrift.git/lib/lua/src/socket.h index 8019ffe..afb827e 100644 --- a/vendor/git.apache.org/thrift.git/lib/lua/src/socket.h +++ b/vendor/git.apache.org/thrift.git/lib/lua/src/socket.h @@ -51,8 +51,8 @@ T_ERRCODE socket_send(p_socket sock, const char *data, size_t len, int timeout); T_ERRCODE socket_recv(p_socket sock, char *data, size_t len, int timeout, int *received); -void socket_setblocking(p_socket sock); -void socket_setnonblocking(p_socket sock); +T_ERRCODE socket_setblocking(p_socket sock); +T_ERRCODE socket_setnonblocking(p_socket sock); T_ERRCODE socket_accept(p_socket sock, p_socket sibling, p_sa addr, socklen_t *addr_len, int timeout); diff --git a/vendor/git.apache.org/thrift.git/lib/lua/src/usocket.c b/vendor/git.apache.org/thrift.git/lib/lua/src/usocket.c index 864fa36..1a1b549 100644 --- a/vendor/git.apache.org/thrift.git/lib/lua/src/usocket.c +++ b/vendor/git.apache.org/thrift.git/lib/lua/src/usocket.c @@ -113,7 +113,7 @@ T_ERRCODE socket_create(p_socket sock, int domain, int type, int protocol) { T_ERRCODE socket_destroy(p_socket sock) { // TODO Figure out if I should be free-ing this if (*sock > 0) { - socket_setblocking(sock); + (void)socket_setblocking(sock); close(*sock); *sock = -1; } @@ -121,13 +121,15 @@ T_ERRCODE socket_destroy(p_socket sock) { } T_ERRCODE socket_bind(p_socket sock, p_sa addr, int addr_len) { - int ret = SUCCESS; - socket_setblocking(sock); + int ret = socket_setblocking(sock); + if (ret != SUCCESS) { + return ret; + } if (bind(*sock, addr, addr_len)) { ret = errno; } - socket_setnonblocking(sock); - return ret; + int ret2 = socket_setnonblocking(sock); + return ret == SUCCESS ? ret2 : ret; } T_ERRCODE socket_get_info(p_socket sock, short *port, char *buf, size_t len) { @@ -168,22 +170,25 @@ T_ERRCODE socket_accept(p_socket sock, p_socket client, if (*client > 0) { return SUCCESS; } - err = errno; - } while (err != EINTR); + } while ((err = errno) == EINTR); + if (err == EAGAIN || err == ECONNABORTED) { return socket_wait(sock, WAIT_MODE_R, timeout); } + return err; } T_ERRCODE socket_listen(p_socket sock, int backlog) { - int ret = SUCCESS; - socket_setblocking(sock); + int ret = socket_setblocking(sock); + if (ret != SUCCESS) { + return ret; + } if (listen(*sock, backlog)) { ret = errno; } - socket_setnonblocking(sock); - return ret; + int ret2 = socket_setnonblocking(sock); + return ret == SUCCESS ? ret2 : ret; } //////////////////////////////////////////////////////////////////////////////// @@ -217,12 +222,12 @@ T_ERRCODE socket_send( if (put > 0) { return SUCCESS; } - err = errno; - } while (err != EINTR); + } while ((err = errno) == EINTR); if (err == EAGAIN) { return socket_wait(sock, WAIT_MODE_W, timeout); } + return err; } @@ -232,8 +237,8 @@ T_ERRCODE socket_recv( if (*sock < 0) { return CLOSED; } + *received = 0; - int flags = fcntl(*sock, F_GETFL, 0); do { got = recv(*sock, data, len, 0); if (got > 0) { @@ -246,27 +251,28 @@ T_ERRCODE socket_recv( if (got == 0) { return CLOSED; } - } while (err != EINTR); + } while (err == EINTR); if (err == EAGAIN) { return socket_wait(sock, WAIT_MODE_R, timeout); } + return err; } //////////////////////////////////////////////////////////////////////////////// // Util -void socket_setnonblocking(p_socket sock) { +T_ERRCODE socket_setnonblocking(p_socket sock) { int flags = fcntl(*sock, F_GETFL, 0); flags |= O_NONBLOCK; - fcntl(*sock, F_SETFL, flags); + return fcntl(*sock, F_SETFL, flags) != -1 ? SUCCESS : errno; } -void socket_setblocking(p_socket sock) { +T_ERRCODE socket_setblocking(p_socket sock) { int flags = fcntl(*sock, F_GETFL, 0); flags &= (~(O_NONBLOCK)); - fcntl(*sock, F_SETFL, flags); + return fcntl(*sock, F_SETFL, flags) != -1 ? SUCCESS : errno; } //////////////////////////////////////////////////////////////////////////////// diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Makefile.am b/vendor/git.apache.org/thrift.git/lib/netcore/Makefile.am new file mode 100644 index 0000000..caf3f34 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Makefile.am @@ -0,0 +1,41 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +SUBDIRS = . + +all-local: + $(DOTNETCORE) build + +check-local: + $(DOTNETCORE) test Tests/Thrift.Tests/Thrift.Tests.csproj + ${DOTNETCORE} test Tests/Thrift.IntegrationTests/Thrift.IntegrationTests.csproj + +clean-local: + $(RM) -r Thrift/bin + $(RM) -r Thrift/obj + +EXTRA_DIST = \ + README.md \ + Tests \ + Thrift \ + Thrift.sln \ + build.cmd \ + build.sh \ + runtests.cmd \ + runtests.sh diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/README.md b/vendor/git.apache.org/thrift.git/lib/netcore/README.md new file mode 100644 index 0000000..94b047f --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/README.md @@ -0,0 +1,24 @@ +# Apache Thrift netcore + +Thrift client library ported to Microsoft .Net Core + +# Content +- Tests/Thrift.PublicInterfaces.Compile.Tests - project for checking public interfaces during adding changes to Thrift library +- Thrift - Thrift library + +# Reused components +- .NET Standard 1.6 (SDK 2.0.0) + +# How to build on Windows +- Get Thrift IDL compiler executable, add to some folder and add path to this folder into PATH variable +- Open the Thrift.sln project with Visual Studio and build. +or +- Build with scripts + +# How to build on Unix +- Ensure you have .NET Core 2.0.0 SDK installed or use the Ubuntu Xenial docker image +- Follow common build practice for Thrift: bootstrap, configure, and make + +# Known issues +- In trace logging mode you can see some not important internal exceptions + diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.IntegrationTests/.gitignore b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.IntegrationTests/.gitignore new file mode 100644 index 0000000..7254c31 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.IntegrationTests/.gitignore @@ -0,0 +1,2 @@ +# ignore for autogenerated files +/Apache diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.IntegrationTests/Protocols/ProtocolsOperationsTests.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.IntegrationTests/Protocols/ProtocolsOperationsTests.cs new file mode 100644 index 0000000..bc4afa1 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.IntegrationTests/Protocols/ProtocolsOperationsTests.cs @@ -0,0 +1,502 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.IO; +using System.Text; +using System.Threading.Tasks; +using KellermanSoftware.CompareNetObjects; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Thrift.Protocols; +using Thrift.Protocols.Entities; +using Thrift.Transports.Client; + +namespace Thrift.IntegrationTests.Protocols +{ + [TestClass] + public class ProtocolsOperationsTests + { + private readonly CompareLogic _compareLogic = new CompareLogic(); + + [DataTestMethod] + [DataRow(typeof(TBinaryProtocol), TMessageType.Call)] + [DataRow(typeof(TBinaryProtocol), TMessageType.Exception)] + [DataRow(typeof(TBinaryProtocol), TMessageType.Oneway)] + [DataRow(typeof(TBinaryProtocol), TMessageType.Reply)] + [DataRow(typeof(TCompactProtocol), TMessageType.Call)] + [DataRow(typeof(TCompactProtocol), TMessageType.Exception)] + [DataRow(typeof(TCompactProtocol), TMessageType.Oneway)] + [DataRow(typeof(TCompactProtocol), TMessageType.Reply)] + [DataRow(typeof(TJsonProtocol), TMessageType.Call)] + [DataRow(typeof(TJsonProtocol), TMessageType.Exception)] + [DataRow(typeof(TJsonProtocol), TMessageType.Oneway)] + [DataRow(typeof(TJsonProtocol), TMessageType.Reply)] + public async Task WriteReadMessage_Test(Type protocolType, TMessageType messageType) + { + var expected = new TMessage(nameof(TMessage), messageType, 1); + + try + { + var tuple = GetProtocolInstance(protocolType); + using (var stream = tuple.Item1) + { + var protocol = tuple.Item2; + + await protocol.WriteMessageBeginAsync(expected); + await protocol.WriteMessageEndAsync(); + + stream.Seek(0, SeekOrigin.Begin); + + var actualMessage = await protocol.ReadMessageBeginAsync(); + await protocol.ReadMessageEndAsync(); + + var result = _compareLogic.Compare(expected, actualMessage); + Assert.IsTrue(result.AreEqual, result.DifferencesString); + } + } + catch (Exception e) + { + throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e); + } + } + + [DataTestMethod] + [DataRow(typeof(TBinaryProtocol))] + [DataRow(typeof(TCompactProtocol))] + [DataRow(typeof(TJsonProtocol))] + [ExpectedException(typeof(Exception))] + public async Task WriteReadStruct_Test(Type protocolType) + { + var expected = new TStruct(nameof(TStruct)); + + try + { + var tuple = GetProtocolInstance(protocolType); + using (var stream = tuple.Item1) + { + var protocol = tuple.Item2; + + await protocol.WriteStructBeginAsync(expected); + await protocol.WriteStructEndAsync(); + + stream?.Seek(0, SeekOrigin.Begin); + + var actual = await protocol.ReadStructBeginAsync(); + await protocol.ReadStructEndAsync(); + + var result = _compareLogic.Compare(expected, actual); + Assert.IsTrue(result.AreEqual, result.DifferencesString); + } + + } + catch (Exception e) + { + throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e); + } + } + + [DataTestMethod] + [DataRow(typeof(TBinaryProtocol))] + [DataRow(typeof(TCompactProtocol))] + [DataRow(typeof(TJsonProtocol))] + [ExpectedException(typeof(Exception))] + public async Task WriteReadField_Test(Type protocolType) + { + var expected = new TField(nameof(TField), TType.String, 1); + + try + { + var tuple = GetProtocolInstance(protocolType); + using (var stream = tuple.Item1) + { + var protocol = tuple.Item2; + + await protocol.WriteFieldBeginAsync(expected); + await protocol.WriteFieldEndAsync(); + + stream?.Seek(0, SeekOrigin.Begin); + + var actual = await protocol.ReadFieldBeginAsync(); + await protocol.ReadFieldEndAsync(); + + var result = _compareLogic.Compare(expected, actual); + Assert.IsTrue(result.AreEqual, result.DifferencesString); + } + } + catch (Exception e) + { + throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e); + } + } + + [DataTestMethod] + [DataRow(typeof(TBinaryProtocol))] + [DataRow(typeof(TCompactProtocol))] + [DataRow(typeof(TJsonProtocol))] + public async Task WriteReadMap_Test(Type protocolType) + { + var expected = new TMap(TType.String, TType.String, 1); + + try + { + var tuple = GetProtocolInstance(protocolType); + using (var stream = tuple.Item1) + { + var protocol = tuple.Item2; + + await protocol.WriteMapBeginAsync(expected); + await protocol.WriteMapEndAsync(); + + stream?.Seek(0, SeekOrigin.Begin); + + var actual = await protocol.ReadMapBeginAsync(); + await protocol.ReadMapEndAsync(); + + var result = _compareLogic.Compare(expected, actual); + Assert.IsTrue(result.AreEqual, result.DifferencesString); + } + } + catch (Exception e) + { + throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e); + } + + } + + [DataTestMethod] + [DataRow(typeof(TBinaryProtocol))] + [DataRow(typeof(TCompactProtocol))] + [DataRow(typeof(TJsonProtocol))] + public async Task WriteReadList_Test(Type protocolType) + { + var expected = new TList(TType.String, 1); + + try + { + var tuple = GetProtocolInstance(protocolType); + using (var stream = tuple.Item1) + { + var protocol = tuple.Item2; + + await protocol.WriteListBeginAsync(expected); + await protocol.WriteListEndAsync(); + + stream?.Seek(0, SeekOrigin.Begin); + + var actual = await protocol.ReadListBeginAsync(); + await protocol.ReadListEndAsync(); + + var result = _compareLogic.Compare(expected, actual); + Assert.IsTrue(result.AreEqual, result.DifferencesString); + } + } + catch (Exception e) + { + throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e); + } + } + + [DataTestMethod] + [DataRow(typeof(TBinaryProtocol))] + [DataRow(typeof(TCompactProtocol))] + [DataRow(typeof(TJsonProtocol))] + public async Task WriteReadSet_Test(Type protocolType) + { + var expected = new TSet(TType.String, 1); + + try + { + var tuple = GetProtocolInstance(protocolType); + using (var stream = tuple.Item1) + { + var protocol = tuple.Item2; + + await protocol.WriteSetBeginAsync(expected); + await protocol.WriteSetEndAsync(); + + stream?.Seek(0, SeekOrigin.Begin); + + var actual = await protocol.ReadSetBeginAsync(); + await protocol.ReadSetEndAsync(); + + var result = _compareLogic.Compare(expected, actual); + Assert.IsTrue(result.AreEqual, result.DifferencesString); + } + } + catch (Exception e) + { + throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e); + } + } + + [DataTestMethod] + [DataRow(typeof(TBinaryProtocol))] + [DataRow(typeof(TCompactProtocol))] + [DataRow(typeof(TJsonProtocol))] + public async Task WriteReadBool_Test(Type protocolType) + { + var expected = true; + + try + { + var tuple = GetProtocolInstance(protocolType); + using (var stream = tuple.Item1) + { + var protocol = tuple.Item2; + + await protocol.WriteBoolAsync(expected); + + stream?.Seek(0, SeekOrigin.Begin); + + var actual = await protocol.ReadBoolAsync(); + + var result = _compareLogic.Compare(expected, actual); + Assert.IsTrue(result.AreEqual, result.DifferencesString); + } + } + catch (Exception e) + { + throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e); + } + } + + [DataTestMethod] + [DataRow(typeof(TBinaryProtocol))] + [DataRow(typeof(TCompactProtocol))] + [DataRow(typeof(TJsonProtocol))] + public async Task WriteReadByte_Test(Type protocolType) + { + var expected = sbyte.MaxValue; + + try + { + var tuple = GetProtocolInstance(protocolType); + using (var stream = tuple.Item1) + { + var protocol = tuple.Item2; + + await protocol.WriteByteAsync(expected); + + stream?.Seek(0, SeekOrigin.Begin); + + var actual = await protocol.ReadByteAsync(); + + var result = _compareLogic.Compare(expected, actual); + Assert.IsTrue(result.AreEqual, result.DifferencesString); + } + } + catch (Exception e) + { + throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e); + } + } + + [DataTestMethod] + [DataRow(typeof(TBinaryProtocol))] + [DataRow(typeof(TCompactProtocol))] + [DataRow(typeof(TJsonProtocol))] + public async Task WriteReadI16_Test(Type protocolType) + { + var expected = short.MaxValue; + + try + { + var tuple = GetProtocolInstance(protocolType); + using (var stream = tuple.Item1) + { + var protocol = tuple.Item2; + + await protocol.WriteI16Async(expected); + + stream?.Seek(0, SeekOrigin.Begin); + + var actual = await protocol.ReadI16Async(); + + var result = _compareLogic.Compare(expected, actual); + Assert.IsTrue(result.AreEqual, result.DifferencesString); + } + } + catch (Exception e) + { + throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e); + } + } + + [DataTestMethod] + [DataRow(typeof(TBinaryProtocol))] + [DataRow(typeof(TCompactProtocol))] + [DataRow(typeof(TJsonProtocol))] + public async Task WriteReadI32_Test(Type protocolType) + { + var expected = int.MaxValue; + + try + { + var tuple = GetProtocolInstance(protocolType); + using (var stream = tuple.Item1) + { + var protocol = tuple.Item2; + + await protocol.WriteI32Async(expected); + + stream?.Seek(0, SeekOrigin.Begin); + + var actual = await protocol.ReadI32Async(); + + var result = _compareLogic.Compare(expected, actual); + Assert.IsTrue(result.AreEqual, result.DifferencesString); + } + } + catch (Exception e) + { + throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e); + } + } + + [DataTestMethod] + [DataRow(typeof(TBinaryProtocol))] + [DataRow(typeof(TCompactProtocol))] + [DataRow(typeof(TJsonProtocol))] + public async Task WriteReadI64_Test(Type protocolType) + { + var expected = long.MaxValue; + + try + { + var tuple = GetProtocolInstance(protocolType); + using (var stream = tuple.Item1) + { + var protocol = tuple.Item2; + + await protocol.WriteI64Async(expected); + + stream?.Seek(0, SeekOrigin.Begin); + + var actual = await protocol.ReadI64Async(); + + var result = _compareLogic.Compare(expected, actual); + Assert.IsTrue(result.AreEqual, result.DifferencesString); + } + } + catch (Exception e) + { + throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e); + } + } + + [DataTestMethod] + [DataRow(typeof(TBinaryProtocol))] + [DataRow(typeof(TCompactProtocol))] + [DataRow(typeof(TJsonProtocol))] + public async Task WriteReadDouble_Test(Type protocolType) + { + var expected = double.MaxValue; + + try + { + var tuple = GetProtocolInstance(protocolType); + using (var stream = tuple.Item1) + { + var protocol = tuple.Item2; + + await protocol.WriteDoubleAsync(expected); + + stream?.Seek(0, SeekOrigin.Begin); + + var actual = await protocol.ReadDoubleAsync(); + + var result = _compareLogic.Compare(expected, actual); + Assert.IsTrue(result.AreEqual, result.DifferencesString); + } + } + catch (Exception e) + { + throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e); + } + } + + [DataTestMethod] + [DataRow(typeof(TBinaryProtocol))] + [DataRow(typeof(TCompactProtocol))] + [DataRow(typeof(TJsonProtocol))] + public async Task WriteReadString_Test(Type protocolType) + { + var expected = nameof(String); + + try + { + var tuple = GetProtocolInstance(protocolType); + using (var stream = tuple.Item1) + { + var protocol = tuple.Item2; + + await protocol.WriteStringAsync(expected); + + stream?.Seek(0, SeekOrigin.Begin); + + var actual = await protocol.ReadStringAsync(); + + var result = _compareLogic.Compare(expected, actual); + Assert.IsTrue(result.AreEqual, result.DifferencesString); + } + } + catch (Exception e) + { + throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e); + } + } + + [DataTestMethod] + [DataRow(typeof(TBinaryProtocol))] + [DataRow(typeof(TCompactProtocol))] + [DataRow(typeof(TJsonProtocol))] + public async Task WriteReadBinary_Test(Type protocolType) + { + var expected = Encoding.UTF8.GetBytes(nameof(String)); + + try + { + var tuple = GetProtocolInstance(protocolType); + using (var stream = tuple.Item1) + { + var protocol = tuple.Item2; + + await protocol.WriteBinaryAsync(expected); + + stream?.Seek(0, SeekOrigin.Begin); + + var actual = await protocol.ReadBinaryAsync(); + + var result = _compareLogic.Compare(expected, actual); + Assert.IsTrue(result.AreEqual, result.DifferencesString); + } + } + catch (Exception e) + { + throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e); + } + } + + private static Tuple GetProtocolInstance(Type protocolType) + { + var memoryStream = new MemoryStream(); + var streamClientTransport = new TStreamClientTransport(memoryStream, memoryStream); + var protocol = (TProtocol) Activator.CreateInstance(protocolType, streamClientTransport); + return new Tuple(memoryStream, protocol); + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.IntegrationTests/Thrift.IntegrationTests.csproj b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.IntegrationTests/Thrift.IntegrationTests.csproj new file mode 100644 index 0000000..f25dac5 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.IntegrationTests/Thrift.IntegrationTests.csproj @@ -0,0 +1,29 @@ + + + netcoreapp2.0 + Thrift.IntegrationTests + Thrift.IntegrationTests + Exe + false + false + false + false + false + false + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/.gitignore b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/.gitignore new file mode 100644 index 0000000..ae929a3 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/.gitignore @@ -0,0 +1,4 @@ +# ignore for autogenerated files +/ThriftTest +/Apache +/Facebook diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/CassandraTest.thrift b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/CassandraTest.thrift new file mode 100644 index 0000000..4b92720 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/CassandraTest.thrift @@ -0,0 +1,705 @@ +#!/usr/local/bin/thrift --java --php --py +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# *** PLEASE REMEMBER TO EDIT THE VERSION CONSTANT WHEN MAKING CHANGES *** +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +# +# Interface definition for Cassandra Service +# + +namespace netcore Apache.Cassandra.Test + +# Thrift.rb has a bug where top-level modules that include modules +# with the same name are not properly referenced, so we can't do +# Cassandra::Cassandra::Client. +namespace rb CassandraThrift + +# The API version (NOT the product version), composed as a dot delimited +# string with major, minor, and patch level components. +# +# - Major: Incremented for backward incompatible changes. An example would +# be changes to the number or disposition of method arguments. +# - Minor: Incremented for backward compatible changes. An example would +# be the addition of a new (optional) method. +# - Patch: Incremented for bug fixes. The patch level should be increased +# for every edit that doesn't result in a change to major/minor. +# +# See the Semantic Versioning Specification (SemVer) http://semver.org. +const string VERSION = "19.24.0" + + +# +# data structures +# + +/** Basic unit of data within a ColumnFamily. + * @param name, the name by which this column is set and retrieved. Maximum 64KB long. + * @param value. The data associated with the name. Maximum 2GB long, but in practice you should limit it to small numbers of MB (since Thrift must read the full value into memory to operate on it). + * @param timestamp. The timestamp is used for conflict detection/resolution when two columns with same name need to be compared. + * @param ttl. An optional, positive delay (in seconds) after which the column will be automatically deleted. + */ +struct Column { + 1: required binary name, + 2: optional binary value, + 3: optional i64 timestamp, + 4: optional i32 ttl, +} + +/** A named list of columns. + * @param name. see Column.name. + * @param columns. A collection of standard Columns. The columns within a super column are defined in an adhoc manner. + * Columns within a super column do not have to have matching structures (similarly named child columns). + */ +struct SuperColumn { + 1: required binary name, + 2: required list columns, +} + +struct CounterColumn { + 1: required binary name, + 2: required i64 value +} + +struct CounterSuperColumn { + 1: required binary name, + 2: required list columns +} + +/** + Methods for fetching rows/records from Cassandra will return either a single instance of ColumnOrSuperColumn or a list + of ColumnOrSuperColumns (get_slice()). If you're looking up a SuperColumn (or list of SuperColumns) then the resulting + instances of ColumnOrSuperColumn will have the requested SuperColumn in the attribute super_column. For queries resulting + in Columns, those values will be in the attribute column. This change was made between 0.3 and 0.4 to standardize on + single query methods that may return either a SuperColumn or Column. + + If the query was on a counter column family, you will either get a counter_column (instead of a column) or a + counter_super_column (instead of a super_column) + + @param column. The Column returned by get() or get_slice(). + @param super_column. The SuperColumn returned by get() or get_slice(). + @param counter_column. The Counterolumn returned by get() or get_slice(). + @param counter_super_column. The CounterSuperColumn returned by get() or get_slice(). + */ +struct ColumnOrSuperColumn { + 1: optional Column column, + 2: optional SuperColumn super_column, + 3: optional CounterColumn counter_column, + 4: optional CounterSuperColumn counter_super_column +} + + +# +# Exceptions +# (note that internal server errors will raise a TApplicationException, courtesy of Thrift) +# + +/** A specific column was requested that does not exist. */ +exception NotFoundException { +} + +/** Invalid request could mean keyspace or column family does not exist, required parameters are missing, or a parameter is malformed. + why contains an associated error message. +*/ +exception InvalidRequestException { + 1: required string why +} + +/** Not all the replicas required could be created and/or read. */ +exception UnavailableException { +} + +/** RPC timeout was exceeded. either a node failed mid-operation, or load was too high, or the requested op was too large. */ +exception TimedOutException { +} + +/** invalid authentication request (invalid keyspace, user does not exist, or credentials invalid) */ +exception AuthenticationException { + 1: required string why +} + +/** invalid authorization request (user does not have access to keyspace) */ +exception AuthorizationException { + 1: required string why +} + +/** schemas are not in agreement across all nodes */ +exception SchemaDisagreementException { +} + + +# +# service api +# +/** + * The ConsistencyLevel is an enum that controls both read and write + * behavior based on the ReplicationFactor of the keyspace. The + * different consistency levels have different meanings, depending on + * if you're doing a write or read operation. + * + * If W + R > ReplicationFactor, where W is the number of nodes to + * block for on write, and R the number to block for on reads, you + * will have strongly consistent behavior; that is, readers will + * always see the most recent write. Of these, the most interesting is + * to do QUORUM reads and writes, which gives you consistency while + * still allowing availability in the face of node failures up to half + * of . Of course if latency is more important than + * consistency then you can use lower values for either or both. + * + * Some ConsistencyLevels (ONE, TWO, THREE) refer to a specific number + * of replicas rather than a logical concept that adjusts + * automatically with the replication factor. Of these, only ONE is + * commonly used; TWO and (even more rarely) THREE are only useful + * when you care more about guaranteeing a certain level of + * durability, than consistency. + * + * Write consistency levels make the following guarantees before reporting success to the client: + * ANY Ensure that the write has been written once somewhere, including possibly being hinted in a non-target node. + * ONE Ensure that the write has been written to at least 1 node's commit log and memory table + * TWO Ensure that the write has been written to at least 2 node's commit log and memory table + * THREE Ensure that the write has been written to at least 3 node's commit log and memory table + * QUORUM Ensure that the write has been written to / 2 + 1 nodes + * LOCAL_QUORUM Ensure that the write has been written to / 2 + 1 nodes, within the local datacenter (requires NetworkTopologyStrategy) + * EACH_QUORUM Ensure that the write has been written to / 2 + 1 nodes in each datacenter (requires NetworkTopologyStrategy) + * ALL Ensure that the write is written to <ReplicationFactor> nodes before responding to the client. + * + * Read consistency levels make the following guarantees before returning successful results to the client: + * ANY Not supported. You probably want ONE instead. + * ONE Returns the record obtained from a single replica. + * TWO Returns the record with the most recent timestamp once two replicas have replied. + * THREE Returns the record with the most recent timestamp once three replicas have replied. + * QUORUM Returns the record with the most recent timestamp once a majority of replicas have replied. + * LOCAL_QUORUM Returns the record with the most recent timestamp once a majority of replicas within the local datacenter have replied. + * EACH_QUORUM Returns the record with the most recent timestamp once a majority of replicas within each datacenter have replied. + * ALL Returns the record with the most recent timestamp once all replicas have replied (implies no replica may be down).. +*/ +enum ConsistencyLevel { + ONE = 1, + QUORUM = 2, + LOCAL_QUORUM = 3, + EACH_QUORUM = 4, + ALL = 5, + ANY = 6, + TWO = 7, + THREE = 8, +} + +/** + ColumnParent is used when selecting groups of columns from the same ColumnFamily. In directory structure terms, imagine + ColumnParent as ColumnPath + '/../'. + + See also ColumnPath + */ +struct ColumnParent { + 3: required string column_family, + 4: optional binary super_column, +} + +/** The ColumnPath is the path to a single column in Cassandra. It might make sense to think of ColumnPath and + * ColumnParent in terms of a directory structure. + * + * ColumnPath is used to looking up a single column. + * + * @param column_family. The name of the CF of the column being looked up. + * @param super_column. The super column name. + * @param column. The column name. + */ +struct ColumnPath { + 3: required string column_family, + 4: optional binary super_column, + 5: optional binary column, +} + +/** + A slice range is a structure that stores basic range, ordering and limit information for a query that will return + multiple columns. It could be thought of as Cassandra's version of LIMIT and ORDER BY + + @param start. The column name to start the slice with. This attribute is not required, though there is no default value, + and can be safely set to '', i.e., an empty byte array, to start with the first column name. Otherwise, it + must a valid value under the rules of the Comparator defined for the given ColumnFamily. + @param finish. The column name to stop the slice at. This attribute is not required, though there is no default value, + and can be safely set to an empty byte array to not stop until 'count' results are seen. Otherwise, it + must also be a valid value to the ColumnFamily Comparator. + @param reversed. Whether the results should be ordered in reversed order. Similar to ORDER BY blah DESC in SQL. + @param count. How many columns to return. Similar to LIMIT in SQL. May be arbitrarily large, but Thrift will + materialize the whole result into memory before returning it to the client, so be aware that you may + be better served by iterating through slices by passing the last value of one call in as the 'start' + of the next instead of increasing 'count' arbitrarily large. + */ +struct SliceRange { + 1: required binary start, + 2: required binary finish, + 3: required bool reversed=0, + 4: required i32 count=100, +} + +/** + A SlicePredicate is similar to a mathematic predicate (see http://en.wikipedia.org/wiki/Predicate_(mathematical_logic)), + which is described as "a property that the elements of a set have in common." + + SlicePredicate's in Cassandra are described with either a list of column_names or a SliceRange. If column_names is + specified, slice_range is ignored. + + @param column_name. A list of column names to retrieve. This can be used similar to Memcached's "multi-get" feature + to fetch N known column names. For instance, if you know you wish to fetch columns 'Joe', 'Jack', + and 'Jim' you can pass those column names as a list to fetch all three at once. + @param slice_range. A SliceRange describing how to range, order, and/or limit the slice. + */ +struct SlicePredicate { + 1: optional list column_names, + 2: optional SliceRange slice_range, +} + +enum IndexOperator { + EQ, + GTE, + GT, + LTE, + LT +} + +struct IndexExpression { + 1: required binary column_name, + 2: required IndexOperator op, + 3: required binary value, +} + +struct IndexClause { + 1: required list expressions + 2: required binary start_key, + 3: required i32 count=100, +} + +/** +The semantics of start keys and tokens are slightly different. +Keys are start-inclusive; tokens are start-exclusive. Token +ranges may also wrap -- that is, the end token may be less +than the start one. Thus, a range from keyX to keyX is a +one-element range, but a range from tokenY to tokenY is the +full ring. +*/ +struct KeyRange { + 1: optional binary start_key, + 2: optional binary end_key, + 3: optional string start_token, + 4: optional string end_token, + 5: required i32 count=100 +} + +/** + A KeySlice is key followed by the data it maps to. A collection of KeySlice is returned by the get_range_slice operation. + + @param key. a row key + @param columns. List of data represented by the key. Typically, the list is pared down to only the columns specified by + a SlicePredicate. + */ +struct KeySlice { + 1: required binary key, + 2: required list columns, +} + +struct KeyCount { + 1: required binary key, + 2: required i32 count +} + +/** + * Note that the timestamp is only optional in case of counter deletion. + */ +struct Deletion { + 1: optional i64 timestamp, + 2: optional binary super_column, + 3: optional SlicePredicate predicate, +} + +/** + A Mutation is either an insert (represented by filling column_or_supercolumn) or a deletion (represented by filling the deletion attribute). + @param column_or_supercolumn. An insert to a column or supercolumn (possibly counter column or supercolumn) + @param deletion. A deletion of a column or supercolumn +*/ +struct Mutation { + 1: optional ColumnOrSuperColumn column_or_supercolumn, + 2: optional Deletion deletion, +} + +struct EndpointDetails { + 1: string host, + 2: string datacenter, + 3: optional string rack +} + +/** + A TokenRange describes part of the Cassandra ring, it is a mapping from a range to + endpoints responsible for that range. + @param start_token The first token in the range + @param end_token The last token in the range + @param endpoints The endpoints responsible for the range (listed by their configured listen_address) + @param rpc_endpoints The endpoints responsible for the range (listed by their configured rpc_address) +*/ +struct TokenRange { + 1: required string start_token, + 2: required string end_token, + 3: required list endpoints, + 4: optional list rpc_endpoints + 5: optional list endpoint_details, +} + +/** + Authentication requests can contain any data, dependent on the IAuthenticator used +*/ +struct AuthenticationRequest { + 1: required map credentials +} + +enum IndexType { + KEYS, + CUSTOM +} + +/* describes a column in a column family. */ +struct ColumnDef { + 1: required binary name, + 2: required string validation_class, + 3: optional IndexType index_type, + 4: optional string index_name, + 5: optional map index_options +} + + +/* describes a column family. */ +struct CfDef { + 1: required string keyspace, + 2: required string name, + 3: optional string column_type="Standard", + 5: optional string comparator_type="BytesType", + 6: optional string subcomparator_type, + 8: optional string comment, + 12: optional double read_repair_chance=1.0, + 13: optional list column_metadata, + 14: optional i32 gc_grace_seconds, + 15: optional string default_validation_class, + 16: optional i32 id, + 17: optional i32 min_compaction_threshold, + 18: optional i32 max_compaction_threshold, + 24: optional bool replicate_on_write, + 25: optional double merge_shards_chance, + 26: optional string key_validation_class, + 28: optional binary key_alias, + 29: optional string compaction_strategy, + 30: optional map compaction_strategy_options, + 32: optional map compression_options, + 33: optional double bloom_filter_fp_chance, +} + +/* describes a keyspace. */ +struct KsDef { + 1: required string name, + 2: required string strategy_class, + 3: optional map strategy_options, + + /** @deprecated */ + 4: optional i32 replication_factor, + + 5: required list cf_defs, + 6: optional bool durable_writes=1, +} + +/** CQL query compression */ +enum Compression { + GZIP = 1, + NONE = 2 +} + +enum CqlResultType { + ROWS = 1, + VOID = 2, + INT = 3 +} + +/** Row returned from a CQL query */ +struct CqlRow { + 1: required binary key, + 2: required list columns +} + +struct CqlMetadata { + 1: required map name_types, + 2: required map value_types, + 3: required string default_name_type, + 4: required string default_value_type +} + +struct CqlResult { + 1: required CqlResultType type, + 2: optional list rows, + 3: optional i32 num, + 4: optional CqlMetadata schema +} + +struct CqlPreparedResult { + 1: required i32 itemId, + 2: required i32 count +} + + +service Cassandra { + # auth methods + void login(1: required AuthenticationRequest auth_request) throws (1:AuthenticationException authnx, 2:AuthorizationException authzx), + + # set keyspace + void set_keyspace(1: required string keyspace) throws (1:InvalidRequestException ire), + + # retrieval methods + + /** + Get the Column or SuperColumn at the given column_path. If no value is present, NotFoundException is thrown. (This is + the only method that can throw an exception under non-failure conditions.) + */ + ColumnOrSuperColumn get(1:required binary key, + 2:required ColumnPath column_path, + 3:required ConsistencyLevel consistency_level=ConsistencyLevel.ONE) + throws (1:InvalidRequestException ire, 2:NotFoundException nfe, 3:UnavailableException ue, 4:TimedOutException te), + + /** + Get the group of columns contained by column_parent (either a ColumnFamily name or a ColumnFamily/SuperColumn name + pair) specified by the given SlicePredicate. If no matching values are found, an empty list is returned. + */ + list get_slice(1:required binary key, + 2:required ColumnParent column_parent, + 3:required SlicePredicate predicate, + 4:required ConsistencyLevel consistency_level=ConsistencyLevel.ONE) + throws (1:InvalidRequestException ire, 2:UnavailableException ue, 3:TimedOutException te), + + /** + returns the number of columns matching predicate for a particular key, + ColumnFamily and optionally SuperColumn. + */ + i32 get_count(1:required binary key, + 2:required ColumnParent column_parent, + 3:required SlicePredicate predicate, + 4:required ConsistencyLevel consistency_level=ConsistencyLevel.ONE) + throws (1:InvalidRequestException ire, 2:UnavailableException ue, 3:TimedOutException te), + + /** + Performs a get_slice for column_parent and predicate for the given keys in parallel. + */ + map> multiget_slice(1:required list keys, + 2:required ColumnParent column_parent, + 3:required SlicePredicate predicate, + 4:required ConsistencyLevel consistency_level=ConsistencyLevel.ONE) + throws (1:InvalidRequestException ire, 2:UnavailableException ue, 3:TimedOutException te), + + /** + Perform a get_count in parallel on the given list keys. The return value maps keys to the count found. + */ + map multiget_count(1:required list keys, + 2:required ColumnParent column_parent, + 3:required SlicePredicate predicate, + 4:required ConsistencyLevel consistency_level=ConsistencyLevel.ONE) + throws (1:InvalidRequestException ire, 2:UnavailableException ue, 3:TimedOutException te), + + /** + returns a subset of columns for a contiguous range of keys. + */ + list get_range_slices(1:required ColumnParent column_parent, + 2:required SlicePredicate predicate, + 3:required KeyRange range, + 4:required ConsistencyLevel consistency_level=ConsistencyLevel.ONE) + throws (1:InvalidRequestException ire, 2:UnavailableException ue, 3:TimedOutException te), + + /** Returns the subset of columns specified in SlicePredicate for the rows matching the IndexClause */ + list get_indexed_slices(1:required ColumnParent column_parent, + 2:required IndexClause index_clause, + 3:required SlicePredicate column_predicate, + 4:required ConsistencyLevel consistency_level=ConsistencyLevel.ONE) + throws (1:InvalidRequestException ire, 2:UnavailableException ue, 3:TimedOutException te), + + # modification methods + + /** + * Insert a Column at the given column_parent.column_family and optional column_parent.super_column. + */ + void insert(1:required binary key, + 2:required ColumnParent column_parent, + 3:required Column column, + 4:required ConsistencyLevel consistency_level=ConsistencyLevel.ONE) + throws (1:InvalidRequestException ire, 2:UnavailableException ue, 3:TimedOutException te), + + /** + * Increment or decrement a counter. + */ + void add(1:required binary key, + 2:required ColumnParent column_parent, + 3:required CounterColumn column, + 4:required ConsistencyLevel consistency_level=ConsistencyLevel.ONE) + throws (1:InvalidRequestException ire, 2:UnavailableException ue, 3:TimedOutException te), + + /** + Remove data from the row specified by key at the granularity specified by column_path, and the given timestamp. Note + that all the values in column_path besides column_path.column_family are truly optional: you can remove the entire + row by just specifying the ColumnFamily, or you can remove a SuperColumn or a single Column by specifying those levels too. + */ + void remove(1:required binary key, + 2:required ColumnPath column_path, + 3:required i64 timestamp, + 4:ConsistencyLevel consistency_level=ConsistencyLevel.ONE) + throws (1:InvalidRequestException ire, 2:UnavailableException ue, 3:TimedOutException te), + + /** + * Remove a counter at the specified location. + * Note that counters have limited support for deletes: if you remove a counter, you must wait to issue any following update + * until the delete has reached all the nodes and all of them have been fully compacted. + */ + void remove_counter(1:required binary key, + 2:required ColumnPath path, + 3:required ConsistencyLevel consistency_level=ConsistencyLevel.ONE) + throws (1:InvalidRequestException ire, 2:UnavailableException ue, 3:TimedOutException te), + + + /** + Mutate many columns or super columns for many row keys. See also: Mutation. + + mutation_map maps key to column family to a list of Mutation objects to take place at that scope. + **/ + void batch_mutate(1:required map>> mutation_map, + 2:required ConsistencyLevel consistency_level=ConsistencyLevel.ONE) + throws (1:InvalidRequestException ire, 2:UnavailableException ue, 3:TimedOutException te), + + /** + Truncate will mark and entire column family as deleted. + From the user's perspective a successful call to truncate will result complete data deletion from cfname. + Internally, however, disk space will not be immediatily released, as with all deletes in cassandra, this one + only marks the data as deleted. + The operation succeeds only if all hosts in the cluster at available and will throw an UnavailableException if + some hosts are down. + */ + void truncate(1:required string cfname) + throws (1: InvalidRequestException ire, 2: UnavailableException ue, 3: TimedOutException te), + + + + // Meta-APIs -- APIs to get information about the node or cluster, + // rather than user data. The nodeprobe program provides usage examples. + + /** + * for each schema version present in the cluster, returns a list of nodes at that version. + * hosts that do not respond will be under the key DatabaseDescriptor.INITIAL_VERSION. + * the cluster is all on the same version if the size of the map is 1. + */ + map> describe_schema_versions() + throws (1: InvalidRequestException ire), + + /** list the defined keyspaces in this cluster */ + list describe_keyspaces() + throws (1:InvalidRequestException ire), + + /** get the cluster name */ + string describe_cluster_name(), + + /** get the thrift api version */ + string describe_version(), + + /** get the token ring: a map of ranges to host addresses, + represented as a set of TokenRange instead of a map from range + to list of endpoints, because you can't use Thrift structs as + map keys: + https://issues.apache.org/jira/browse/THRIFT-162 + + for the same reason, we can't return a set here, even though + order is neither important nor predictable. */ + list describe_ring(1:required string keyspace) + throws (1:InvalidRequestException ire), + + /** returns the partitioner used by this cluster */ + string describe_partitioner(), + + /** returns the snitch used by this cluster */ + string describe_snitch(), + + /** describe specified keyspace */ + KsDef describe_keyspace(1:required string keyspace) + throws (1:NotFoundException nfe, 2:InvalidRequestException ire), + + /** experimental API for hadoop/parallel query support. + may change violently and without warning. + + returns list of token strings such that first subrange is (list[0], list[1]], + next is (list[1], list[2]], etc. */ + list describe_splits(1:required string cfName, + 2:required string start_token, + 3:required string end_token, + 4:required i32 keys_per_split) + throws (1:InvalidRequestException ire), + + /** adds a column family. returns the new schema id. */ + string system_add_column_family(1:required CfDef cf_def) + throws (1:InvalidRequestException ire, 2:SchemaDisagreementException sde), + + /** drops a column family. returns the new schema id. */ + string system_drop_column_family(1:required string column_family) + throws (1:InvalidRequestException ire, 2:SchemaDisagreementException sde), + + /** adds a keyspace and any column families that are part of it. returns the new schema id. */ + string system_add_keyspace(1:required KsDef ks_def) + throws (1:InvalidRequestException ire, 2:SchemaDisagreementException sde), + + /** drops a keyspace and any column families that are part of it. returns the new schema id. */ + string system_drop_keyspace(1:required string keyspace) + throws (1:InvalidRequestException ire, 2:SchemaDisagreementException sde), + + /** updates properties of a keyspace. returns the new schema id. */ + string system_update_keyspace(1:required KsDef ks_def) + throws (1:InvalidRequestException ire, 2:SchemaDisagreementException sde), + + /** updates properties of a column family. returns the new schema id. */ + string system_update_column_family(1:required CfDef cf_def) + throws (1:InvalidRequestException ire, 2:SchemaDisagreementException sde), + + /** + * Executes a CQL (Cassandra Query Language) statement and returns a + * CqlResult containing the results. + */ + CqlResult execute_cql_query(1:required binary query, 2:required Compression compression) + throws (1:InvalidRequestException ire, + 2:UnavailableException ue, + 3:TimedOutException te, + 4:SchemaDisagreementException sde) + + + /** + * Prepare a CQL (Cassandra Query Language) statement by compiling and returning + * - the type of CQL statement + * - an id token of the compiled CQL stored on the server side. + * - a count of the discovered bound markers in the statement + */ + CqlPreparedResult prepare_cql_query(1:required binary query, 2:required Compression compression) + throws (1:InvalidRequestException ire) + + + /** + * Executes a prepared CQL (Cassandra Query Language) statement by passing an id token and a list of variables + * to bind and returns a CqlResult containing the results. + */ + CqlResult execute_prepared_cql_query(1:required i32 itemId, 2:required list values) + throws (1:InvalidRequestException ire, + 2:UnavailableException ue, + 3:TimedOutException te, + 4:SchemaDisagreementException sde) + + +} diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/Properties/AssemblyInfo.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..0bb460f --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/Properties/AssemblyInfo.cs @@ -0,0 +1,40 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. + +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("The Apache Software Foundation")] +[assembly: AssemblyProduct("Thrift")] +[assembly: AssemblyCopyright("The Apache Software Foundation")] +[assembly: AssemblyTrademark("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. + +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM + +[assembly: Guid("d0d3706b-fed5-4cf5-b984-04f448de9d7b")] \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/Thrift.PublicInterfaces.Compile.Tests.csproj b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/Thrift.PublicInterfaces.Compile.Tests.csproj new file mode 100644 index 0000000..c4a84a3 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/Thrift.PublicInterfaces.Compile.Tests.csproj @@ -0,0 +1,36 @@ + + + + netcoreapp2.0 + Thrift.PublicInterfaces.Compile.Tests + Thrift.PublicInterfaces.Compile.Tests + false + false + false + false + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.Tests/Collections/TCollectionsTests.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.Tests/Collections/TCollectionsTests.cs new file mode 100644 index 0000000..1be99b4 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.Tests/Collections/TCollectionsTests.cs @@ -0,0 +1,83 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Collections.Generic; +using System.Text; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Thrift.Collections; + +namespace Thrift.Tests.Collections +{ + // ReSharper disable once InconsistentNaming + [TestClass] + public class TCollectionsTests + { + //TODO: Add tests for IEnumerable with objects and primitive values inside + + [TestMethod] + public void TCollection_Equals_Primitive_Test() + { + var collection1 = new List {1,2,3}; + var collection2 = new List {1,2,3}; + + var result = TCollections.Equals(collection1, collection2); + + Assert.IsTrue(result); + } + + [TestMethod] + public void TCollection_Equals_Primitive_Different_Test() + { + var collection1 = new List { 1, 2, 3 }; + var collection2 = new List { 1, 2 }; + + var result = TCollections.Equals(collection1, collection2); + + Assert.IsFalse(result); + } + + [TestMethod] + public void TCollection_Equals_Objects_Test() + { + var collection1 = new List { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } }; + var collection2 = new List { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } }; + + var result = TCollections.Equals(collection1, collection2); + + // references to different collections + Assert.IsFalse(result); + } + + [TestMethod] + public void TCollection_Equals_OneAndTheSameObject_Test() + { + var collection1 = new List { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } }; + var collection2 = collection1; + + var result = TCollections.Equals(collection1, collection2); + + // references to one and the same collection + Assert.IsTrue(result); + } + + private class ExampleClass + { + public int X { get; set; } + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.Tests/Collections/THashSetTests.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.Tests/Collections/THashSetTests.cs new file mode 100644 index 0000000..8de573e --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.Tests/Collections/THashSetTests.cs @@ -0,0 +1,71 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Thrift.Collections; + +namespace Thrift.Tests.Collections +{ + // ReSharper disable once InconsistentNaming + [TestClass] + public class THashSetTests + { + [TestMethod] + public void THashSet_Equals_Primitive_Test() + { + const int value = 1; + + var hashSet = new THashSet {value}; + + Assert.IsTrue(hashSet.Contains(value)); + + hashSet.Remove(value); + + Assert.IsTrue(hashSet.Count == 0); + + hashSet.Add(value); + + Assert.IsTrue(hashSet.Contains(value)); + + hashSet.Clear(); + + Assert.IsTrue(hashSet.Count == 0); + + var newArr = new int[1]; + hashSet.Add(value); + hashSet.CopyTo(newArr, 0); + + Assert.IsTrue(newArr.Contains(value)); + + var en = hashSet.GetEnumerator(); + en.MoveNext(); + + Assert.IsTrue((int)en.Current == value); + + using (var ien = ((IEnumerable)hashSet).GetEnumerator()) + { + ien.MoveNext(); + + Assert.IsTrue(ien.Current == value); + } + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.Tests/Protocols/TJsonProtocolHelperTests.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.Tests/Protocols/TJsonProtocolHelperTests.cs new file mode 100644 index 0000000..cdc8317 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.Tests/Protocols/TJsonProtocolHelperTests.cs @@ -0,0 +1,172 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Thrift.Protocols; +using Thrift.Protocols.Entities; +using Thrift.Protocols.Utilities; + +namespace Thrift.Tests.Protocols +{ + [TestClass] + public class TJSONProtocolHelperTests + { + [TestMethod] + public void GetTypeNameForTypeId_Test() + { + // input/output + var sets = new List> + { + new Tuple(TType.Bool, TJSONProtocolConstants.TypeNames.NameBool), + new Tuple(TType.Byte, TJSONProtocolConstants.TypeNames.NameByte), + new Tuple(TType.I16, TJSONProtocolConstants.TypeNames.NameI16), + new Tuple(TType.I32, TJSONProtocolConstants.TypeNames.NameI32), + new Tuple(TType.I64, TJSONProtocolConstants.TypeNames.NameI64), + new Tuple(TType.Double, TJSONProtocolConstants.TypeNames.NameDouble), + new Tuple(TType.String, TJSONProtocolConstants.TypeNames.NameString), + new Tuple(TType.Struct, TJSONProtocolConstants.TypeNames.NameStruct), + new Tuple(TType.Map, TJSONProtocolConstants.TypeNames.NameMap), + new Tuple(TType.Set, TJSONProtocolConstants.TypeNames.NameSet), + new Tuple(TType.List, TJSONProtocolConstants.TypeNames.NameList), + }; + + foreach (var t in sets) + { + Assert.IsTrue(TJSONProtocolHelper.GetTypeNameForTypeId(t.Item1) == t.Item2, $"Wrong mapping of TypeName {t.Item2} to TType: {t.Item1}"); + } + } + + [TestMethod] + [ExpectedException(typeof(TProtocolException))] + public void GetTypeNameForTypeId_TStop_Test() + { + TJSONProtocolHelper.GetTypeNameForTypeId(TType.Stop); + } + + [TestMethod] + [ExpectedException(typeof(TProtocolException))] + public void GetTypeNameForTypeId_NonExistingTType_Test() + { + TJSONProtocolHelper.GetTypeNameForTypeId((TType)100); + } + + [TestMethod] + public void GetTypeIdForTypeName_Test() + { + // input/output + var sets = new List> + { + new Tuple(TType.Bool, TJSONProtocolConstants.TypeNames.NameBool), + new Tuple(TType.Byte, TJSONProtocolConstants.TypeNames.NameByte), + new Tuple(TType.I16, TJSONProtocolConstants.TypeNames.NameI16), + new Tuple(TType.I32, TJSONProtocolConstants.TypeNames.NameI32), + new Tuple(TType.I64, TJSONProtocolConstants.TypeNames.NameI64), + new Tuple(TType.Double, TJSONProtocolConstants.TypeNames.NameDouble), + new Tuple(TType.String, TJSONProtocolConstants.TypeNames.NameString), + new Tuple(TType.Struct, TJSONProtocolConstants.TypeNames.NameStruct), + new Tuple(TType.Map, TJSONProtocolConstants.TypeNames.NameMap), + new Tuple(TType.Set, TJSONProtocolConstants.TypeNames.NameSet), + new Tuple(TType.List, TJSONProtocolConstants.TypeNames.NameList), + }; + + foreach (var t in sets) + { + Assert.IsTrue(TJSONProtocolHelper.GetTypeIdForTypeName(t.Item2) == t.Item1, $"Wrong mapping of TypeName {t.Item2} to TType: {t.Item1}"); + } + } + + [TestMethod] + [ExpectedException(typeof(TProtocolException))] + public void GetTypeIdForTypeName_TStopTypeName_Test() + { + TJSONProtocolHelper.GetTypeIdForTypeName(new []{(byte)TType.Stop, (byte)TType.Stop}); + } + + [TestMethod] + [ExpectedException(typeof(TProtocolException))] + public void GetTypeIdForTypeName_NonExistingTypeName_Test() + { + TJSONProtocolHelper.GetTypeIdForTypeName(new byte[]{100}); + } + + [TestMethod] + [ExpectedException(typeof(TProtocolException))] + public void GetTypeIdForTypeName_EmptyName_Test() + { + TJSONProtocolHelper.GetTypeIdForTypeName(new byte[] {}); + } + + [TestMethod] + public void IsJsonNumeric_Test() + { + // input/output + var correctJsonNumeric = "+-.0123456789Ee"; + var incorrectJsonNumeric = "AaBcDd/*\\"; + + var sets = correctJsonNumeric.Select(ch => new Tuple((byte) ch, true)).ToList(); + sets.AddRange(incorrectJsonNumeric.Select(ch => new Tuple((byte) ch, false))); + + foreach (var t in sets) + { + Assert.IsTrue(TJSONProtocolHelper.IsJsonNumeric(t.Item1) == t.Item2, $"Wrong mapping of Char {t.Item1} to bool: {t.Item2}"); + } + } + + [TestMethod] + public void ToHexVal_Test() + { + // input/output + var chars = "0123456789abcdef"; + var expectedHexValues = new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; + + var sets = chars.Select((ch, i) => new Tuple(ch, expectedHexValues[i])).ToList(); + + foreach (var t in sets) + { + var actualResult = TJSONProtocolHelper.ToHexVal((byte)t.Item1); + Assert.IsTrue(actualResult == t.Item2, $"Wrong mapping of char byte {t.Item1} to it expected hex value: {t.Item2}. Actual hex value: {actualResult}"); + } + } + + [TestMethod] + [ExpectedException(typeof(TProtocolException))] + public void ToHexVal_WrongInputChar_Test() + { + TJSONProtocolHelper.ToHexVal((byte)'s'); + } + + [TestMethod] + public void ToHexChar_Test() + { + // input/output + var hexValues = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; + var expectedChars = "0123456789abcdef"; + + + var sets = hexValues.Select((hv, i) => new Tuple(hv, expectedChars[i])).ToList(); + + foreach (var t in sets) + { + var actualResult = TJSONProtocolHelper.ToHexChar(t.Item1); + Assert.IsTrue(actualResult == t.Item2, $"Wrong mapping of hex value {t.Item1} to it expected char: {t.Item2}. Actual hex value: {actualResult}"); + } + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.Tests/Protocols/TJsonProtocolTests.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.Tests/Protocols/TJsonProtocolTests.cs new file mode 100644 index 0000000..5237360 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.Tests/Protocols/TJsonProtocolTests.cs @@ -0,0 +1,67 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using NSubstitute; +using Thrift.Protocols; +using Thrift.Protocols.Entities; +using Thrift.Transports; +using Thrift.Transports.Client; + +namespace Thrift.Tests.Protocols +{ + // ReSharper disable once InconsistentNaming + [TestClass] + public class TJSONProtocolTests + { + [TestMethod] + public void TJSONProtocol_Can_Create_Instance_Test() + { + var httpClientTransport = Substitute.For(new Uri("http://localhost"), null); + + var result = new TJSONProtocolWrapper(httpClientTransport); + + Assert.IsNotNull(result); + Assert.IsNotNull(result.WrappedContext); + Assert.IsNotNull(result.WrappedReader); + Assert.IsNotNull(result.Transport); + Assert.IsTrue(result.WrappedRecursionDepth == 0); + Assert.IsTrue(result.WrappedRecursionLimit == TProtocol.DefaultRecursionDepth); + + Assert.IsTrue(result.Transport.Equals(httpClientTransport)); + Assert.IsTrue(result.WrappedContext.GetType().Name.Equals("JSONBaseContext", StringComparison.OrdinalIgnoreCase)); + Assert.IsTrue(result.WrappedReader.GetType().Name.Equals("LookaheadReader", StringComparison.OrdinalIgnoreCase)); + } + + private class TJSONProtocolWrapper : TJsonProtocol + { + public TJSONProtocolWrapper(TClientTransport trans) : base(trans) + { + } + + public object WrappedContext => Context; + public object WrappedReader => Reader; + public int WrappedRecursionDepth => RecursionDepth; + public int WrappedRecursionLimit => RecursionLimit; + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.Tests/Thrift.Tests.csproj b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.Tests/Thrift.Tests.csproj new file mode 100644 index 0000000..e46f165 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Tests/Thrift.Tests/Thrift.Tests.csproj @@ -0,0 +1,18 @@ + + + netcoreapp2.0 + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift.sln b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift.sln new file mode 100644 index 0000000..fe30aa5 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift.sln @@ -0,0 +1,85 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26730.12 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{F51FC4DA-CAC0-48B1-A069-B1712BCAA5BE}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Thrift", "Thrift\Thrift.csproj", "{D85F572F-7D80-40A4-9A9B-2731ED187C24}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Thrift.IntegrationTests", "Tests\Thrift.IntegrationTests\Thrift.IntegrationTests.csproj", "{9F9A11BF-3C95-4E80-AFBF-768541996844}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Thrift.Tests", "Tests\Thrift.Tests\Thrift.Tests.csproj", "{75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Thrift.PublicInterfaces.Compile.Tests", "Tests\Thrift.PublicInterfaces.Compile.Tests\Thrift.PublicInterfaces.Compile.Tests.csproj", "{A429F05B-F511-45EF-AE7B-04E1AE9C9367}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D85F572F-7D80-40A4-9A9B-2731ED187C24}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D85F572F-7D80-40A4-9A9B-2731ED187C24}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D85F572F-7D80-40A4-9A9B-2731ED187C24}.Debug|x64.ActiveCfg = Debug|Any CPU + {D85F572F-7D80-40A4-9A9B-2731ED187C24}.Debug|x64.Build.0 = Debug|Any CPU + {D85F572F-7D80-40A4-9A9B-2731ED187C24}.Debug|x86.ActiveCfg = Debug|Any CPU + {D85F572F-7D80-40A4-9A9B-2731ED187C24}.Debug|x86.Build.0 = Debug|Any CPU + {D85F572F-7D80-40A4-9A9B-2731ED187C24}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D85F572F-7D80-40A4-9A9B-2731ED187C24}.Release|Any CPU.Build.0 = Release|Any CPU + {D85F572F-7D80-40A4-9A9B-2731ED187C24}.Release|x64.ActiveCfg = Release|Any CPU + {D85F572F-7D80-40A4-9A9B-2731ED187C24}.Release|x64.Build.0 = Release|Any CPU + {D85F572F-7D80-40A4-9A9B-2731ED187C24}.Release|x86.ActiveCfg = Release|Any CPU + {D85F572F-7D80-40A4-9A9B-2731ED187C24}.Release|x86.Build.0 = Release|Any CPU + {9F9A11BF-3C95-4E80-AFBF-768541996844}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9F9A11BF-3C95-4E80-AFBF-768541996844}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9F9A11BF-3C95-4E80-AFBF-768541996844}.Debug|x64.ActiveCfg = Debug|Any CPU + {9F9A11BF-3C95-4E80-AFBF-768541996844}.Debug|x64.Build.0 = Debug|Any CPU + {9F9A11BF-3C95-4E80-AFBF-768541996844}.Debug|x86.ActiveCfg = Debug|Any CPU + {9F9A11BF-3C95-4E80-AFBF-768541996844}.Debug|x86.Build.0 = Debug|Any CPU + {9F9A11BF-3C95-4E80-AFBF-768541996844}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9F9A11BF-3C95-4E80-AFBF-768541996844}.Release|Any CPU.Build.0 = Release|Any CPU + {9F9A11BF-3C95-4E80-AFBF-768541996844}.Release|x64.ActiveCfg = Release|Any CPU + {9F9A11BF-3C95-4E80-AFBF-768541996844}.Release|x64.Build.0 = Release|Any CPU + {9F9A11BF-3C95-4E80-AFBF-768541996844}.Release|x86.ActiveCfg = Release|Any CPU + {9F9A11BF-3C95-4E80-AFBF-768541996844}.Release|x86.Build.0 = Release|Any CPU + {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Debug|x64.ActiveCfg = Debug|Any CPU + {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Debug|x64.Build.0 = Debug|Any CPU + {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Debug|x86.ActiveCfg = Debug|Any CPU + {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Debug|x86.Build.0 = Debug|Any CPU + {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Release|Any CPU.Build.0 = Release|Any CPU + {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Release|x64.ActiveCfg = Release|Any CPU + {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Release|x64.Build.0 = Release|Any CPU + {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Release|x86.ActiveCfg = Release|Any CPU + {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Release|x86.Build.0 = Release|Any CPU + {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Debug|x64.ActiveCfg = Debug|Any CPU + {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Debug|x64.Build.0 = Debug|Any CPU + {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Debug|x86.ActiveCfg = Debug|Any CPU + {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Debug|x86.Build.0 = Debug|Any CPU + {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Release|Any CPU.Build.0 = Release|Any CPU + {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Release|x64.ActiveCfg = Release|Any CPU + {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Release|x64.Build.0 = Release|Any CPU + {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Release|x86.ActiveCfg = Release|Any CPU + {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {9F9A11BF-3C95-4E80-AFBF-768541996844} = {F51FC4DA-CAC0-48B1-A069-B1712BCAA5BE} + {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1} = {F51FC4DA-CAC0-48B1-A069-B1712BCAA5BE} + {A429F05B-F511-45EF-AE7B-04E1AE9C9367} = {F51FC4DA-CAC0-48B1-A069-B1712BCAA5BE} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {FD20BC4A-0109-41D8-8C0C-893E784D7EF9} + EndGlobalSection +EndGlobal diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Collections/TCollections.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Collections/TCollections.cs new file mode 100644 index 0000000..147bfc7 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Collections/TCollections.cs @@ -0,0 +1,101 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System.Collections; + +namespace Thrift.Collections +{ + // ReSharper disable once InconsistentNaming + public class TCollections + { + /// + /// This will return true if the two collections are value-wise the same. + /// If the collection contains a collection, the collections will be compared using this method. + /// + public static bool Equals(IEnumerable first, IEnumerable second) + { + if (first == null && second == null) + { + return true; + } + + if (first == null || second == null) + { + return false; + } + + var fiter = first.GetEnumerator(); + var siter = second.GetEnumerator(); + + var fnext = fiter.MoveNext(); + var snext = siter.MoveNext(); + + while (fnext && snext) + { + var fenum = fiter.Current as IEnumerable; + var senum = siter.Current as IEnumerable; + + if (fenum != null && senum != null) + { + if (!Equals(fenum, senum)) + { + return false; + } + } + else if (fenum == null ^ senum == null) + { + return false; + } + else if (!Equals(fiter.Current, siter.Current)) + { + return false; + } + + fnext = fiter.MoveNext(); + snext = siter.MoveNext(); + } + + return fnext == snext; + } + + /// + /// This returns a hashcode based on the value of the enumerable. + /// + public static int GetHashCode(IEnumerable enumerable) + { + if (enumerable == null) + { + return 0; + } + + var hashcode = 0; + + foreach (var obj in enumerable) + { + var enum2 = obj as IEnumerable; + var objHash = enum2 == null ? obj.GetHashCode() : GetHashCode(enum2); + + unchecked + { + hashcode = (hashcode*397) ^ (objHash); + } + } + + return hashcode; + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Collections/THashSet.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Collections/THashSet.cs new file mode 100644 index 0000000..011f0a0 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Collections/THashSet.cs @@ -0,0 +1,67 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System.Collections; +using System.Collections.Generic; + +namespace Thrift.Collections +{ + // ReSharper disable once InconsistentNaming + public class THashSet : ICollection + { + private readonly HashSet _set = new HashSet(); + + public int Count => _set.Count; + + public bool IsReadOnly => false; + + public void Add(T item) + { + _set.Add(item); + } + + public void Clear() + { + _set.Clear(); + } + + public bool Contains(T item) + { + return _set.Contains(item); + } + + public void CopyTo(T[] array, int arrayIndex) + { + _set.CopyTo(array, arrayIndex); + } + + public IEnumerator GetEnumerator() + { + return _set.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable) _set).GetEnumerator(); + } + + public bool Remove(T item) + { + return _set.Remove(item); + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/ITAsyncProcessor.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/ITAsyncProcessor.cs new file mode 100644 index 0000000..db8e40a --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/ITAsyncProcessor.cs @@ -0,0 +1,29 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System.Threading; +using System.Threading.Tasks; +using Thrift.Protocols; + +namespace Thrift +{ + public interface ITAsyncProcessor + { + Task ProcessAsync(TProtocol iprot, TProtocol oprot); + Task ProcessAsync(TProtocol iprot, TProtocol oprot, CancellationToken cancellationToken); + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/ITProcessorFactory.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/ITProcessorFactory.cs new file mode 100644 index 0000000..5133e5c --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/ITProcessorFactory.cs @@ -0,0 +1,28 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using Thrift.Server; +using Thrift.Transports; + +namespace Thrift +{ + // ReSharper disable once InconsistentNaming + public interface ITProcessorFactory + { + ITAsyncProcessor GetAsyncProcessor(TClientTransport trans, TBaseServer baseServer = null); + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Properties/AssemblyInfo.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..68cd49c --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Properties/AssemblyInfo.cs @@ -0,0 +1,56 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System.Reflection; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. + +[assembly: AssemblyTitle("Thrift")] +[assembly: AssemblyDescription("C# .NET Core bindings for the Apache Thrift RPC system")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("The Apache Software Foundation")] +[assembly: AssemblyProduct("Thrift")] +[assembly: AssemblyCopyright("The Apache Software Foundation")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] +//@TODO where to put License information? + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a exType in this assembly from +// COM, set the ComVisible attribute to true on that exType. + +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM + +[assembly: Guid("df3f8ef0-e0a3-4c86-a65b-8ec84e016b1d")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: + +[assembly: AssemblyVersion("0.12.0.0")] +[assembly: AssemblyFileVersion("0.12.0.0")] diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TField.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TField.cs new file mode 100644 index 0000000..d311535 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TField.cs @@ -0,0 +1,37 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +namespace Thrift.Protocols.Entities +{ + // ReSharper disable once InconsistentNaming + public struct TField + { + public TField(string name, TType type, short id) + { + Name = name; + Type = type; + ID = id; + } + + public string Name { get; set; } + + public TType Type { get; set; } + + // ReSharper disable once InconsistentNaming - do not rename - it used for generation + public short ID { get; set; } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TList.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TList.cs new file mode 100644 index 0000000..ce23220 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TList.cs @@ -0,0 +1,33 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +namespace Thrift.Protocols.Entities +{ + // ReSharper disable once InconsistentNaming + public struct TList + { + public TList(TType elementType, int count) + { + ElementType = elementType; + Count = count; + } + + public TType ElementType { get; set; } + + public int Count { get; set; } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TMap.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TMap.cs new file mode 100644 index 0000000..9195593 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TMap.cs @@ -0,0 +1,36 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +namespace Thrift.Protocols.Entities +{ + // ReSharper disable once InconsistentNaming + public struct TMap + { + public TMap(TType keyType, TType valueType, int count) + { + KeyType = keyType; + ValueType = valueType; + Count = count; + } + + public TType KeyType { get; set; } + + public TType ValueType { get; set; } + + public int Count { get; set; } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TMessage.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TMessage.cs new file mode 100644 index 0000000..17f4929 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TMessage.cs @@ -0,0 +1,37 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +namespace Thrift.Protocols.Entities +{ + // ReSharper disable once InconsistentNaming + public struct TMessage + { + public TMessage(string name, TMessageType type, int seqid) + { + Name = name; + Type = type; + SeqID = seqid; + } + + public string Name { get; set; } + + public TMessageType Type { get; set; } + + // ReSharper disable once InconsistentNaming - do not rename - it used for generation + public int SeqID { get; set; } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TMessageType.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TMessageType.cs new file mode 100644 index 0000000..d7b9a22 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TMessageType.cs @@ -0,0 +1,28 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +namespace Thrift.Protocols.Entities +{ + // ReSharper disable once InconsistentNaming + public enum TMessageType + { + Call = 1, + Reply = 2, + Exception = 3, + Oneway = 4 + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TSet.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TSet.cs new file mode 100644 index 0000000..a583b54 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TSet.cs @@ -0,0 +1,38 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +namespace Thrift.Protocols.Entities +{ + // ReSharper disable once InconsistentNaming + public struct TSet + { + public TSet(TType elementType, int count) + { + ElementType = elementType; + Count = count; + } + + public TSet(TList list) + : this(list.ElementType, list.Count) + { + } + + public TType ElementType { get; set; } + + public int Count { get; set; } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TStruct.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TStruct.cs new file mode 100644 index 0000000..a28dcc3 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TStruct.cs @@ -0,0 +1,30 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +namespace Thrift.Protocols.Entities +{ + // ReSharper disable once InconsistentNaming + public struct TStruct + { + public TStruct(string name) + { + Name = name; + } + + public string Name { get; set; } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TType.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TType.cs new file mode 100644 index 0000000..ebe781c --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Entities/TType.cs @@ -0,0 +1,37 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +namespace Thrift.Protocols.Entities +{ + // ReSharper disable once InconsistentNaming + public enum TType : byte + { + Stop = 0, + Void = 1, + Bool = 2, + Byte = 3, + Double = 4, + I16 = 6, + I32 = 8, + I64 = 10, + String = 11, + Struct = 12, + Map = 13, + Set = 14, + List = 15 + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/ITProtocolFactory.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/ITProtocolFactory.cs new file mode 100644 index 0000000..ecc5cc4 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/ITProtocolFactory.cs @@ -0,0 +1,27 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using Thrift.Transports; + +namespace Thrift.Protocols +{ + // ReSharper disable once InconsistentNaming + public interface ITProtocolFactory + { + TProtocol GetProtocol(TClientTransport trans); + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TAbstractBase.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TAbstractBase.cs new file mode 100644 index 0000000..4e18681 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TAbstractBase.cs @@ -0,0 +1,28 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System.Threading; +using System.Threading.Tasks; + +namespace Thrift.Protocols +{ + // ReSharper disable once InconsistentNaming + public interface TAbstractBase + { + Task WriteAsync(TProtocol tProtocol, CancellationToken cancellationToken); + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TBase.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TBase.cs new file mode 100644 index 0000000..014e1ae --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TBase.cs @@ -0,0 +1,28 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System.Threading; +using System.Threading.Tasks; + +namespace Thrift.Protocols +{ + // ReSharper disable once InconsistentNaming + public interface TBase : TAbstractBase + { + Task ReadAsync(TProtocol tProtocol, CancellationToken cancellationToken); + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TBinaryProtocol.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TBinaryProtocol.cs new file mode 100644 index 0000000..deec85c --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TBinaryProtocol.cs @@ -0,0 +1,613 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Thrift.Protocols.Entities; +using Thrift.Transports; + +namespace Thrift.Protocols +{ + // ReSharper disable once InconsistentNaming + public class TBinaryProtocol : TProtocol + { + //TODO: Unit tests + //TODO: Localization + //TODO: pragma + + protected const uint VersionMask = 0xffff0000; + protected const uint Version1 = 0x80010000; + + protected bool StrictRead; + protected bool StrictWrite; + + public TBinaryProtocol(TClientTransport trans) + : this(trans, false, true) + { + } + + public TBinaryProtocol(TClientTransport trans, bool strictRead, bool strictWrite) + : base(trans) + { + StrictRead = strictRead; + StrictWrite = strictWrite; + } + + public override async Task WriteMessageBeginAsync(TMessage message, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + if (StrictWrite) + { + var version = Version1 | (uint) message.Type; + await WriteI32Async((int) version, cancellationToken); + await WriteStringAsync(message.Name, cancellationToken); + await WriteI32Async(message.SeqID, cancellationToken); + } + else + { + await WriteStringAsync(message.Name, cancellationToken); + await WriteByteAsync((sbyte) message.Type, cancellationToken); + await WriteI32Async(message.SeqID, cancellationToken); + } + } + + public override async Task WriteMessageEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task WriteStructBeginAsync(TStruct @struct, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task WriteStructEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task WriteFieldBeginAsync(TField field, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + await WriteByteAsync((sbyte) field.Type, cancellationToken); + await WriteI16Async(field.ID, cancellationToken); + } + + public override async Task WriteFieldEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task WriteFieldStopAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + await WriteByteAsync((sbyte) TType.Stop, cancellationToken); + } + + public override async Task WriteMapBeginAsync(TMap map, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + await WriteByteAsync((sbyte) map.KeyType, cancellationToken); + await WriteByteAsync((sbyte) map.ValueType, cancellationToken); + await WriteI32Async(map.Count, cancellationToken); + } + + public override async Task WriteMapEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task WriteListBeginAsync(TList list, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + await WriteByteAsync((sbyte) list.ElementType, cancellationToken); + await WriteI32Async(list.Count, cancellationToken); + } + + public override async Task WriteListEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task WriteSetBeginAsync(TSet set, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + await WriteByteAsync((sbyte) set.ElementType, cancellationToken); + await WriteI32Async(set.Count, cancellationToken); + } + + public override async Task WriteSetEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task WriteBoolAsync(bool b, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + await WriteByteAsync(b ? (sbyte) 1 : (sbyte) 0, cancellationToken); + } + + protected internal static byte[] CreateWriteByte(sbyte b) + { + var bout = new byte[1]; + + bout[0] = (byte) b; + + return bout; + } + + public override async Task WriteByteAsync(sbyte b, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + var bout = CreateWriteByte(b); + await Trans.WriteAsync(bout, 0, 1, cancellationToken); + } + + protected internal static byte[] CreateWriteI16(short s) + { + var i16Out = new byte[2]; + + i16Out[0] = (byte) (0xff & (s >> 8)); + i16Out[1] = (byte) (0xff & s); + + return i16Out; + } + + public override async Task WriteI16Async(short i16, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + var i16Out = CreateWriteI16(i16); + await Trans.WriteAsync(i16Out, 0, 2, cancellationToken); + } + + protected internal static byte[] CreateWriteI32(int i32) + { + var i32Out = new byte[4]; + + i32Out[0] = (byte) (0xff & (i32 >> 24)); + i32Out[1] = (byte) (0xff & (i32 >> 16)); + i32Out[2] = (byte) (0xff & (i32 >> 8)); + i32Out[3] = (byte) (0xff & i32); + + return i32Out; + } + + public override async Task WriteI32Async(int i32, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + var i32Out = CreateWriteI32(i32); + await Trans.WriteAsync(i32Out, 0, 4, cancellationToken); + } + + protected internal static byte[] CreateWriteI64(long i64) + { + var i64Out = new byte[8]; + + i64Out[0] = (byte) (0xff & (i64 >> 56)); + i64Out[1] = (byte) (0xff & (i64 >> 48)); + i64Out[2] = (byte) (0xff & (i64 >> 40)); + i64Out[3] = (byte) (0xff & (i64 >> 32)); + i64Out[4] = (byte) (0xff & (i64 >> 24)); + i64Out[5] = (byte) (0xff & (i64 >> 16)); + i64Out[6] = (byte) (0xff & (i64 >> 8)); + i64Out[7] = (byte) (0xff & i64); + + return i64Out; + } + + public override async Task WriteI64Async(long i64, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + var i64Out = CreateWriteI64(i64); + await Trans.WriteAsync(i64Out, 0, 8, cancellationToken); + } + + public override async Task WriteDoubleAsync(double d, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + await WriteI64Async(BitConverter.DoubleToInt64Bits(d), cancellationToken); + } + + public override async Task WriteBinaryAsync(byte[] bytes, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + await WriteI32Async(bytes.Length, cancellationToken); + await Trans.WriteAsync(bytes, 0, bytes.Length, cancellationToken); + } + + public override async Task ReadMessageBeginAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + var message = new TMessage(); + var size = await ReadI32Async(cancellationToken); + if (size < 0) + { + var version = (uint) size & VersionMask; + if (version != Version1) + { + throw new TProtocolException(TProtocolException.BAD_VERSION, + $"Bad version in ReadMessageBegin: {version}"); + } + message.Type = (TMessageType) (size & 0x000000ff); + message.Name = await ReadStringAsync(cancellationToken); + message.SeqID = await ReadI32Async(cancellationToken); + } + else + { + if (StrictRead) + { + throw new TProtocolException(TProtocolException.BAD_VERSION, + "Missing version in ReadMessageBegin, old client?"); + } + message.Name = await ReadStringBodyAsync(size, cancellationToken); + message.Type = (TMessageType) await ReadByteAsync(cancellationToken); + message.SeqID = await ReadI32Async(cancellationToken); + } + return message; + } + + public override async Task ReadMessageEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task ReadStructBeginAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + + //TODO: no read from internal transport? + return new TStruct(); + } + + public override async Task ReadStructEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task ReadFieldBeginAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + var field = new TField + { + Type = (TType) await ReadByteAsync(cancellationToken) + }; + + if (field.Type != TType.Stop) + { + field.ID = await ReadI16Async(cancellationToken); + } + + return field; + } + + public override async Task ReadFieldEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task ReadMapBeginAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + var map = new TMap + { + KeyType = (TType) await ReadByteAsync(cancellationToken), + ValueType = (TType) await ReadByteAsync(cancellationToken), + Count = await ReadI32Async(cancellationToken) + }; + + return map; + } + + public override async Task ReadMapEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task ReadListBeginAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + var list = new TList + { + ElementType = (TType) await ReadByteAsync(cancellationToken), + Count = await ReadI32Async(cancellationToken) + }; + + return list; + } + + public override async Task ReadListEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task ReadSetBeginAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + var set = new TSet + { + ElementType = (TType) await ReadByteAsync(cancellationToken), + Count = await ReadI32Async(cancellationToken) + }; + + return set; + } + + public override async Task ReadSetEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task ReadBoolAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + return await ReadByteAsync(cancellationToken) == 1; + } + + public override async Task ReadByteAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + var bin = new byte[1]; + await Trans.ReadAllAsync(bin, 0, 1, cancellationToken); //TODO: why readall ? + return (sbyte) bin[0]; + } + + public override async Task ReadI16Async(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + var i16In = new byte[2]; + await Trans.ReadAllAsync(i16In, 0, 2, cancellationToken); + var result = (short) (((i16In[0] & 0xff) << 8) | i16In[1] & 0xff); + return result; + } + + public override async Task ReadI32Async(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + var i32In = new byte[4]; + await Trans.ReadAllAsync(i32In, 0, 4, cancellationToken); + + var result = + ((i32In[0] & 0xff) << 24) | + ((i32In[1] & 0xff) << 16) | + ((i32In[2] & 0xff) << 8) | + i32In[3] & 0xff; + + return result; + } + +#pragma warning disable 675 + + protected internal long CreateReadI64(byte[] buf) + { + var result = + ((long) (buf[0] & 0xff) << 56) | + ((long) (buf[1] & 0xff) << 48) | + ((long) (buf[2] & 0xff) << 40) | + ((long) (buf[3] & 0xff) << 32) | + ((long) (buf[4] & 0xff) << 24) | + ((long) (buf[5] & 0xff) << 16) | + ((long) (buf[6] & 0xff) << 8) | + buf[7] & 0xff; + + return result; + } + +#pragma warning restore 675 + + public override async Task ReadI64Async(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + var i64In = new byte[8]; + await Trans.ReadAllAsync(i64In, 0, 8, cancellationToken); + return CreateReadI64(i64In); + } + + public override async Task ReadDoubleAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + var d = await ReadI64Async(cancellationToken); + return BitConverter.Int64BitsToDouble(d); + } + + public override async Task ReadBinaryAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + var size = await ReadI32Async(cancellationToken); + var buf = new byte[size]; + await Trans.ReadAllAsync(buf, 0, size, cancellationToken); + return buf; + } + + private async Task ReadStringBodyAsync(int size, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + + var buf = new byte[size]; + await Trans.ReadAllAsync(buf, 0, size, cancellationToken); + return Encoding.UTF8.GetString(buf, 0, buf.Length); + } + + public class Factory : ITProtocolFactory + { + protected bool StrictRead; + protected bool StrictWrite; + + public Factory() + : this(false, true) + { + } + + public Factory(bool strictRead, bool strictWrite) + { + StrictRead = strictRead; + StrictWrite = strictWrite; + } + + public TProtocol GetProtocol(TClientTransport trans) + { + return new TBinaryProtocol(trans, StrictRead, StrictWrite); + } + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TCompactProtocol.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TCompactProtocol.cs new file mode 100644 index 0000000..cecdf03 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TCompactProtocol.cs @@ -0,0 +1,922 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Thrift.Protocols.Entities; +using Thrift.Transports; + +namespace Thrift.Protocols +{ + //TODO: implementation of TProtocol + + // ReSharper disable once InconsistentNaming + public class TCompactProtocol : TProtocol + { + private const byte ProtocolId = 0x82; + private const byte Version = 1; + private const byte VersionMask = 0x1f; // 0001 1111 + private const byte TypeMask = 0xE0; // 1110 0000 + private const byte TypeBits = 0x07; // 0000 0111 + private const int TypeShiftAmount = 5; + private static readonly TStruct AnonymousStruct = new TStruct(string.Empty); + private static readonly TField Tstop = new TField(string.Empty, TType.Stop, 0); + + // ReSharper disable once InconsistentNaming + private static readonly byte[] TTypeToCompactType = new byte[16]; + + /// + /// Used to keep track of the last field for the current and previous structs, so we can do the delta stuff. + /// + private readonly Stack _lastField = new Stack(15); + + /// + /// If we encounter a boolean field begin, save the TField here so it can have the value incorporated. + /// + private TField? _booleanField; + + /// + /// If we Read a field header, and it's a boolean field, save the boolean value here so that ReadBool can use it. + /// + private bool? _boolValue; + + private short _lastFieldId; + + public TCompactProtocol(TClientTransport trans) + : base(trans) + { + TTypeToCompactType[(int) TType.Stop] = Types.Stop; + TTypeToCompactType[(int) TType.Bool] = Types.BooleanTrue; + TTypeToCompactType[(int) TType.Byte] = Types.Byte; + TTypeToCompactType[(int) TType.I16] = Types.I16; + TTypeToCompactType[(int) TType.I32] = Types.I32; + TTypeToCompactType[(int) TType.I64] = Types.I64; + TTypeToCompactType[(int) TType.Double] = Types.Double; + TTypeToCompactType[(int) TType.String] = Types.Binary; + TTypeToCompactType[(int) TType.List] = Types.List; + TTypeToCompactType[(int) TType.Set] = Types.Set; + TTypeToCompactType[(int) TType.Map] = Types.Map; + TTypeToCompactType[(int) TType.Struct] = Types.Struct; + } + + public void Reset() + { + _lastField.Clear(); + _lastFieldId = 0; + } + + public override async Task WriteMessageBeginAsync(TMessage message, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + await Trans.WriteAsync(new[] {ProtocolId}, cancellationToken); + await + Trans.WriteAsync( + new[] {(byte) ((Version & VersionMask) | (((uint) message.Type << TypeShiftAmount) & TypeMask))}, + cancellationToken); + + var bufferTuple = CreateWriteVarInt32((uint) message.SeqID); + await Trans.WriteAsync(bufferTuple.Item1, 0, bufferTuple.Item2, cancellationToken); + + await WriteStringAsync(message.Name, cancellationToken); + } + + public override async Task WriteMessageEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + /// + /// Write a struct begin. This doesn't actually put anything on the wire. We + /// use it as an opportunity to put special placeholder markers on the field + /// stack so we can get the field id deltas correct. + /// + public override async Task WriteStructBeginAsync(TStruct @struct, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + + _lastField.Push(_lastFieldId); + _lastFieldId = 0; + } + + public override async Task WriteStructEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + + _lastFieldId = _lastField.Pop(); + } + + private async Task WriteFieldBeginInternalAsync(TField field, byte typeOverride, + CancellationToken cancellationToken) + { + // if there's a exType override, use that. + var typeToWrite = typeOverride == 0xFF ? GetCompactType(field.Type) : typeOverride; + + // check if we can use delta encoding for the field id + if ((field.ID > _lastFieldId) && (field.ID - _lastFieldId <= 15)) + { + var b = (byte) (((field.ID - _lastFieldId) << 4) | typeToWrite); + // Write them together + await Trans.WriteAsync(new[] {b}, cancellationToken); + } + else + { + // Write them separate + await Trans.WriteAsync(new[] {typeToWrite}, cancellationToken); + await WriteI16Async(field.ID, cancellationToken); + } + + _lastFieldId = field.ID; + } + + public override async Task WriteFieldBeginAsync(TField field, CancellationToken cancellationToken) + { + if (field.Type == TType.Bool) + { + _booleanField = field; + } + else + { + await WriteFieldBeginInternalAsync(field, 0xFF, cancellationToken); + } + } + + public override async Task WriteFieldEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task WriteFieldStopAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + await Trans.WriteAsync(new[] {Types.Stop}, cancellationToken); + } + + protected async Task WriteCollectionBeginAsync(TType elemType, int size, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + /* + Abstract method for writing the start of lists and sets. List and sets on + the wire differ only by the exType indicator. + */ + + if (size <= 14) + { + await Trans.WriteAsync(new[] {(byte) ((size << 4) | GetCompactType(elemType))}, cancellationToken); + } + else + { + await Trans.WriteAsync(new[] {(byte) (0xf0 | GetCompactType(elemType))}, cancellationToken); + + var bufferTuple = CreateWriteVarInt32((uint) size); + await Trans.WriteAsync(bufferTuple.Item1, 0, bufferTuple.Item2, cancellationToken); + } + } + + public override async Task WriteListBeginAsync(TList list, CancellationToken cancellationToken) + { + await WriteCollectionBeginAsync(list.ElementType, list.Count, cancellationToken); + } + + public override async Task WriteListEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task WriteSetBeginAsync(TSet set, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + await WriteCollectionBeginAsync(set.ElementType, set.Count, cancellationToken); + } + + public override async Task WriteSetEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task WriteBoolAsync(bool b, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + /* + Write a boolean value. Potentially, this could be a boolean field, in + which case the field header info isn't written yet. If so, decide what the + right exType header is for the value and then Write the field header. + Otherwise, Write a single byte. + */ + + if (_booleanField != null) + { + // we haven't written the field header yet + await + WriteFieldBeginInternalAsync(_booleanField.Value, b ? Types.BooleanTrue : Types.BooleanFalse, + cancellationToken); + _booleanField = null; + } + else + { + // we're not part of a field, so just Write the value. + await Trans.WriteAsync(new[] {b ? Types.BooleanTrue : Types.BooleanFalse}, cancellationToken); + } + } + + public override async Task WriteByteAsync(sbyte b, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + await Trans.WriteAsync(new[] {(byte) b}, cancellationToken); + } + + public override async Task WriteI16Async(short i16, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + var bufferTuple = CreateWriteVarInt32(IntToZigzag(i16)); + await Trans.WriteAsync(bufferTuple.Item1, 0, bufferTuple.Item2, cancellationToken); + } + + protected internal Tuple CreateWriteVarInt32(uint n) + { + // Write an i32 as a varint.Results in 1 - 5 bytes on the wire. + var i32Buf = new byte[5]; + var idx = 0; + + while (true) + { + if ((n & ~0x7F) == 0) + { + i32Buf[idx++] = (byte) n; + break; + } + + i32Buf[idx++] = (byte) ((n & 0x7F) | 0x80); + n >>= 7; + } + + return new Tuple(i32Buf, idx); + } + + public override async Task WriteI32Async(int i32, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + var bufferTuple = CreateWriteVarInt32(IntToZigzag(i32)); + await Trans.WriteAsync(bufferTuple.Item1, 0, bufferTuple.Item2, cancellationToken); + } + + protected internal Tuple CreateWriteVarInt64(ulong n) + { + // Write an i64 as a varint. Results in 1-10 bytes on the wire. + var buf = new byte[10]; + var idx = 0; + + while (true) + { + if ((n & ~(ulong) 0x7FL) == 0) + { + buf[idx++] = (byte) n; + break; + } + buf[idx++] = (byte) ((n & 0x7F) | 0x80); + n >>= 7; + } + + return new Tuple(buf, idx); + } + + public override async Task WriteI64Async(long i64, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + var bufferTuple = CreateWriteVarInt64(LongToZigzag(i64)); + await Trans.WriteAsync(bufferTuple.Item1, 0, bufferTuple.Item2, cancellationToken); + } + + public override async Task WriteDoubleAsync(double d, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + var data = new byte[8]; + FixedLongToBytes(BitConverter.DoubleToInt64Bits(d), data, 0); + await Trans.WriteAsync(data, cancellationToken); + } + + public override async Task WriteStringAsync(string str, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + var bytes = Encoding.UTF8.GetBytes(str); + + var bufferTuple = CreateWriteVarInt32((uint) bytes.Length); + await Trans.WriteAsync(bufferTuple.Item1, 0, bufferTuple.Item2, cancellationToken); + await Trans.WriteAsync(bytes, 0, bytes.Length, cancellationToken); + } + + public override async Task WriteBinaryAsync(byte[] bytes, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + var bufferTuple = CreateWriteVarInt32((uint) bytes.Length); + await Trans.WriteAsync(bufferTuple.Item1, 0, bufferTuple.Item2, cancellationToken); + await Trans.WriteAsync(bytes, 0, bytes.Length, cancellationToken); + } + + public override async Task WriteMapBeginAsync(TMap map, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + if (map.Count == 0) + { + await Trans.WriteAsync(new[] {(byte) 0}, cancellationToken); + } + else + { + var bufferTuple = CreateWriteVarInt32((uint) map.Count); + await Trans.WriteAsync(bufferTuple.Item1, 0, bufferTuple.Item2, cancellationToken); + await + Trans.WriteAsync( + new[] {(byte) ((GetCompactType(map.KeyType) << 4) | GetCompactType(map.ValueType))}, + cancellationToken); + } + } + + public override async Task WriteMapEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task ReadMessageBeginAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + var protocolId = (byte) await ReadByteAsync(cancellationToken); + if (protocolId != ProtocolId) + { + throw new TProtocolException($"Expected protocol id {ProtocolId:X} but got {protocolId:X}"); + } + + var versionAndType = (byte) await ReadByteAsync(cancellationToken); + var version = (byte) (versionAndType & VersionMask); + + if (version != Version) + { + throw new TProtocolException($"Expected version {Version} but got {version}"); + } + + var type = (byte) ((versionAndType >> TypeShiftAmount) & TypeBits); + var seqid = (int) await ReadVarInt32Async(cancellationToken); + var messageName = await ReadStringAsync(cancellationToken); + + return new TMessage(messageName, (TMessageType) type, seqid); + } + + public override async Task ReadMessageEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task ReadStructBeginAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + // some magic is here ) + + _lastField.Push(_lastFieldId); + _lastFieldId = 0; + + return AnonymousStruct; + } + + public override async Task ReadStructEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + + /* + Doesn't actually consume any wire data, just removes the last field for + this struct from the field stack. + */ + + // consume the last field we Read off the wire. + _lastFieldId = _lastField.Pop(); + } + + public override async Task ReadFieldBeginAsync(CancellationToken cancellationToken) + { + // Read a field header off the wire. + var type = (byte) await ReadByteAsync(cancellationToken); + // if it's a stop, then we can return immediately, as the struct is over. + if (type == Types.Stop) + { + return Tstop; + } + + short fieldId; + // mask off the 4 MSB of the exType header. it could contain a field id delta. + var modifier = (short) ((type & 0xf0) >> 4); + if (modifier == 0) + { + fieldId = await ReadI16Async(cancellationToken); + } + else + { + fieldId = (short) (_lastFieldId + modifier); + } + + var field = new TField(string.Empty, GetTType((byte) (type & 0x0f)), fieldId); + // if this happens to be a boolean field, the value is encoded in the exType + if (IsBoolType(type)) + { + _boolValue = (byte) (type & 0x0f) == Types.BooleanTrue; + } + + // push the new field onto the field stack so we can keep the deltas going. + _lastFieldId = field.ID; + return field; + } + + public override async Task ReadFieldEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task ReadMapBeginAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + + /* + Read a map header off the wire. If the size is zero, skip Reading the key + and value exType. This means that 0-length maps will yield TMaps without the + "correct" types. + */ + + var size = (int) await ReadVarInt32Async(cancellationToken); + var keyAndValueType = size == 0 ? (byte) 0 : (byte) await ReadByteAsync(cancellationToken); + return new TMap(GetTType((byte) (keyAndValueType >> 4)), GetTType((byte) (keyAndValueType & 0xf)), size); + } + + public override async Task ReadMapEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task ReadSetBeginAsync(CancellationToken cancellationToken) + { + /* + Read a set header off the wire. If the set size is 0-14, the size will + be packed into the element exType header. If it's a longer set, the 4 MSB + of the element exType header will be 0xF, and a varint will follow with the + true size. + */ + + return new TSet(await ReadListBeginAsync(cancellationToken)); + } + + public override async Task ReadBoolAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + /* + Read a boolean off the wire. If this is a boolean field, the value should + already have been Read during ReadFieldBegin, so we'll just consume the + pre-stored value. Otherwise, Read a byte. + */ + + if (_boolValue != null) + { + var result = _boolValue.Value; + _boolValue = null; + return result; + } + + return await ReadByteAsync(cancellationToken) == Types.BooleanTrue; + } + + public override async Task ReadByteAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + // Read a single byte off the wire. Nothing interesting here. + var buf = new byte[1]; + await Trans.ReadAllAsync(buf, 0, 1, cancellationToken); + return (sbyte) buf[0]; + } + + public override async Task ReadI16Async(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + return (short) ZigzagToInt(await ReadVarInt32Async(cancellationToken)); + } + + public override async Task ReadI32Async(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + return ZigzagToInt(await ReadVarInt32Async(cancellationToken)); + } + + public override async Task ReadI64Async(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + return ZigzagToLong(await ReadVarInt64Async(cancellationToken)); + } + + public override async Task ReadDoubleAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + var longBits = new byte[8]; + await Trans.ReadAllAsync(longBits, 0, 8, cancellationToken); + + return BitConverter.Int64BitsToDouble(BytesToLong(longBits)); + } + + public override async Task ReadStringAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + + // Reads a byte[] (via ReadBinary), and then UTF-8 decodes it. + var length = (int) await ReadVarInt32Async(cancellationToken); + + if (length == 0) + { + return string.Empty; + } + + var buf = new byte[length]; + await Trans.ReadAllAsync(buf, 0, length, cancellationToken); + + return Encoding.UTF8.GetString(buf); + } + + public override async Task ReadBinaryAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + // Read a byte[] from the wire. + var length = (int) await ReadVarInt32Async(cancellationToken); + if (length == 0) + { + return new byte[0]; + } + + var buf = new byte[length]; + await Trans.ReadAllAsync(buf, 0, length, cancellationToken); + return buf; + } + + public override async Task ReadListBeginAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + + /* + Read a list header off the wire. If the list size is 0-14, the size will + be packed into the element exType header. If it's a longer list, the 4 MSB + of the element exType header will be 0xF, and a varint will follow with the + true size. + */ + + var sizeAndType = (byte) await ReadByteAsync(cancellationToken); + var size = (sizeAndType >> 4) & 0x0f; + if (size == 15) + { + size = (int) await ReadVarInt32Async(cancellationToken); + } + + var type = GetTType(sizeAndType); + return new TList(type, size); + } + + public override async Task ReadListEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task ReadSetEndAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + private static byte GetCompactType(TType ttype) + { + // Given a TType value, find the appropriate TCompactProtocol.Types constant. + return TTypeToCompactType[(int) ttype]; + } + + + private async Task ReadVarInt32Async(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + /* + Read an i32 from the wire as a varint. The MSB of each byte is set + if there is another byte to follow. This can Read up to 5 bytes. + */ + + uint result = 0; + var shift = 0; + + while (true) + { + var b = (byte) await ReadByteAsync(cancellationToken); + result |= (uint) (b & 0x7f) << shift; + if ((b & 0x80) != 0x80) + { + break; + } + shift += 7; + } + + return result; + } + + private async Task ReadVarInt64Async(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + /* + Read an i64 from the wire as a proper varint. The MSB of each byte is set + if there is another byte to follow. This can Read up to 10 bytes. + */ + + var shift = 0; + ulong result = 0; + while (true) + { + var b = (byte) await ReadByteAsync(cancellationToken); + result |= (ulong) (b & 0x7f) << shift; + if ((b & 0x80) != 0x80) + { + break; + } + shift += 7; + } + + return result; + } + + private static int ZigzagToInt(uint n) + { + return (int) (n >> 1) ^ -(int) (n & 1); + } + + private static long ZigzagToLong(ulong n) + { + return (long) (n >> 1) ^ -(long) (n & 1); + } + + private static long BytesToLong(byte[] bytes) + { + /* + Note that it's important that the mask bytes are long literals, + otherwise they'll default to ints, and when you shift an int left 56 bits, + you just get a messed up int. + */ + + return + ((bytes[7] & 0xffL) << 56) | + ((bytes[6] & 0xffL) << 48) | + ((bytes[5] & 0xffL) << 40) | + ((bytes[4] & 0xffL) << 32) | + ((bytes[3] & 0xffL) << 24) | + ((bytes[2] & 0xffL) << 16) | + ((bytes[1] & 0xffL) << 8) | + (bytes[0] & 0xffL); + } + + private static bool IsBoolType(byte b) + { + var lowerNibble = b & 0x0f; + return (lowerNibble == Types.BooleanTrue) || (lowerNibble == Types.BooleanFalse); + } + + private static TType GetTType(byte type) + { + // Given a TCompactProtocol.Types constant, convert it to its corresponding TType value. + switch ((byte) (type & 0x0f)) + { + case Types.Stop: + return TType.Stop; + case Types.BooleanFalse: + case Types.BooleanTrue: + return TType.Bool; + case Types.Byte: + return TType.Byte; + case Types.I16: + return TType.I16; + case Types.I32: + return TType.I32; + case Types.I64: + return TType.I64; + case Types.Double: + return TType.Double; + case Types.Binary: + return TType.String; + case Types.List: + return TType.List; + case Types.Set: + return TType.Set; + case Types.Map: + return TType.Map; + case Types.Struct: + return TType.Struct; + default: + throw new TProtocolException($"Don't know what exType: {(byte) (type & 0x0f)}"); + } + } + + private static ulong LongToZigzag(long n) + { + // Convert l into a zigzag long. This allows negative numbers to be represented compactly as a varint + return (ulong) (n << 1) ^ (ulong) (n >> 63); + } + + private static uint IntToZigzag(int n) + { + // Convert n into a zigzag int. This allows negative numbers to be represented compactly as a varint + return (uint) (n << 1) ^ (uint) (n >> 31); + } + + private static void FixedLongToBytes(long n, byte[] buf, int off) + { + // Convert a long into little-endian bytes in buf starting at off and going until off+7. + buf[off + 0] = (byte) (n & 0xff); + buf[off + 1] = (byte) ((n >> 8) & 0xff); + buf[off + 2] = (byte) ((n >> 16) & 0xff); + buf[off + 3] = (byte) ((n >> 24) & 0xff); + buf[off + 4] = (byte) ((n >> 32) & 0xff); + buf[off + 5] = (byte) ((n >> 40) & 0xff); + buf[off + 6] = (byte) ((n >> 48) & 0xff); + buf[off + 7] = (byte) ((n >> 56) & 0xff); + } + + public class Factory : ITProtocolFactory + { + public TProtocol GetProtocol(TClientTransport trans) + { + return new TCompactProtocol(trans); + } + } + + /// + /// All of the on-wire exType codes. + /// + private static class Types + { + public const byte Stop = 0x00; + public const byte BooleanTrue = 0x01; + public const byte BooleanFalse = 0x02; + public const byte Byte = 0x03; + public const byte I16 = 0x04; + public const byte I32 = 0x05; + public const byte I64 = 0x06; + public const byte Double = 0x07; + public const byte Binary = 0x08; + public const byte List = 0x09; + public const byte Set = 0x0A; + public const byte Map = 0x0B; + public const byte Struct = 0x0C; + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TJSONProtocol.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TJSONProtocol.cs new file mode 100644 index 0000000..6d33f02 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TJSONProtocol.cs @@ -0,0 +1,981 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Thrift.Protocols.Entities; +using Thrift.Protocols.Utilities; +using Thrift.Transports; + +namespace Thrift.Protocols +{ + /// + /// JSON protocol implementation for thrift. + /// This is a full-featured protocol supporting Write and Read. + /// Please see the C++ class header for a detailed description of the + /// protocol's wire format. + /// Adapted from the Java version. + /// + // ReSharper disable once InconsistentNaming + public class TJsonProtocol : TProtocol + { + private const long Version = 1; + + // Temporary buffer used by several methods + private readonly byte[] _tempBuffer = new byte[4]; + + // Current context that we are in + protected JSONBaseContext Context; + + // Stack of nested contexts that we may be in + protected Stack ContextStack = new Stack(); + + // Reader that manages a 1-byte buffer + protected LookaheadReader Reader; + + // Default encoding + protected Encoding Utf8Encoding = Encoding.UTF8; + + /// + /// TJsonProtocol Constructor + /// + public TJsonProtocol(TClientTransport trans) + : base(trans) + { + Context = new JSONBaseContext(this); + Reader = new LookaheadReader(this); + } + + /// + /// Push a new JSON context onto the stack. + /// + protected void PushContext(JSONBaseContext c) + { + ContextStack.Push(Context); + Context = c; + } + + /// + /// Pop the last JSON context off the stack + /// + protected void PopContext() + { + Context = ContextStack.Pop(); + } + + /// + /// Read a byte that must match b[0]; otherwise an exception is thrown. + /// Marked protected to avoid synthetic accessor in JSONListContext.Read + /// and JSONPairContext.Read + /// + protected async Task ReadJsonSyntaxCharAsync(byte[] bytes, CancellationToken cancellationToken) + { + var ch = await Reader.ReadAsync(cancellationToken); + if (ch != bytes[0]) + { + throw new TProtocolException(TProtocolException.INVALID_DATA, $"Unexpected character: {(char) ch}"); + } + } + + /// + /// Write the bytes in array buf as a JSON characters, escaping as needed + /// + private async Task WriteJsonStringAsync(byte[] bytes, CancellationToken cancellationToken) + { + await Context.WriteAsync(cancellationToken); + await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken); + + var len = bytes.Length; + for (var i = 0; i < len; i++) + { + if ((bytes[i] & 0x00FF) >= 0x30) + { + if (bytes[i] == TJSONProtocolConstants.Backslash[0]) + { + await Trans.WriteAsync(TJSONProtocolConstants.Backslash, cancellationToken); + await Trans.WriteAsync(TJSONProtocolConstants.Backslash, cancellationToken); + } + else + { + await Trans.WriteAsync(bytes.ToArray(), i, 1, cancellationToken); + } + } + else + { + _tempBuffer[0] = TJSONProtocolConstants.JsonCharTable[bytes[i]]; + if (_tempBuffer[0] == 1) + { + await Trans.WriteAsync(bytes, i, 1, cancellationToken); + } + else if (_tempBuffer[0] > 1) + { + await Trans.WriteAsync(TJSONProtocolConstants.Backslash, cancellationToken); + await Trans.WriteAsync(_tempBuffer, 0, 1, cancellationToken); + } + else + { + await Trans.WriteAsync(TJSONProtocolConstants.EscSequences, cancellationToken); + _tempBuffer[0] = TJSONProtocolHelper.ToHexChar((byte) (bytes[i] >> 4)); + _tempBuffer[1] = TJSONProtocolHelper.ToHexChar(bytes[i]); + await Trans.WriteAsync(_tempBuffer, 0, 2, cancellationToken); + } + } + } + await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken); + } + + /// + /// Write out number as a JSON value. If the context dictates so, it will be + /// wrapped in quotes to output as a JSON string. + /// + private async Task WriteJsonIntegerAsync(long num, CancellationToken cancellationToken) + { + await Context.WriteAsync(cancellationToken); + var str = num.ToString(); + + var escapeNum = Context.EscapeNumbers(); + if (escapeNum) + { + await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken); + } + + var bytes = Utf8Encoding.GetBytes(str); + await Trans.WriteAsync(bytes, cancellationToken); + + if (escapeNum) + { + await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken); + } + } + + /// + /// Write out a double as a JSON value. If it is NaN or infinity or if the + /// context dictates escaping, Write out as JSON string. + /// + private async Task WriteJsonDoubleAsync(double num, CancellationToken cancellationToken) + { + await Context.WriteAsync(cancellationToken); + var str = num.ToString("G17", CultureInfo.InvariantCulture); + var special = false; + + switch (str[0]) + { + case 'N': // NaN + case 'I': // Infinity + special = true; + break; + case '-': + if (str[1] == 'I') + { + // -Infinity + special = true; + } + break; + } + + var escapeNum = special || Context.EscapeNumbers(); + + if (escapeNum) + { + await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken); + } + + await Trans.WriteAsync(Utf8Encoding.GetBytes(str), cancellationToken); + + if (escapeNum) + { + await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken); + } + } + + /// + /// Write out contents of byte array b as a JSON string with base-64 encoded + /// data + /// + private async Task WriteJsonBase64Async(byte[] bytes, CancellationToken cancellationToken) + { + await Context.WriteAsync(cancellationToken); + await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken); + + var len = bytes.Length; + var off = 0; + + while (len >= 3) + { + // Encode 3 bytes at a time + TBase64Helper.Encode(bytes, off, 3, _tempBuffer, 0); + await Trans.WriteAsync(_tempBuffer, 0, 4, cancellationToken); + off += 3; + len -= 3; + } + + if (len > 0) + { + // Encode remainder + TBase64Helper.Encode(bytes, off, len, _tempBuffer, 0); + await Trans.WriteAsync(_tempBuffer, 0, len + 1, cancellationToken); + } + + await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken); + } + + private async Task WriteJsonObjectStartAsync(CancellationToken cancellationToken) + { + await Context.WriteAsync(cancellationToken); + await Trans.WriteAsync(TJSONProtocolConstants.LeftBrace, cancellationToken); + PushContext(new JSONPairContext(this)); + } + + private async Task WriteJsonObjectEndAsync(CancellationToken cancellationToken) + { + PopContext(); + await Trans.WriteAsync(TJSONProtocolConstants.RightBrace, cancellationToken); + } + + private async Task WriteJsonArrayStartAsync(CancellationToken cancellationToken) + { + await Context.WriteAsync(cancellationToken); + await Trans.WriteAsync(TJSONProtocolConstants.LeftBracket, cancellationToken); + PushContext(new JSONListContext(this)); + } + + private async Task WriteJsonArrayEndAsync(CancellationToken cancellationToken) + { + PopContext(); + await Trans.WriteAsync(TJSONProtocolConstants.RightBracket, cancellationToken); + } + + public override async Task WriteMessageBeginAsync(TMessage message, CancellationToken cancellationToken) + { + await WriteJsonArrayStartAsync(cancellationToken); + await WriteJsonIntegerAsync(Version, cancellationToken); + + var b = Utf8Encoding.GetBytes(message.Name); + await WriteJsonStringAsync(b, cancellationToken); + + await WriteJsonIntegerAsync((long) message.Type, cancellationToken); + await WriteJsonIntegerAsync(message.SeqID, cancellationToken); + } + + public override async Task WriteMessageEndAsync(CancellationToken cancellationToken) + { + await WriteJsonArrayEndAsync(cancellationToken); + } + + public override async Task WriteStructBeginAsync(TStruct @struct, CancellationToken cancellationToken) + { + await WriteJsonObjectStartAsync(cancellationToken); + } + + public override async Task WriteStructEndAsync(CancellationToken cancellationToken) + { + await WriteJsonObjectEndAsync(cancellationToken); + } + + public override async Task WriteFieldBeginAsync(TField field, CancellationToken cancellationToken) + { + await WriteJsonIntegerAsync(field.ID, cancellationToken); + await WriteJsonObjectStartAsync(cancellationToken); + await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(field.Type), cancellationToken); + } + + public override async Task WriteFieldEndAsync(CancellationToken cancellationToken) + { + await WriteJsonObjectEndAsync(cancellationToken); + } + + public override async Task WriteFieldStopAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override async Task WriteMapBeginAsync(TMap map, CancellationToken cancellationToken) + { + await WriteJsonArrayStartAsync(cancellationToken); + await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(map.KeyType), cancellationToken); + await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(map.ValueType), cancellationToken); + await WriteJsonIntegerAsync(map.Count, cancellationToken); + await WriteJsonObjectStartAsync(cancellationToken); + } + + public override async Task WriteMapEndAsync(CancellationToken cancellationToken) + { + await WriteJsonObjectEndAsync(cancellationToken); + await WriteJsonArrayEndAsync(cancellationToken); + } + + public override async Task WriteListBeginAsync(TList list, CancellationToken cancellationToken) + { + await WriteJsonArrayStartAsync(cancellationToken); + await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(list.ElementType), cancellationToken); + await WriteJsonIntegerAsync(list.Count, cancellationToken); + } + + public override async Task WriteListEndAsync(CancellationToken cancellationToken) + { + await WriteJsonArrayEndAsync(cancellationToken); + } + + public override async Task WriteSetBeginAsync(TSet set, CancellationToken cancellationToken) + { + await WriteJsonArrayStartAsync(cancellationToken); + await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(set.ElementType), cancellationToken); + await WriteJsonIntegerAsync(set.Count, cancellationToken); + } + + public override async Task WriteSetEndAsync(CancellationToken cancellationToken) + { + await WriteJsonArrayEndAsync(cancellationToken); + } + + public override async Task WriteBoolAsync(bool b, CancellationToken cancellationToken) + { + await WriteJsonIntegerAsync(b ? 1 : 0, cancellationToken); + } + + public override async Task WriteByteAsync(sbyte b, CancellationToken cancellationToken) + { + await WriteJsonIntegerAsync(b, cancellationToken); + } + + public override async Task WriteI16Async(short i16, CancellationToken cancellationToken) + { + await WriteJsonIntegerAsync(i16, cancellationToken); + } + + public override async Task WriteI32Async(int i32, CancellationToken cancellationToken) + { + await WriteJsonIntegerAsync(i32, cancellationToken); + } + + public override async Task WriteI64Async(long i64, CancellationToken cancellationToken) + { + await WriteJsonIntegerAsync(i64, cancellationToken); + } + + public override async Task WriteDoubleAsync(double d, CancellationToken cancellationToken) + { + await WriteJsonDoubleAsync(d, cancellationToken); + } + + public override async Task WriteStringAsync(string s, CancellationToken cancellationToken) + { + var b = Utf8Encoding.GetBytes(s); + await WriteJsonStringAsync(b, cancellationToken); + } + + public override async Task WriteBinaryAsync(byte[] bytes, CancellationToken cancellationToken) + { + await WriteJsonBase64Async(bytes, cancellationToken); + } + + /// + /// Read in a JSON string, unescaping as appropriate.. Skip Reading from the + /// context if skipContext is true. + /// + private async Task ReadJsonStringAsync(bool skipContext, CancellationToken cancellationToken) + { + using (var buffer = new MemoryStream()) + { + var codeunits = new List(); + + + if (!skipContext) + { + await Context.ReadAsync(cancellationToken); + } + + await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Quote, cancellationToken); + + while (true) + { + var ch = await Reader.ReadAsync(cancellationToken); + if (ch == TJSONProtocolConstants.Quote[0]) + { + break; + } + + // escaped? + if (ch != TJSONProtocolConstants.EscSequences[0]) + { + await buffer.WriteAsync(new[] {ch}, 0, 1, cancellationToken); + continue; + } + + // distinguish between \uXXXX and \? + ch = await Reader.ReadAsync(cancellationToken); + if (ch != TJSONProtocolConstants.EscSequences[1]) // control chars like \n + { + var off = Array.IndexOf(TJSONProtocolConstants.EscapeChars, (char) ch); + if (off == -1) + { + throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected control char"); + } + ch = TJSONProtocolConstants.EscapeCharValues[off]; + await buffer.WriteAsync(new[] {ch}, 0, 1, cancellationToken); + continue; + } + + // it's \uXXXX + await Trans.ReadAllAsync(_tempBuffer, 0, 4, cancellationToken); + + var wch = (short) ((TJSONProtocolHelper.ToHexVal(_tempBuffer[0]) << 12) + + (TJSONProtocolHelper.ToHexVal(_tempBuffer[1]) << 8) + + (TJSONProtocolHelper.ToHexVal(_tempBuffer[2]) << 4) + + TJSONProtocolHelper.ToHexVal(_tempBuffer[3])); + + if (char.IsHighSurrogate((char) wch)) + { + if (codeunits.Count > 0) + { + throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected low surrogate char"); + } + codeunits.Add((char) wch); + } + else if (char.IsLowSurrogate((char) wch)) + { + if (codeunits.Count == 0) + { + throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected high surrogate char"); + } + + codeunits.Add((char) wch); + var tmp = Utf8Encoding.GetBytes(codeunits.ToArray()); + await buffer.WriteAsync(tmp, 0, tmp.Length, cancellationToken); + codeunits.Clear(); + } + else + { + var tmp = Utf8Encoding.GetBytes(new[] {(char) wch}); + await buffer.WriteAsync(tmp, 0, tmp.Length, cancellationToken); + } + } + + if (codeunits.Count > 0) + { + throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected low surrogate char"); + } + + return buffer.ToArray(); + } + } + + /// + /// Read in a sequence of characters that are all valid in JSON numbers. Does + /// not do a complete regex check to validate that this is actually a number. + /// + private async Task ReadJsonNumericCharsAsync(CancellationToken cancellationToken) + { + var strbld = new StringBuilder(); + while (true) + { + //TODO: workaround for primitive types with TJsonProtocol, think - how to rewrite into more easy form without exceptions + try + { + var ch = await Reader.PeekAsync(cancellationToken); + if (!TJSONProtocolHelper.IsJsonNumeric(ch)) + { + break; + } + var c = (char)await Reader.ReadAsync(cancellationToken); + strbld.Append(c); + } + catch (TTransportException) + { + break; + } + } + return strbld.ToString(); + } + + /// + /// Read in a JSON number. If the context dictates, Read in enclosing quotes. + /// + private async Task ReadJsonIntegerAsync(CancellationToken cancellationToken) + { + await Context.ReadAsync(cancellationToken); + if (Context.EscapeNumbers()) + { + await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Quote, cancellationToken); + } + + var str = await ReadJsonNumericCharsAsync(cancellationToken); + if (Context.EscapeNumbers()) + { + await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Quote, cancellationToken); + } + + try + { + return long.Parse(str); + } + catch (FormatException) + { + throw new TProtocolException(TProtocolException.INVALID_DATA, "Bad data encounted in numeric data"); + } + } + + /// + /// Read in a JSON double value. Throw if the value is not wrapped in quotes + /// when expected or if wrapped in quotes when not expected. + /// + private async Task ReadJsonDoubleAsync(CancellationToken cancellationToken) + { + await Context.ReadAsync(cancellationToken); + if (await Reader.PeekAsync(cancellationToken) == TJSONProtocolConstants.Quote[0]) + { + var arr = await ReadJsonStringAsync(true, cancellationToken); + var dub = double.Parse(Utf8Encoding.GetString(arr, 0, arr.Length), CultureInfo.InvariantCulture); + + if (!Context.EscapeNumbers() && !double.IsNaN(dub) && !double.IsInfinity(dub)) + { + // Throw exception -- we should not be in a string in this case + throw new TProtocolException(TProtocolException.INVALID_DATA, "Numeric data unexpectedly quoted"); + } + + return dub; + } + + if (Context.EscapeNumbers()) + { + // This will throw - we should have had a quote if escapeNum == true + await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Quote, cancellationToken); + } + + try + { + return double.Parse(await ReadJsonNumericCharsAsync(cancellationToken), CultureInfo.InvariantCulture); + } + catch (FormatException) + { + throw new TProtocolException(TProtocolException.INVALID_DATA, "Bad data encounted in numeric data"); + } + } + + /// + /// Read in a JSON string containing base-64 encoded data and decode it. + /// + private async Task ReadJsonBase64Async(CancellationToken cancellationToken) + { + var b = await ReadJsonStringAsync(false, cancellationToken); + var len = b.Length; + var off = 0; + var size = 0; + + // reduce len to ignore fill bytes + while ((len > 0) && (b[len - 1] == '=')) + { + --len; + } + + // read & decode full byte triplets = 4 source bytes + while (len > 4) + { + // Decode 4 bytes at a time + TBase64Helper.Decode(b, off, 4, b, size); // NB: decoded in place + off += 4; + len -= 4; + size += 3; + } + + // Don't decode if we hit the end or got a single leftover byte (invalid + // base64 but legal for skip of regular string exType) + if (len > 1) + { + // Decode remainder + TBase64Helper.Decode(b, off, len, b, size); // NB: decoded in place + size += len - 1; + } + + // Sadly we must copy the byte[] (any way around this?) + var result = new byte[size]; + Array.Copy(b, 0, result, 0, size); + return result; + } + + private async Task ReadJsonObjectStartAsync(CancellationToken cancellationToken) + { + await Context.ReadAsync(cancellationToken); + await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.LeftBrace, cancellationToken); + PushContext(new JSONPairContext(this)); + } + + private async Task ReadJsonObjectEndAsync(CancellationToken cancellationToken) + { + await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.RightBrace, cancellationToken); + PopContext(); + } + + private async Task ReadJsonArrayStartAsync(CancellationToken cancellationToken) + { + await Context.ReadAsync(cancellationToken); + await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.LeftBracket, cancellationToken); + PushContext(new JSONListContext(this)); + } + + private async Task ReadJsonArrayEndAsync(CancellationToken cancellationToken) + { + await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.RightBracket, cancellationToken); + PopContext(); + } + + public override async Task ReadMessageBeginAsync(CancellationToken cancellationToken) + { + var message = new TMessage(); + await ReadJsonArrayStartAsync(cancellationToken); + if (await ReadJsonIntegerAsync(cancellationToken) != Version) + { + throw new TProtocolException(TProtocolException.BAD_VERSION, "Message contained bad version."); + } + + var buf = await ReadJsonStringAsync(false, cancellationToken); + message.Name = Utf8Encoding.GetString(buf, 0, buf.Length); + message.Type = (TMessageType) await ReadJsonIntegerAsync(cancellationToken); + message.SeqID = (int) await ReadJsonIntegerAsync(cancellationToken); + return message; + } + + public override async Task ReadMessageEndAsync(CancellationToken cancellationToken) + { + await ReadJsonArrayEndAsync(cancellationToken); + } + + public override async Task ReadStructBeginAsync(CancellationToken cancellationToken) + { + await ReadJsonObjectStartAsync(cancellationToken); + return new TStruct(); + } + + public override async Task ReadStructEndAsync(CancellationToken cancellationToken) + { + await ReadJsonObjectEndAsync(cancellationToken); + } + + public override async Task ReadFieldBeginAsync(CancellationToken cancellationToken) + { + var field = new TField(); + var ch = await Reader.PeekAsync(cancellationToken); + if (ch == TJSONProtocolConstants.RightBrace[0]) + { + field.Type = TType.Stop; + } + else + { + field.ID = (short) await ReadJsonIntegerAsync(cancellationToken); + await ReadJsonObjectStartAsync(cancellationToken); + field.Type = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken)); + } + return field; + } + + public override async Task ReadFieldEndAsync(CancellationToken cancellationToken) + { + await ReadJsonObjectEndAsync(cancellationToken); + } + + public override async Task ReadMapBeginAsync(CancellationToken cancellationToken) + { + var map = new TMap(); + await ReadJsonArrayStartAsync(cancellationToken); + map.KeyType = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken)); + map.ValueType = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken)); + map.Count = (int) await ReadJsonIntegerAsync(cancellationToken); + await ReadJsonObjectStartAsync(cancellationToken); + return map; + } + + public override async Task ReadMapEndAsync(CancellationToken cancellationToken) + { + await ReadJsonObjectEndAsync(cancellationToken); + await ReadJsonArrayEndAsync(cancellationToken); + } + + public override async Task ReadListBeginAsync(CancellationToken cancellationToken) + { + var list = new TList(); + await ReadJsonArrayStartAsync(cancellationToken); + list.ElementType = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken)); + list.Count = (int) await ReadJsonIntegerAsync(cancellationToken); + return list; + } + + public override async Task ReadListEndAsync(CancellationToken cancellationToken) + { + await ReadJsonArrayEndAsync(cancellationToken); + } + + public override async Task ReadSetBeginAsync(CancellationToken cancellationToken) + { + var set = new TSet(); + await ReadJsonArrayStartAsync(cancellationToken); + set.ElementType = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken)); + set.Count = (int) await ReadJsonIntegerAsync(cancellationToken); + return set; + } + + public override async Task ReadSetEndAsync(CancellationToken cancellationToken) + { + await ReadJsonArrayEndAsync(cancellationToken); + } + + public override async Task ReadBoolAsync(CancellationToken cancellationToken) + { + return await ReadJsonIntegerAsync(cancellationToken) != 0; + } + + public override async Task ReadByteAsync(CancellationToken cancellationToken) + { + return (sbyte) await ReadJsonIntegerAsync(cancellationToken); + } + + public override async Task ReadI16Async(CancellationToken cancellationToken) + { + return (short) await ReadJsonIntegerAsync(cancellationToken); + } + + public override async Task ReadI32Async(CancellationToken cancellationToken) + { + return (int) await ReadJsonIntegerAsync(cancellationToken); + } + + public override async Task ReadI64Async(CancellationToken cancellationToken) + { + return await ReadJsonIntegerAsync(cancellationToken); + } + + public override async Task ReadDoubleAsync(CancellationToken cancellationToken) + { + return await ReadJsonDoubleAsync(cancellationToken); + } + + public override async Task ReadStringAsync(CancellationToken cancellationToken) + { + var buf = await ReadJsonStringAsync(false, cancellationToken); + return Utf8Encoding.GetString(buf, 0, buf.Length); + } + + public override async Task ReadBinaryAsync(CancellationToken cancellationToken) + { + return await ReadJsonBase64Async(cancellationToken); + } + + /// + /// Factory for JSON protocol objects + /// + public class Factory : ITProtocolFactory + { + public TProtocol GetProtocol(TClientTransport trans) + { + return new TJsonProtocol(trans); + } + } + + /// + /// Base class for tracking JSON contexts that may require + /// inserting/Reading additional JSON syntax characters + /// This base context does nothing. + /// + protected class JSONBaseContext + { + protected TJsonProtocol Proto; + + public JSONBaseContext(TJsonProtocol proto) + { + Proto = proto; + } + + public virtual async Task WriteAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public virtual async Task ReadAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public virtual bool EscapeNumbers() + { + return false; + } + } + + /// + /// Context for JSON lists. Will insert/Read commas before each item except + /// for the first one + /// + protected class JSONListContext : JSONBaseContext + { + private bool _first = true; + + public JSONListContext(TJsonProtocol protocol) + : base(protocol) + { + } + + public override async Task WriteAsync(CancellationToken cancellationToken) + { + if (_first) + { + _first = false; + } + else + { + await Proto.Trans.WriteAsync(TJSONProtocolConstants.Comma, cancellationToken); + } + } + + public override async Task ReadAsync(CancellationToken cancellationToken) + { + if (_first) + { + _first = false; + } + else + { + await Proto.ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Comma, cancellationToken); + } + } + } + + /// + /// Context for JSON records. Will insert/Read colons before the value portion + /// of each record pair, and commas before each key except the first. In + /// addition, will indicate that numbers in the key position need to be + /// escaped in quotes (since JSON keys must be strings). + /// + // ReSharper disable once InconsistentNaming + protected class JSONPairContext : JSONBaseContext + { + private bool _colon = true; + + private bool _first = true; + + public JSONPairContext(TJsonProtocol proto) + : base(proto) + { + } + + public override async Task WriteAsync(CancellationToken cancellationToken) + { + if (_first) + { + _first = false; + _colon = true; + } + else + { + await Proto.Trans.WriteAsync(_colon ? TJSONProtocolConstants.Colon : TJSONProtocolConstants.Comma, cancellationToken); + _colon = !_colon; + } + } + + public override async Task ReadAsync(CancellationToken cancellationToken) + { + if (_first) + { + _first = false; + _colon = true; + } + else + { + await Proto.ReadJsonSyntaxCharAsync(_colon ? TJSONProtocolConstants.Colon : TJSONProtocolConstants.Comma, cancellationToken); + _colon = !_colon; + } + } + + public override bool EscapeNumbers() + { + return _colon; + } + } + + /// + /// Holds up to one byte from the transport + /// + protected class LookaheadReader + { + private readonly byte[] _data = new byte[1]; + + private bool _hasData; + protected TJsonProtocol Proto; + + public LookaheadReader(TJsonProtocol proto) + { + Proto = proto; + } + + /// + /// Return and consume the next byte to be Read, either taking it from the + /// data buffer if present or getting it from the transport otherwise. + /// + public async Task ReadAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + if (_hasData) + { + _hasData = false; + } + else + { + // find more easy way to avoid exception on reading primitive types + await Proto.Trans.ReadAllAsync(_data, 0, 1, cancellationToken); + } + return _data[0]; + } + + /// + /// Return the next byte to be Read without consuming, filling the data + /// buffer if it has not been filled alReady. + /// + public async Task PeekAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + if (!_hasData) + { + // find more easy way to avoid exception on reading primitive types + await Proto.Trans.ReadAllAsync(_data, 0, 1, cancellationToken); + } + _hasData = true; + return _data[0]; + } + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TMultiplexedProtocol.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TMultiplexedProtocol.cs new file mode 100644 index 0000000..367e4e6 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TMultiplexedProtocol.cs @@ -0,0 +1,91 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System.Threading; +using System.Threading.Tasks; +using Thrift.Protocols.Entities; + +namespace Thrift.Protocols +{ + /** + * TMultiplexedProtocol is a protocol-independent concrete decorator that allows a Thrift + * client to communicate with a multiplexing Thrift server, by prepending the service name + * to the function name during function calls. + * + * NOTE: THIS IS NOT TO BE USED BY SERVERS. + * On the server, use TMultiplexedProcessor to handle requests from a multiplexing client. + * + * This example uses a single socket transport to invoke two services: + * + * TSocketClientTransport transport = new TSocketClientTransport("localhost", 9090); + * transport.open(); + * + * TBinaryProtocol protocol = new TBinaryProtocol(transport); + * + * TMultiplexedProtocol mp = new TMultiplexedProtocol(protocol, "Calculator"); + * Calculator.Client service = new Calculator.Client(mp); + * + * TMultiplexedProtocol mp2 = new TMultiplexedProtocol(protocol, "WeatherReport"); + * WeatherReport.Client service2 = new WeatherReport.Client(mp2); + * + * System.out.println(service.add(2,2)); + * System.out.println(service2.getTemperature()); + * + */ + + //TODO: implementation of TProtocol + + // ReSharper disable once InconsistentNaming + public class TMultiplexedProtocol : TProtocolDecorator + { + /** Used to delimit the service name from the function name */ + public const string Separator = ":"; + + private readonly string _serviceName; + + /** + * Wrap the specified protocol, allowing it to be used to communicate with a + * multiplexing server. The serviceName is required as it is + * prepended to the message header so that the multiplexing server can broker + * the function call to the proper service. + * + * Args: + * protocol Your communication protocol of choice, e.g. TBinaryProtocol + * serviceName The service name of the service communicating via this protocol. + */ + + public TMultiplexedProtocol(TProtocol protocol, string serviceName) + : base(protocol) + { + _serviceName = serviceName; + } + + public override async Task WriteMessageBeginAsync(TMessage message, CancellationToken cancellationToken) + { + switch (message.Type) + { + case TMessageType.Call: + case TMessageType.Oneway: + await base.WriteMessageBeginAsync(new TMessage($"{_serviceName}{Separator}{message.Name}", message.Type, message.SeqID), cancellationToken); + break; + default: + await base.WriteMessageBeginAsync(message, cancellationToken); + break; + } + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TProtocol.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TProtocol.cs new file mode 100644 index 0000000..91e009d --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TProtocol.cs @@ -0,0 +1,376 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Thrift.Protocols.Entities; +using Thrift.Transports; + +namespace Thrift.Protocols +{ + // ReSharper disable once InconsistentNaming + public abstract class TProtocol : IDisposable + { + public const int DefaultRecursionDepth = 64; + private bool _isDisposed; + protected int RecursionDepth; + + protected TClientTransport Trans; + + protected TProtocol(TClientTransport trans) + { + Trans = trans; + RecursionLimit = DefaultRecursionDepth; + RecursionDepth = 0; + } + + public TClientTransport Transport => Trans; + + protected int RecursionLimit { get; set; } + + public void Dispose() + { + Dispose(true); + } + + public void IncrementRecursionDepth() + { + if (RecursionDepth < RecursionLimit) + { + ++RecursionDepth; + } + else + { + throw new TProtocolException(TProtocolException.DEPTH_LIMIT, "Depth limit exceeded"); + } + } + + public void DecrementRecursionDepth() + { + --RecursionDepth; + } + + protected virtual void Dispose(bool disposing) + { + if (!_isDisposed) + { + if (disposing) + { + (Trans as IDisposable)?.Dispose(); + } + } + _isDisposed = true; + } + + public virtual async Task WriteMessageBeginAsync(TMessage message) + { + await WriteMessageBeginAsync(message, CancellationToken.None); + } + + public abstract Task WriteMessageBeginAsync(TMessage message, CancellationToken cancellationToken); + + public virtual async Task WriteMessageEndAsync() + { + await WriteMessageEndAsync(CancellationToken.None); + } + + public abstract Task WriteMessageEndAsync(CancellationToken cancellationToken); + + public virtual async Task WriteStructBeginAsync(TStruct @struct) + { + await WriteStructBeginAsync(@struct, CancellationToken.None); + } + + public abstract Task WriteStructBeginAsync(TStruct @struct, CancellationToken cancellationToken); + + public virtual async Task WriteStructEndAsync() + { + await WriteStructEndAsync(CancellationToken.None); + } + + public abstract Task WriteStructEndAsync(CancellationToken cancellationToken); + + public virtual async Task WriteFieldBeginAsync(TField field) + { + await WriteFieldBeginAsync(field, CancellationToken.None); + } + + public abstract Task WriteFieldBeginAsync(TField field, CancellationToken cancellationToken); + + public virtual async Task WriteFieldEndAsync() + { + await WriteFieldEndAsync(CancellationToken.None); + } + + public abstract Task WriteFieldEndAsync(CancellationToken cancellationToken); + + public virtual async Task WriteFieldStopAsync() + { + await WriteFieldStopAsync(CancellationToken.None); + } + + public abstract Task WriteFieldStopAsync(CancellationToken cancellationToken); + + public virtual async Task WriteMapBeginAsync(TMap map) + { + await WriteMapBeginAsync(map, CancellationToken.None); + } + + public abstract Task WriteMapBeginAsync(TMap map, CancellationToken cancellationToken); + + public virtual async Task WriteMapEndAsync() + { + await WriteMapEndAsync(CancellationToken.None); + } + + public abstract Task WriteMapEndAsync(CancellationToken cancellationToken); + + public virtual async Task WriteListBeginAsync(TList list) + { + await WriteListBeginAsync(list, CancellationToken.None); + } + + public abstract Task WriteListBeginAsync(TList list, CancellationToken cancellationToken); + + public virtual async Task WriteListEndAsync() + { + await WriteListEndAsync(CancellationToken.None); + } + + public abstract Task WriteListEndAsync(CancellationToken cancellationToken); + + public virtual async Task WriteSetBeginAsync(TSet set) + { + await WriteSetBeginAsync(set, CancellationToken.None); + } + + public abstract Task WriteSetBeginAsync(TSet set, CancellationToken cancellationToken); + + public virtual async Task WriteSetEndAsync() + { + await WriteSetEndAsync(CancellationToken.None); + } + + public abstract Task WriteSetEndAsync(CancellationToken cancellationToken); + + public virtual async Task WriteBoolAsync(bool b) + { + await WriteBoolAsync(b, CancellationToken.None); + } + + public abstract Task WriteBoolAsync(bool b, CancellationToken cancellationToken); + + public virtual async Task WriteByteAsync(sbyte b) + { + await WriteByteAsync(b, CancellationToken.None); + } + + public abstract Task WriteByteAsync(sbyte b, CancellationToken cancellationToken); + + public virtual async Task WriteI16Async(short i16) + { + await WriteI16Async(i16, CancellationToken.None); + } + + public abstract Task WriteI16Async(short i16, CancellationToken cancellationToken); + + public virtual async Task WriteI32Async(int i32) + { + await WriteI32Async(i32, CancellationToken.None); + } + + public abstract Task WriteI32Async(int i32, CancellationToken cancellationToken); + + public virtual async Task WriteI64Async(long i64) + { + await WriteI64Async(i64, CancellationToken.None); + } + + public abstract Task WriteI64Async(long i64, CancellationToken cancellationToken); + + public virtual async Task WriteDoubleAsync(double d) + { + await WriteDoubleAsync(d, CancellationToken.None); + } + + public abstract Task WriteDoubleAsync(double d, CancellationToken cancellationToken); + + public virtual async Task WriteStringAsync(string s) + { + await WriteStringAsync(s, CancellationToken.None); + } + + public virtual async Task WriteStringAsync(string s, CancellationToken cancellationToken) + { + var bytes = Encoding.UTF8.GetBytes(s); + await WriteBinaryAsync(bytes, cancellationToken); + } + + public virtual async Task WriteBinaryAsync(byte[] bytes) + { + await WriteBinaryAsync(bytes, CancellationToken.None); + } + + public abstract Task WriteBinaryAsync(byte[] bytes, CancellationToken cancellationToken); + + public virtual async Task ReadMessageBeginAsync() + { + return await ReadMessageBeginAsync(CancellationToken.None); + } + + public abstract Task ReadMessageBeginAsync(CancellationToken cancellationToken); + + public virtual async Task ReadMessageEndAsync() + { + await ReadMessageEndAsync(CancellationToken.None); + } + + public abstract Task ReadMessageEndAsync(CancellationToken cancellationToken); + + public virtual async Task ReadStructBeginAsync() + { + return await ReadStructBeginAsync(CancellationToken.None); + } + + public abstract Task ReadStructBeginAsync(CancellationToken cancellationToken); + + public virtual async Task ReadStructEndAsync() + { + await ReadStructEndAsync(CancellationToken.None); + } + + public abstract Task ReadStructEndAsync(CancellationToken cancellationToken); + + public virtual async Task ReadFieldBeginAsync() + { + return await ReadFieldBeginAsync(CancellationToken.None); + } + + public abstract Task ReadFieldBeginAsync(CancellationToken cancellationToken); + + public virtual async Task ReadFieldEndAsync() + { + await ReadFieldEndAsync(CancellationToken.None); + } + + public abstract Task ReadFieldEndAsync(CancellationToken cancellationToken); + + public virtual async Task ReadMapBeginAsync() + { + return await ReadMapBeginAsync(CancellationToken.None); + } + + public abstract Task ReadMapBeginAsync(CancellationToken cancellationToken); + + public virtual async Task ReadMapEndAsync() + { + await ReadMapEndAsync(CancellationToken.None); + } + + public abstract Task ReadMapEndAsync(CancellationToken cancellationToken); + + public virtual async Task ReadListBeginAsync() + { + return await ReadListBeginAsync(CancellationToken.None); + } + + public abstract Task ReadListBeginAsync(CancellationToken cancellationToken); + + public virtual async Task ReadListEndAsync() + { + await ReadListEndAsync(CancellationToken.None); + } + + public abstract Task ReadListEndAsync(CancellationToken cancellationToken); + + public virtual async Task ReadSetBeginAsync() + { + return await ReadSetBeginAsync(CancellationToken.None); + } + + public abstract Task ReadSetBeginAsync(CancellationToken cancellationToken); + + public virtual async Task ReadSetEndAsync() + { + await ReadSetEndAsync(CancellationToken.None); + } + + public abstract Task ReadSetEndAsync(CancellationToken cancellationToken); + + public virtual async Task ReadBoolAsync() + { + return await ReadBoolAsync(CancellationToken.None); + } + + public abstract Task ReadBoolAsync(CancellationToken cancellationToken); + + public virtual async Task ReadByteAsync() + { + return await ReadByteAsync(CancellationToken.None); + } + + public abstract Task ReadByteAsync(CancellationToken cancellationToken); + + public virtual async Task ReadI16Async() + { + return await ReadI16Async(CancellationToken.None); + } + + public abstract Task ReadI16Async(CancellationToken cancellationToken); + + public virtual async Task ReadI32Async() + { + return await ReadI32Async(CancellationToken.None); + } + + public abstract Task ReadI32Async(CancellationToken cancellationToken); + + public virtual async Task ReadI64Async() + { + return await ReadI64Async(CancellationToken.None); + } + + public abstract Task ReadI64Async(CancellationToken cancellationToken); + + public virtual async Task ReadDoubleAsync() + { + return await ReadDoubleAsync(CancellationToken.None); + } + + public abstract Task ReadDoubleAsync(CancellationToken cancellationToken); + + public virtual async Task ReadStringAsync() + { + return await ReadStringAsync(CancellationToken.None); + } + + public virtual async Task ReadStringAsync(CancellationToken cancellationToken) + { + var buf = await ReadBinaryAsync(cancellationToken); + return Encoding.UTF8.GetString(buf, 0, buf.Length); + } + + public virtual async Task ReadBinaryAsync() + { + return await ReadBinaryAsync(CancellationToken.None); + } + + public abstract Task ReadBinaryAsync(CancellationToken cancellationToken); + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TProtocolDecorator.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TProtocolDecorator.cs new file mode 100644 index 0000000..3222754 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TProtocolDecorator.cs @@ -0,0 +1,247 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Threading; +using System.Threading.Tasks; +using Thrift.Protocols.Entities; + +namespace Thrift.Protocols +{ + // ReSharper disable once InconsistentNaming + /// + /// TProtocolDecorator forwards all requests to an enclosed TProtocol instance, + /// providing a way to author concise concrete decorator subclasses.While it has + /// no abstract methods, it is marked abstract as a reminder that by itself, + /// it does not modify the behaviour of the enclosed TProtocol. + /// + public abstract class TProtocolDecorator : TProtocol + { + private readonly TProtocol _wrappedProtocol; + + protected TProtocolDecorator(TProtocol protocol) + : base(protocol.Transport) + { + _wrappedProtocol = protocol ?? throw new ArgumentNullException(nameof(protocol)); + } + + public override async Task WriteMessageBeginAsync(TMessage message, CancellationToken cancellationToken) + { + await _wrappedProtocol.WriteMessageBeginAsync(message, cancellationToken); + } + + public override async Task WriteMessageEndAsync(CancellationToken cancellationToken) + { + await _wrappedProtocol.WriteMessageEndAsync(cancellationToken); + } + + public override async Task WriteStructBeginAsync(TStruct @struct, CancellationToken cancellationToken) + { + await _wrappedProtocol.WriteStructBeginAsync(@struct, cancellationToken); + } + + public override async Task WriteStructEndAsync(CancellationToken cancellationToken) + { + await _wrappedProtocol.WriteStructEndAsync(cancellationToken); + } + + public override async Task WriteFieldBeginAsync(TField field, CancellationToken cancellationToken) + { + await _wrappedProtocol.WriteFieldBeginAsync(field, cancellationToken); + } + + public override async Task WriteFieldEndAsync(CancellationToken cancellationToken) + { + await _wrappedProtocol.WriteFieldEndAsync(cancellationToken); + } + + public override async Task WriteFieldStopAsync(CancellationToken cancellationToken) + { + await _wrappedProtocol.WriteFieldStopAsync(cancellationToken); + } + + public override async Task WriteMapBeginAsync(TMap map, CancellationToken cancellationToken) + { + await _wrappedProtocol.WriteMapBeginAsync(map, cancellationToken); + } + + public override async Task WriteMapEndAsync(CancellationToken cancellationToken) + { + await _wrappedProtocol.WriteMapEndAsync(cancellationToken); + } + + public override async Task WriteListBeginAsync(TList list, CancellationToken cancellationToken) + { + await _wrappedProtocol.WriteListBeginAsync(list, cancellationToken); + } + + public override async Task WriteListEndAsync(CancellationToken cancellationToken) + { + await _wrappedProtocol.WriteListEndAsync(cancellationToken); + } + + public override async Task WriteSetBeginAsync(TSet set, CancellationToken cancellationToken) + { + await _wrappedProtocol.WriteSetBeginAsync(set, cancellationToken); + } + + public override async Task WriteSetEndAsync(CancellationToken cancellationToken) + { + await _wrappedProtocol.WriteSetEndAsync(cancellationToken); + } + + public override async Task WriteBoolAsync(bool b, CancellationToken cancellationToken) + { + await _wrappedProtocol.WriteBoolAsync(b, cancellationToken); + } + + public override async Task WriteByteAsync(sbyte b, CancellationToken cancellationToken) + { + await _wrappedProtocol.WriteByteAsync(b, cancellationToken); + } + + public override async Task WriteI16Async(short i16, CancellationToken cancellationToken) + { + await _wrappedProtocol.WriteI16Async(i16, cancellationToken); + } + + public override async Task WriteI32Async(int i32, CancellationToken cancellationToken) + { + await _wrappedProtocol.WriteI32Async(i32, cancellationToken); + } + + public override async Task WriteI64Async(long i64, CancellationToken cancellationToken) + { + await _wrappedProtocol.WriteI64Async(i64, cancellationToken); + } + + public override async Task WriteDoubleAsync(double d, CancellationToken cancellationToken) + { + await _wrappedProtocol.WriteDoubleAsync(d, cancellationToken); + } + + public override async Task WriteStringAsync(string s, CancellationToken cancellationToken) + { + await _wrappedProtocol.WriteStringAsync(s, cancellationToken); + } + + public override async Task WriteBinaryAsync(byte[] bytes, CancellationToken cancellationToken) + { + await _wrappedProtocol.WriteBinaryAsync(bytes, cancellationToken); + } + + public override async Task ReadMessageBeginAsync(CancellationToken cancellationToken) + { + return await _wrappedProtocol.ReadMessageBeginAsync(cancellationToken); + } + + public override async Task ReadMessageEndAsync(CancellationToken cancellationToken) + { + await _wrappedProtocol.ReadMessageEndAsync(cancellationToken); + } + + public override async Task ReadStructBeginAsync(CancellationToken cancellationToken) + { + return await _wrappedProtocol.ReadStructBeginAsync(cancellationToken); + } + + public override async Task ReadStructEndAsync(CancellationToken cancellationToken) + { + await _wrappedProtocol.ReadStructEndAsync(cancellationToken); + } + + public override async Task ReadFieldBeginAsync(CancellationToken cancellationToken) + { + return await _wrappedProtocol.ReadFieldBeginAsync(cancellationToken); + } + + public override async Task ReadFieldEndAsync(CancellationToken cancellationToken) + { + await _wrappedProtocol.ReadFieldEndAsync(cancellationToken); + } + + public override async Task ReadMapBeginAsync(CancellationToken cancellationToken) + { + return await _wrappedProtocol.ReadMapBeginAsync(cancellationToken); + } + + public override async Task ReadMapEndAsync(CancellationToken cancellationToken) + { + await _wrappedProtocol.ReadMapEndAsync(cancellationToken); + } + + public override async Task ReadListBeginAsync(CancellationToken cancellationToken) + { + return await _wrappedProtocol.ReadListBeginAsync(cancellationToken); + } + + public override async Task ReadListEndAsync(CancellationToken cancellationToken) + { + await _wrappedProtocol.ReadListEndAsync(cancellationToken); + } + + public override async Task ReadSetBeginAsync(CancellationToken cancellationToken) + { + return await _wrappedProtocol.ReadSetBeginAsync(cancellationToken); + } + + public override async Task ReadSetEndAsync(CancellationToken cancellationToken) + { + await _wrappedProtocol.ReadSetEndAsync(cancellationToken); + } + + public override async Task ReadBoolAsync(CancellationToken cancellationToken) + { + return await _wrappedProtocol.ReadBoolAsync(cancellationToken); + } + + public override async Task ReadByteAsync(CancellationToken cancellationToken) + { + return await _wrappedProtocol.ReadByteAsync(cancellationToken); + } + + public override async Task ReadI16Async(CancellationToken cancellationToken) + { + return await _wrappedProtocol.ReadI16Async(cancellationToken); + } + + public override async Task ReadI32Async(CancellationToken cancellationToken) + { + return await _wrappedProtocol.ReadI32Async(cancellationToken); + } + + public override async Task ReadI64Async(CancellationToken cancellationToken) + { + return await _wrappedProtocol.ReadI64Async(cancellationToken); + } + + public override async Task ReadDoubleAsync(CancellationToken cancellationToken) + { + return await _wrappedProtocol.ReadDoubleAsync(cancellationToken); + } + + public override async Task ReadStringAsync(CancellationToken cancellationToken) + { + return await _wrappedProtocol.ReadStringAsync(cancellationToken); + } + + public override async Task ReadBinaryAsync(CancellationToken cancellationToken) + { + return await _wrappedProtocol.ReadBinaryAsync(cancellationToken); + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TProtocolException.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TProtocolException.cs new file mode 100644 index 0000000..8c67c3b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/TProtocolException.cs @@ -0,0 +1,59 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +// ReSharper disable InconsistentNaming +namespace Thrift.Protocols +{ + public class TProtocolException : TException + { + // do not rename public constants - they used in generated files + public const int UNKNOWN = 0; + public const int INVALID_DATA = 1; + public const int NEGATIVE_SIZE = 2; + public const int SIZE_LIMIT = 3; + public const int BAD_VERSION = 4; + public const int NOT_IMPLEMENTED = 5; + public const int DEPTH_LIMIT = 6; + + protected int Type = UNKNOWN; + + public TProtocolException() + { + } + + public TProtocolException(int type) + { + Type = type; + } + + public TProtocolException(int type, string message) + : base(message) + { + Type = type; + } + + public TProtocolException(string message) + : base(message) + { + } + + public int GetExceptionType() + { + return Type; + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Utilities/TBase64Helper.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Utilities/TBase64Helper.cs new file mode 100644 index 0000000..7eff5e1 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Utilities/TBase64Helper.cs @@ -0,0 +1,101 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; + +namespace Thrift.Protocols.Utilities +{ + // ReSharper disable once InconsistentNaming + internal static class TBase64Helper + { + //TODO: Constants + //TODO: Check for args + //TODO: Unitests + + internal const string EncodeTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + + private static readonly int[] DecodeTable = + { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, + -1, 0, 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, -1, -1, -1, -1, -1, + -1, 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, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + }; + + internal static void Encode(byte[] src, int srcOff, int len, byte[] dst, int dstOff) + { + if (src == null) + { + throw new ArgumentNullException(nameof(src)); + } + + dst[dstOff] = (byte) EncodeTable[(src[srcOff] >> 2) & 0x3F]; + + if (len == 3) + { + dst[dstOff + 1] = (byte) EncodeTable[((src[srcOff] << 4) & 0x30) | ((src[srcOff + 1] >> 4) & 0x0F)]; + dst[dstOff + 2] = (byte) EncodeTable[((src[srcOff + 1] << 2) & 0x3C) | ((src[srcOff + 2] >> 6) & 0x03)]; + dst[dstOff + 3] = (byte) EncodeTable[src[srcOff + 2] & 0x3F]; + } + else if (len == 2) + { + dst[dstOff + 1] = (byte) EncodeTable[((src[srcOff] << 4) & 0x30) | ((src[srcOff + 1] >> 4) & 0x0F)]; + dst[dstOff + 2] = (byte) EncodeTable[(src[srcOff + 1] << 2) & 0x3C]; + } + else + { + // len == 1 + dst[dstOff + 1] = (byte) EncodeTable[(src[srcOff] << 4) & 0x30]; + } + } + + internal static void Decode(byte[] src, int srcOff, int len, byte[] dst, int dstOff) + { + if (src == null) + { + throw new ArgumentNullException(nameof(src)); + } + + dst[dstOff] = (byte) ((DecodeTable[src[srcOff] & 0x0FF] << 2) | (DecodeTable[src[srcOff + 1] & 0x0FF] >> 4)); + + if (len > 2) + { + dst[dstOff + 1] = + (byte) + (((DecodeTable[src[srcOff + 1] & 0x0FF] << 4) & 0xF0) | (DecodeTable[src[srcOff + 2] & 0x0FF] >> 2)); + if (len > 3) + { + dst[dstOff + 2] = + (byte) + (((DecodeTable[src[srcOff + 2] & 0x0FF] << 6) & 0xC0) | DecodeTable[src[srcOff + 3] & 0x0FF]); + } + } + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Utilities/TBase64Utils.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Utilities/TBase64Utils.cs new file mode 100644 index 0000000..15fd45c --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Utilities/TBase64Utils.cs @@ -0,0 +1,101 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; + +namespace Thrift.Protocols.Utilities +{ + // ReSharper disable once InconsistentNaming + internal static class TBase64Utils + { + //TODO: Constants + //TODO: Check for args + //TODO: Unitests + + internal const string EncodeTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + + private static readonly int[] DecodeTable = + { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, + -1, 0, 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, -1, -1, -1, -1, -1, + -1, 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, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + }; + + internal static void Encode(byte[] src, int srcOff, int len, byte[] dst, int dstOff) + { + if (src == null) + { + throw new ArgumentNullException(nameof(src)); + } + + dst[dstOff] = (byte) EncodeTable[(src[srcOff] >> 2) & 0x3F]; + + if (len == 3) + { + dst[dstOff + 1] = (byte) EncodeTable[((src[srcOff] << 4) & 0x30) | ((src[srcOff + 1] >> 4) & 0x0F)]; + dst[dstOff + 2] = (byte) EncodeTable[((src[srcOff + 1] << 2) & 0x3C) | ((src[srcOff + 2] >> 6) & 0x03)]; + dst[dstOff + 3] = (byte) EncodeTable[src[srcOff + 2] & 0x3F]; + } + else if (len == 2) + { + dst[dstOff + 1] = (byte) EncodeTable[((src[srcOff] << 4) & 0x30) | ((src[srcOff + 1] >> 4) & 0x0F)]; + dst[dstOff + 2] = (byte) EncodeTable[(src[srcOff + 1] << 2) & 0x3C]; + } + else + { + // len == 1 + dst[dstOff + 1] = (byte) EncodeTable[(src[srcOff] << 4) & 0x30]; + } + } + + internal static void Decode(byte[] src, int srcOff, int len, byte[] dst, int dstOff) + { + if (src == null) + { + throw new ArgumentNullException(nameof(src)); + } + + dst[dstOff] = (byte) ((DecodeTable[src[srcOff] & 0x0FF] << 2) | (DecodeTable[src[srcOff + 1] & 0x0FF] >> 4)); + + if (len > 2) + { + dst[dstOff + 1] = + (byte) + (((DecodeTable[src[srcOff + 1] & 0x0FF] << 4) & 0xF0) | (DecodeTable[src[srcOff + 2] & 0x0FF] >> 2)); + if (len > 3) + { + dst[dstOff + 2] = + (byte) + (((DecodeTable[src[srcOff + 2] & 0x0FF] << 6) & 0xC0) | DecodeTable[src[srcOff + 3] & 0x0FF]); + } + } + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Utilities/TJsonProtocolConstants.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Utilities/TJsonProtocolConstants.cs new file mode 100644 index 0000000..93eff78 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Utilities/TJsonProtocolConstants.cs @@ -0,0 +1,61 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +namespace Thrift.Protocols.Utilities +{ + // ReSharper disable once InconsistentNaming + public static class TJSONProtocolConstants + { + //TODO Check for performance for reusing ImmutableArray from System.Collections.Immutable (https://blogs.msdn.microsoft.com/dotnet/2013/06/24/please-welcome-immutablearrayt/) + // can be possible to get better performance and also better GC + + public static readonly byte[] Comma = {(byte) ','}; + public static readonly byte[] Colon = {(byte) ':'}; + public static readonly byte[] LeftBrace = {(byte) '{'}; + public static readonly byte[] RightBrace = {(byte) '}'}; + public static readonly byte[] LeftBracket = {(byte) '['}; + public static readonly byte[] RightBracket = {(byte) ']'}; + public static readonly byte[] Quote = {(byte) '"'}; + public static readonly byte[] Backslash = {(byte) '\\'}; + + public static readonly byte[] JsonCharTable = + { + 0, 0, 0, 0, 0, 0, 0, 0, (byte) 'b', (byte) 't', (byte) 'n', 0, (byte) 'f', (byte) 'r', 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, (byte) '"', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 + }; + + public static readonly char[] EscapeChars = "\"\\/bfnrt".ToCharArray(); + public static readonly byte[] EscapeCharValues = {(byte) '"', (byte) '\\', (byte) '/', (byte) '\b', (byte) '\f', (byte) '\n', (byte) '\r', (byte) '\t'}; + public static readonly byte[] EscSequences = {(byte) '\\', (byte) 'u', (byte) '0', (byte) '0'}; + + public static class TypeNames + { + public static readonly byte[] NameBool = { (byte)'t', (byte)'f' }; + public static readonly byte[] NameByte = { (byte)'i', (byte)'8' }; + public static readonly byte[] NameI16 = { (byte)'i', (byte)'1', (byte)'6' }; + public static readonly byte[] NameI32 = { (byte)'i', (byte)'3', (byte)'2' }; + public static readonly byte[] NameI64 = { (byte)'i', (byte)'6', (byte)'4' }; + public static readonly byte[] NameDouble = { (byte)'d', (byte)'b', (byte)'l' }; + public static readonly byte[] NameStruct = { (byte)'r', (byte)'e', (byte)'c' }; + public static readonly byte[] NameString = { (byte)'s', (byte)'t', (byte)'r' }; + public static readonly byte[] NameMap = { (byte)'m', (byte)'a', (byte)'p' }; + public static readonly byte[] NameList = { (byte)'l', (byte)'s', (byte)'t' }; + public static readonly byte[] NameSet = { (byte)'s', (byte)'e', (byte)'t' }; + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Utilities/TJsonProtocolHelper.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Utilities/TJsonProtocolHelper.cs new file mode 100644 index 0000000..adc26a9 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Utilities/TJsonProtocolHelper.cs @@ -0,0 +1,176 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using Thrift.Protocols.Entities; + +namespace Thrift.Protocols.Utilities +{ + // ReSharper disable once InconsistentNaming + public static class TJSONProtocolHelper + { + public static byte[] GetTypeNameForTypeId(TType typeId) + { + switch (typeId) + { + case TType.Bool: + return TJSONProtocolConstants.TypeNames.NameBool; + case TType.Byte: + return TJSONProtocolConstants.TypeNames.NameByte; + case TType.I16: + return TJSONProtocolConstants.TypeNames.NameI16; + case TType.I32: + return TJSONProtocolConstants.TypeNames.NameI32; + case TType.I64: + return TJSONProtocolConstants.TypeNames.NameI64; + case TType.Double: + return TJSONProtocolConstants.TypeNames.NameDouble; + case TType.String: + return TJSONProtocolConstants.TypeNames.NameString; + case TType.Struct: + return TJSONProtocolConstants.TypeNames.NameStruct; + case TType.Map: + return TJSONProtocolConstants.TypeNames.NameMap; + case TType.Set: + return TJSONProtocolConstants.TypeNames.NameSet; + case TType.List: + return TJSONProtocolConstants.TypeNames.NameList; + default: + throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, "Unrecognized exType"); + } + } + + public static TType GetTypeIdForTypeName(byte[] name) + { + var result = TType.Stop; + if (name.Length > 1) + { + switch (name[0]) + { + case (byte) 'd': + result = TType.Double; + break; + case (byte) 'i': + switch (name[1]) + { + case (byte) '8': + result = TType.Byte; + break; + case (byte) '1': + result = TType.I16; + break; + case (byte) '3': + result = TType.I32; + break; + case (byte) '6': + result = TType.I64; + break; + } + break; + case (byte) 'l': + result = TType.List; + break; + case (byte) 'm': + result = TType.Map; + break; + case (byte) 'r': + result = TType.Struct; + break; + case (byte) 's': + if (name[1] == (byte) 't') + { + result = TType.String; + } + else if (name[1] == (byte) 'e') + { + result = TType.Set; + } + break; + case (byte) 't': + result = TType.Bool; + break; + } + } + if (result == TType.Stop) + { + throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, "Unrecognized exType"); + } + return result; + } + + /// + /// Return true if the given byte could be a valid part of a JSON number. + /// + public static bool IsJsonNumeric(byte b) + { + switch (b) + { + case (byte)'+': + case (byte)'-': + case (byte)'.': + case (byte)'0': + case (byte)'1': + case (byte)'2': + case (byte)'3': + case (byte)'4': + case (byte)'5': + case (byte)'6': + case (byte)'7': + case (byte)'8': + case (byte)'9': + case (byte)'E': + case (byte)'e': + return true; + default: + return false; + } + } + + /// + /// Convert a byte containing a hex char ('0'-'9' or 'a'-'f') into its + /// corresponding hex value + /// + public static byte ToHexVal(byte ch) + { + if (ch >= '0' && ch <= '9') + { + return (byte)((char)ch - '0'); + } + + if (ch >= 'a' && ch <= 'f') + { + ch += 10; + return (byte)((char)ch - 'a'); + } + + throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected hex character"); + } + + /// + /// Convert a byte containing a hex value to its corresponding hex character + /// + public static byte ToHexChar(byte val) + { + val &= 0x0F; + if (val < 10) + { + return (byte)((char)val + '0'); + } + val -= 10; + return (byte)((char)val + 'a'); + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Utilities/TProtocolUtil.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Utilities/TProtocolUtil.cs new file mode 100644 index 0000000..50b0385 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Protocols/Utilities/TProtocolUtil.cs @@ -0,0 +1,110 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System.Threading; +using System.Threading.Tasks; +using Thrift.Protocols.Entities; + +namespace Thrift.Protocols.Utilities +{ + // ReSharper disable once InconsistentNaming + public static class TProtocolUtil + { + public static async Task SkipAsync(TProtocol protocol, TType type, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + + protocol.IncrementRecursionDepth(); + try + { + switch (type) + { + case TType.Bool: + await protocol.ReadBoolAsync(cancellationToken); + break; + case TType.Byte: + await protocol.ReadByteAsync(cancellationToken); + break; + case TType.I16: + await protocol.ReadI16Async(cancellationToken); + break; + case TType.I32: + await protocol.ReadI32Async(cancellationToken); + break; + case TType.I64: + await protocol.ReadI64Async(cancellationToken); + break; + case TType.Double: + await protocol.ReadDoubleAsync(cancellationToken); + break; + case TType.String: + // Don't try to decode the string, just skip it. + await protocol.ReadBinaryAsync(cancellationToken); + break; + case TType.Struct: + await protocol.ReadStructBeginAsync(cancellationToken); + while (true) + { + var field = await protocol.ReadFieldBeginAsync(cancellationToken); + if (field.Type == TType.Stop) + { + break; + } + await SkipAsync(protocol, field.Type, cancellationToken); + await protocol.ReadFieldEndAsync(cancellationToken); + } + await protocol.ReadStructEndAsync(cancellationToken); + break; + case TType.Map: + var map = await protocol.ReadMapBeginAsync(cancellationToken); + for (var i = 0; i < map.Count; i++) + { + await SkipAsync(protocol, map.KeyType, cancellationToken); + await SkipAsync(protocol, map.ValueType, cancellationToken); + } + await protocol.ReadMapEndAsync(cancellationToken); + break; + case TType.Set: + var set = await protocol.ReadSetBeginAsync(cancellationToken); + for (var i = 0; i < set.Count; i++) + { + await SkipAsync(protocol, set.ElementType, cancellationToken); + } + await protocol.ReadSetEndAsync(cancellationToken); + break; + case TType.List: + var list = await protocol.ReadListBeginAsync(cancellationToken); + for (var i = 0; i < list.Count; i++) + { + await SkipAsync(protocol, list.ElementType, cancellationToken); + } + await protocol.ReadListEndAsync(cancellationToken); + break; + default: + throw new TProtocolException(TProtocolException.INVALID_DATA, "Unknown data type " + type.ToString("d")); + } + } + finally + { + protocol.DecrementRecursionDepth(); + } + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Server/AsyncBaseServer.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Server/AsyncBaseServer.cs new file mode 100644 index 0000000..325c39c --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Server/AsyncBaseServer.cs @@ -0,0 +1,183 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Thrift.Protocols; +using Thrift.Transports; + +namespace Thrift.Server +{ + //TODO: unhandled exceptions, etc. + + // ReSharper disable once InconsistentNaming + public class AsyncBaseServer : TBaseServer + { + private readonly int _clientWaitingDelay; + private volatile Task _serverTask; + + public AsyncBaseServer(ITAsyncProcessor processor, TServerTransport serverTransport, + ITProtocolFactory inputProtocolFactory, ITProtocolFactory outputProtocolFactory, + ILoggerFactory loggerFactory, int clientWaitingDelay = 10) + : this(new SingletonTProcessorFactory(processor), serverTransport, + new TTransportFactory(), new TTransportFactory(), + inputProtocolFactory, outputProtocolFactory, + loggerFactory.CreateLogger(nameof(AsyncBaseServer)), clientWaitingDelay) + { + } + + public AsyncBaseServer(ITProcessorFactory itProcessorFactory, TServerTransport serverTransport, + TTransportFactory inputTransportFactory, TTransportFactory outputTransportFactory, + ITProtocolFactory inputProtocolFactory, ITProtocolFactory outputProtocolFactory, + ILogger logger, int clientWaitingDelay = 10) + : base(itProcessorFactory, serverTransport, inputTransportFactory, outputTransportFactory, + inputProtocolFactory, outputProtocolFactory, logger) + { + _clientWaitingDelay = clientWaitingDelay; + } + + public override async Task ServeAsync(CancellationToken cancellationToken) + { + try + { + // cancelation token + _serverTask = Task.Factory.StartNew(() => StartListening(cancellationToken), TaskCreationOptions.LongRunning); + await _serverTask; + } + catch (Exception ex) + { + Logger.LogError(ex.ToString()); + } + } + + private async Task StartListening(CancellationToken cancellationToken) + { + ServerTransport.Listen(); + + Logger.LogTrace("Started listening at server"); + + if (ServerEventHandler != null) + { + await ServerEventHandler.PreServeAsync(cancellationToken); + } + + while (!cancellationToken.IsCancellationRequested) + { + if (ServerTransport.IsClientPending()) + { + Logger.LogTrace("Waiting for client connection"); + + try + { + var client = await ServerTransport.AcceptAsync(cancellationToken); + await Task.Factory.StartNew(() => Execute(client, cancellationToken), cancellationToken); + } + catch (TTransportException ttx) + { + Logger.LogTrace($"Transport exception: {ttx}"); + + if (ttx.Type != TTransportException.ExceptionType.Interrupted) + { + Logger.LogError(ttx.ToString()); + } + } + } + else + { + try + { + await Task.Delay(TimeSpan.FromMilliseconds(_clientWaitingDelay), cancellationToken); + } + catch(TaskCanceledException) { } + } + } + + ServerTransport.Close(); + + Logger.LogTrace("Completed listening at server"); + } + + public override void Stop() + { + } + + private async Task Execute(TClientTransport client, CancellationToken cancellationToken) + { + Logger.LogTrace("Started client request processing"); + + var processor = ItProcessorFactory.GetAsyncProcessor(client, this); + + TClientTransport inputTransport = null; + TClientTransport outputTransport = null; + TProtocol inputProtocol = null; + TProtocol outputProtocol = null; + object connectionContext = null; + + try + { + inputTransport = InputTransportFactory.GetTransport(client); + outputTransport = OutputTransportFactory.GetTransport(client); + + inputProtocol = InputProtocolFactory.GetProtocol(inputTransport); + outputProtocol = OutputProtocolFactory.GetProtocol(outputTransport); + + if (ServerEventHandler != null) + { + connectionContext = await ServerEventHandler.CreateContextAsync(inputProtocol, outputProtocol, cancellationToken); + } + + while (!cancellationToken.IsCancellationRequested) + { + if (!await inputTransport.PeekAsync(cancellationToken)) + { + break; + } + + if (ServerEventHandler != null) + { + await ServerEventHandler.ProcessContextAsync(connectionContext, inputTransport, cancellationToken); + } + + if (!await processor.ProcessAsync(inputProtocol, outputProtocol, cancellationToken)) + { + break; + } + } + } + catch (TTransportException ttx) + { + Logger.LogTrace($"Transport exception: {ttx}"); + } + catch (Exception x) + { + Logger.LogError($"Error: {x}"); + } + + if (ServerEventHandler != null) + { + await ServerEventHandler.DeleteContextAsync(connectionContext, inputProtocol, outputProtocol, cancellationToken); + } + + inputTransport?.Close(); + outputTransport?.Close(); + + Logger.LogTrace("Completed client request processing"); + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Server/TBaseServer.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Server/TBaseServer.cs new file mode 100644 index 0000000..741dd5c --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Server/TBaseServer.cs @@ -0,0 +1,79 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Thrift.Protocols; +using Thrift.Transports; + +namespace Thrift.Server +{ + // ReSharper disable once InconsistentNaming + public abstract class TBaseServer + { + protected readonly ILogger Logger; + protected ITProtocolFactory InputProtocolFactory; + protected TTransportFactory InputTransportFactory; + protected ITProcessorFactory ItProcessorFactory; + protected ITProtocolFactory OutputProtocolFactory; + protected TTransportFactory OutputTransportFactory; + + protected TServerEventHandler ServerEventHandler; + protected TServerTransport ServerTransport; + + protected TBaseServer(ITProcessorFactory itProcessorFactory, TServerTransport serverTransport, + TTransportFactory inputTransportFactory, TTransportFactory outputTransportFactory, + ITProtocolFactory inputProtocolFactory, ITProtocolFactory outputProtocolFactory, + ILogger logger) + { + ItProcessorFactory = itProcessorFactory ?? throw new ArgumentNullException(nameof(itProcessorFactory)); + ServerTransport = serverTransport; + InputTransportFactory = inputTransportFactory ?? throw new ArgumentNullException(nameof(inputTransportFactory)); + OutputTransportFactory = outputTransportFactory ?? throw new ArgumentNullException(nameof(outputTransportFactory)); + InputProtocolFactory = inputProtocolFactory ?? throw new ArgumentNullException(nameof(inputProtocolFactory)); + OutputProtocolFactory = outputProtocolFactory ?? throw new ArgumentNullException(nameof(outputProtocolFactory)); + Logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public void SetEventHandler(TServerEventHandler seh) + { + ServerEventHandler = seh; + } + + public TServerEventHandler GetEventHandler() + { + return ServerEventHandler; + } + + public abstract void Stop(); + + public virtual void Start() + { + // do nothing + } + + public virtual async Task ServeAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Server/TServerEventHandler.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Server/TServerEventHandler.cs new file mode 100644 index 0000000..733bb4b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Server/TServerEventHandler.cs @@ -0,0 +1,54 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System.Threading; +using System.Threading.Tasks; +using Thrift.Protocols; +using Thrift.Transports; + +namespace Thrift.Server +{ + //TODO: replacement by event? + + /// + /// Interface implemented by server users to handle events from the server + /// + // ReSharper disable once InconsistentNaming + public interface TServerEventHandler + { + /// + /// Called before the server begins */ + /// + Task PreServeAsync(CancellationToken cancellationToken); + + /// + /// Called when a new client has connected and is about to being processing */ + /// + Task CreateContextAsync(TProtocol input, TProtocol output, CancellationToken cancellationToken); + + /// + /// Called when a client has finished request-handling to delete server context */ + /// + Task DeleteContextAsync(object serverContext, TProtocol input, TProtocol output, + CancellationToken cancellationToken); + + /// + /// Called when a client is about to call the processor */ + /// + Task ProcessContextAsync(object serverContext, TClientTransport transport, CancellationToken cancellationToken); + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/SingletonTProcessorFactory.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/SingletonTProcessorFactory.cs new file mode 100644 index 0000000..c351233 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/SingletonTProcessorFactory.cs @@ -0,0 +1,38 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using Thrift.Server; +using Thrift.Transports; + +namespace Thrift +{ + // ReSharper disable once InconsistentNaming + public class SingletonTProcessorFactory : ITProcessorFactory + { + private readonly ITAsyncProcessor _tAsyncProcessor; + + public SingletonTProcessorFactory(ITAsyncProcessor tAsyncProcessor) + { + _tAsyncProcessor = tAsyncProcessor; + } + + public ITAsyncProcessor GetAsyncProcessor(TClientTransport trans, TBaseServer baseServer = null) + { + return _tAsyncProcessor; + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/TApplicationException.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/TApplicationException.cs new file mode 100644 index 0000000..9ec145a --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/TApplicationException.cs @@ -0,0 +1,150 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System.Threading; +using System.Threading.Tasks; +using Thrift.Protocols; +using Thrift.Protocols.Entities; +using Thrift.Protocols.Utilities; + +namespace Thrift +{ + // ReSharper disable once InconsistentNaming + public class TApplicationException : TException + { + public enum ExceptionType + { + Unknown, + UnknownMethod, + InvalidMessageType, + WrongMethodName, + BadSequenceId, + MissingResult, + InternalError, + ProtocolError, + InvalidTransform, + InvalidProtocol, + UnsupportedClientType + } + + private const int MessageTypeFieldId = 1; + private const int ExTypeFieldId = 2; + + protected ExceptionType Type; + + public TApplicationException() + { + } + + public TApplicationException(ExceptionType type) + { + Type = type; + } + + public TApplicationException(ExceptionType type, string message) + : base(message) + { + Type = type; + } + + public static async Task ReadAsync(TProtocol inputProtocol, CancellationToken cancellationToken) + { + string message = null; + var type = ExceptionType.Unknown; + + await inputProtocol.ReadStructBeginAsync(cancellationToken); + while (true) + { + var field = await inputProtocol.ReadFieldBeginAsync(cancellationToken); + if (field.Type == TType.Stop) + { + break; + } + + switch (field.ID) + { + case MessageTypeFieldId: + if (field.Type == TType.String) + { + message = await inputProtocol.ReadStringAsync(cancellationToken); + } + else + { + await TProtocolUtil.SkipAsync(inputProtocol, field.Type, cancellationToken); + } + break; + case ExTypeFieldId: + if (field.Type == TType.I32) + { + type = (ExceptionType) await inputProtocol.ReadI32Async(cancellationToken); + } + else + { + await TProtocolUtil.SkipAsync(inputProtocol, field.Type, cancellationToken); + } + break; + default: + await TProtocolUtil.SkipAsync(inputProtocol, field.Type, cancellationToken); + break; + } + + await inputProtocol.ReadFieldEndAsync(cancellationToken); + } + + await inputProtocol.ReadStructEndAsync(cancellationToken); + + return new TApplicationException(type, message); + } + + public async Task WriteAsync(TProtocol outputProtocol, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + + const string messageTypeFieldName = "message"; + const string exTypeFieldName = "exType"; + const string structApplicationExceptionName = "TApplicationException"; + + var struc = new TStruct(structApplicationExceptionName); + var field = new TField(); + + await outputProtocol.WriteStructBeginAsync(struc, cancellationToken); + + if (!string.IsNullOrEmpty(Message)) + { + field.Name = messageTypeFieldName; + field.Type = TType.String; + field.ID = MessageTypeFieldId; + await outputProtocol.WriteFieldBeginAsync(field, cancellationToken); + await outputProtocol.WriteStringAsync(Message, cancellationToken); + await outputProtocol.WriteFieldEndAsync(cancellationToken); + } + + field.Name = exTypeFieldName; + field.Type = TType.I32; + field.ID = ExTypeFieldId; + + await outputProtocol.WriteFieldBeginAsync(field, cancellationToken); + await outputProtocol.WriteI32Async((int) Type, cancellationToken); + await outputProtocol.WriteFieldEndAsync(cancellationToken); + await outputProtocol.WriteFieldStopAsync(cancellationToken); + await outputProtocol.WriteStructEndAsync(cancellationToken); + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/TBaseClient.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/TBaseClient.cs new file mode 100644 index 0000000..e019251 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/TBaseClient.cs @@ -0,0 +1,91 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Threading; +using System.Threading.Tasks; +using Thrift.Protocols; + +namespace Thrift +{ + // ReSharper disable once InconsistentNaming + /// + /// TBaseClient. + /// Base client for generated clients. + /// Do not change this class without checking generated code (namings, etc.) + /// + public abstract class TBaseClient + { + private readonly TProtocol _inputProtocol; + private readonly TProtocol _outputProtocol; + private bool _isDisposed; + private int _seqId; + public readonly Guid ClientId = Guid.NewGuid(); + + protected TBaseClient(TProtocol inputProtocol, TProtocol outputProtocol) + { + _inputProtocol = inputProtocol ?? throw new ArgumentNullException(nameof(inputProtocol)); + _outputProtocol = outputProtocol ?? throw new ArgumentNullException(nameof(outputProtocol)); + } + + public TProtocol InputProtocol => _inputProtocol; + + public TProtocol OutputProtocol => _outputProtocol; + + public int SeqId + { + get { return ++_seqId; } + } + + public virtual async Task OpenTransportAsync() + { + await OpenTransportAsync(CancellationToken.None); + } + + public virtual async Task OpenTransportAsync(CancellationToken cancellationToken) + { + if (!_inputProtocol.Transport.IsOpen) + { + await _inputProtocol.Transport.OpenAsync(cancellationToken); + } + + if (!_inputProtocol.Transport.IsOpen) + { + await _outputProtocol.Transport.OpenAsync(cancellationToken); + } + } + + public void Dispose() + { + Dispose(true); + } + + protected virtual void Dispose(bool disposing) + { + if (!_isDisposed) + { + if (disposing) + { + _inputProtocol?.Dispose(); + _outputProtocol?.Dispose(); + } + } + + _isDisposed = true; + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/TException.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/TException.cs new file mode 100644 index 0000000..6aa588d --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/TException.cs @@ -0,0 +1,34 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; + +namespace Thrift +{ + // ReSharper disable once InconsistentNaming + public class TException : Exception + { + public TException() + { + } + + public TException(string message) + : base(message) + { + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/TMultiplexedProcessor.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/TMultiplexedProcessor.cs new file mode 100644 index 0000000..ad0e749 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/TMultiplexedProcessor.cs @@ -0,0 +1,143 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Thrift.Protocols; +using Thrift.Protocols.Entities; + +namespace Thrift +{ + // ReSharper disable once InconsistentNaming + public class TMultiplexedProcessor : ITAsyncProcessor + { + //TODO: Localization + + private readonly Dictionary _serviceProcessorMap = + new Dictionary(); + + public async Task ProcessAsync(TProtocol iprot, TProtocol oprot) + { + return await ProcessAsync(iprot, oprot, CancellationToken.None); + } + + public async Task ProcessAsync(TProtocol iprot, TProtocol oprot, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + try + { + var message = await iprot.ReadMessageBeginAsync(cancellationToken); + + if ((message.Type != TMessageType.Call) && (message.Type != TMessageType.Oneway)) + { + await FailAsync(oprot, message, TApplicationException.ExceptionType.InvalidMessageType, + "Message exType CALL or ONEWAY expected", cancellationToken); + return false; + } + + // Extract the service name + var index = message.Name.IndexOf(TMultiplexedProtocol.Separator, StringComparison.Ordinal); + if (index < 0) + { + await FailAsync(oprot, message, TApplicationException.ExceptionType.InvalidProtocol, + $"Service name not found in message name: {message.Name}. Did you forget to use a TMultiplexProtocol in your client?", + cancellationToken); + return false; + } + + // Create a new TMessage, something that can be consumed by any TProtocol + var serviceName = message.Name.Substring(0, index); + ITAsyncProcessor actualProcessor; + if (!_serviceProcessorMap.TryGetValue(serviceName, out actualProcessor)) + { + await FailAsync(oprot, message, TApplicationException.ExceptionType.InternalError, + $"Service name not found: {serviceName}. Did you forget to call RegisterProcessor()?", + cancellationToken); + return false; + } + + // Create a new TMessage, removing the service name + var newMessage = new TMessage( + message.Name.Substring(serviceName.Length + TMultiplexedProtocol.Separator.Length), + message.Type, + message.SeqID); + + // Dispatch processing to the stored processor + return + await + actualProcessor.ProcessAsync(new StoredMessageProtocol(iprot, newMessage), oprot, + cancellationToken); + } + catch (IOException) + { + return false; // similar to all other processors + } + } + + public void RegisterProcessor(string serviceName, ITAsyncProcessor processor) + { + if (_serviceProcessorMap.ContainsKey(serviceName)) + { + throw new InvalidOperationException( + $"Processor map already contains processor with name: '{serviceName}'"); + } + + _serviceProcessorMap.Add(serviceName, processor); + } + + private async Task FailAsync(TProtocol oprot, TMessage message, TApplicationException.ExceptionType extype, + string etxt, CancellationToken cancellationToken) + { + var appex = new TApplicationException(extype, etxt); + + var newMessage = new TMessage(message.Name, TMessageType.Exception, message.SeqID); + + await oprot.WriteMessageBeginAsync(newMessage, cancellationToken); + await appex.WriteAsync(oprot, cancellationToken); + await oprot.WriteMessageEndAsync(cancellationToken); + await oprot.Transport.FlushAsync(cancellationToken); + } + + private class StoredMessageProtocol : TProtocolDecorator + { + readonly TMessage _msgBegin; + + public StoredMessageProtocol(TProtocol protocol, TMessage messageBegin) + : base(protocol) + { + _msgBegin = messageBegin; + } + + public override async Task ReadMessageBeginAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + return _msgBegin; + } + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Thrift.csproj b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Thrift.csproj new file mode 100644 index 0000000..e806fed --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Thrift.csproj @@ -0,0 +1,31 @@ + + + + netstandard2.0 + Thrift + Thrift + true + true + false + false + false + false + false + false + false + false + + + + + + + + + + + + + + + diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TBufferedClientTransport.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TBufferedClientTransport.cs new file mode 100644 index 0000000..761f1ac --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TBufferedClientTransport.cs @@ -0,0 +1,206 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace Thrift.Transports.Client +{ + // ReSharper disable once InconsistentNaming + public class TBufferedClientTransport : TClientTransport + { + private readonly int _bufSize; + private readonly MemoryStream _inputBuffer = new MemoryStream(0); + private readonly MemoryStream _outputBuffer = new MemoryStream(0); + private readonly TClientTransport _transport; + private bool _isDisposed; + + //TODO: should support only specified input transport? + public TBufferedClientTransport(TClientTransport transport, int bufSize = 1024) + { + if (bufSize <= 0) + { + throw new ArgumentOutOfRangeException(nameof(bufSize), "Buffer size must be a positive number."); + } + + _transport = transport ?? throw new ArgumentNullException(nameof(transport)); + _bufSize = bufSize; + } + + public TClientTransport UnderlyingTransport + { + get + { + CheckNotDisposed(); + + return _transport; + } + } + + public override bool IsOpen => !_isDisposed && _transport.IsOpen; + + public override async Task OpenAsync(CancellationToken cancellationToken) + { + CheckNotDisposed(); + + await _transport.OpenAsync(cancellationToken); + } + + public override void Close() + { + CheckNotDisposed(); + + _transport.Close(); + } + + public override async Task ReadAsync(byte[] buffer, int offset, int length, + CancellationToken cancellationToken) + { + //TODO: investigate how it should work correctly + CheckNotDisposed(); + + ValidateBufferArgs(buffer, offset, length); + + if (!IsOpen) + { + throw new TTransportException(TTransportException.ExceptionType.NotOpen); + } + + if (_inputBuffer.Capacity < _bufSize) + { + _inputBuffer.Capacity = _bufSize; + } + + var got = await _inputBuffer.ReadAsync(buffer, offset, length, cancellationToken); + if (got > 0) + { + return got; + } + + _inputBuffer.Seek(0, SeekOrigin.Begin); + _inputBuffer.SetLength(_inputBuffer.Capacity); + + ArraySegment bufSegment; + _inputBuffer.TryGetBuffer(out bufSegment); + + // investigate + var filled = await _transport.ReadAsync(bufSegment.Array, 0, (int) _inputBuffer.Length, cancellationToken); + _inputBuffer.SetLength(filled); + + if (filled == 0) + { + return 0; + } + + return await ReadAsync(buffer, offset, length, cancellationToken); + } + + public override async Task WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) + { + CheckNotDisposed(); + + ValidateBufferArgs(buffer, offset, length); + + if (!IsOpen) + { + throw new TTransportException(TTransportException.ExceptionType.NotOpen); + } + + // Relative offset from "off" argument + var writtenCount = 0; + if (_outputBuffer.Length > 0) + { + var capa = (int) (_outputBuffer.Capacity - _outputBuffer.Length); + var writeSize = capa <= length ? capa : length; + await _outputBuffer.WriteAsync(buffer, offset, writeSize, cancellationToken); + + writtenCount += writeSize; + if (writeSize == capa) + { + //ArraySegment bufSegment; + //_outputBuffer.TryGetBuffer(out bufSegment); + var data = _outputBuffer.ToArray(); + //await _transport.WriteAsync(bufSegment.Array, cancellationToken); + await _transport.WriteAsync(data, cancellationToken); + _outputBuffer.SetLength(0); + } + } + + while (length - writtenCount >= _bufSize) + { + await _transport.WriteAsync(buffer, offset + writtenCount, _bufSize, cancellationToken); + writtenCount += _bufSize; + } + + var remain = length - writtenCount; + if (remain > 0) + { + if (_outputBuffer.Capacity < _bufSize) + { + _outputBuffer.Capacity = _bufSize; + } + await _outputBuffer.WriteAsync(buffer, offset + writtenCount, remain, cancellationToken); + } + } + + public override async Task FlushAsync(CancellationToken cancellationToken) + { + CheckNotDisposed(); + + if (!IsOpen) + { + throw new TTransportException(TTransportException.ExceptionType.NotOpen); + } + + if (_outputBuffer.Length > 0) + { + //ArraySegment bufSegment; + var data = _outputBuffer.ToArray(); // TryGetBuffer(out bufSegment); + + await _transport.WriteAsync(data /*bufSegment.Array*/, cancellationToken); + _outputBuffer.SetLength(0); + } + + await _transport.FlushAsync(cancellationToken); + } + + private void CheckNotDisposed() + { + if (_isDisposed) + { + throw new ObjectDisposedException(nameof(_transport)); + } + } + + // IDisposable + protected override void Dispose(bool disposing) + { + if (!_isDisposed) + { + if (disposing) + { + _inputBuffer?.Dispose(); + _outputBuffer?.Dispose(); + _transport?.Dispose(); + } + } + _isDisposed = true; + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TFramedClientTransport.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TFramedClientTransport.cs new file mode 100644 index 0000000..d11bb95 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TFramedClientTransport.cs @@ -0,0 +1,201 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace Thrift.Transports.Client +{ + //TODO: check for correct implementation + + // ReSharper disable once InconsistentNaming + public class TFramedClientTransport : TClientTransport + { + private const int HeaderSize = 4; + private readonly byte[] _headerBuf = new byte[HeaderSize]; + private readonly MemoryStream _readBuffer = new MemoryStream(1024); + private readonly TClientTransport _transport; + private readonly MemoryStream _writeBuffer = new MemoryStream(1024); + + private bool _isDisposed; + + public TFramedClientTransport(TClientTransport transport) + { + _transport = transport ?? throw new ArgumentNullException(nameof(transport)); + + InitWriteBuffer(); + } + + public override bool IsOpen => !_isDisposed && _transport.IsOpen; + + public override async Task OpenAsync(CancellationToken cancellationToken) + { + CheckNotDisposed(); + + await _transport.OpenAsync(cancellationToken); + } + + public override void Close() + { + CheckNotDisposed(); + + _transport.Close(); + } + + public override async Task ReadAsync(byte[] buffer, int offset, int length, + CancellationToken cancellationToken) + { + CheckNotDisposed(); + + ValidateBufferArgs(buffer, offset, length); + + if (!IsOpen) + { + throw new TTransportException(TTransportException.ExceptionType.NotOpen); + } + + var got = await _readBuffer.ReadAsync(buffer, offset, length, cancellationToken); + if (got > 0) + { + return got; + } + + // Read another frame of data + await ReadFrameAsync(cancellationToken); + + return await _readBuffer.ReadAsync(buffer, offset, length, cancellationToken); + } + + private async Task ReadFrameAsync(CancellationToken cancellationToken) + { + await _transport.ReadAllAsync(_headerBuf, 0, HeaderSize, cancellationToken); + + var size = DecodeFrameSize(_headerBuf); + + _readBuffer.SetLength(size); + _readBuffer.Seek(0, SeekOrigin.Begin); + + ArraySegment bufSegment; + _readBuffer.TryGetBuffer(out bufSegment); + + var buff = bufSegment.Array; + + await _transport.ReadAllAsync(buff, 0, size, cancellationToken); + } + + public override async Task WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) + { + CheckNotDisposed(); + + ValidateBufferArgs(buffer, offset, length); + + if (!IsOpen) + { + throw new TTransportException(TTransportException.ExceptionType.NotOpen); + } + + if (_writeBuffer.Length + length > int.MaxValue) + { + await FlushAsync(cancellationToken); + } + + await _writeBuffer.WriteAsync(buffer, offset, length, cancellationToken); + } + + public override async Task FlushAsync(CancellationToken cancellationToken) + { + CheckNotDisposed(); + + if (!IsOpen) + { + throw new TTransportException(TTransportException.ExceptionType.NotOpen); + } + + //ArraySegment bufSegment; + //_writeBuffer.TryGetBuffer(out bufSegment); + //var buf = bufSegment.Array; + var buf = _writeBuffer.ToArray(); + + //var len = (int)_writeBuffer.Length; + var dataLen = (int) _writeBuffer.Length - HeaderSize; + if (dataLen < 0) + { + throw new InvalidOperationException(); // logic error actually + } + + // Inject message header into the reserved buffer space + EncodeFrameSize(dataLen, buf); + + // Send the entire message at once + await _transport.WriteAsync(buf, cancellationToken); + + InitWriteBuffer(); + + await _transport.FlushAsync(cancellationToken); + } + + private void InitWriteBuffer() + { + // Reserve space for message header to be put right before sending it out + _writeBuffer.SetLength(HeaderSize); + _writeBuffer.Seek(0, SeekOrigin.End); + } + + private static void EncodeFrameSize(int frameSize, byte[] buf) + { + buf[0] = (byte) (0xff & (frameSize >> 24)); + buf[1] = (byte) (0xff & (frameSize >> 16)); + buf[2] = (byte) (0xff & (frameSize >> 8)); + buf[3] = (byte) (0xff & (frameSize)); + } + + private static int DecodeFrameSize(byte[] buf) + { + return + ((buf[0] & 0xff) << 24) | + ((buf[1] & 0xff) << 16) | + ((buf[2] & 0xff) << 8) | + (buf[3] & 0xff); + } + + + private void CheckNotDisposed() + { + if (_isDisposed) + { + throw new ObjectDisposedException("TFramedClientTransport"); + } + } + + // IDisposable + protected override void Dispose(bool disposing) + { + if (!_isDisposed) + { + if (disposing) + { + _readBuffer?.Dispose(); + _writeBuffer?.Dispose(); + _transport?.Dispose(); + } + } + _isDisposed = true; + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/THttpClientTransport.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/THttpClientTransport.cs new file mode 100644 index 0000000..6067141 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/THttpClientTransport.cs @@ -0,0 +1,226 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Security.Cryptography.X509Certificates; +using System.Threading; +using System.Threading.Tasks; + +namespace Thrift.Transports.Client +{ + // ReSharper disable once InconsistentNaming + public class THttpClientTransport : TClientTransport + { + private readonly X509Certificate[] _certificates; + private readonly Uri _uri; + + // Timeouts in milliseconds + private int _connectTimeout = 30000; + private HttpClient _httpClient; + private Stream _inputStream; + + private bool _isDisposed; + private MemoryStream _outputStream = new MemoryStream(); + + public THttpClientTransport(Uri u, IDictionary customHeaders) + : this(u, Enumerable.Empty(), customHeaders) + { + } + + public THttpClientTransport(Uri u, IEnumerable certificates, + IDictionary customHeaders) + { + _uri = u; + _certificates = (certificates ?? Enumerable.Empty()).ToArray(); + CustomHeaders = customHeaders; + + // due to current bug with performance of Dispose in netcore https://github.com/dotnet/corefx/issues/8809 + // this can be switched to default way (create client->use->dispose per flush) later + _httpClient = CreateClient(); + } + + public IDictionary CustomHeaders { get; } + + public int ConnectTimeout + { + set { _connectTimeout = value; } + } + + public override bool IsOpen => true; + + public override async Task OpenAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override void Close() + { + if (_inputStream != null) + { + _inputStream.Dispose(); + _inputStream = null; + } + + if (_outputStream != null) + { + _outputStream.Dispose(); + _outputStream = null; + } + + if (_httpClient != null) + { + _httpClient.Dispose(); + _httpClient = null; + } + } + + public override async Task ReadAsync(byte[] buffer, int offset, int length, + CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + if (_inputStream == null) + { + throw new TTransportException(TTransportException.ExceptionType.NotOpen, "No request has been sent"); + } + + try + { + var ret = await _inputStream.ReadAsync(buffer, offset, length, cancellationToken); + + if (ret == -1) + { + throw new TTransportException(TTransportException.ExceptionType.EndOfFile, "No more data available"); + } + + return ret; + } + catch (IOException iox) + { + throw new TTransportException(TTransportException.ExceptionType.Unknown, iox.ToString()); + } + } + + public override async Task WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + + await _outputStream.WriteAsync(buffer, offset, length, cancellationToken); + } + + private HttpClient CreateClient() + { + var handler = new HttpClientHandler(); + handler.ClientCertificates.AddRange(_certificates); + + var httpClient = new HttpClient(handler); + + if (_connectTimeout > 0) + { + httpClient.Timeout = TimeSpan.FromSeconds(_connectTimeout); + } + + httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-thrift")); + httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("THttpClientTransport", "0.12.0")); + + if (CustomHeaders != null) + { + foreach (var item in CustomHeaders) + { + httpClient.DefaultRequestHeaders.Add(item.Key, item.Value); + } + } + + return httpClient; + } + + public override async Task FlushAsync(CancellationToken cancellationToken) + { + try + { + try + { + if (_outputStream.CanSeek) + { + _outputStream.Seek(0, SeekOrigin.Begin); + } + + using (var outStream = new StreamContent(_outputStream)) + { + var msg = await _httpClient.PostAsync(_uri, outStream, cancellationToken); + + msg.EnsureSuccessStatusCode(); + + if (_inputStream != null) + { + _inputStream.Dispose(); + _inputStream = null; + } + + _inputStream = await msg.Content.ReadAsStreamAsync(); + if (_inputStream.CanSeek) + { + _inputStream.Seek(0, SeekOrigin.Begin); + } + } + } + catch (IOException iox) + { + throw new TTransportException(TTransportException.ExceptionType.Unknown, iox.ToString()); + } + catch (HttpRequestException wx) + { + throw new TTransportException(TTransportException.ExceptionType.Unknown, + "Couldn't connect to server: " + wx); + } + } + finally + { + _outputStream = new MemoryStream(); + } + } + + // IDisposable + protected override void Dispose(bool disposing) + { + if (!_isDisposed) + { + if (disposing) + { + _inputStream?.Dispose(); + _outputStream?.Dispose(); + _httpClient?.Dispose(); + } + } + _isDisposed = true; + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TMemoryBufferClientTransport.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TMemoryBufferClientTransport.cs new file mode 100644 index 0000000..46a55a6 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TMemoryBufferClientTransport.cs @@ -0,0 +1,97 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace Thrift.Transports.Client +{ + // ReSharper disable once InconsistentNaming + public class TMemoryBufferClientTransport : TClientTransport + { + private readonly MemoryStream _byteStream; + private bool _isDisposed; + + public TMemoryBufferClientTransport() + { + _byteStream = new MemoryStream(); + } + + public TMemoryBufferClientTransport(byte[] buf) + { + _byteStream = new MemoryStream(buf); + } + + public override bool IsOpen => true; + + public override async Task OpenAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override void Close() + { + /** do nothing **/ + } + + public override async Task ReadAsync(byte[] buffer, int offset, int length, + CancellationToken cancellationToken) + { + return await _byteStream.ReadAsync(buffer, offset, length, cancellationToken); + } + + public override async Task WriteAsync(byte[] buffer, CancellationToken cancellationToken) + { + await _byteStream.WriteAsync(buffer, 0, buffer.Length, cancellationToken); + } + + public override async Task WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) + { + await _byteStream.WriteAsync(buffer, offset, length, cancellationToken); + } + + public override async Task FlushAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public byte[] GetBuffer() + { + return _byteStream.ToArray(); + } + + // IDisposable + protected override void Dispose(bool disposing) + { + if (!_isDisposed) + { + if (disposing) + { + _byteStream?.Dispose(); + } + } + _isDisposed = true; + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TNamedPipeClientTransport.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TNamedPipeClientTransport.cs new file mode 100644 index 0000000..f5e4baf --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TNamedPipeClientTransport.cs @@ -0,0 +1,95 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System.IO.Pipes; +using System.Threading; +using System.Threading.Tasks; + +namespace Thrift.Transports.Client +{ + // ReSharper disable once InconsistentNaming + public class TNamedPipeClientTransport : TClientTransport + { + private NamedPipeClientStream _client; + + public TNamedPipeClientTransport(string pipe) : this(".", pipe) + { + } + + public TNamedPipeClientTransport(string server, string pipe) + { + var serverName = string.IsNullOrWhiteSpace(server) ? server : "."; + + _client = new NamedPipeClientStream(serverName, pipe, PipeDirection.InOut, PipeOptions.None); + } + + public override bool IsOpen => _client != null && _client.IsConnected; + + public override async Task OpenAsync(CancellationToken cancellationToken) + { + if (IsOpen) + { + throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen); + } + + await _client.ConnectAsync(cancellationToken); + } + + public override void Close() + { + if (_client != null) + { + _client.Dispose(); + _client = null; + } + } + + public override async Task ReadAsync(byte[] buffer, int offset, int length, + CancellationToken cancellationToken) + { + if (_client == null) + { + throw new TTransportException(TTransportException.ExceptionType.NotOpen); + } + + return await _client.ReadAsync(buffer, offset, length, cancellationToken); + } + + public override async Task WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) + { + if (_client == null) + { + throw new TTransportException(TTransportException.ExceptionType.NotOpen); + } + + await _client.WriteAsync(buffer, offset, length, cancellationToken); + } + + public override async Task FlushAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + protected override void Dispose(bool disposing) + { + _client.Dispose(); + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TSocketClientTransport.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TSocketClientTransport.cs new file mode 100644 index 0000000..e769d14 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TSocketClientTransport.cs @@ -0,0 +1,139 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Net; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; + +namespace Thrift.Transports.Client +{ + // ReSharper disable once InconsistentNaming + public class TSocketClientTransport : TStreamClientTransport + { + private bool _isDisposed; + + public TSocketClientTransport(TcpClient client) + { + TcpClient = client ?? throw new ArgumentNullException(nameof(client)); + + if (IsOpen) + { + InputStream = client.GetStream(); + OutputStream = client.GetStream(); + } + } + + public TSocketClientTransport(IPAddress host, int port) + : this(host, port, 0) + { + } + + public TSocketClientTransport(IPAddress host, int port, int timeout) + { + Host = host; + Port = port; + + TcpClient = new TcpClient(); + TcpClient.ReceiveTimeout = TcpClient.SendTimeout = timeout; + TcpClient.Client.NoDelay = true; + } + + public TcpClient TcpClient { get; private set; } + public IPAddress Host { get; } + public int Port { get; } + + public int Timeout + { + set + { + if (TcpClient != null) + { + TcpClient.ReceiveTimeout = TcpClient.SendTimeout = value; + } + } + } + + public override bool IsOpen + { + get + { + if (TcpClient == null) + { + return false; + } + + return TcpClient.Connected; + } + } + + public override async Task OpenAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + + if (IsOpen) + { + throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen, "Socket already connected"); + } + + if (Port <= 0) + { + throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open without port"); + } + + if (TcpClient == null) + { + throw new InvalidOperationException("Invalid or not initialized tcp client"); + } + + await TcpClient.ConnectAsync(Host, Port); + + InputStream = TcpClient.GetStream(); + OutputStream = TcpClient.GetStream(); + } + + public override void Close() + { + base.Close(); + + if (TcpClient != null) + { + TcpClient.Dispose(); + TcpClient = null; + } + } + + // IDisposable + protected override void Dispose(bool disposing) + { + if (!_isDisposed) + { + if (disposing) + { + TcpClient?.Dispose(); + + base.Dispose(disposing); + } + } + _isDisposed = true; + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TStreamClientTransport.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TStreamClientTransport.cs new file mode 100644 index 0000000..f7164f0 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TStreamClientTransport.cs @@ -0,0 +1,110 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace Thrift.Transports.Client +{ + // ReSharper disable once InconsistentNaming + public class TStreamClientTransport : TClientTransport + { + private bool _isDisposed; + + protected TStreamClientTransport() + { + } + + public TStreamClientTransport(Stream inputStream, Stream outputStream) + { + InputStream = inputStream; + OutputStream = outputStream; + } + + protected Stream OutputStream { get; set; } + + protected Stream InputStream { get; set; } + + public override bool IsOpen => true; + + public override async Task OpenAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override void Close() + { + if (InputStream != null) + { + InputStream.Dispose(); + InputStream = null; + } + + if (OutputStream != null) + { + OutputStream.Dispose(); + OutputStream = null; + } + } + + public override async Task ReadAsync(byte[] buffer, int offset, int length, + CancellationToken cancellationToken) + { + if (InputStream == null) + { + throw new TTransportException(TTransportException.ExceptionType.NotOpen, + "Cannot read from null inputstream"); + } + + return await InputStream.ReadAsync(buffer, offset, length, cancellationToken); + } + + public override async Task WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) + { + if (OutputStream == null) + { + throw new TTransportException(TTransportException.ExceptionType.NotOpen, + "Cannot read from null inputstream"); + } + + await OutputStream.WriteAsync(buffer, offset, length, cancellationToken); + } + + public override async Task FlushAsync(CancellationToken cancellationToken) + { + await OutputStream.FlushAsync(cancellationToken); + } + + // IDisposable + protected override void Dispose(bool disposing) + { + if (!_isDisposed) + { + if (disposing) + { + InputStream?.Dispose(); + OutputStream?.Dispose(); + } + } + _isDisposed = true; + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TTlsSocketClientTransport.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TTlsSocketClientTransport.cs new file mode 100644 index 0000000..c8be4ed --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Client/TTlsSocketClientTransport.cs @@ -0,0 +1,237 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Net; +using System.Net.Security; +using System.Net.Sockets; +using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; +using System.Threading; +using System.Threading.Tasks; + +namespace Thrift.Transports.Client +{ + //TODO: check for correct work + + // ReSharper disable once InconsistentNaming + public class TTlsSocketClientTransport : TStreamClientTransport + { + private readonly X509Certificate2 _certificate; + private readonly RemoteCertificateValidationCallback _certValidator; + private readonly IPAddress _host; + private readonly bool _isServer; + private readonly LocalCertificateSelectionCallback _localCertificateSelectionCallback; + private readonly int _port; + private readonly SslProtocols _sslProtocols; + private TcpClient _client; + private SslStream _secureStream; + private int _timeout; + + public TTlsSocketClientTransport(TcpClient client, X509Certificate2 certificate, bool isServer = false, + RemoteCertificateValidationCallback certValidator = null, + LocalCertificateSelectionCallback localCertificateSelectionCallback = null, + SslProtocols sslProtocols = SslProtocols.Tls12) + { + _client = client; + _certificate = certificate; + _certValidator = certValidator; + _localCertificateSelectionCallback = localCertificateSelectionCallback; + _sslProtocols = sslProtocols; + _isServer = isServer; + + if (isServer && certificate == null) + { + throw new ArgumentException("TTlsSocketClientTransport needs certificate to be used for server", + nameof(certificate)); + } + + if (IsOpen) + { + InputStream = client.GetStream(); + OutputStream = client.GetStream(); + } + } + + public TTlsSocketClientTransport(IPAddress host, int port, string certificatePath, + RemoteCertificateValidationCallback certValidator = null, + LocalCertificateSelectionCallback localCertificateSelectionCallback = null, + SslProtocols sslProtocols = SslProtocols.Tls12) + : this(host, port, 0, + new X509Certificate2(certificatePath), + certValidator, + localCertificateSelectionCallback, + sslProtocols) + { + } + + public TTlsSocketClientTransport(IPAddress host, int port, + X509Certificate2 certificate = null, + RemoteCertificateValidationCallback certValidator = null, + LocalCertificateSelectionCallback localCertificateSelectionCallback = null, + SslProtocols sslProtocols = SslProtocols.Tls12) + : this(host, port, 0, + certificate, + certValidator, + localCertificateSelectionCallback, + sslProtocols) + { + } + + public TTlsSocketClientTransport(IPAddress host, int port, int timeout, + X509Certificate2 certificate, + RemoteCertificateValidationCallback certValidator = null, + LocalCertificateSelectionCallback localCertificateSelectionCallback = null, + SslProtocols sslProtocols = SslProtocols.Tls12) + { + _host = host; + _port = port; + _timeout = timeout; + _certificate = certificate; + _certValidator = certValidator; + _localCertificateSelectionCallback = localCertificateSelectionCallback; + _sslProtocols = sslProtocols; + + InitSocket(); + } + + public int Timeout + { + set { _client.ReceiveTimeout = _client.SendTimeout = _timeout = value; } + } + + public TcpClient TcpClient => _client; + + public IPAddress Host => _host; + + public int Port => _port; + + public override bool IsOpen + { + get + { + if (_client == null) + { + return false; + } + + return _client.Connected; + } + } + + private void InitSocket() + { + _client = new TcpClient(); + _client.ReceiveTimeout = _client.SendTimeout = _timeout; + _client.Client.NoDelay = true; + } + + private bool DefaultCertificateValidator(object sender, X509Certificate certificate, X509Chain chain, + SslPolicyErrors sslValidationErrors) + { + return sslValidationErrors == SslPolicyErrors.None; + } + + public override async Task OpenAsync(CancellationToken cancellationToken) + { + if (IsOpen) + { + throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen, "Socket already connected"); + } + + if (_host == null) + { + throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open null host"); + } + + if (_port <= 0) + { + throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open without port"); + } + + if (_client == null) + { + InitSocket(); + } + + if (_client != null) + { + await _client.ConnectAsync(_host, _port); + await SetupTlsAsync(); + } + } + + public async Task SetupTlsAsync() + { + var validator = _certValidator ?? DefaultCertificateValidator; + + if (_localCertificateSelectionCallback != null) + { + _secureStream = new SslStream(_client.GetStream(), false, validator, _localCertificateSelectionCallback); + } + else + { + _secureStream = new SslStream(_client.GetStream(), false, validator); + } + + try + { + if (_isServer) + { + // Server authentication + await + _secureStream.AuthenticateAsServerAsync(_certificate, _certValidator != null, _sslProtocols, + true); + } + else + { + // Client authentication + var certs = _certificate != null + ? new X509CertificateCollection {_certificate} + : new X509CertificateCollection(); + + var targetHost = _host.ToString(); + await _secureStream.AuthenticateAsClientAsync(targetHost, certs, _sslProtocols, true); + } + } + catch (Exception) + { + Close(); + throw; + } + + InputStream = _secureStream; + OutputStream = _secureStream; + } + + public override void Close() + { + base.Close(); + if (_client != null) + { + _client.Dispose(); + _client = null; + } + + if (_secureStream != null) + { + _secureStream.Dispose(); + _secureStream = null; + } + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Server/THttpServerTransport.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Server/THttpServerTransport.cs new file mode 100644 index 0000000..032063a --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Server/THttpServerTransport.cs @@ -0,0 +1,98 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; +using Thrift.Protocols; +using Thrift.Transports.Client; + +namespace Thrift.Transports.Server +{ + // ReSharper disable once InconsistentNaming + public class THttpServerTransport + { + protected const string ContentType = "application/x-thrift"; + private readonly ILogger _logger; + private readonly RequestDelegate _next; + protected Encoding Encoding = Encoding.UTF8; + + protected ITProtocolFactory InputProtocolFactory; + protected ITProtocolFactory OutputProtocolFactory; + + protected ITAsyncProcessor Processor; + + public THttpServerTransport(ITAsyncProcessor processor, RequestDelegate next, ILoggerFactory loggerFactory) + : this(processor, new TBinaryProtocol.Factory(), next, loggerFactory) + { + } + + public THttpServerTransport(ITAsyncProcessor processor, ITProtocolFactory protocolFactory, RequestDelegate next, + ILoggerFactory loggerFactory) + : this(processor, protocolFactory, protocolFactory, next, loggerFactory) + { + } + + public THttpServerTransport(ITAsyncProcessor processor, ITProtocolFactory inputProtocolFactory, + ITProtocolFactory outputProtocolFactory, RequestDelegate next, ILoggerFactory loggerFactory) + { + if (loggerFactory == null) + { + throw new ArgumentNullException(nameof(loggerFactory)); + } + + Processor = processor ?? throw new ArgumentNullException(nameof(processor)); + InputProtocolFactory = inputProtocolFactory ?? throw new ArgumentNullException(nameof(inputProtocolFactory)); + OutputProtocolFactory = outputProtocolFactory ?? throw new ArgumentNullException(nameof(outputProtocolFactory)); + + _next = next; + _logger = loggerFactory.CreateLogger(); + } + + public async Task Invoke(HttpContext context) + { + context.Response.ContentType = ContentType; + await ProcessRequestAsync(context, context.RequestAborted); //TODO: check for correct logic + } + + public async Task ProcessRequestAsync(HttpContext context, CancellationToken cancellationToken) + { + var transport = new TStreamClientTransport(context.Request.Body, context.Response.Body); + + try + { + var input = InputProtocolFactory.GetProtocol(transport); + var output = OutputProtocolFactory.GetProtocol(transport); + + while (await Processor.ProcessAsync(input, output, cancellationToken)) + { + } + } + catch (TTransportException) + { + // Client died, just move on + } + finally + { + transport.Close(); + } + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Server/TNamedPipeServerTransport.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Server/TNamedPipeServerTransport.cs new file mode 100644 index 0000000..186786e --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Server/TNamedPipeServerTransport.cs @@ -0,0 +1,191 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.IO.Pipes; +using System.Threading; +using System.Threading.Tasks; + +namespace Thrift.Transports.Server +{ + // ReSharper disable once InconsistentNaming + public class TNamedPipeServerTransport : TServerTransport + { + /// + /// This is the address of the Pipe on the localhost. + /// + private readonly string _pipeAddress; + + private bool _asyncMode = true; + private volatile bool _isPending = true; + + private NamedPipeServerStream _stream = null; + + public TNamedPipeServerTransport(string pipeAddress) + { + _pipeAddress = pipeAddress; + } + + public override void Listen() + { + // nothing to do here + } + + public override void Close() + { + if (_stream != null) + { + try + { + //TODO: check for disconection + _stream.Disconnect(); + _stream.Dispose(); + } + finally + { + _stream = null; + _isPending = false; + } + } + } + + public override bool IsClientPending() + { + return _isPending; + } + + private void EnsurePipeInstance() + { + if (_stream == null) + { + var direction = PipeDirection.InOut; + var maxconn = 254; + var mode = PipeTransmissionMode.Byte; + var options = _asyncMode ? PipeOptions.Asynchronous : PipeOptions.None; + var inbuf = 4096; + var outbuf = 4096; + // TODO: security + + try + { + _stream = new NamedPipeServerStream(_pipeAddress, direction, maxconn, mode, options, inbuf, outbuf); + } + catch (NotImplementedException) // Mono still does not support async, fallback to sync + { + if (_asyncMode) + { + options &= (~PipeOptions.Asynchronous); + _stream = new NamedPipeServerStream(_pipeAddress, direction, maxconn, mode, options, inbuf, + outbuf); + _asyncMode = false; + } + else + { + throw; + } + } + } + } + + protected override async Task AcceptImplementationAsync(CancellationToken cancellationToken) + { + try + { + EnsurePipeInstance(); + + await _stream.WaitForConnectionAsync(cancellationToken); + + var trans = new ServerTransport(_stream); + _stream = null; // pass ownership to ServerTransport + + //_isPending = false; + + return trans; + } + catch (TTransportException) + { + Close(); + throw; + } + catch (Exception e) + { + Close(); + throw new TTransportException(TTransportException.ExceptionType.NotOpen, e.Message); + } + } + + private class ServerTransport : TClientTransport + { + private readonly NamedPipeServerStream _stream; + + public ServerTransport(NamedPipeServerStream stream) + { + _stream = stream; + } + + public override bool IsOpen => _stream != null && _stream.IsConnected; + + public override async Task OpenAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + public override void Close() + { + _stream?.Dispose(); + } + + public override async Task ReadAsync(byte[] buffer, int offset, int length, + CancellationToken cancellationToken) + { + if (_stream == null) + { + throw new TTransportException(TTransportException.ExceptionType.NotOpen); + } + + return await _stream.ReadAsync(buffer, offset, length, cancellationToken); + } + + public override async Task WriteAsync(byte[] buffer, int offset, int length, + CancellationToken cancellationToken) + { + if (_stream == null) + { + throw new TTransportException(TTransportException.ExceptionType.NotOpen); + } + + await _stream.WriteAsync(buffer, offset, length, cancellationToken); + } + + public override async Task FlushAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + await Task.FromCanceled(cancellationToken); + } + } + + protected override void Dispose(bool disposing) + { + _stream?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Server/TServerFramedTransport.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Server/TServerFramedTransport.cs new file mode 100644 index 0000000..0b86e9e --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Server/TServerFramedTransport.cs @@ -0,0 +1,150 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Net; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; +using Thrift.Transports.Client; + +namespace Thrift.Transports.Server +{ + // ReSharper disable once InconsistentNaming + public class TServerFramedTransport : TServerTransport + { + private readonly int _clientTimeout; + private readonly int _port; + private TcpListener _server; + + public TServerFramedTransport(TcpListener listener) + : this(listener, 0) + { + } + + public TServerFramedTransport(TcpListener listener, int clientTimeout) + { + _server = listener; + _clientTimeout = clientTimeout; + } + + public TServerFramedTransport(int port) + : this(port, 0) + { + } + + public TServerFramedTransport(int port, int clientTimeout) + { + _port = port; + _clientTimeout = clientTimeout; + try + { + // Make server socket + _server = new TcpListener(IPAddress.Any, _port); + _server.Server.NoDelay = true; + } + catch (Exception) + { + _server = null; + throw new TTransportException("Could not create ServerSocket on port " + port + "."); + } + } + + public override void Listen() + { + // Make sure not to block on accept + if (_server != null) + { + try + { + _server.Start(); + } + catch (SocketException sx) + { + throw new TTransportException("Could not accept on listening socket: " + sx.Message); + } + } + } + + public override bool IsClientPending() + { + return _server.Pending(); + } + + protected override async Task AcceptImplementationAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + if (_server == null) + { + throw new TTransportException(TTransportException.ExceptionType.NotOpen, "No underlying server socket."); + } + + try + { + TFramedClientTransport tSocketTransport = null; + var tcpClient = await _server.AcceptTcpClientAsync(); + + try + { + tSocketTransport = new TFramedClientTransport(new TSocketClientTransport(tcpClient) + { + Timeout = _clientTimeout + }); + + return tSocketTransport; + } + catch (Exception) + { + if (tSocketTransport != null) + { + tSocketTransport.Dispose(); + } + else // Otherwise, clean it up ourselves. + { + ((IDisposable) tcpClient).Dispose(); + } + + throw; + } + } + catch (Exception ex) + { + throw new TTransportException(ex.ToString()); + } + } + + public override void Close() + { + if (_server != null) + { + try + { + _server.Stop(); + } + catch (Exception ex) + { + throw new TTransportException("WARNING: Could not close server socket: " + ex); + } + _server = null; + } + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Server/TServerSocketTransport.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Server/TServerSocketTransport.cs new file mode 100644 index 0000000..3a9d8a1 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Server/TServerSocketTransport.cs @@ -0,0 +1,174 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Net; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; +using Thrift.Transports.Client; + +namespace Thrift.Transports.Server +{ + // ReSharper disable once InconsistentNaming + public class TServerSocketTransport : TServerTransport + { + private readonly int _clientTimeout; + private readonly int _port; + private readonly bool _useBufferedSockets; + private readonly bool _useFramedTransport; + private TcpListener _server; + + public TServerSocketTransport(TcpListener listener) + : this(listener, 0) + { + } + + public TServerSocketTransport(TcpListener listener, int clientTimeout) + { + _server = listener; + _clientTimeout = clientTimeout; + } + + public TServerSocketTransport(int port) + : this(port, 0) + { + } + + public TServerSocketTransport(int port, int clientTimeout) + : this(port, clientTimeout, false) + { + } + + public TServerSocketTransport(int port, int clientTimeout, bool useBufferedSockets): + this(port, clientTimeout, useBufferedSockets, false) + { + } + + public TServerSocketTransport(int port, int clientTimeout, bool useBufferedSockets, bool useFramedTransport) + { + _port = port; + _clientTimeout = clientTimeout; + _useBufferedSockets = useBufferedSockets; + _useFramedTransport = useFramedTransport; + try + { + // Make server socket + _server = new TcpListener(IPAddress.Any, _port); + _server.Server.NoDelay = true; + } + catch (Exception) + { + _server = null; + throw new TTransportException("Could not create ServerSocket on port " + port + "."); + } + } + + public override void Listen() + { + // Make sure not to block on accept + if (_server != null) + { + try + { + _server.Start(); + } + catch (SocketException sx) + { + throw new TTransportException("Could not accept on listening socket: " + sx.Message); + } + } + } + + public override bool IsClientPending() + { + return _server.Pending(); + } + + protected override async Task AcceptImplementationAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + if (_server == null) + { + throw new TTransportException(TTransportException.ExceptionType.NotOpen, "No underlying server socket."); + } + + try + { + TClientTransport tSocketTransport = null; + var tcpClient = await _server.AcceptTcpClientAsync(); + + try + { + tSocketTransport = new TSocketClientTransport(tcpClient) + { + Timeout = _clientTimeout + }; + + if (_useBufferedSockets) + { + tSocketTransport = new TBufferedClientTransport(tSocketTransport); + } + + if (_useFramedTransport) + { + tSocketTransport = new TFramedClientTransport(tSocketTransport); + } + + return tSocketTransport; + } + catch (Exception) + { + if (tSocketTransport != null) + { + tSocketTransport.Dispose(); + } + else // Otherwise, clean it up ourselves. + { + ((IDisposable) tcpClient).Dispose(); + } + + throw; + } + } + catch (Exception ex) + { + throw new TTransportException(ex.ToString()); + } + } + + public override void Close() + { + if (_server != null) + { + try + { + _server.Stop(); + } + catch (Exception ex) + { + throw new TTransportException("WARNING: Could not close server socket: " + ex); + } + _server = null; + } + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Server/TTlsServerSocketTransport.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Server/TTlsServerSocketTransport.cs new file mode 100644 index 0000000..759feed --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/Server/TTlsServerSocketTransport.cs @@ -0,0 +1,177 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Net; +using System.Net.Security; +using System.Net.Sockets; +using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; +using System.Threading; +using System.Threading.Tasks; +using Thrift.Transports.Client; + +namespace Thrift.Transports.Server +{ + // ReSharper disable once InconsistentNaming + public class TTlsServerSocketTransport : TServerTransport + { + private readonly RemoteCertificateValidationCallback _clientCertValidator; + private readonly int _clientTimeout = 0; + private readonly LocalCertificateSelectionCallback _localCertificateSelectionCallback; + private readonly int _port; + private readonly X509Certificate2 _serverCertificate; + private readonly SslProtocols _sslProtocols; + private readonly bool _useBufferedSockets; + private readonly bool _useFramedTransport; + private TcpListener _server; + + public TTlsServerSocketTransport(int port, X509Certificate2 certificate) + : this(port, false, certificate) + { + } + + public TTlsServerSocketTransport( + int port, + bool useBufferedSockets, + X509Certificate2 certificate, + RemoteCertificateValidationCallback clientCertValidator = null, + LocalCertificateSelectionCallback localCertificateSelectionCallback = null, + SslProtocols sslProtocols = SslProtocols.Tls12) + : this(port, useBufferedSockets, false, certificate, + clientCertValidator, localCertificateSelectionCallback, sslProtocols) + { + } + + public TTlsServerSocketTransport( + int port, + bool useBufferedSockets, + bool useFramedTransport, + X509Certificate2 certificate, + RemoteCertificateValidationCallback clientCertValidator = null, + LocalCertificateSelectionCallback localCertificateSelectionCallback = null, + SslProtocols sslProtocols = SslProtocols.Tls12) + { + if (!certificate.HasPrivateKey) + { + throw new TTransportException(TTransportException.ExceptionType.Unknown, + "Your server-certificate needs to have a private key"); + } + + _port = port; + _serverCertificate = certificate; + _useBufferedSockets = useBufferedSockets; + _useFramedTransport = useFramedTransport; + _clientCertValidator = clientCertValidator; + _localCertificateSelectionCallback = localCertificateSelectionCallback; + _sslProtocols = sslProtocols; + + try + { + // Create server socket + _server = new TcpListener(IPAddress.Any, _port); + _server.Server.NoDelay = true; + } + catch (Exception) + { + _server = null; + throw new TTransportException($"Could not create ServerSocket on port {port}."); + } + } + + public override void Listen() + { + // Make sure accept is not blocking + if (_server != null) + { + try + { + _server.Start(); + } + catch (SocketException sx) + { + throw new TTransportException($"Could not accept on listening socket: {sx.Message}"); + } + } + } + + public override bool IsClientPending() + { + return _server.Pending(); + } + + protected override async Task AcceptImplementationAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + if (_server == null) + { + throw new TTransportException(TTransportException.ExceptionType.NotOpen, "No underlying server socket."); + } + + try + { + var client = await _server.AcceptTcpClientAsync(); + client.SendTimeout = client.ReceiveTimeout = _clientTimeout; + + //wrap the client in an SSL Socket passing in the SSL cert + var tTlsSocket = new TTlsSocketClientTransport(client, _serverCertificate, true, _clientCertValidator, + _localCertificateSelectionCallback, _sslProtocols); + + await tTlsSocket.SetupTlsAsync(); + + TClientTransport trans = tTlsSocket; + + if (_useBufferedSockets) + { + trans = new TBufferedClientTransport(trans); + } + + if (_useFramedTransport) + { + trans = new TFramedClientTransport(trans); + } + + return trans; + } + catch (Exception ex) + { + throw new TTransportException(ex.ToString()); + } + } + + public override void Close() + { + if (_server != null) + { + try + { + _server.Stop(); + } + catch (Exception ex) + { + throw new TTransportException($"WARNING: Could not close server socket: {ex}"); + } + + _server = null; + } + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/TClientTransport.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/TClientTransport.cs new file mode 100644 index 0000000..0dd96cb --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/TClientTransport.cs @@ -0,0 +1,179 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace Thrift.Transports +{ + //TODO: think about client info + // ReSharper disable once InconsistentNaming + public abstract class TClientTransport : IDisposable + { + //TODO: think how to avoid peek byte + private readonly byte[] _peekBuffer = new byte[1]; + private bool _hasPeekByte; + public abstract bool IsOpen { get; } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + public async Task PeekAsync(CancellationToken cancellationToken) + { + //If we already have a byte read but not consumed, do nothing. + if (_hasPeekByte) + { + return true; + } + + //If transport closed we can't peek. + if (!IsOpen) + { + return false; + } + + //Try to read one byte. If succeeds we will need to store it for the next read. + try + { + var bytes = await ReadAsync(_peekBuffer, 0, 1, cancellationToken); + if (bytes == 0) + { + return false; + } + } + catch (IOException) + { + return false; + } + + _hasPeekByte = true; + return true; + } + + public virtual async Task OpenAsync() + { + await OpenAsync(CancellationToken.None); + } + + public abstract Task OpenAsync(CancellationToken cancellationToken); + + public abstract void Close(); + + protected static void ValidateBufferArgs(byte[] buffer, int offset, int length) + { + if (buffer == null) + { + throw new ArgumentNullException(nameof(buffer)); + } + + if (offset < 0) + { + throw new ArgumentOutOfRangeException(nameof(offset), "Buffer offset is smaller than zero."); + } + + if (length < 0) + { + throw new ArgumentOutOfRangeException(nameof(length), "Buffer length is smaller than zero."); + } + + if (offset + length > buffer.Length) + { + throw new ArgumentOutOfRangeException(nameof(buffer), "Not enough data."); + } + } + + public virtual async Task ReadAsync(byte[] buffer, int offset, int length) + { + return await ReadAsync(buffer, offset, length, CancellationToken.None); + } + + public abstract Task ReadAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken); + + public virtual async Task ReadAllAsync(byte[] buffer, int offset, int length) + { + return await ReadAllAsync(buffer, offset, length, CancellationToken.None); + } + + public virtual async Task ReadAllAsync(byte[] buffer, int offset, int length, + CancellationToken cancellationToken) + { + ValidateBufferArgs(buffer, offset, length); + + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + var retrieved = 0; + + //If we previously peeked a byte, we need to use that first. + if (_hasPeekByte) + { + buffer[offset + retrieved++] = _peekBuffer[0]; + _hasPeekByte = false; + } + + while (retrieved < length) + { + if (cancellationToken.IsCancellationRequested) + { + return await Task.FromCanceled(cancellationToken); + } + + var returnedCount = await ReadAsync(buffer, offset + retrieved, length - retrieved, cancellationToken); + if (returnedCount <= 0) + { + throw new TTransportException(TTransportException.ExceptionType.EndOfFile, + "Cannot read, Remote side has closed"); + } + retrieved += returnedCount; + } + return retrieved; + } + + public virtual async Task WriteAsync(byte[] buffer) + { + await WriteAsync(buffer, CancellationToken.None); + } + + public virtual async Task WriteAsync(byte[] buffer, CancellationToken cancellationToken) + { + await WriteAsync(buffer, 0, buffer.Length, CancellationToken.None); + } + + public virtual async Task WriteAsync(byte[] buffer, int offset, int length) + { + await WriteAsync(buffer, offset, length, CancellationToken.None); + } + + public abstract Task WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken); + + public virtual async Task FlushAsync() + { + await FlushAsync(CancellationToken.None); + } + + public abstract Task FlushAsync(CancellationToken cancellationToken); + + protected abstract void Dispose(bool disposing); + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/TServerTransport.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/TServerTransport.cs new file mode 100644 index 0000000..0d45a55 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/TServerTransport.cs @@ -0,0 +1,54 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System.Threading; +using System.Threading.Tasks; + +namespace Thrift.Transports +{ + // ReSharper disable once InconsistentNaming + public abstract class TServerTransport + { + public abstract void Listen(); + public abstract void Close(); + public abstract bool IsClientPending(); + + protected virtual async Task AcceptImplementationAsync() + { + return await AcceptImplementationAsync(CancellationToken.None); + } + + protected abstract Task AcceptImplementationAsync(CancellationToken cancellationToken); + + public async Task AcceptAsync() + { + return await AcceptAsync(CancellationToken.None); + } + + public async Task AcceptAsync(CancellationToken cancellationToken) + { + var transport = await AcceptImplementationAsync(cancellationToken); + + if (transport == null) + { + throw new TTransportException($"{nameof(AcceptImplementationAsync)} should not return null"); + } + + return transport; + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/TTransportException.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/TTransportException.cs new file mode 100644 index 0000000..b7c42e3 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/TTransportException.cs @@ -0,0 +1,58 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +namespace Thrift.Transports +{ + // ReSharper disable once InconsistentNaming + public class TTransportException : TException + { + public enum ExceptionType + { + Unknown, + NotOpen, + AlreadyOpen, + TimedOut, + EndOfFile, + Interrupted + } + + protected ExceptionType ExType; + + public TTransportException() + { + } + + public TTransportException(ExceptionType exType) + : this() + { + ExType = exType; + } + + public TTransportException(ExceptionType exType, string message) + : base(message) + { + ExType = exType; + } + + public TTransportException(string message) + : base(message) + { + } + + public ExceptionType Type => ExType; + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/TTransportFactory.cs b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/TTransportFactory.cs new file mode 100644 index 0000000..26c3cc4 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/Thrift/Transports/TTransportFactory.cs @@ -0,0 +1,35 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +namespace Thrift.Transports +{ + /// + /// From Mark Slee & Aditya Agarwal of Facebook: + /// Factory class used to create wrapped instance of Transports. + /// This is used primarily in servers, which get Transports from + /// a ServerTransport and then may want to mutate them (i.e. create + /// a BufferedTransport from the underlying base transport) + /// + // ReSharper disable once InconsistentNaming + public class TTransportFactory + { + public virtual TClientTransport GetTransport(TClientTransport trans) + { + return trans; + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/build.cmd b/vendor/git.apache.org/thrift.git/lib/netcore/build.cmd new file mode 100644 index 0000000..863c4b4 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/build.cmd @@ -0,0 +1,27 @@ +@echo off +rem /* +rem * Licensed to the Apache Software Foundation (ASF) under one +rem * or more contributor license agreements. See the NOTICE file +rem * distributed with this work for additional information +rem * regarding copyright ownership. The ASF licenses this file +rem * to you under the Apache License, Version 2.0 (the +rem * "License"); you may not use this file except in compliance +rem * with the License. You may obtain a copy of the License at +rem * +rem * http://www.apache.org/licenses/LICENSE-2.0 +rem * +rem * Unless required by applicable law or agreed to in writing, +rem * software distributed under the License is distributed on an +rem * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +rem * KIND, either express or implied. See the License for the +rem * specific language governing permissions and limitations +rem * under the License. +rem */ + +setlocal + +thrift -version +dotnet --info +dotnet build + +:eof diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/build.sh b/vendor/git.apache.org/thrift.git/lib/netcore/build.sh new file mode 100644 index 0000000..ae18bce --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/build.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash + +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +#exit if any command fails +#set -e + +thrift --version +dotnet --info +dotnet build + +#revision=${TRAVIS_JOB_ID:=1} +#revision=$(printf "%04d" $revision) + +#dotnet pack ./src/PROJECT_NAME -c Release -o ./artifacts --version-suffix=$revision diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/runtests.cmd b/vendor/git.apache.org/thrift.git/lib/netcore/runtests.cmd new file mode 100644 index 0000000..5114bc5 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/runtests.cmd @@ -0,0 +1,28 @@ +@echo off +rem /* +rem * Licensed to the Apache Software Foundation (ASF) under one +rem * or more contributor license agreements. See the NOTICE file +rem * distributed with this work for additional information +rem * regarding copyright ownership. The ASF licenses this file +rem * to you under the Apache License, Version 2.0 (the +rem * "License"); you may not use this file except in compliance +rem * with the License. You may obtain a copy of the License at +rem * +rem * http://www.apache.org/licenses/LICENSE-2.0 +rem * +rem * Unless required by applicable law or agreed to in writing, +rem * software distributed under the License is distributed on an +rem * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +rem * KIND, either express or implied. See the License for the +rem * specific language governing permissions and limitations +rem * under the License. +rem */ +setlocal + +thrift -version +dotnet --info + +dotnet test Tests\Thrift.IntegrationTests\Thrift.IntegrationTests.csproj +dotnet test Tests\Thrift.Tests\Thrift.Tests.csproj + +:eof diff --git a/vendor/git.apache.org/thrift.git/lib/netcore/runtests.sh b/vendor/git.apache.org/thrift.git/lib/netcore/runtests.sh new file mode 100644 index 0000000..a26cc36 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/netcore/runtests.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash + +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +thrift -version +dotnet --info + +dotnet test Tests\Thrift.IntegrationTests\Thrift.IntegrationTests.csproj +dotnet test Tests\Thrift.Tests\Thrift.Tests.csproj \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/Makefile.am b/vendor/git.apache.org/thrift.git/lib/nodejs/Makefile.am index 6d785be..68ea3ea 100755 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/Makefile.am +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/Makefile.am @@ -15,21 +15,21 @@ # specific language governing permissions and limitations # under the License. - -THRIFT = $(top_builddir)/compiler/cpp/thrift +# We call npm twice to work around npm issues stubs: $(top_srcdir)/test/ThriftTest.thrift $(THRIFT) --gen js:node -o test/ $(top_srcdir)/test/ThriftTest.thrift deps: $(top_srcdir)/package.json - $(NPM) install --no-bin-links $(top_srcdir)/ + $(NPM) install $(top_srcdir)/ || $(NPM) install $(top_srcdir)/ all-local: deps precross: deps stubs +# TODO: Lint nodejs lib and gen-code as part of build check: deps - cd $(top_srcdir) && $(NPM) test && cd lib/nodejs + cd $(top_srcdir) && $(NPM) test && $(NPM) run lint-tests && cd lib/nodejs clean-local: $(RM) -r test/gen-nodejs diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/README.md b/vendor/git.apache.org/thrift.git/lib/nodejs/README.md index 88499f7..50acfbd 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/README.md +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/README.md @@ -20,6 +20,9 @@ KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +## Compatibility + +node version 6 or later is required ## Install @@ -35,30 +38,32 @@ You can compile IDL sources for Node.js with the following command: Here is a Cassandra example: - var thrift = require('thrift'), - Cassandra = require('./gen-nodejs/Cassandra') - ttypes = require('./gen-nodejs/cassandra_types'); +```js +var thrift = require('thrift'), + Cassandra = require('./gen-nodejs/Cassandra') + ttypes = require('./gen-nodejs/cassandra_types'); - var connection = thrift.createConnection("localhost", 9160), - client = thrift.createClient(Cassandra, connection); +var connection = thrift.createConnection("localhost", 9160), + client = thrift.createClient(Cassandra, connection); - connection.on('error', function(err) { - console.error(err); - }); +connection.on('error', function(err) { + console.error(err); +}); - client.get_slice("Keyspace", "key", new ttypes.ColumnParent({column_family: "ExampleCF"}), new ttypes.SlicePredicate({slice_range: new ttypes.SliceRange({start: '', finish: ''})}), ttypes.ConsistencyLevel.ONE, function(err, data) { - if (err) { - // handle err - } else { - // data == [ttypes.ColumnOrSuperColumn, ...] - } - connection.end(); - }); +client.get_slice("Keyspace", "key", new ttypes.ColumnParent({column_family: "ExampleCF"}), new ttypes.SlicePredicate({slice_range: new ttypes.SliceRange({start: '', finish: ''})}), ttypes.ConsistencyLevel.ONE, function(err, data) { + if (err) { + // handle err + } else { + // data == [ttypes.ColumnOrSuperColumn, ...] + } + connection.end(); +}); +``` ## Int64 -Since JavaScript represents all numbers as doubles, int64 values cannot be accurately represented naturally. To solve this, int64 values in responses will be wrapped with Thirft.Int64 objects. The Int64 implementation used is [broofa/node-int64](https://github.com/broofa/node-int64). +Since JavaScript represents all numbers as doubles, int64 values cannot be accurately represented naturally. To solve this, int64 values in responses will be wrapped with Thrift.Int64 objects. The Int64 implementation used is [broofa/node-int64](https://github.com/broofa/node-int64). ## Client and server examples diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/examples/httpServer.py b/vendor/git.apache.org/thrift.git/lib/nodejs/examples/httpServer.py index b8ba586..b712fcd 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/examples/httpServer.py +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/examples/httpServer.py @@ -7,7 +7,7 @@ from thrift.server import THttpServer class HelloSvcHandler: def hello_func(self): - print "Hello Called" + print("Hello Called") return "hello from Python" processor = HelloSvc.Processor(HelloSvcHandler()) @@ -16,4 +16,3 @@ port = 9090 server = THttpServer.THttpServer(processor, ("localhost", port), protoFactory) print "Python server running on port " + str(port) server.serve() - diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/binary_protocol.js b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/binary_protocol.js index 6d3918e..b57c8c5 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/binary_protocol.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/binary_protocol.js @@ -37,6 +37,7 @@ function TBinaryProtocol(trans, strictRead, strictWrite) { this.trans = trans; this.strictRead = (strictRead !== undefined ? strictRead : false); this.strictWrite = (strictWrite !== undefined ? strictWrite : true); + this._seqid = null; }; TBinaryProtocol.prototype.flush = function() { @@ -54,8 +55,7 @@ TBinaryProtocol.prototype.writeMessageBegin = function(name, type, seqid) { this.writeI32(seqid); } // Record client seqid to find callback again - if (this._seqid) { - // TODO better logging log warning + if (this._seqid !== null) { log.warning('SeqId already set', { 'name': name }); } else { this._seqid = seqid; @@ -64,7 +64,7 @@ TBinaryProtocol.prototype.writeMessageBegin = function(name, type, seqid) { }; TBinaryProtocol.prototype.writeMessageEnd = function() { - if (this._seqid) { + if (this._seqid !== null) { this._seqid = null; } else { log.warning('No seqid to unset'); @@ -177,7 +177,6 @@ TBinaryProtocol.prototype.readMessageBegin = function() { if (sz < 0) { var version = sz & VERSION_MASK; if (version != VERSION_1) { - console.log("BAD: " + version); throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.BAD_VERSION, "Bad version in readMessageBegin: " + sz); } type = sz & TYPE_MASK; diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/browser.js b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/browser.js index 4593a8f..67ce853 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/browser.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/browser.js @@ -32,3 +32,5 @@ exports.TFramedTransport = require('./framed_transport'); exports.Protocol = exports.TJSONProtocol = require('./json_protocol'); exports.TBinaryProtocol = require('./binary_protocol'); exports.TCompactProtocol = require('./compact_protocol'); + +exports.Int64 = require('node-int64'); diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/buffered_transport.js b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/buffered_transport.js index 13636b5..a9e006e 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/buffered_transport.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/buffered_transport.js @@ -33,6 +33,14 @@ function TBufferedTransport(buffer, callback) { this.onFlush = callback; }; +TBufferedTransport.prototype.reset = function() { + this.inBuf = new Buffer(this.defaultReadBufferSize); + this.readCursor = 0; + this.writeCursor = 0; + this.outBuffers = []; + this.outCount = 0; +} + TBufferedTransport.receiver = function(callback, seqid) { var reader = new TBufferedTransport(); diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/compact_protocol.js b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/compact_protocol.js index b0e9148..5c531e5 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/compact_protocol.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/compact_protocol.js @@ -249,7 +249,6 @@ TCompactProtocol.prototype.writeMessageBegin = function(name, type, seqid) { // Record client seqid to find callback again if (this._seqid) { - // TODO better logging log warning log.warning('SeqId already set', { 'name': name }); } else { this._seqid = seqid; diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/connection.js b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/connection.js index 575d516..b545454 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/connection.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/connection.js @@ -17,10 +17,12 @@ * under the License. */ var util = require('util'); -var EventEmitter = require("events").EventEmitter; +var EventEmitter = require('events').EventEmitter; +var constants = require('constants'); var net = require('net'); var tls = require('tls'); var thrift = require('./thrift'); +var log = require('./log'); var TBufferedTransport = require('./buffered_transport'); var TBinaryProtocol = require('./binary_protocol'); @@ -121,7 +123,6 @@ var Connection = exports.Connection = function(stream, options) { var service_name = self.seqId2Service[header.rseqid]; if (service_name) { client = self.client[service_name]; - delete self.seqId2Service[header.rseqid]; } /*jshint -W083 */ client._reqs[dummy_seqid] = function(err, success){ @@ -129,6 +130,9 @@ var Connection = exports.Connection = function(stream, options) { var callback = client._reqs[header.rseqid]; delete client._reqs[header.rseqid]; + if (service_name) { + delete self.seqId2Service[header.rseqid]; + } if (callback) { callback(err, success); } @@ -201,9 +205,7 @@ Connection.prototype.connection_gone = function () { this.retry_delay = Math.floor(this.retry_delay * this.retry_backoff); } - if (self._debug) { - console.log("Retry connection in " + this.retry_delay + " ms"); - } + log.debug("Retry connection in " + this.retry_delay + " ms"); if (this.max_attempts && this.attempts >= this.max_attempts) { this.retry_timer = null; @@ -219,9 +221,7 @@ Connection.prototype.connection_gone = function () { }); this.retry_timer = setTimeout(function () { - if (self._debug) { - console.log("Retrying connection..."); - } + log.debug("Retrying connection..."); self.retry_totaltime += self.retry_delay; @@ -232,7 +232,11 @@ Connection.prototype.connection_gone = function () { return; } - self.connection.connect(self.port, self.host); + if (self.path !== undefined) { + self.connection.connect(self.path); + } else { + self.connection.connect(self.port, self.host); + } self.retry_timer = null; }, this.retry_delay); }; @@ -246,7 +250,20 @@ exports.createConnection = function(host, port, options) { return connection; }; +exports.createUDSConnection = function(path, options) { + var stream = net.createConnection(path); + var connection = new Connection(stream, options); + connection.path = path; + + return connection; +}; + exports.createSSLConnection = function(host, port, options) { + if (!('secureProtocol' in options) && !('secureOptions' in options)) { + options.secureProtocol = "SSLv23_method"; + options.secureOptions = constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3; + } + var stream = tls.connect(port, host, options); var connection = new Connection(stream, options); connection.host = host; @@ -268,20 +285,19 @@ var StdIOConnection = exports.StdIOConnection = function(command, options) { var self = this; EventEmitter.call(this); - this._debug = options.debug || false; this.connection = child.stdin; this.options = options || {}; this.transport = this.options.transport || TBufferedTransport; this.protocol = this.options.protocol || TBinaryProtocol; this.offline_queue = []; - if(this._debug === true){ - this.child.stderr.on('data',function(err){ - console.log(err.toString(),'CHILD ERROR'); + if (log.getLogLevel() === 'debug') { + this.child.stderr.on('data', function (err) { + log.debug(err.toString(), 'CHILD ERROR'); }); - this.child.on('exit',function(code,signal){ - console.log(code+':'+signal,'CHILD EXITED'); + this.child.on('exit', function (code,signal) { + log.debug(code + ':' + signal, 'CHILD EXITED'); }); } diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/http_connection.js b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/http_connection.js index 18bfadb..3c2ab0f 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/http_connection.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/http_connection.js @@ -59,8 +59,6 @@ var createClient = require('./create_client'); * Initializes a Thrift HttpConnection instance (use createHttpConnection() rather than * instantiating directly). * @constructor - * @param {string} host - The host name or IP to connect to. - * @param {number} port - The TCP port to connect to. * @param {ConnectOptions} options - The configuration options to use. * @throws {error} Exceptions other than InputBufferUnderrunError are rethrown * @event {error} The "error" event is fired when a Node.js error event occurs during @@ -71,15 +69,16 @@ var createClient = require('./create_client'); * semantics implemented over the Node.js http.request() method. * @see {@link createHttpConnection} */ -var HttpConnection = exports.HttpConnection = function(host, port, options) { +var HttpConnection = exports.HttpConnection = function(options) { //Initialize the emitter base object EventEmitter.call(this); //Set configuration var self = this; this.options = options || {}; - this.host = host; - this.port = port; + this.host = this.options.host; + this.port = this.options.port; + this.socketPath = this.options.socketPath; this.https = this.options.https || false; this.transport = this.options.transport || TBufferedTransport; this.protocol = this.options.protocol || TBinaryProtocol; @@ -87,7 +86,8 @@ var HttpConnection = exports.HttpConnection = function(host, port, options) { //Prepare Node.js options this.nodeOptions = { host: this.host, - port: this.port || 80, + port: this.port, + socketPath: this.socketPath, path: this.options.path || '/', method: 'POST', headers: this.options.headers || {}, @@ -169,6 +169,10 @@ var HttpConnection = exports.HttpConnection = function(host, port, options) { var data = []; var dataLen = 0; + if (response.statusCode !== 200) { + this.emit("error", new THTTPException(response)); + } + response.on('error', function (e) { self.emit("error", e); }); @@ -210,10 +214,13 @@ util.inherits(HttpConnection, EventEmitter); */ HttpConnection.prototype.write = function(data) { var self = this; - self.nodeOptions.headers["Content-length"] = data.length; + var opts = self.nodeOptions; + opts.headers["Content-length"] = data.length; + if (!opts.headers["Content-Type"]) + opts.headers["Content-Type"] = "application/x-thrift"; var req = (self.https) ? - https.request(self.nodeOptions, self.responseCallback) : - http.request(self.nodeOptions, self.responseCallback); + https.request(opts, self.responseCallback) : + http.request(opts, self.responseCallback); req.on('error', function(err) { self.emit("error", err); }); @@ -231,8 +238,26 @@ HttpConnection.prototype.write = function(data) { * @see {@link ConnectOptions} */ exports.createHttpConnection = function(host, port, options) { - return new HttpConnection(host, port, options); + options.host = host; + options.port = port || 80; + return new HttpConnection(options); +}; + +exports.createHttpUDSConnection = function(path, options) { + options.socketPath = path; + return new HttpConnection(options); }; exports.createHttpClient = createClient + +function THTTPException(response) { + thrift.TApplicationException.call(this); + Error.captureStackTrace(this, this.constructor); + this.name = this.constructor.name; + this.statusCode = response.statusCode; + this.response = response; + this.type = thrift.TApplicationExceptionType.PROTOCOL_ERROR; + this.message = "Received a response with a bad HTTP status code: " + response.statusCode; +} +util.inherits(THTTPException, thrift.TApplicationException); diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/index.js b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/index.js index 61e5cbd..b09953d 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/index.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/index.js @@ -18,10 +18,16 @@ */ exports.Thrift = require('./thrift'); +var log = require('./log'); +exports.setLogFunc = log.setLogFunc; +exports.setLogLevel = log.setLogLevel; +exports.getLogLevel = log.getLogLevel; + var connection = require('./connection'); exports.Connection = connection.Connection; exports.createClient = connection.createClient; exports.createConnection = connection.createConnection; +exports.createUDSConnection = connection.createUDSConnection; exports.createSSLConnection = connection.createSSLConnection; exports.createStdIOClient = connection.createStdIOClient; exports.createStdIOConnection = connection.createStdIOConnection; @@ -29,6 +35,7 @@ exports.createStdIOConnection = connection.createStdIOConnection; var httpConnection = require('./http_connection'); exports.HttpConnection = httpConnection.HttpConnection; exports.createHttpConnection = httpConnection.createHttpConnection; +exports.createHttpUDSConnection = httpConnection.createHttpUDSConnection; exports.createHttpClient = httpConnection.createHttpClient; var wsConnection = require('./ws_connection'); diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/json_protocol.js b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/json_protocol.js index f31e3b2..727a3b2 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/json_protocol.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/json_protocol.js @@ -17,9 +17,7 @@ * under the License. */ -var log = require('./log'); var Int64 = require('node-int64'); -var InputBufferUnderrunError = require('./transport').InputBufferUnderrunError; var Thrift = require('./thrift'); var Type = Thrift.Type; var util = require("util"); @@ -739,5 +737,65 @@ TJSONProtocol.prototype.getTransport = function() { * Method to arbitrarily skip over data */ TJSONProtocol.prototype.skip = function(type) { - throw new Error('skip not supported yet'); + switch (type) { + case Type.STOP: + return; + case Type.BOOL: + this.readBool(); + break; + case Type.BYTE: + this.readByte(); + break; + case Type.I16: + this.readI16(); + break; + case Type.I32: + this.readI32(); + break; + case Type.I64: + this.readI64(); + break; + case Type.DOUBLE: + this.readDouble(); + break; + case Type.STRING: + this.readString(); + break; + case Type.STRUCT: + this.readStructBegin(); + while (true) { + var r = this.readFieldBegin(); + if (r.ftype === Type.STOP) { + break; + } + this.skip(r.ftype); + this.readFieldEnd(); + } + this.readStructEnd(); + break; + case Type.MAP: + var mapBegin = this.readMapBegin(); + for (var i = 0; i < mapBegin.size; ++i) { + this.skip(mapBegin.ktype); + this.skip(mapBegin.vtype); + } + this.readMapEnd(); + break; + case Type.SET: + var setBegin = this.readSetBegin(); + for (var i2 = 0; i2 < setBegin.size; ++i2) { + this.skip(setBegin.etype); + } + this.readSetEnd(); + break; + case Type.LIST: + var listBegin = this.readListBegin(); + for (var i3 = 0; i3 < listBegin.size; ++i3) { + this.skip(listBegin.etype); + } + this.readListEnd(); + break; + default: + throw new Error("Invalid type: " + type); + } }; diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/log.js b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/log.js index 0e13ea8..053e813 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/log.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/log.js @@ -17,10 +17,71 @@ * under the License. */ -module.exports = { - 'info' : function logInfo() {}, - 'warning' : function logWarning() {}, - 'error' : function logError() {}, - 'debug' : function logDebug() {}, - 'trace' : function logTrace() {} +var util = require('util'); + +var disabled = function () {}; +var logFunc = console.log; +var logLevel = 'error'; // default level + +function factory(level) { + return function () { + // better use spread syntax, but due to compatibility, + // use legacy method here. + var args = ['thrift: [' + level + '] '].concat(Array.from(arguments)); + return logFunc(util.format.apply(null, args)); + }; +} + +var trace = disabled; +var debug = disabled; +var error = disabled; +var warning = disabled; +var info = disabled; + +exports.setLogFunc = function (func) { + logFunc = func; +}; + +var setLogLevel = exports.setLogLevel = function (level) { + trace = debug = error = warning = info = disabled; + logLevel = level; + switch (logLevel) { + case 'trace': + trace = factory('TRACE'); + case 'debug': + debug = factory('DEBUG'); + case 'error': + error = factory('ERROR'); + case 'warning': + warning = factory('WARN'); + case 'info': + info = factory('INFO'); + } +}; + +// set default +setLogLevel(logLevel); + +exports.getLogLevel = function () { + return logLevel; +}; + +exports.trace = function () { + return trace.apply(null, arguments); +}; + +exports.debug = function () { + return debug.apply(null, arguments); +}; + +exports.error = function () { + return error.apply(null, arguments); +}; + +exports.warning = function () { + return warning.apply(null, arguments); +}; + +exports.info = function () { + return info.apply(null, arguments); }; diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/multiplexed_protocol.js b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/multiplexed_protocol.js index 9caf6ab..d078aa2 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/multiplexed_protocol.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/multiplexed_protocol.js @@ -52,17 +52,17 @@ Multiplexer.prototype.createClient = function(serviceName, ServiceClient, connec if (ServiceClient.Client) { ServiceClient = ServiceClient.Client; } - var self = this; - ServiceClient.prototype.new_seqid = function() { - self.seqid += 1; - return self.seqid; - }; var writeCb = function(buf, seqid) { connection.write(buf,seqid); }; var transport = new connection.transport(undefined, writeCb); var protocolWrapper = new Wrapper(serviceName, connection.protocol, connection); var client = new ServiceClient(transport, protocolWrapper); + var self = this; + client.new_seqid = function() { + self.seqid += 1; + return self.seqid; + }; if (typeof connection.client !== 'object') { connection.client = {}; diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/server.js b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/server.js index 921bb86..e124acc 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/server.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/server.js @@ -16,6 +16,8 @@ * specific language governing permissions and limitations * under the License. */ + +var constants = require('constants'); var net = require('net'); var tls = require('tls'); @@ -87,6 +89,10 @@ exports.createMultiplexServer = function(processor, options) { } if (options && options.tls) { + if (!('secureProtocol' in options.tls) && !('secureOptions' in options.tls)) { + options.tls.secureProtocol = "SSLv23_method"; + options.tls.secureOptions = constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3; + } return tls.createServer(options.tls, serverImpl); } else { return net.createServer(serverImpl); diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/web_server.js b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/web_server.js index 37159ea..a33f47a 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/web_server.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/web_server.js @@ -22,6 +22,7 @@ var url = require("url"); var path = require("path"); var fs = require("fs"); var crypto = require("crypto"); +var log = require('./log'); var MultiplexedProcessor = require('./multiplexed_processor').MultiplexedProcessor; @@ -284,7 +285,7 @@ exports.createWebServer = function(options) { '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.png': 'image/png', -   '.svg': 'image/svg+xml' + '.svg': 'image/svg+xml' }; //Setup all of the services @@ -414,7 +415,15 @@ exports.createWebServer = function(options) { //Locate the file requested and send it var uri = url.parse(request.url).pathname; - var filename = path.join(baseDir, uri); + var filename = path.resolve(path.join(baseDir, uri)); + + //Ensure the basedir path is not able to be escaped + if (filename.indexOf(baseDir) != 0) { + response.writeHead(400, "Invalid request path", {}); + response.end(); + return; + } + fs.exists(filename, function(exists) { if(!exists) { response.writeHead(404); @@ -547,7 +556,7 @@ exports.createWebServer = function(options) { frame = result.nextFrame; } } catch(e) { - console.log("TWebSocketTransport Exception: " + e); + log.error('TWebSocketTransport Exception: ' + e); socket.destroy(); } }); @@ -556,9 +565,3 @@ exports.createWebServer = function(options) { //Return the server return server; }; - - - - - - diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/ws_transport.js b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/ws_transport.js index 8e750e2..3513b84 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/ws_transport.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/lib/thrift/ws_transport.js @@ -17,6 +17,8 @@ * under the License. */ +var log = require('./log'); + module.exports = TWebSocketTransport; /** @@ -105,7 +107,7 @@ TWebSocketTransport.prototype.__onMessage = function(evt) { }; TWebSocketTransport.prototype.__onError = function(evt) { - console.log("Thrift WebSocket Error: " + evt.toString()); + log.error('websocket: ' + evt.toString()); this.socket.close(); }; diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/test/binary.test.js b/vendor/git.apache.org/thrift.git/lib/nodejs/test/binary.test.js index 38ba634..187cd18 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/test/binary.test.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/test/binary.test.js @@ -17,19 +17,19 @@ * under the License. */ -var test = require('tape'); -var binary = require('thrift/binary'); +const test = require("tape"); +const binary = require("thrift/binary"); -var cases = { - "Should read signed byte": function(assert){ +const cases = { + "Should read signed byte": function(assert) { assert.equal(1, binary.readByte(0x01)); - assert.equal(-1, binary.readByte(0xFF)); + assert.equal(-1, binary.readByte(0xff)); - assert.equal(127, binary.readByte(0x7F)); + assert.equal(127, binary.readByte(0x7f)); assert.equal(-128, binary.readByte(0x80)); assert.end(); }, - "Should write byte": function(assert){ + "Should write byte": function(assert) { //Protocol simply writes to the buffer. Nothing to test.. yet. assert.ok(true); assert.end(); @@ -76,58 +76,135 @@ var cases = { assert.deepEqual([0xff, 0xff, 0xff, 0xff], binary.writeI32([], -1)); // Min I32 - assert.deepEqual([0x80, 0x00, 0x00, 0x00], binary.writeI32([], -2147483648)); + assert.deepEqual( + [0x80, 0x00, 0x00, 0x00], + binary.writeI32([], -2147483648) + ); // Max I32 assert.deepEqual([0x7f, 0xff, 0xff, 0xff], binary.writeI32([], 2147483647)); assert.end(); }, "Should read doubles": function(assert) { - assert.equal(0, binary.readDouble([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) - assert.equal(0, binary.readDouble([0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) - assert.equal(1, binary.readDouble([0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) - assert.equal(2, binary.readDouble([0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) - assert.equal(-2, binary.readDouble([0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) + assert.equal( + 0, + binary.readDouble([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + ); + assert.equal( + 0, + binary.readDouble([0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + ); + assert.equal( + 1, + binary.readDouble([0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + ); + assert.equal( + 2, + binary.readDouble([0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + ); + assert.equal( + -2, + binary.readDouble([0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + ); - assert.equal(Math.PI, binary.readDouble([0x40, 0x9, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18])) + assert.equal( + Math.PI, + binary.readDouble([0x40, 0x9, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18]) + ); - assert.equal(Infinity, binary.readDouble([0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) - assert.equal(-Infinity, binary.readDouble([0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) + assert.equal( + Infinity, + binary.readDouble([0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + ); + assert.equal( + -Infinity, + binary.readDouble([0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + ); - assert.ok(isNaN(binary.readDouble([0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]))) + assert.ok( + isNaN(binary.readDouble([0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) + ); - assert.equal(1/3, binary.readDouble([0x3f, 0xd5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55])) + assert.equal( + 1 / 3, + binary.readDouble([0x3f, 0xd5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55]) + ); // Min subnormal positive double - assert.equal(4.9406564584124654e-324, binary.readDouble([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01])) + assert.equal( + 4.9406564584124654e-324, + binary.readDouble([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01]) + ); // Min normal positive double - assert.equal(2.2250738585072014e-308, binary.readDouble([0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) + assert.equal( + 2.2250738585072014e-308, + binary.readDouble([0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + ); // Max positive double - assert.equal(1.7976931348623157e308, binary.readDouble([0x7f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff])) + assert.equal( + 1.7976931348623157e308, + binary.readDouble([0x7f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]) + ); assert.end(); }, "Should write doubles": function(assert) { - assert.deepEqual([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], binary.writeDouble([], 0)); - assert.deepEqual([0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], binary.writeDouble([], 1)); - assert.deepEqual([0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], binary.writeDouble([], 2)); - assert.deepEqual([0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], binary.writeDouble([], -2)); + assert.deepEqual( + [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + binary.writeDouble([], 0) + ); + assert.deepEqual( + [0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + binary.writeDouble([], 1) + ); + assert.deepEqual( + [0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + binary.writeDouble([], 2) + ); + assert.deepEqual( + [0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + binary.writeDouble([], -2) + ); - assert.deepEqual([0x40, 0x9, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18], binary.writeDouble([], Math.PI)); + assert.deepEqual( + [0x40, 0x9, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18], + binary.writeDouble([], Math.PI) + ); - assert.deepEqual([0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], binary.writeDouble([], Infinity)); - assert.deepEqual([0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], binary.writeDouble([], -Infinity)); + assert.deepEqual( + [0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + binary.writeDouble([], Infinity) + ); + assert.deepEqual( + [0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + binary.writeDouble([], -Infinity) + ); - assert.deepEqual([0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], binary.writeDouble([], NaN)); + assert.deepEqual( + [0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + binary.writeDouble([], NaN) + ); - assert.deepEqual([0x3f, 0xd5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55], binary.writeDouble([], 1/3)); + assert.deepEqual( + [0x3f, 0xd5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55], + binary.writeDouble([], 1 / 3) + ); // Min subnormal positive double - assert.deepEqual([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01], binary.writeDouble([], 4.9406564584124654e-324)); + assert.deepEqual( + [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01], + binary.writeDouble([], 4.9406564584124654e-324) + ); // Min normal positive double - assert.deepEqual([0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], binary.writeDouble([], 2.2250738585072014e-308)); + assert.deepEqual( + [0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + binary.writeDouble([], 2.2250738585072014e-308) + ); // Max positive double - assert.deepEqual([0x7f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff], binary.writeDouble([], 1.7976931348623157e308)); + assert.deepEqual( + [0x7f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff], + binary.writeDouble([], 1.7976931348623157e308) + ); assert.end(); } }; diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/test/browser_client.js b/vendor/git.apache.org/thrift.git/lib/nodejs/test/browser_client.js deleted file mode 100644 index 27db543..0000000 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/test/browser_client.js +++ /dev/null @@ -1,27 +0,0 @@ - -var assert = require('assert'); -var thrift = require('thrift'); -var helpers = require('./helpers'); -var ThriftTest = require('./gen-nodejs/ThriftTest'); -var ThriftTestDriver = require('./test_driver').ThriftTestDriver; - -// createXHRConnection createWSConnection -var connection = thrift.createXHRConnection("localhost", 9090, { - transport: helpers.transports['buffered'], - protocol: helpers.protocols['json'], - path: '/test' -}); - -connection.on('error', function(err) { - assert(false, err); -}); - -// Uncomment the following line to start a websockets connection -// connection.open(); - -// createWSClient createXHRClient -var client = thrift.createXHRClient(ThriftTest, connection); - -ThriftTestDriver(client, function (status) { - console.log('Browser:', status); -}); diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/test/client.js b/vendor/git.apache.org/thrift.git/lib/nodejs/test/client.js index a38a66b..49e3a5e 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/test/client.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/test/client.js @@ -19,109 +19,149 @@ * under the License. */ -var fs = require('fs'); -var assert = require('assert'); -var thrift = require('thrift'); -var helpers = require('./helpers'); -var ThriftTest = require('./gen-nodejs/ThriftTest'); -var ThriftTestDriver = require('./test_driver').ThriftTestDriver; -var ThriftTestDriverPromise = require('./test_driver').ThriftTestDriverPromise; -var SecondService = require('./gen-nodejs/SecondService'); -var ttypes = require('./gen-nodejs/ThriftTest_types'); +const assert = require("assert"); +const thrift = require("thrift"); +const helpers = require("./helpers"); -var program = require('commander'); +const ThriftTest = require(`./${helpers.genPath}/ThriftTest`); +const ThriftTestDriver = require("./test_driver").ThriftTestDriver; +const ThriftTestDriverPromise = require("./test_driver") + .ThriftTestDriverPromise; +const SecondService = require(`./${helpers.genPath}/SecondService`); + +const program = require("commander"); program - .option('-p, --protocol ', 'Set thrift protocol (binary|json) [protocol]') - .option('-t, --transport ', 'Set thrift transport (buffered|framed) [transport]') - .option('--port ', 'Set thrift server port number to connect', 9090) - .option('--host ', 'Set thrift server host to connect', 'localhost') - .option('--ssl', 'use SSL transport') - .option('--promise', 'test with promise style functions') - .option('-t, --type ', 'Select server type (tcp|multiplex|http)', 'tcp') + .option( + "-p, --protocol ", + "Set thrift protocol (binary|compact|json) [protocol]" + ) + .option( + "-t, --transport ", + "Set thrift transport (buffered|framed|http) [transport]" + ) + .option("--port ", "Set thrift server port number to connect", 9090) + .option("--host ", "Set thrift server host to connect", "localhost") + .option( + "--domain-socket ", + "Set thrift server unix domain socket to connect" + ) + .option("--ssl", "use SSL transport") + .option("--callback", "test with callback style functions") + .option( + "-t, --type ", + "Select server type (http|multiplex|tcp|websocket)", + "tcp" + ) + .option("--es6", "Use es6 code") + .option("--es5", "Use es5 code") .parse(process.argv); -var host = program.host; -var port = program.port; -var type = program.type; -var ssl = program.ssl; -var promise = program.promise; +const host = program.host; +const port = program.port; +const domainSocket = program.domainSocket; +const ssl = program.ssl; +let type = program.type; -var options = { +/* for compatibility with cross test invocation for http transport testing */ +if (program.transport === "http") { + program.transport = "buffered"; + type = "http"; +} + +const options = { transport: helpers.transports[program.transport], protocol: helpers.protocols[program.protocol] }; -if (type === 'http' || type === 'websocket') { - options.path = '/test'; +if (type === "http" || type === "websocket") { + options.path = "/test"; } -if (type === 'http') { - options.headers = {"Connection": "close"}; +if (type === "http") { + options.headers = { Connection: "close" }; } if (ssl) { - if (type === 'tcp' || type === 'multiplex') { + if (type === "tcp" || type === "multiplex") { options.rejectUnauthorized = false; - } else if (type === 'http') { + } else if (type === "http") { options.nodeOptions = { rejectUnauthorized: false }; options.https = true; - } else if (type === 'websocket') { + } else if (type === "websocket") { options.wsOptions = { rejectUnauthorized: false }; options.secure = true; } } -var connection; -var client; -var testDriver = promise ? ThriftTestDriverPromise : ThriftTestDriver; +let connection; +let client; +const testDriver = program.callback + ? ThriftTestDriver + : ThriftTestDriverPromise; +if (helpers.ecmaMode === "es6" && program.callback) { + console.log("ES6 does not support callback style"); + process.exit(0); +} -if (type === 'tcp' || type === 'multiplex') { - connection = ssl ? - thrift.createSSLConnection(host, port, options) : - thrift.createConnection(host, port, options); -} else if (type === 'http') { - connection = thrift.createHttpConnection(host, port, options); -} else if (type === 'websocket') { +if (type === "tcp" || type === "multiplex") { + if (domainSocket) { + connection = thrift.createUDSConnection(domainSocket, options); + } else { + connection = ssl + ? thrift.createSSLConnection(host, port, options) + : thrift.createConnection(host, port, options); + } +} else if (type === "http") { + if (domainSocket) { + connection = thrift.createHttpUDSConnection(domainSocket, options); + } else { + connection = thrift.createHttpConnection(host, port, options); + } +} else if (type === "websocket") { connection = thrift.createWSConnection(host, port, options); connection.open(); } -connection.on('error', function(err) { - assert(false, err); +connection.on("error", function(err) { + assert(false, err); }); -if (type === 'tcp') { +if (type === "tcp") { client = thrift.createClient(ThriftTest, connection); runTests(); -} else if (type === 'multiplex') { - var mp = new thrift.Multiplexer(); +} else if (type === "multiplex") { + const mp = new thrift.Multiplexer(); client = mp.createClient("ThriftTest", ThriftTest, connection); - secondclient = mp.createClient("SecondService", SecondService, connection); + const secondclient = mp.createClient( + "SecondService", + SecondService, + connection + ); - connection.on('connect', function() { + connection.on("connect", function() { secondclient.secondtestString("Test", function(err, response) { assert(!err); - assert.equal("Test", response); + assert.equal('testString("Test")', response); }); runTests(); }); -} else if (type === 'http') { +} else if (type === "http") { client = thrift.createHttpClient(ThriftTest, connection); runTests(); -} else if (type === 'websocket') { +} else if (type === "websocket") { client = thrift.createWSClient(ThriftTest, connection); runTests(); } function runTests() { - testDriver(client, function (status) { + testDriver(client, function(status) { console.log(status); - if (type !== 'http' && type !== 'websocket') { + if (type !== "http" && type !== "websocket") { connection.end(); } - if (type !== 'multiplex') { + if (type !== "multiplex") { process.exit(0); } }); diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/test/deep-constructor.test.js b/vendor/git.apache.org/thrift.git/lib/nodejs/test/deep-constructor.test.js index 2caeb82..504dacf 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/test/deep-constructor.test.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/test/deep-constructor.test.js @@ -1,36 +1,52 @@ -var ttypes = require('./gen-nodejs/JsDeepConstructorTest_types'); -var thrift = require('thrift'); -var test = require('tape'); -var bufferEquals = require('buffer-equals'); +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +const ttypes = require("./gen-nodejs/JsDeepConstructorTest_types"); +const thrift = require("thrift"); +const test = require("tape"); +const bufferEquals = require("buffer-equals"); function serializeBinary(data) { - var buff; - var transport = new thrift.TBufferedTransport(null, function(msg){ + let buff; + const transport = new thrift.TBufferedTransport(null, function(msg) { buff = msg; }); - var prot = new thrift.TBinaryProtocol(transport); + const prot = new thrift.TBinaryProtocol(transport); data.write(prot); prot.flush(); return buff; - } - function deserializeBinary(serialized, type) { - var t = new thrift.TFramedTransport(serialized); - var p = new thrift.TBinaryProtocol(t); - var data = new type(); + const t = new thrift.TFramedTransport(serialized); + const p = new thrift.TBinaryProtocol(t); + const data = new type(); data.read(p); return data; } - function serializeJSON(data) { - var buff; - var transport = new thrift.TBufferedTransport(null, function(msg){ + let buff; + const transport = new thrift.TBufferedTransport(null, function(msg) { buff = msg; }); - var protocol = new thrift.TJSONProtocol(transport); + const protocol = new thrift.TJSONProtocol(transport); protocol.writeMessageBegin("", 0, 0); data.write(protocol); protocol.writeMessageEnd(); @@ -38,45 +54,41 @@ function serializeJSON(data) { return buff; } - function deserializeJSON(serialized, type) { - var transport = new thrift.TFramedTransport(serialized); - var protocol = new thrift.TJSONProtocol(transport); + const transport = new thrift.TFramedTransport(serialized); + const protocol = new thrift.TJSONProtocol(transport); protocol.readMessageBegin(); - var data = new type(); + const data = new type(); data.read(protocol); protocol.readMessageEnd(); return data; } - function createThriftObj() { - return new ttypes.Complex({ - - struct_field: new ttypes.Simple({value: 'a'}), + struct_field: new ttypes.Simple({ value: "a" }), struct_list_field: [ - new ttypes.Simple({value: 'b'}), - new ttypes.Simple({value: 'c'}), + new ttypes.Simple({ value: "b" }), + new ttypes.Simple({ value: "c" }) ], struct_set_field: [ - new ttypes.Simple({value: 'd'}), - new ttypes.Simple({value: 'e'}), + new ttypes.Simple({ value: "d" }), + new ttypes.Simple({ value: "e" }) ], struct_map_field: { - A: new ttypes.Simple({value: 'f'}), - B: new ttypes.Simple({value: 'g'}) + A: new ttypes.Simple({ value: "f" }), + B: new ttypes.Simple({ value: "g" }) }, struct_nested_containers_field: [ [ { C: [ - new ttypes.Simple({value: 'h'}), - new ttypes.Simple({value: 'i'}) + new ttypes.Simple({ value: "h" }), + new ttypes.Simple({ value: "i" }) ] } ] @@ -85,59 +97,57 @@ function createThriftObj() { struct_nested_containers_field2: { D: [ { - DA: new ttypes.Simple({value: 'j'}) + DA: new ttypes.Simple({ value: "j" }) }, { - DB: new ttypes.Simple({value: 'k'}) + DB: new ttypes.Simple({ value: "k" }) } ] }, list_of_list_field: [ - ['l00', 'l01', 'l02'], - ['l10', 'l11', 'l12'], - ['l20', 'l21', 'l22'], + ["l00", "l01", "l02"], + ["l10", "l11", "l12"], + ["l20", "l21", "l22"] ], list_of_list_of_list_field: [ - [['m000', 'm001', 'm002'], ['m010', 'm011', 'm012'], ['m020', 'm021', 'm022']], - [['m100', 'm101', 'm102'], ['m110', 'm111', 'm112'], ['m120', 'm121', 'm122']], - [['m200', 'm201', 'm202'], ['m210', 'm211', 'm212'], ['m220', 'm221', 'm222']], - ], - - + [ + ["m000", "m001", "m002"], + ["m010", "m011", "m012"], + ["m020", "m021", "m022"] + ], + [ + ["m100", "m101", "m102"], + ["m110", "m111", "m112"], + ["m120", "m121", "m122"] + ], + [ + ["m200", "m201", "m202"], + ["m210", "m211", "m212"], + ["m220", "m221", "m222"] + ] + ] }); } - function createJsObj() { - return { + struct_field: { value: "a" }, - struct_field: {value: 'a'}, + struct_list_field: [{ value: "b" }, { value: "c" }], - struct_list_field: [ - {value: 'b'}, - {value: 'c'}, - ], - - struct_set_field: [ - {value: 'd'}, - {value: 'e'}, - ], + struct_set_field: [{ value: "d" }, { value: "e" }], struct_map_field: { - A: {value: 'f'}, - B: {value: 'g'} + A: { value: "f" }, + B: { value: "g" } }, struct_nested_containers_field: [ [ { - C: [ - {value: 'h'}, - {value: 'i'} - ] + C: [{ value: "h" }, { value: "i" }] } ] ], @@ -145,131 +155,142 @@ function createJsObj() { struct_nested_containers_field2: { D: [ { - DA: {value: 'j'} + DA: { value: "j" } }, { - DB: {value: 'k'} + DB: { value: "k" } } ] }, list_of_list_field: [ - ['l00', 'l01', 'l02'], - ['l10', 'l11', 'l12'], - ['l20', 'l21', 'l22'], + ["l00", "l01", "l02"], + ["l10", "l11", "l12"], + ["l20", "l21", "l22"] ], list_of_list_of_list_field: [ - [['m000', 'm001', 'm002'], ['m010', 'm011', 'm012'], ['m020', 'm021', 'm022']], - [['m100', 'm101', 'm102'], ['m110', 'm111', 'm112'], ['m120', 'm121', 'm122']], - [['m200', 'm201', 'm202'], ['m210', 'm211', 'm212'], ['m220', 'm221', 'm222']], - ], - + [ + ["m000", "m001", "m002"], + ["m010", "m011", "m012"], + ["m020", "m021", "m022"] + ], + [ + ["m100", "m101", "m102"], + ["m110", "m111", "m112"], + ["m120", "m121", "m122"] + ], + [ + ["m200", "m201", "m202"], + ["m210", "m211", "m212"], + ["m220", "m221", "m222"] + ] + ] }; } - function assertValues(obj, assert) { - assert.equals(obj.struct_field.value, 'a'); - assert.equals(obj.struct_list_field[0].value, 'b'); - assert.equals(obj.struct_list_field[1].value, 'c'); - assert.equals(obj.struct_set_field[0].value, 'd'); - assert.equals(obj.struct_set_field[1].value, 'e'); - assert.equals(obj.struct_map_field.A.value, 'f'); - assert.equals(obj.struct_map_field.B.value, 'g'); - assert.equals(obj.struct_nested_containers_field[0][0].C[0].value, 'h'); - assert.equals(obj.struct_nested_containers_field[0][0].C[1].value, 'i'); - assert.equals(obj.struct_nested_containers_field2.D[0].DA.value, 'j'); - assert.equals(obj.struct_nested_containers_field2.D[1].DB.value, 'k'); - assert.equals(obj.list_of_list_field[0][0], 'l00'); - assert.equals(obj.list_of_list_field[0][1], 'l01'); - assert.equals(obj.list_of_list_field[0][2], 'l02'); - assert.equals(obj.list_of_list_field[1][0], 'l10'); - assert.equals(obj.list_of_list_field[1][1], 'l11'); - assert.equals(obj.list_of_list_field[1][2], 'l12'); - assert.equals(obj.list_of_list_field[2][0], 'l20'); - assert.equals(obj.list_of_list_field[2][1], 'l21'); - assert.equals(obj.list_of_list_field[2][2], 'l22'); + assert.equals(obj.struct_field.value, "a"); + assert.equals(obj.struct_list_field[0].value, "b"); + assert.equals(obj.struct_list_field[1].value, "c"); + assert.equals(obj.struct_set_field[0].value, "d"); + assert.equals(obj.struct_set_field[1].value, "e"); + assert.equals(obj.struct_map_field.A.value, "f"); + assert.equals(obj.struct_map_field.B.value, "g"); + assert.equals(obj.struct_nested_containers_field[0][0].C[0].value, "h"); + assert.equals(obj.struct_nested_containers_field[0][0].C[1].value, "i"); + assert.equals(obj.struct_nested_containers_field2.D[0].DA.value, "j"); + assert.equals(obj.struct_nested_containers_field2.D[1].DB.value, "k"); + assert.equals(obj.list_of_list_field[0][0], "l00"); + assert.equals(obj.list_of_list_field[0][1], "l01"); + assert.equals(obj.list_of_list_field[0][2], "l02"); + assert.equals(obj.list_of_list_field[1][0], "l10"); + assert.equals(obj.list_of_list_field[1][1], "l11"); + assert.equals(obj.list_of_list_field[1][2], "l12"); + assert.equals(obj.list_of_list_field[2][0], "l20"); + assert.equals(obj.list_of_list_field[2][1], "l21"); + assert.equals(obj.list_of_list_field[2][2], "l22"); - assert.equals(obj.list_of_list_of_list_field[0][0][0], 'm000'); - assert.equals(obj.list_of_list_of_list_field[0][0][1], 'm001'); - assert.equals(obj.list_of_list_of_list_field[0][0][2], 'm002'); - assert.equals(obj.list_of_list_of_list_field[0][1][0], 'm010'); - assert.equals(obj.list_of_list_of_list_field[0][1][1], 'm011'); - assert.equals(obj.list_of_list_of_list_field[0][1][2], 'm012'); - assert.equals(obj.list_of_list_of_list_field[0][2][0], 'm020'); - assert.equals(obj.list_of_list_of_list_field[0][2][1], 'm021'); - assert.equals(obj.list_of_list_of_list_field[0][2][2], 'm022'); + assert.equals(obj.list_of_list_of_list_field[0][0][0], "m000"); + assert.equals(obj.list_of_list_of_list_field[0][0][1], "m001"); + assert.equals(obj.list_of_list_of_list_field[0][0][2], "m002"); + assert.equals(obj.list_of_list_of_list_field[0][1][0], "m010"); + assert.equals(obj.list_of_list_of_list_field[0][1][1], "m011"); + assert.equals(obj.list_of_list_of_list_field[0][1][2], "m012"); + assert.equals(obj.list_of_list_of_list_field[0][2][0], "m020"); + assert.equals(obj.list_of_list_of_list_field[0][2][1], "m021"); + assert.equals(obj.list_of_list_of_list_field[0][2][2], "m022"); - assert.equals(obj.list_of_list_of_list_field[1][0][0], 'm100'); - assert.equals(obj.list_of_list_of_list_field[1][0][1], 'm101'); - assert.equals(obj.list_of_list_of_list_field[1][0][2], 'm102'); - assert.equals(obj.list_of_list_of_list_field[1][1][0], 'm110'); - assert.equals(obj.list_of_list_of_list_field[1][1][1], 'm111'); - assert.equals(obj.list_of_list_of_list_field[1][1][2], 'm112'); - assert.equals(obj.list_of_list_of_list_field[1][2][0], 'm120'); - assert.equals(obj.list_of_list_of_list_field[1][2][1], 'm121'); - assert.equals(obj.list_of_list_of_list_field[1][2][2], 'm122'); + assert.equals(obj.list_of_list_of_list_field[1][0][0], "m100"); + assert.equals(obj.list_of_list_of_list_field[1][0][1], "m101"); + assert.equals(obj.list_of_list_of_list_field[1][0][2], "m102"); + assert.equals(obj.list_of_list_of_list_field[1][1][0], "m110"); + assert.equals(obj.list_of_list_of_list_field[1][1][1], "m111"); + assert.equals(obj.list_of_list_of_list_field[1][1][2], "m112"); + assert.equals(obj.list_of_list_of_list_field[1][2][0], "m120"); + assert.equals(obj.list_of_list_of_list_field[1][2][1], "m121"); + assert.equals(obj.list_of_list_of_list_field[1][2][2], "m122"); - assert.equals(obj.list_of_list_of_list_field[2][0][0], 'm200'); - assert.equals(obj.list_of_list_of_list_field[2][0][1], 'm201'); - assert.equals(obj.list_of_list_of_list_field[2][0][2], 'm202'); - assert.equals(obj.list_of_list_of_list_field[2][1][0], 'm210'); - assert.equals(obj.list_of_list_of_list_field[2][1][1], 'm211'); - assert.equals(obj.list_of_list_of_list_field[2][1][2], 'm212'); - assert.equals(obj.list_of_list_of_list_field[2][2][0], 'm220'); - assert.equals(obj.list_of_list_of_list_field[2][2][1], 'm221'); - assert.equals(obj.list_of_list_of_list_field[2][2][2], 'm222'); + assert.equals(obj.list_of_list_of_list_field[2][0][0], "m200"); + assert.equals(obj.list_of_list_of_list_field[2][0][1], "m201"); + assert.equals(obj.list_of_list_of_list_field[2][0][2], "m202"); + assert.equals(obj.list_of_list_of_list_field[2][1][0], "m210"); + assert.equals(obj.list_of_list_of_list_field[2][1][1], "m211"); + assert.equals(obj.list_of_list_of_list_field[2][1][2], "m212"); + assert.equals(obj.list_of_list_of_list_field[2][2][0], "m220"); + assert.equals(obj.list_of_list_of_list_field[2][2][1], "m221"); + assert.equals(obj.list_of_list_of_list_field[2][2][2], "m222"); } function createTestCases(serialize, deserialize) { - - var cases = { - - "Serialize/deserialize should return equal object": function(assert){ - var tObj = createThriftObj(); - var received = deserialize(serialize(tObj), ttypes.Complex); - assert.ok(tObj !== received, 'not the same object'); + const cases = { + "Serialize/deserialize should return equal object": function(assert) { + const tObj = createThriftObj(); + const received = deserialize(serialize(tObj), ttypes.Complex); + assert.ok(tObj !== received, "not the same object"); assert.deepEqual(tObj, received); assert.end(); }, - "Nested structs and containers initialized from plain js objects should serialize same as if initialized from thrift objects": function(assert) { - var tObj1 = createThriftObj(); - var tObj2 = new ttypes.Complex(createJsObj()); + "Nested structs and containers initialized from plain js objects should serialize same as if initialized from thrift objects": function( + assert + ) { + const tObj1 = createThriftObj(); + const tObj2 = new ttypes.Complex(createJsObj()); assertValues(tObj2, assert); - var s1 = serialize(tObj1); - var s2 = serialize(tObj2); + const s1 = serialize(tObj1); + const s2 = serialize(tObj2); assert.ok(bufferEquals(s1, s2)); assert.end(); }, - "Modifications to args object should not affect constructed Thrift object": function (assert) { - - var args = createJsObj(); + "Modifications to args object should not affect constructed Thrift object": function( + assert + ) { + const args = createJsObj(); assertValues(args, assert); - var tObj = new ttypes.Complex(args); + const tObj = new ttypes.Complex(args); assertValues(tObj, assert); - args.struct_field.value = 'ZZZ'; - args.struct_list_field[0].value = 'ZZZ'; - args.struct_list_field[1].value = 'ZZZ'; - args.struct_set_field[0].value = 'ZZZ'; - args.struct_set_field[1].value = 'ZZZ'; - args.struct_map_field.A.value = 'ZZZ'; - args.struct_map_field.B.value = 'ZZZ'; - args.struct_nested_containers_field[0][0].C[0] = 'ZZZ'; - args.struct_nested_containers_field[0][0].C[1] = 'ZZZ'; - args.struct_nested_containers_field2.D[0].DA = 'ZZZ'; - args.struct_nested_containers_field2.D[0].DB = 'ZZZ'; + args.struct_field.value = "ZZZ"; + args.struct_list_field[0].value = "ZZZ"; + args.struct_list_field[1].value = "ZZZ"; + args.struct_set_field[0].value = "ZZZ"; + args.struct_set_field[1].value = "ZZZ"; + args.struct_map_field.A.value = "ZZZ"; + args.struct_map_field.B.value = "ZZZ"; + args.struct_nested_containers_field[0][0].C[0] = "ZZZ"; + args.struct_nested_containers_field[0][0].C[1] = "ZZZ"; + args.struct_nested_containers_field2.D[0].DA = "ZZZ"; + args.struct_nested_containers_field2.D[0].DB = "ZZZ"; assertValues(tObj, assert); assert.end(); }, "nulls are ok": function(assert) { - var tObj = new ttypes.Complex({ + const tObj = new ttypes.Complex({ struct_field: null, struct_list_field: null, struct_set_field: null, @@ -277,7 +298,7 @@ function createTestCases(serialize, deserialize) { struct_nested_containers_field: null, struct_nested_containers_field2: null }); - var received = deserialize(serialize(tObj), ttypes.Complex); + const received = deserialize(serialize(tObj), ttypes.Complex); assert.strictEqual(tObj.struct_field, null); assert.ok(tObj !== received); assert.deepEqual(tObj, received); @@ -285,11 +306,11 @@ function createTestCases(serialize, deserialize) { }, "Can make list with objects": function(assert) { - var tObj = new ttypes.ComplexList({ - "struct_list_field": [new ttypes.Complex({})] + const tObj = new ttypes.ComplexList({ + struct_list_field: [new ttypes.Complex({})] }); - var innerObj = tObj.struct_list_field[0]; - assert.ok(innerObj instanceof ttypes.Complex) + const innerObj = tObj.struct_list_field[0]; + assert.ok(innerObj instanceof ttypes.Complex); assert.strictEqual(innerObj.struct_field, null); assert.strictEqual(innerObj.struct_list_field, null); assert.strictEqual(innerObj.struct_set_field, null); @@ -298,17 +319,15 @@ function createTestCases(serialize, deserialize) { assert.strictEqual(innerObj.struct_nested_containers_field2, null); assert.end(); } - }; return cases; } - -function run(name, cases){ +function run(name, cases) { Object.keys(cases).forEach(function(caseName) { - test(name + ': ' + caseName, cases[caseName]); + test(name + ": " + caseName, cases[caseName]); }); } -run('binary', createTestCases(serializeBinary, deserializeBinary)); -run('json', createTestCases(serializeJSON, deserializeJSON)); +run("binary", createTestCases(serializeBinary, deserializeBinary)); +run("json", createTestCases(serializeJSON, deserializeJSON)); diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/test/exceptions.js b/vendor/git.apache.org/thrift.git/lib/nodejs/test/exceptions.js index c6f2e4d..ab2798a 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/test/exceptions.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/test/exceptions.js @@ -1,55 +1,146 @@ -'use strict'; -var test = require('tape'); -var thrift = require('../lib/thrift/thrift.js'); -var InputBufferUnderrunError = require('../lib/thrift/input_buffer_underrun_error'); +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ -test('TApplicationException', function t(assert) { - var e = new thrift.TApplicationException(1, 'foo'); - assert.ok(e instanceof thrift.TApplicationException, 'is instanceof TApplicationException'); - assert.ok(e instanceof thrift.TException, 'is instanceof TException'); - assert.ok(e instanceof Error, 'is instanceof Error'); - assert.equal(typeof e.stack, 'string', 'has stack trace'); - assert.ok(/^TApplicationException: foo/.test(e.stack), 'Stack trace has correct error name and message'); - assert.ok(e.stack.indexOf('test/exceptions.js:7:11') !== -1, 'stack trace starts on correct line and column'); - assert.equal(e.name, 'TApplicationException', 'has function name TApplicationException'); - assert.equal(e.message, 'foo', 'has error message "foo"'); - assert.equal(e.type, 1, 'has type 1'); +"use strict"; +const test = require("tape"); +const thrift = require("../lib/thrift/thrift.js"); +const InputBufferUnderrunError = require("../lib/thrift/input_buffer_underrun_error"); + +test("TApplicationException", function t(assert) { + const e = new thrift.TApplicationException(1, "foo"); + assert.ok( + e instanceof thrift.TApplicationException, + "is instanceof TApplicationException" + ); + assert.ok(e instanceof thrift.TException, "is instanceof TException"); + assert.ok(e instanceof Error, "is instanceof Error"); + assert.equal(typeof e.stack, "string", "has stack trace"); + assert.ok( + /^TApplicationException: foo/.test(e.stack), + "Stack trace has correct error name and message" + ); + assert.ok( + e.stack.indexOf("test/exceptions.js:7:11") !== -1, + "stack trace starts on correct line and column" + ); + assert.equal( + e.name, + "TApplicationException", + "has function name TApplicationException" + ); + assert.equal(e.message, "foo", 'has error message "foo"'); + assert.equal(e.type, 1, "has type 1"); assert.end(); }); -test('TException', function t(assert) { - var e = new thrift.TException('foo'); - assert.ok(e instanceof thrift.TException, 'is instanceof TException'); - assert.ok(e instanceof Error, 'is instanceof Error'); - assert.equal(typeof e.stack, 'string', 'has stack trace'); - assert.ok(/^TException: foo/.test(e.stack), 'Stack trace has correct error name and message'); - assert.ok(e.stack.indexOf('test/exceptions.js:21:11') !== -1, 'stack trace starts on correct line and column'); - assert.equal(e.name, 'TException', 'has function name TException'); - assert.equal(e.message, 'foo', 'has error message "foo"'); +test("unexpected TApplicationException ", function t(assert) { + const e = new thrift.TApplicationException(1, 100); + assert.ok( + e instanceof thrift.TApplicationException, + "is instanceof TApplicationException" + ); + assert.ok(e instanceof thrift.TException, "is instanceof TException"); + assert.ok(e instanceof Error, "is instanceof Error"); + assert.equal(typeof e.stack, "string", "has stack trace"); + assert.ok( + /^TApplicationException: 100/.test(e.stack), + "Stack trace has correct error name and message" + ); + assert.ok( + e.stack.indexOf("test/exceptions.js:7:11") !== -1, + "stack trace starts on correct line and column" + ); + assert.equal( + e.name, + "TApplicationException", + "has function name TApplicationException" + ); + assert.equal(e.message, 100, "has error message 100"); + assert.equal(e.type, 1, "has type 1"); assert.end(); }); -test('TProtocolException', function t(assert) { - var e = new thrift.TProtocolException(1, 'foo'); - assert.ok(e instanceof thrift.TProtocolException, 'is instanceof TProtocolException'); - assert.ok(e instanceof Error, 'is instanceof Error'); - assert.equal(typeof e.stack, 'string', 'has stack trace'); - assert.ok(/^TProtocolException: foo/.test(e.stack), 'Stack trace has correct error name and message'); - assert.ok(e.stack.indexOf('test/exceptions.js:33:11') !== -1, 'stack trace starts on correct line and column'); - assert.equal(e.name, 'TProtocolException', 'has function name TProtocolException'); - assert.equal(e.message, 'foo', 'has error message "foo"'); - assert.equal(e.type, 1, 'has type 1'); +test("TException", function t(assert) { + const e = new thrift.TException("foo"); + assert.ok(e instanceof thrift.TException, "is instanceof TException"); + assert.ok(e instanceof Error, "is instanceof Error"); + assert.equal(typeof e.stack, "string", "has stack trace"); + assert.ok( + /^TException: foo/.test(e.stack), + "Stack trace has correct error name and message" + ); + assert.ok( + e.stack.indexOf("test/exceptions.js:21:11") !== -1, + "stack trace starts on correct line and column" + ); + assert.equal(e.name, "TException", "has function name TException"); + assert.equal(e.message, "foo", 'has error message "foo"'); assert.end(); }); -test('InputBufferUnderrunError', function t(assert) { - var e = new InputBufferUnderrunError('foo'); - assert.ok(e instanceof InputBufferUnderrunError, 'is instanceof InputBufferUnderrunError'); - assert.ok(e instanceof Error, 'is instanceof Error'); - assert.equal(typeof e.stack, 'string', 'has stack trace'); - assert.ok(/^InputBufferUnderrunError: foo/.test(e.stack), 'Stack trace has correct error name and message'); - assert.ok(e.stack.indexOf('test/exceptions.js:46:11') !== -1, 'stack trace starts on correct line and column'); - assert.equal(e.name, 'InputBufferUnderrunError', 'has function name InputBufferUnderrunError'); - assert.equal(e.message, 'foo', 'has error message "foo"'); +test("TProtocolException", function t(assert) { + const e = new thrift.TProtocolException(1, "foo"); + assert.ok( + e instanceof thrift.TProtocolException, + "is instanceof TProtocolException" + ); + assert.ok(e instanceof Error, "is instanceof Error"); + assert.equal(typeof e.stack, "string", "has stack trace"); + assert.ok( + /^TProtocolException: foo/.test(e.stack), + "Stack trace has correct error name and message" + ); + assert.ok( + e.stack.indexOf("test/exceptions.js:33:11") !== -1, + "stack trace starts on correct line and column" + ); + assert.equal( + e.name, + "TProtocolException", + "has function name TProtocolException" + ); + assert.equal(e.message, "foo", 'has error message "foo"'); + assert.equal(e.type, 1, "has type 1"); + assert.end(); +}); + +test("InputBufferUnderrunError", function t(assert) { + const e = new InputBufferUnderrunError("foo"); + assert.ok( + e instanceof InputBufferUnderrunError, + "is instanceof InputBufferUnderrunError" + ); + assert.ok(e instanceof Error, "is instanceof Error"); + assert.equal(typeof e.stack, "string", "has stack trace"); + assert.ok( + /^InputBufferUnderrunError: foo/.test(e.stack), + "Stack trace has correct error name and message" + ); + assert.ok( + e.stack.indexOf("test/exceptions.js:46:11") !== -1, + "stack trace starts on correct line and column" + ); + assert.equal( + e.name, + "InputBufferUnderrunError", + "has function name InputBufferUnderrunError" + ); + assert.equal(e.message, "foo", 'has error message "foo"'); assert.end(); }); diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/test/helpers.js b/vendor/git.apache.org/thrift.git/lib/nodejs/test/helpers.js index c850c46..72d128d 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/test/helpers.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/test/helpers.js @@ -1,13 +1,37 @@ -'use strict'; -var thrift = require('../lib/thrift'); +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +"use strict"; +const thrift = require("../lib/thrift"); module.exports.transports = { - 'buffered': thrift.TBufferedTransport, - 'framed': thrift.TFramedTransport + buffered: thrift.TBufferedTransport, + framed: thrift.TFramedTransport }; module.exports.protocols = { - 'json': thrift.TJSONProtocol, - 'binary': thrift.TBinaryProtocol, - 'compact': thrift.TCompactProtocol + json: thrift.TJSONProtocol, + binary: thrift.TBinaryProtocol, + compact: thrift.TCompactProtocol }; + +module.exports.ecmaMode = process.argv.includes("--es6") ? "es6" : "es5"; +module.exports.genPath = process.argv.includes("--es6") + ? "gen-nodejs-es6" + : "gen-nodejs"; diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/test/server.js b/vendor/git.apache.org/thrift.git/lib/nodejs/test/server.js index 6e5cdfa..7402094 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/test/server.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/test/server.js @@ -19,83 +19,119 @@ * under the License. */ -var fs = require('fs'); -var path = require('path'); -var thrift = require('../lib/thrift'); -var program = require('commander'); -var helpers = require('./helpers'); - -var ThriftTest = require('./gen-nodejs/ThriftTest'); -var SecondService = require('./gen-nodejs/SecondService'); -var ThriftTestHandler = require('./test_handler').AsyncThriftTestHandler; -var ThriftTestHandlerPromise = require('./test_handler').SyncThriftTestHandler; -var ttypes = require('./gen-nodejs/ThriftTest_types'); +const fs = require("fs"); +const path = require("path"); +const thrift = require("../lib/thrift"); +const program = require("commander"); +const helpers = require("./helpers"); program - .option('-p, --protocol ', 'Set thrift protocol (binary|json|compact)', 'binary') - .option('-t, --transport ', 'Set thrift transport (buffered|framed)', 'buffered') - .option('--ssl', 'use ssl transport') - .option('--port ', 'Set thrift server port', 9090) - .option('--promise', 'test with promise style functions') - .option('-t, --type ', 'Select server type (tcp|multiplex|http)', 'tcp') + .option( + "-p, --protocol ", + "Set thrift protocol (binary|compact|json)", + "binary" + ) + .option( + "-t, --transport ", + "Set thrift transport (buffered|framed|http)", + "buffered" + ) + .option("--ssl", "use ssl transport") + .option("--port ", "Set thrift server port", 9090) + .option("--domain-socket ", "Set thift server unix domain socket") + .option( + "-t, --type ", + "Select server type (http|multiplex|tcp|websocket)", + "tcp" + ) + .option("--callback", "test with callback style functions") + .option("--es6", "Use es6 code") + .option("--es5", "Use es5 code") .parse(process.argv); -var port = program.port; -var type = program.type; -var ssl = program.ssl; -var promise = program.promise; +const ThriftTest = require(`./${helpers.genPath}/ThriftTest`); +const SecondService = require(`./${helpers.genPath}/SecondService`); +const { ThriftTestHandler } = require("./test_handler"); -var handler = program.promise ? ThriftTestHandler : ThriftTestHandlerPromise; +const port = program.port; +const domainSocket = program.domainSocket; +const ssl = program.ssl; -var options = { +let type = program.type; +if (program.transport === "http") { + program.transport = "buffered"; + type = "http"; +} + +let options = { transport: helpers.transports[program.transport], protocol: helpers.protocols[program.protocol] }; -if (type === 'http' || type ==='websocket') { - options.handler = handler; +if (type === "http" || type === "websocket") { + options.handler = ThriftTestHandler; options.processor = ThriftTest; options = { services: { "/test": options }, cors: { - '*': true + "*": true } - } + }; } -if (type === 'multiplex') { - var SecondServiceHandler = { +let processor; +if (type === "multiplex") { + const SecondServiceHandler = { secondtestString: function(thing, result) { - console.log('testString(\'' + thing + '\')'); - result(null, thing); + console.log('testString("' + thing + '")'); + result(null, 'testString("' + thing + '")'); } }; - var processor = new thrift.MultiplexedProcessor(); + processor = new thrift.MultiplexedProcessor(); - processor.registerProcessor("ThriftTest", - new ThriftTest.Processor(ThriftTestHandler)); - - processor.registerProcessor("SecondService", - new SecondService.Processor(SecondServiceHandler)); + processor.registerProcessor( + "ThriftTest", + new ThriftTest.Processor(ThriftTestHandler) + ); + processor.registerProcessor( + "SecondService", + new SecondService.Processor(SecondServiceHandler) + ); } if (ssl) { - options.tls = { - key: fs.readFileSync(path.resolve(__dirname, 'server.key')), - cert: fs.readFileSync(path.resolve(__dirname, 'server.crt')) - }; + if ( + type === "tcp" || + type === "multiplex" || + type === "http" || + type === "websocket" + ) { + options.tls = { + key: fs.readFileSync(path.resolve(__dirname, "server.key")), + cert: fs.readFileSync(path.resolve(__dirname, "server.crt")) + }; + } } -var server; -if (type === 'tcp') { - server = thrift.createServer(ThriftTest, handler, options); -} else if (type === 'multiplex') { +let server; +if (type === "tcp") { + server = thrift.createServer(ThriftTest, ThriftTestHandler, options); +} else if (type === "multiplex") { server = thrift.createMultiplexServer(processor, options); -} else if (type === 'http' || type === 'websocket') { +} else if (type === "http" || type === "websocket") { server = thrift.createWebServer(options); } -server.listen(port); +if (domainSocket) { + server.listen(domainSocket); +} else if ( + type === "tcp" || + type === "multiplex" || + type === "http" || + type === "websocket" +) { + server.listen(port); +} diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/test/test-cases.js b/vendor/git.apache.org/thrift.git/lib/nodejs/test/test-cases.js index 13722be..02c566f 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/test/test-cases.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/test/test-cases.js @@ -1,136 +1,172 @@ -'use strict'; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ -var ttypes = require('./gen-nodejs/ThriftTest_types'); -var Int64 = require('node-int64'); +"use strict"; + +const helpers = require("./helpers"); +const ttypes = require(`./${helpers.genPath}/ThriftTest_types`); +const Int64 = require("node-int64"); //all Languages in UTF-8 /*jshint -W100 */ -var stringTest = module.exports.stringTest = "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, " + - "Asturianu, Aymar aru, AzÉ™rbaycan, Башҡорт, Boarisch, ŽemaitÄ—Å¡ka, " + - "БеларуÑкаÑ, БеларуÑÐºÐ°Ñ (тарашкевіца), БългарÑки, Bamanankan, " + - "বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Ðохчийн, " + - "Cebuano, á£áŽ³áŽ©, ÄŒesky, СловѣÌньÑкъ / ⰔⰎⰑⰂⰡâ°â° â°”â°â°Ÿ, Чӑвашла, Cymraeg, " + - "Dansk, Zazaki, Þ‹Þ¨ÞˆÞ¬Þ€Þ¨Þ„Þ¦ÞÞ°, Ελληνικά, Emiliàn e rumagnòl, English, " + - "Esperanto, Español, Eesti, Euskara, ÙØ§Ø±Ø³ÛŒ, Suomi, Võro, Føroyskt, " + - "Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, " + - "Avañe'ẽ, ગà«àªœàª°àª¾àª¤à«€, Gaelg, עברית, हिनà¥à¤¦à¥€, Fiji Hindi, Hrvatski, " + - "Kreyòl ayisyen, Magyar, Õ€Õ¡ÕµÕ¥Ö€Õ¥Õ¶, Interlingua, Bahasa Indonesia, " + - "Ilokano, Ido, Ãslenska, Italiano, 日本語, Lojban, Basa Jawa, " + - "ქáƒáƒ áƒ—ული, Kongo, Kalaallisut, ಕನà³à²¨à²¡, 한국어, Къарачай-Малкъар, " + - "Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, " + - "Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, LatvieÅ¡u, Basa " + - "Banyumasan, Malagasy, МакедонÑки, മലയാളം, मराठी, Ù…Ø§Ø²ÙØ±ÙˆÙ†ÛŒ, Bahasa " + - "Melayu, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, ‪" + - "Norsk (nynorsk)‬, ‪Norsk (bokmÃ¥l)‬, Nouormand, Diné bizaad, " + - "Occitan, Иронау, Papiamentu, Deitsch, Polski, پنجابی, پښتو, " + - "Norfuk / Pitkern, Português, Runa Simi, Rumantsch, Romani, Română, " + - "РуÑÑкий, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple " + - "English, SlovenÄina, SlovenÅ¡Äina, СрпÑки / Srpski, Seeltersk, " + - "Svenska, Kiswahili, தமிழà¯, తెలà±à°—à±, Тоҷикӣ, ไทย, Türkmençe, Tagalog, " + - "Türkçe, Татарча/Tatarça, УкраїнÑька, اردو, Tiếng Việt, Volapük, " + - "Walon, Winaray, å´è¯­, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, " + - "Bân-lâm-gú, 粵語"; +const stringTest = (module.exports.stringTest = + "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, " + + "Asturianu, Aymar aru, AzÉ™rbaycan, Башҡорт, Boarisch, ŽemaitÄ—Å¡ka, " + + "БеларуÑкаÑ, БеларуÑÐºÐ°Ñ (тарашкевіца), БългарÑки, Bamanankan, " + + "বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Ðохчийн, " + + "Cebuano, á£áŽ³áŽ©, ÄŒesky, СловѣÌньÑкъ / ⰔⰎⰑⰂⰡâ°â° â°”â°â°Ÿ, Чӑвашла, Cymraeg, " + + "Dansk, Zazaki, Þ‹Þ¨ÞˆÞ¬Þ€Þ¨Þ„Þ¦ÞÞ°, Ελληνικά, Emiliàn e rumagnòl, English, " + + "Esperanto, Español, Eesti, Euskara, ÙØ§Ø±Ø³ÛŒ, Suomi, Võro, Føroyskt, " + + "Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, " + + "Avañe'ẽ, ગà«àªœàª°àª¾àª¤à«€, Gaelg, עברית, हिनà¥à¤¦à¥€, Fiji Hindi, Hrvatski, " + + "Kreyòl ayisyen, Magyar, Õ€Õ¡ÕµÕ¥Ö€Õ¥Õ¶, Interlingua, Bahasa Indonesia, " + + "Ilokano, Ido, Ãslenska, Italiano, 日本語, Lojban, Basa Jawa, " + + "ქáƒáƒ áƒ—ული, Kongo, Kalaallisut, ಕನà³à²¨à²¡, 한국어, Къарачай-Малкъар, " + + "Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, " + + "Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, LatvieÅ¡u, Basa " + + "Banyumasan, Malagasy, МакедонÑки, മലയാളം, मराठी, Ù…Ø§Ø²ÙØ±ÙˆÙ†ÛŒ, Bahasa " + + "Melayu, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, ‪" + + "Norsk (nynorsk)‬, ‪Norsk (bokmÃ¥l)‬, Nouormand, Diné bizaad, " + + "Occitan, Иронау, Papiamentu, Deitsch, Polski, پنجابی, پښتو, " + + "Norfuk / Pitkern, Português, Runa Simi, Rumantsch, Romani, Română, " + + "РуÑÑкий, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple " + + "English, SlovenÄina, SlovenÅ¡Äina, СрпÑки / Srpski, Seeltersk, " + + "Svenska, Kiswahili, தமிழà¯, తెలà±à°—à±, Тоҷикӣ, ไทย, Türkmençe, Tagalog, " + + "Türkçe, Татарча/Tatarça, УкраїнÑька, اردو, Tiếng Việt, Volapük, " + + "Walon, Winaray, å´è¯­, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, " + + "Bân-lâm-gú, 粵語"); /*jshint +W100 */ -var specialCharacters = module.exports.specialCharacters = 'quote: \" backslash:' + - ' forwardslash-escaped: \/ ' + - ' backspace: \b formfeed: \f newline: \n return: \r tab: ' + - ' now-all-of-them-together: "\\\/\b\n\r\t' + - ' now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><' + - ' char-to-test-json-parsing: ]] \"]] \\" }}}{ [[[ '; +const specialCharacters = (module.exports.specialCharacters = + 'quote: " backslash:' + + " forwardslash-escaped: / " + + " backspace: \b formfeed: \f newline: \n return: \r tab: " + + ' now-all-of-them-together: "\\/\b\n\r\t' + + " now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><" + + ' char-to-test-json-parsing: ]] "]] \\" }}}{ [[[ '); -var mapTestInput = module.exports.mapTestInput = { - "a":"123", "a b":"with spaces ", "same":"same", "0":"numeric key", - "longValue":stringTest, stringTest:"long key" -}; +const mapTestInput = (module.exports.mapTestInput = { + a: "123", + "a b": "with spaces ", + same: "same", + "0": "numeric key", + longValue: stringTest, + stringTest: "long key" +}); -var simple = [ - ['testVoid', undefined], - ['testString', 'Test'], - ['testString', ''], - ['testString', stringTest], - ['testString', specialCharacters], - ['testBool', true], - ['testBool', false], - ['testByte', 1], - ['testByte', 0], - ['testByte', -1], - ['testByte', -127], - ['testI32', -1], - ['testDouble', -5.2098523], - ['testDouble', 7.012052175215044], - ['testEnum', ttypes.Numberz.ONE], - ['testI64', 5], - ['testI64', -5], - ['testI64', 734359738368], - ['testI64', -734359738368], - ['testI64', new Int64(new Buffer([0, 0x20, 0, 0, 0, 0, 0, 1]))], // 2^53+1 - ['testI64', new Int64( - new Buffer([0xff, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]))], // -2^53-1 - ['testTypedef', 69] -] +const simple = [ + ["testVoid", undefined], + ["testString", "Test"], + ["testString", ""], + ["testString", stringTest], + ["testString", specialCharacters], + ["testBool", true], + ["testBool", false], + ["testByte", 1], + ["testByte", 0], + ["testByte", -1], + ["testByte", -127], + ["testI32", -1], + ["testDouble", -5.2098523], + ["testDouble", 7.012052175215044], + ["testEnum", ttypes.Numberz.ONE], + ["testI64", 5], + ["testI64", -5], + ["testI64", 734359738368], + ["testI64", -734359738368], + ["testI64", new Int64(new Buffer([0, 0x20, 0, 0, 0, 0, 0, 1]))], // 2^53+1 + [ + "testI64", + new Int64(new Buffer([0xff, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff])) + ], // -2^53-1 + ["testTypedef", 69] +]; -var mapout = {}; -for (var i = 0; i < 5; ++i) { - mapout[i] = i-10; +const mapout = {}; +for (let i = 0; i < 5; ++i) { + mapout[i] = i - 10; } -var deep = [ - ['testList', [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]], +const deep = [ + [ + "testList", + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] + ] ]; -var deepUnordered = [ - ['testMap', mapout], - ['testSet', [1,2,3]], - ['testStringMap', mapTestInput] +const deepUnordered = [ + ["testMap", mapout], + ["testSet", [1, 2, 3]], + ["testStringMap", mapTestInput] ]; -var out = new ttypes.Xtruct({ - string_thing: 'Zero', +const out = new ttypes.Xtruct({ + string_thing: "Zero", byte_thing: 1, i32_thing: -3, i64_thing: 1000000 }); -var out2 = new ttypes.Xtruct2(); +const out2 = new ttypes.Xtruct2(); out2.byte_thing = 1; out2.struct_thing = out; out2.i32_thing = 5; -var crazy = new ttypes.Insanity({ - "userMap":{ "5":5, "8":8 }, - "xtructs":[new ttypes.Xtruct({ - "string_thing":"Goodbye4", - "byte_thing":4, - "i32_thing":4, - "i64_thing":4 - }), new ttypes.Xtruct({ - "string_thing":"Hello2", - "byte_thing":2, - "i32_thing":2, - "i64_thing":2 - })] +const crazy = new ttypes.Insanity({ + userMap: { "5": 5, "8": 8 }, + xtructs: [ + new ttypes.Xtruct({ + string_thing: "Goodbye4", + byte_thing: 4, + i32_thing: 4, + i64_thing: 4 + }), + new ttypes.Xtruct({ + string_thing: "Hello2", + byte_thing: 2, + i32_thing: 2, + i64_thing: 2 + }) + ] }); -var crazy2 = new ttypes.Insanity({ - "userMap":{ "5":5, "8":8 }, - "xtructs":[{ - "string_thing":"Goodbye4", - "byte_thing":4, - "i32_thing":4, - "i64_thing":4 - }, { - "string_thing":"Hello2", - "byte_thing":2, - "i32_thing":2, - "i64_thing":2 - }] +const crazy2 = new ttypes.Insanity({ + userMap: { "5": 5, "8": 8 }, + xtructs: [ + { + string_thing: "Goodbye4", + byte_thing: 4, + i32_thing: 4, + i64_thing: 4 + }, + { + string_thing: "Hello2", + byte_thing: 2, + i32_thing: 2, + i64_thing: 2 + } + ] }); - -var insanity = { - "1":{ "2": crazy, "3": crazy }, - "2":{ "6":{ "userMap":{}, "xtructs":[] } } +const insanity = { + "1": { "2": crazy, "3": crazy }, + "2": { "6": { userMap: {}, xtructs: [] } } }; module.exports.simple = simple; diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/test/testAll.sh b/vendor/git.apache.org/thrift.git/lib/nodejs/test/testAll.sh index 38b284a..24f1f2e 100755 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/test/testAll.sh +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/test/testAll.sh @@ -24,7 +24,6 @@ fi DIR="$( cd "$( dirname "$0" )" && pwd )" ISTANBUL="$DIR/../../../node_modules/istanbul/lib/cli.js" -RUNBROWSER="$DIR/../../../node_modules/run-browser/bin/cli.js" REPORT_PREFIX="${DIR}/../coverage/report" @@ -34,37 +33,27 @@ export NODE_PATH="${DIR}:${DIR}/../lib:${NODE_PATH}" testServer() { - echo " Testing $1 Client/Server with protocol $2 and transport $3 $4"; + echo " [ECMA $1] Testing $2 Client/Server with protocol $3 and transport $4 $5"; RET=0 if [ -n "${COVER}" ]; then - ${ISTANBUL} cover ${DIR}/server.js --dir ${REPORT_PREFIX}${COUNT} --handle-sigint -- --type $1 -p $2 -t $3 $4 & + ${ISTANBUL} cover ${DIR}/server.js --dir ${REPORT_PREFIX}${COUNT} --handle-sigint -- --type $2 -p $3 -t $4 $5 & COUNT=$((COUNT+1)) else - node ${DIR}/server.js --type $1 -p $2 -t $3 $4 & + node ${DIR}/server.js --${1} --type $2 -p $3 -t $4 $5 & fi SERVERPID=$! - sleep 1 + sleep 0.1 if [ -n "${COVER}" ]; then - ${ISTANBUL} cover ${DIR}/client.js --dir ${REPORT_PREFIX}${COUNT} -- --type $1 -p $2 -t $3 $4 || RET=1 + ${ISTANBUL} cover ${DIR}/client.js --dir ${REPORT_PREFIX}${COUNT} -- --${1} --type $2 -p $3 -t $4 $5 || RET=1 COUNT=$((COUNT+1)) else - node ${DIR}/client.js --type $1 -p $2 -t $3 $4 || RET=1 + node ${DIR}/client.js --${1} --type $2 -p $3 -t $4 $5 || RET=1 fi kill -2 $SERVERPID || RET=1 + wait $SERVERPID return $RET } -testBrowser() -{ - echo " Testing browser client with http server with json protocol and buffered transport"; - RET=0 - node ${DIR}/server.js --type http -p json -t buffered & - SERVERPID=$! - sleep 1 - ${RUNBROWSER} ${DIR}/browser_client.js --phantom || RET=1 - kill -2 $SERVERPID || RET=1 - return $RET -} TESTOK=0 @@ -72,6 +61,9 @@ TESTOK=0 ${DIR}/../../../compiler/cpp/thrift -o ${DIR} --gen js:node ${DIR}/../../../test/ThriftTest.thrift ${DIR}/../../../compiler/cpp/thrift -o ${DIR} --gen js:node ${DIR}/../../../test/JsDeepConstructorTest.thrift +mkdir ${DIR}/gen-nodejs-es6 +${DIR}/../../../compiler/cpp/thrift -out ${DIR}/gen-nodejs-es6 --gen js:node,es6 ${DIR}/../../../test/ThriftTest.thrift +${DIR}/../../../compiler/cpp/thrift -out ${DIR}/gen-nodejs-es6 --gen js:node,es6 ${DIR}/../../../test/JsDeepConstructorTest.thrift #unit tests @@ -82,21 +74,20 @@ node ${DIR}/deep-constructor.test.js || TESTOK=1 for type in tcp multiplex websocket http do - for protocol in compact binary json do - for transport in buffered framed do - testServer $type $protocol $transport || TESTOK=1 - testServer $type $protocol $transport --ssl || TESTOK=1 - testServer $type $protocol $transport --promise || TESTOK=1 + for ecma_version in es5 es6 + do + testServer $ecma_version $type $protocol $transport || TESTOK=1 + testServer $ecma_version $type $protocol $transport --ssl || TESTOK=1 + testServer $ecma_version $type $protocol $transport --callback || TESTOK=1 + done done done done -# XHR only until phantomjs 2 is released. -testBrowser if [ -n "${COVER}" ]; then ${ISTANBUL} report --dir "${DIR}/../coverage" --include "${DIR}/../coverage/report*/coverage.json" lcov cobertura html diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/test/test_driver.js b/vendor/git.apache.org/thrift.git/lib/nodejs/test/test_driver.js index 03ec513..7c9a919 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/test/test_driver.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/test/test_driver.js @@ -17,247 +17,279 @@ * under the License. */ - // This is the Node.js test driver for the standard Apache Thrift - // test service. The driver invokes every function defined in the - // Thrift Test service with a representative range of parameters. - // - // The ThriftTestDriver function requires a client object - // connected to a server hosting the Thrift Test service and - // supports an optional callback function which is called with - // a status message when the test is complete. +// This is the Node.js test driver for the standard Apache Thrift +// test service. The driver invokes every function defined in the +// Thrift Test service with a representative range of parameters. +// +// The ThriftTestDriver function requires a client object +// connected to a server hosting the Thrift Test service and +// supports an optional callback function which is called with +// a status message when the test is complete. -var test = require('tape'); -//var assert = require('assert'); -var ttypes = require('./gen-nodejs/ThriftTest_types'); -var TException = require('thrift').Thrift.TException; -var Int64 = require('node-int64'); -var testCases = require('./test-cases'); +const test = require("tape"); + +const helpers = require("./helpers"); +const ttypes = require(`./${helpers.genPath}/ThriftTest_types`); +const TException = require("thrift").Thrift.TException; +const Int64 = require("node-int64"); +const testCases = require("./test-cases"); exports.ThriftTestDriver = function(client, callback) { + test( + "NodeJS Style Callback Client Tests", + { skip: helpers.ecmaMode === "es6" }, + function(assert) { + const checkRecursively = makeRecursiveCheck(assert); - test('NodeJS Style Callback Client Tests', function(assert) { - - var checkRecursively = makeRecursiveCheck(assert); - - function makeAsserter(assertionFn) { - return function(c) { - var fnName = c[0]; - var expected = c[1]; - client[fnName](expected, function(err, actual) { - assert.error(err, fnName + ': no callback error'); - assertionFn(actual, expected, fnName); - }) - }; - } - - testCases.simple.forEach(makeAsserter(function(a, e, m){ - if (a instanceof Int64) { - var e64 = e instanceof Int64 ? e : new Int64(e); - assert.deepEqual(a.buffer, e64.buffer, m); - } else { - assert.equal(a, e, m); + function makeAsserter(assertionFn) { + return function(c) { + const fnName = c[0]; + const expected = c[1]; + client[fnName](expected, function(err, actual) { + assert.error(err, fnName + ": no callback error"); + assertionFn(actual, expected, fnName); + }); + }; } - })); - testCases.deep.forEach(makeAsserter(assert.deepEqual)); - testCases.deepUnordered.forEach(makeAsserter(makeUnorderedDeepEqual(assert))); - var arr = []; - for (var i = 0; i < 256; ++i) { - arr[i] = 255 - i; - } - var buf = new Buffer(arr); - client.testBinary(buf, function(err, response) { - assert.error(err, 'testBinary: no callback error'); - assert.equal(response.length, 256, 'testBinary'); - assert.deepEqual(response, buf, 'testBinary(Buffer)'); - }); - var buf = new Buffer(arr); - client.testBinary(buf.toString('binary'), function(err, response) { - assert.error(err, 'testBinary: no callback error'); - assert.equal(response.length, 256, 'testBinary'); - assert.deepEqual(response, buf, 'testBinary(string)'); - }); + testCases.simple.forEach( + makeAsserter(function(a, e, m) { + if (a instanceof Int64) { + const e64 = e instanceof Int64 ? e : new Int64(e); + assert.deepEqual(a.buffer, e64.buffer, m); + } else { + assert.equal(a, e, m); + } + }) + ); + testCases.deep.forEach(makeAsserter(assert.deepEqual)); + testCases.deepUnordered.forEach( + makeAsserter(makeUnorderedDeepEqual(assert)) + ); - client.testMapMap(42, function(err, response) { - var expected = { - "4": {"1":1, "2":2, "3":3, "4":4}, - "-4": {"-4":-4, "-3":-3, "-2":-2, "-1":-1} - }; - assert.error(err, 'testMapMap: no callback error'); - assert.deepEqual(expected, response, 'testMapMap'); - }); - - client.testStruct(testCases.out, function(err, response) { - assert.error(err, 'testStruct: no callback error'); - checkRecursively(testCases.out, response, 'testStruct'); - }); - - client.testNest(testCases.out2, function(err, response) { - assert.error(err, 'testNest: no callback error'); - checkRecursively(testCases.out2, response, 'testNest'); - }); - - client.testInsanity(testCases.crazy, function(err, response) { - assert.error(err, 'testInsanity: no callback error'); - checkRecursively(testCases.insanity, response, 'testInsanity'); - }); - - client.testInsanity(testCases.crazy2, function(err, response) { - assert.error(err, 'testInsanity2: no callback error'); - checkRecursively(testCases.insanity, response, 'testInsanity2'); - }); - - client.testException('TException', function(err, response) { - assert.ok(err instanceof TException, 'testException: correct error type'); - assert.ok(!response, 'testException: no response'); - }); - - client.testException('Xception', function(err, response) { - assert.ok(err instanceof ttypes.Xception, 'testException: correct error type'); - assert.ok(!response, 'testException: no response'); - assert.equal(err.errorCode, 1001, 'testException: correct error code'); - assert.equal('Xception', err.message, 'testException: correct error message'); - }); - - client.testException('no Exception', function(err, response) { - assert.error(err, 'testException: no callback error'); - assert.ok(!response, 'testException: no response'); - }); - - client.testOneway(0, function(err, response) { - assert.fail('testOneway should not answer'); - }); - - checkOffByOne(function(done) { - client.testI32(-1, function(err, response) { - assert.error(err, 'checkOffByOne: no callback error'); - assert.equal(-1, response); - assert.end(); - done(); + const arr = []; + for (let i = 0; i < 256; ++i) { + arr[i] = 255 - i; + } + let buf = new Buffer(arr); + client.testBinary(buf, function(err, response) { + assert.error(err, "testBinary: no callback error"); + assert.equal(response.length, 256, "testBinary"); + assert.deepEqual(response, buf, "testBinary(Buffer)"); + }); + buf = new Buffer(arr); + client.testBinary(buf.toString("binary"), function(err, response) { + assert.error(err, "testBinary: no callback error"); + assert.equal(response.length, 256, "testBinary"); + assert.deepEqual(response, buf, "testBinary(string)"); }); - }, callback); - }); + client.testMapMap(42, function(err, response) { + const expected = { + "4": { "1": 1, "2": 2, "3": 3, "4": 4 }, + "-4": { "-4": -4, "-3": -3, "-2": -2, "-1": -1 } + }; + assert.error(err, "testMapMap: no callback error"); + assert.deepEqual(expected, response, "testMapMap"); + }); + + client.testStruct(testCases.out, function(err, response) { + assert.error(err, "testStruct: no callback error"); + checkRecursively(testCases.out, response, "testStruct"); + }); + + client.testNest(testCases.out2, function(err, response) { + assert.error(err, "testNest: no callback error"); + checkRecursively(testCases.out2, response, "testNest"); + }); + + client.testInsanity(testCases.crazy, function(err, response) { + assert.error(err, "testInsanity: no callback error"); + checkRecursively(testCases.insanity, response, "testInsanity"); + }); + + client.testInsanity(testCases.crazy2, function(err, response) { + assert.error(err, "testInsanity2: no callback error"); + checkRecursively(testCases.insanity, response, "testInsanity2"); + }); + + client.testException("TException", function(err, response) { + assert.ok( + err instanceof TException, + "testException: correct error type" + ); + assert.ok(!response, "testException: no response"); + }); + + client.testException("Xception", function(err, response) { + assert.ok( + err instanceof ttypes.Xception, + "testException: correct error type" + ); + assert.ok(!response, "testException: no response"); + assert.equal(err.errorCode, 1001, "testException: correct error code"); + assert.equal( + "Xception", + err.message, + "testException: correct error message" + ); + }); + + client.testException("no Exception", function(err, response) { + assert.error(err, "testException: no callback error"); + assert.ok(!response, "testException: no response"); + }); + + client.testOneway(0, function(err, response) { + assert.error(err, "testOneway: no callback error"); + assert.strictEqual(response, undefined, "testOneway: void response"); + }); + + checkOffByOne(function(done) { + client.testI32(-1, function(err, response) { + assert.error(err, "checkOffByOne: no callback error"); + assert.equal(-1, response); + assert.end(); + done(); + }); + }, callback); + } + ); + + // ES6 does not support callback style + if (helpers.ecmaMode === "es6") { + checkOffByOne(done => done(), callback); + } }; exports.ThriftTestDriverPromise = function(client, callback) { - - test('Q Promise Client Tests', function(assert) { - - var checkRecursively = makeRecursiveCheck(assert); - - function fail(msg) { - return function() { - assert.fail(msg); - } - } + test("Promise Client Tests", function(assert) { + const checkRecursively = makeRecursiveCheck(assert); function makeAsserter(assertionFn) { return function(c) { - var fnName = c[0]; - var expected = c[1]; + const fnName = c[0]; + const expected = c[1]; client[fnName](expected) .then(function(actual) { assertionFn(actual, expected, fnName); }) - .fail(fail('fnName')); + .catch(() => assert.fail("fnName")); }; } - testCases.simple.forEach(makeAsserter(function(a, e, m){ - if (a instanceof Int64) { - var e64 = e instanceof Int64 ? e : new Int64(e); - assert.deepEqual(a.buffer, e64.buffer, m); - } else { - assert.equal(a, e, m); - } - })); + testCases.simple.forEach( + makeAsserter(function(a, e, m) { + if (a instanceof Int64) { + const e64 = e instanceof Int64 ? e : new Int64(e); + assert.deepEqual(a.buffer, e64.buffer, m); + } else { + assert.equal(a, e, m); + } + }) + ); testCases.deep.forEach(makeAsserter(assert.deepEqual)); - testCases.deepUnordered.forEach(makeAsserter(makeUnorderedDeepEqual(assert))); + testCases.deepUnordered.forEach( + makeAsserter(makeUnorderedDeepEqual(assert)) + ); - client.testStruct(testCases.out) + client + .testStruct(testCases.out) .then(function(response) { - checkRecursively(testCases.out, response, 'testStruct'); + checkRecursively(testCases.out, response, "testStruct"); }) - .fail(fail('testStruct')); + .catch(() => assert.fail("testStruct")); - client.testNest(testCases.out2) + client + .testNest(testCases.out2) .then(function(response) { - checkRecursively(testCases.out2, response, 'testNest'); + checkRecursively(testCases.out2, response, "testNest"); }) - .fail(fail('testNest')); + .catch(() => assert.fail("testNest")); - client.testInsanity(testCases.crazy) + client + .testInsanity(testCases.crazy) .then(function(response) { - checkRecursively(testCases.insanity, response, 'testInsanity'); + checkRecursively(testCases.insanity, response, "testInsanity"); }) - .fail(fail('testInsanity')); + .catch(() => assert.fail("testInsanity")); - client.testInsanity(testCases.crazy2) + client + .testInsanity(testCases.crazy2) .then(function(response) { - checkRecursively(testCases.insanity, response, 'testInsanity2'); + checkRecursively(testCases.insanity, response, "testInsanity2"); }) - .fail(fail('testInsanity2')); + .catch(() => assert.fail("testInsanity2")); - client.testException('TException') - .then(function(response) { - fail('testException: TException'); + client + .testException("TException") + .then(function() { + assert.fail("testException: TException"); }) - .fail(function(err) { + .catch(function(err) { assert.ok(err instanceof TException); }); - client.testException('Xception') - .then(function(response) { - fail('testException: Xception'); + client + .testException("Xception") + .then(function() { + assert.fail("testException: Xception"); }) - .fail(function(err) { + .catch(function(err) { assert.ok(err instanceof ttypes.Xception); assert.equal(err.errorCode, 1001); - assert.equal('Xception', err.message); + assert.equal("Xception", err.message); }); - client.testException('no Exception') + client + .testException("no Exception") .then(function(response) { assert.equal(undefined, response); //void }) - .fail(fail('testException')); + .catch(() => assert.fail("testException")); - client.testOneway(0, fail('testOneway: should not answer')); + client + .testOneway(0) + .then(function(response) { + assert.strictEqual(response, undefined, "testOneway: void response"); + }) + .catch(() => assert.fail("testOneway: should not reject")); checkOffByOne(function(done) { - client.testI32(-1) + client + .testI32(-1) .then(function(response) { - assert.equal(-1, response); - assert.end(); - done(); + assert.equal(-1, response); + assert.end(); + done(); }) - .fail(fail('checkOffByOne')); + .catch(() => assert.fail("checkOffByOne")); }, callback); }); }; - // Helper Functions // ========================================================= function makeRecursiveCheck(assert) { - - return function (map1, map2, msg) { - var equal = true; - - var equal = checkRecursively(map1, map2); + return function(map1, map2, msg) { + const equal = checkRecursively(map1, map2); assert.ok(equal, msg); // deepEqual doesn't work with fields using node-int64 function checkRecursively(map1, map2) { - if (typeof map1 !== 'function' && typeof map2 !== 'function') { - if (!map1 || typeof map1 !== 'object') { + if (typeof map1 !== "function" && typeof map2 !== "function") { + if (!map1 || typeof map1 !== "object") { //Handle int64 types (which use node-int64 in Node.js JavaScript) - if ((typeof map1 === "number") && (typeof map2 === "object") && - (map2.buffer) && (map2.buffer instanceof Buffer) && (map2.buffer.length === 8)) { - var n = new Int64(map2.buffer); + if ( + typeof map1 === "number" && + typeof map2 === "object" && + map2.buffer && + map2.buffer instanceof Buffer && + map2.buffer.length === 8 + ) { + const n = new Int64(map2.buffer); return map1 === n.toNumber(); } else { return map1 == map2; @@ -269,15 +301,14 @@ function makeRecursiveCheck(assert) { } } } - } + }; } function checkOffByOne(done, callback) { - - var retry_limit = 30; - var retry_interval = 100; - var test_complete = false; - var retrys = 0; + const retry_limit = 30; + const retry_interval = 100; + let test_complete = false; + let retrys = 0; /** * redo a simple test after the oneway to make sure we aren't "off by one" -- @@ -294,14 +325,17 @@ function checkOffByOne(done, callback) { //We wait up to retry_limit * retry_interval for the test suite to complete function TestForCompletion() { - if(test_complete && callback) { + if (test_complete && callback) { callback("Server successfully tested!"); } else { if (++retrys < retry_limit) { setTimeout(TestForCompletion, retry_interval); } else if (callback) { - callback("Server test failed to complete after " + - (retry_limit * retry_interval / 1000) + " seconds"); + callback( + "Server test failed to complete after " + + (retry_limit * retry_interval) / 1000 + + " seconds" + ); } } } @@ -312,15 +346,15 @@ function checkOffByOne(done, callback) { function makeUnorderedDeepEqual(assert) { return function(actual, expected, name) { assert.equal(actual.length, expected.length, name); - for (var k in actual) { - var found = false; - for (var k2 in expected) { + for (const k in actual) { + let found = false; + for (const k2 in expected) { if (actual[k] === expected[k2]) { found = true; } } if (!found) { - assert.fail('Unexpected value ' + actual[k] + ' with key ' + k); + assert.fail("Unexpected value " + actual[k] + " with key " + k); } } }; diff --git a/vendor/git.apache.org/thrift.git/lib/nodejs/test/test_handler.js b/vendor/git.apache.org/thrift.git/lib/nodejs/test/test_handler.js index 5c89f7a..317a7c8 100644 --- a/vendor/git.apache.org/thrift.git/lib/nodejs/test/test_handler.js +++ b/vendor/git.apache.org/thrift.git/lib/nodejs/test/test_handler.js @@ -19,18 +19,17 @@ //This is the server side Node test handler for the standard // Apache Thrift test service. +const helpers = require("./helpers"); +const ttypes = require(`./${helpers.genPath}/ThriftTest_types`); +const TException = require("thrift").Thrift.TException; -var ttypes = require('./gen-nodejs/ThriftTest_types'); -var TException = require('thrift').Thrift.TException; - -function makeSyncHandler(label) { +function makeSyncHandler() { return function(thing) { - //console.log(label + '(\'' + thing + '\')'); return thing; - } + }; } -var syncHandlers = { +const syncHandlers = { testVoid: testVoid, testMapMap: testMapMap, testInsanity: testInsanity, @@ -44,10 +43,10 @@ function makeAsyncHandler(label) { return function(thing, result) { thing = syncHandlers[label](thing); result(null, thing); - } + }; } -var asyncHandlers = { +const asyncHandlers = { testVoid: testVoidAsync, testMulti: testMultiAsync, testException: testExceptionAsync, @@ -55,22 +54,22 @@ var asyncHandlers = { testOneway: testOnewayAsync }; -var identityHandlers = [ - 'testString', - 'testBool', - 'testByte', - 'testI32', - 'testI64', - 'testDouble', - 'testBinary', - 'testStruct', - 'testNest', - 'testMap', - 'testStringMap', - 'testSet', - 'testList', - 'testEnum', - 'testTypedef' +const identityHandlers = [ + "testString", + "testBool", + "testByte", + "testI32", + "testI64", + "testDouble", + "testBinary", + "testStruct", + "testNest", + "testMap", + "testStringMap", + "testSet", + "testList", + "testEnum", + "testTypedef" ]; function testVoid() { @@ -81,13 +80,11 @@ function testVoidAsync(result) { result(testVoid()); } -function testMapMap(hello) { - //console.log('testMapMap(' + hello + ')'); - - var mapmap = []; - var pos = []; - var neg = []; - for (var i = 1; i < 5; i++) { +function testMapMap() { + const mapmap = []; + const pos = []; + const neg = []; + for (let i = 1; i < 5; i++) { pos[i] = i; neg[-i] = -i; } @@ -102,16 +99,16 @@ function testInsanity(argument) { //console.log(argument); //console.log(')'); - var first_map = []; - var second_map = []; + const first_map = []; + const second_map = []; first_map[ttypes.Numberz.TWO] = argument; first_map[ttypes.Numberz.THREE] = argument; - var looney = new ttypes.Insanity(); + const looney = new ttypes.Insanity(); second_map[ttypes.Numberz.SIX] = looney; - var insane = []; + const insane = []; insane[1] = first_map; insane[2] = second_map; @@ -120,11 +117,11 @@ function testInsanity(argument) { return insane; } -function testMulti(arg0, arg1, arg2, arg3, arg4, arg5) { +function testMulti(arg0, arg1, arg2) { //console.log('testMulti()'); - var hello = new ttypes.Xtruct(); - hello.string_thing = 'Hello2'; + const hello = new ttypes.Xtruct(); + hello.string_thing = "Hello2"; hello.byte_thing = arg0; hello.i32_thing = arg1; hello.i64_thing = arg2; @@ -132,18 +129,18 @@ function testMulti(arg0, arg1, arg2, arg3, arg4, arg5) { } function testMultiAsync(arg0, arg1, arg2, arg3, arg4, arg5, result) { - var hello = testMulti(arg0, arg1, arg2, arg3, arg4, arg5); + const hello = testMulti(arg0, arg1, arg2, arg3, arg4, arg5); result(null, hello); } function testException(arg) { //console.log('testException('+arg+')'); - if (arg === 'Xception') { - var x = new ttypes.Xception(); + if (arg === "Xception") { + const x = new ttypes.Xception(); x.errorCode = 1001; x.message = arg; throw x; - } else if (arg === 'TException') { + } else if (arg === "TException") { throw new TException(arg); } else { return; @@ -152,12 +149,12 @@ function testException(arg) { function testExceptionAsync(arg, result) { //console.log('testException('+arg+')'); - if (arg === 'Xception') { - var x = new ttypes.Xception(); + if (arg === "Xception") { + const x = new ttypes.Xception(); x.errorCode = 1001; x.message = arg; result(x); - } else if (arg === 'TException') { + } else if (arg === "TException") { result(new TException(arg)); } else { result(null); @@ -166,49 +163,48 @@ function testExceptionAsync(arg, result) { function testMultiException(arg0, arg1) { //console.log('testMultiException(' + arg0 + ', ' + arg1 + ')'); - if (arg0 === ('Xception')) { - var x = new ttypes.Xception(); + if (arg0 === "Xception") { + const x = new ttypes.Xception(); x.errorCode = 1001; - x.message = 'This is an Xception'; + x.message = "This is an Xception"; throw x; - } else if (arg0 === ('Xception2')) { - var x2 = new ttypes.Xception2(); + } else if (arg0 === "Xception2") { + const x2 = new ttypes.Xception2(); x2.errorCode = 2002; x2.struct_thing = new ttypes.Xtruct(); - x2.struct_thing.string_thing = 'This is an Xception2'; + x2.struct_thing.string_thing = "This is an Xception2"; throw x2; } - var res = new ttypes.Xtruct(); + const res = new ttypes.Xtruct(); res.string_thing = arg1; return res; } function testMultiExceptionAsync(arg0, arg1, result) { //console.log('testMultiException(' + arg0 + ', ' + arg1 + ')'); - if (arg0 === ('Xception')) { - var x = new ttypes.Xception(); + if (arg0 === "Xception") { + const x = new ttypes.Xception(); x.errorCode = 1001; - x.message = 'This is an Xception'; + x.message = "This is an Xception"; result(x); - } else if (arg0 === ('Xception2')) { - var x2 = new ttypes.Xception2(); + } else if (arg0 === "Xception2") { + const x2 = new ttypes.Xception2(); x2.errorCode = 2002; x2.struct_thing = new ttypes.Xtruct(); - x2.struct_thing.string_thing = 'This is an Xception2'; + x2.struct_thing.string_thing = "This is an Xception2"; result(x2); } else { - var res = new ttypes.Xtruct(); + const res = new ttypes.Xtruct(); res.string_thing = arg1; result(null, res); } } -function testOneway(sleepFor) { - //console.log('testOneway(' + sleepFor + ') => JavaScript (like Rust) never sleeps!'); -} +//console.log('testOneway(' + sleepFor + ') => JavaScript (like Rust) never sleeps!'); +function testOneway() {} -function testOnewayAsync(sleepFor, result) { +function testOnewayAsync(sleepFor) { testOneway(sleepFor); } @@ -217,11 +213,8 @@ identityHandlers.forEach(function(label) { asyncHandlers[label] = makeAsyncHandler(label); }); -['testMapMap', 'testInsanity'].forEach(function(label) { +["testMapMap", "testInsanity"].forEach(function(label) { asyncHandlers[label] = makeAsyncHandler(label); }); exports.ThriftTestHandler = asyncHandlers; - -exports.AsyncThriftTestHandler = asyncHandlers; -exports.SyncThriftTestHandler = asyncHandlers; diff --git a/vendor/git.apache.org/thrift.git/lib/nodets/.gitignore b/vendor/git.apache.org/thrift.git/lib/nodets/.gitignore new file mode 100644 index 0000000..c7aba89 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/nodets/.gitignore @@ -0,0 +1 @@ +test-compiled/ diff --git a/vendor/git.apache.org/thrift.git/lib/nodets/Makefile.am b/vendor/git.apache.org/thrift.git/lib/nodets/Makefile.am new file mode 100755 index 0000000..ea640cf --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/nodets/Makefile.am @@ -0,0 +1,45 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +# We call npm twice to work around npm issues + +stubs: $(top_srcdir)/test/ThriftTest.thrift + mkdir -p test-compiled + $(THRIFT) --gen js:node,ts -o test/ $(top_srcdir)/test/ThriftTest.thrift && $(THRIFT) --gen js:node,ts -o test-compiled $(top_srcdir)/test/ThriftTest.thrift + +ts-compile: stubs + mkdir -p test-compiled + ../../node_modules/typescript/bin/tsc --outDir test-compiled/ --project test/tsconfig.json + +deps: $(top_srcdir)/package.json + $(NPM) install $(top_srcdir)/ || $(NPM) install $(top_srcdir)/ + +all-local: deps ts-compile + +precross: deps stubs ts-compile + +check: deps ts-compile + cd $(top_srcdir) && $(NPM) run test-ts && cd lib/nodets + +clean-local: + $(RM) -r test/gen-nodejs + $(RM) -r $(top_srcdir)/node_modules + $(RM) -r test-compiled + +EXTRA_DIST = \ + test \ + coding_standards.md diff --git a/vendor/git.apache.org/thrift.git/lib/nodets/coding_standards.md b/vendor/git.apache.org/thrift.git/lib/nodets/coding_standards.md new file mode 100644 index 0000000..fa0390b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/nodets/coding_standards.md @@ -0,0 +1 @@ +Please follow [General Coding Standards](/doc/coding_standards.md) diff --git a/vendor/git.apache.org/thrift.git/lib/nodets/test/client.ts b/vendor/git.apache.org/thrift.git/lib/nodets/test/client.ts new file mode 100644 index 0000000..4fa3c28 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/nodets/test/client.ts @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +import assert = require("assert"); +import thrift = require("thrift"); +import Thrift = thrift.Thrift; +import ThriftTest = require("./gen-nodejs/ThriftTest"); +import test_driver = require("./test_driver"); +import ThriftTestDriver = test_driver.ThriftTestDriver; +import ThriftTestDriverPromise = test_driver.ThriftTestDriverPromise; + +// var program = require("commander"); +import * as program from "commander"; + +program + .option("--port ", "Set thrift server port number to connect", 9090) + .option("--promise", "test with promise style functions") + .option("--protocol", "Set thrift protocol (binary) [protocol]") + .parse(process.argv); + +var port: number = program.port; +var promise = program.promise; + +var options = { + transport: Thrift.TBufferedTransport, + protocol: Thrift.TBinaryProtocol +}; + +var testDriver = promise ? ThriftTestDriverPromise : ThriftTestDriver; + +var connection = thrift.createConnection("localhost", port, options); + +connection.on("error", function(err: string) { + assert(false, err); +}); + +var client = thrift.createClient(ThriftTest.Client, connection); +runTests(); + +function runTests() { + testDriver(client, function (status: string) { + console.log(status); + process.exit(0); + }); +} + +exports.expressoTest = function() {}; diff --git a/vendor/git.apache.org/thrift.git/lib/nodets/test/runClient.sh b/vendor/git.apache.org/thrift.git/lib/nodets/test/runClient.sh new file mode 100755 index 0000000..8d5e9a3 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/nodets/test/runClient.sh @@ -0,0 +1,18 @@ +#! /bin/sh + +DIR="$( cd "$( dirname "$0" )" && pwd )" + +mkdir -p $DIR/../test-compiled + +COMPILEDDIR="$(cd $DIR && cd ../test-compiled && pwd)" +export NODE_PATH="${DIR}:${DIR}/../../nodejs/lib:${NODE_PATH}" + +compile() +{ + #generating thrift code + ${DIR}/../../../compiler/cpp/thrift -o ${DIR} --gen js:node,ts ${DIR}/../../../test/ThriftTest.thrift + ${DIR}/../../../compiler/cpp/thrift -o ${COMPILEDDIR} --gen js:node,ts ${DIR}/../../../test/ThriftTest.thrift +} +compile + +node ${COMPILEDDIR}/client.js $* diff --git a/vendor/git.apache.org/thrift.git/lib/nodets/test/runServer.sh b/vendor/git.apache.org/thrift.git/lib/nodets/test/runServer.sh new file mode 100755 index 0000000..4eee927 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/nodets/test/runServer.sh @@ -0,0 +1,20 @@ +#! /bin/sh + +DIR="$( cd "$( dirname "$0" )" && pwd )" + +mkdir -p $DIR/../test-compiled + +COMPILEDDIR="$(cd $DIR && cd ../test-compiled && pwd)" +export NODE_PATH="${DIR}:${DIR}/../../nodejs/lib:${NODE_PATH}" + +compile() +{ + #generating thrift code + ${DIR}/../../../compiler/cpp/thrift -o ${DIR} --gen js:node,ts ${DIR}/../../../test/ThriftTest.thrift + ${DIR}/../../../compiler/cpp/thrift -o ${COMPILEDDIR} --gen js:node,ts ${DIR}/../../../test/ThriftTest.thrift +} +compile + +node ${COMPILEDDIR}/server.js $* + + diff --git a/vendor/git.apache.org/thrift.git/lib/nodets/test/server.ts b/vendor/git.apache.org/thrift.git/lib/nodets/test/server.ts new file mode 100644 index 0000000..2da53ae --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/nodets/test/server.ts @@ -0,0 +1,26 @@ +import thrift = require("thrift"); +var program = require('commander'); +import ThriftTest = require('./gen-nodejs/ThriftTest'); +import test_handler = require('./test_handler'); + + +program + .option('--port ', 'Set thrift server port', 9090) + .option('--promise', 'test with promise style functions') + .option('--protocol', '"Set thrift protocol (binary) [protocol]"') + .parse(process.argv); + +var port: number = program.port; + +var options: thrift.ServerOptions = { + transport: thrift.TBufferedTransport, + protocol: thrift.TBinaryProtocol +}; + +var server: thrift.Server; +if (program.promise) { + server = thrift.createServer(ThriftTest.Processor, new test_handler.AsyncThriftTestHandler(), options); +} else { + server = thrift.createServer(ThriftTest.Processor, new test_handler.SyncThriftTestHandler(), options); +} +server.listen(port); diff --git a/vendor/git.apache.org/thrift.git/lib/nodets/test/test-cases.ts b/vendor/git.apache.org/thrift.git/lib/nodets/test/test-cases.ts new file mode 100644 index 0000000..ca740ec --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/nodets/test/test-cases.ts @@ -0,0 +1,113 @@ +'use strict'; + +import ttypes = require('./gen-nodejs/ThriftTest_types'); + +//all Languages in UTF-8 +/*jshint -W100 */ +export var stringTest = "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, " + + "Asturianu, Aymar aru, AzÉ™rbaycan, Башҡорт, Boarisch, ŽemaitÄ—Å¡ka, " + + "БеларуÑкаÑ, БеларуÑÐºÐ°Ñ (тарашкевіца), БългарÑки, Bamanankan, " + + "বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Ðохчийн, " + + "Cebuano, á£áŽ³áŽ©, ÄŒesky, СловѣÌньÑкъ / ⰔⰎⰑⰂⰡâ°â° â°”â°â°Ÿ, Чӑвашла, Cymraeg, " + + "Dansk, Zazaki, Þ‹Þ¨ÞˆÞ¬Þ€Þ¨Þ„Þ¦ÞÞ°, Ελληνικά, Emiliàn e rumagnòl, English, " + + "Esperanto, Español, Eesti, Euskara, ÙØ§Ø±Ø³ÛŒ, Suomi, Võro, Føroyskt, " + + "Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, " + + "Avañe'ẽ, ગà«àªœàª°àª¾àª¤à«€, Gaelg, עברית, हिनà¥à¤¦à¥€, Fiji Hindi, Hrvatski, " + + "Kreyòl ayisyen, Magyar, Õ€Õ¡ÕµÕ¥Ö€Õ¥Õ¶, Interlingua, Bahasa Indonesia, " + + "Ilokano, Ido, Ãslenska, Italiano, 日本語, Lojban, Basa Jawa, " + + "ქáƒáƒ áƒ—ული, Kongo, Kalaallisut, ಕನà³à²¨à²¡, 한국어, Къарачай-Малкъар, " + + "Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, " + + "Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, LatvieÅ¡u, Basa " + + "Banyumasan, Malagasy, МакедонÑки, മലയാളം, मराठी, Ù…Ø§Ø²ÙØ±ÙˆÙ†ÛŒ, Bahasa " + + "Melayu, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, ‪" + + "Norsk (nynorsk)‬, ‪Norsk (bokmÃ¥l)‬, Nouormand, Diné bizaad, " + + "Occitan, Иронау, Papiamentu, Deitsch, Polski, پنجابی, پښتو, " + + "Norfuk / Pitkern, Português, Runa Simi, Rumantsch, Romani, Română, " + + "РуÑÑкий, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple " + + "English, SlovenÄina, SlovenÅ¡Äina, СрпÑки / Srpski, Seeltersk, " + + "Svenska, Kiswahili, தமிழà¯, తెలà±à°—à±, Тоҷикӣ, ไทย, Türkmençe, Tagalog, " + + "Türkçe, Татарча/Tatarça, УкраїнÑька, اردو, Tiếng Việt, Volapük, " + + "Walon, Winaray, å´è¯­, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, " + + "Bân-lâm-gú, 粵語"; +/*jshint +W100 */ + +export var specialCharacters = 'quote: \" backslash:' + + ' forwardslash-escaped: \/ ' + + ' backspace: \b formfeed: \f newline: \n return: \r tab: ' + + ' now-all-of-them-together: "\\\/\b\n\r\t' + + ' now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><' + + ' char-to-test-json-parsing: ]] \"]] \\" }}}{ [[[ '; + +export var mapTestInput = { + "a":"123", "a b":"with spaces ", "same":"same", "0":"numeric key", + "longValue":stringTest, stringTest:"long key" +}; + +export var simple = [ + ['testVoid', undefined], + ['testString', 'Test'], + ['testString', ''], + ['testString', stringTest], + ['testString', specialCharacters], + ['testByte', 1], + ['testByte', 0], + ['testByte', -1], + ['testByte', -127], + ['testI32', -1], + ['testDouble', -5.2098523], + ['testDouble', 7.012052175215044], + ['testEnum', ttypes.Numberz.ONE] +]; + +export var simpleLoose = [ + ['testI64', 5], + ['testI64', -5], + ['testI64', 734359738368], + ['testI64', -34359738368], + ['testI64', -734359738368], + ['testTypedef', 69] +] + +var mapout: {[key: number]: number; } = {}; +for (var i = 0; i < 5; ++i) { + mapout[i] = i-10; +} + +export var deep = [ + ['testMap', mapout], + ['testSet', [1,2,3]], + ['testList', [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]], + ['testStringMap', mapTestInput] +]; + +export var out = new ttypes.Xtruct({ + string_thing: 'Zero', + byte_thing: 1, + i32_thing: -3, + i64_thing: 1000000 +}); + +export var out2 = new ttypes.Xtruct2(); +out2.byte_thing = 1; +out2.struct_thing = out; +out2.i32_thing = 5; + +export var crazy = new ttypes.Insanity({ + "userMap":{ "5":5, "8":8 }, + "xtructs":[new ttypes.Xtruct({ + "string_thing":"Goodbye4", + "byte_thing":4, + "i32_thing":4, + "i64_thing":4 + }), new ttypes.Xtruct({ + "string_thing":"Hello2", + "byte_thing":2, + "i32_thing":2, + "i64_thing":2 + })] +}); + +export var insanity: any = { + "1":{ "2": crazy, "3": crazy }, + "2":{ "6":{ "userMap":{}, "xtructs":[] } } +}; diff --git a/vendor/git.apache.org/thrift.git/lib/nodets/test/testAll.sh b/vendor/git.apache.org/thrift.git/lib/nodets/test/testAll.sh new file mode 100755 index 0000000..a7c00bf --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/nodets/test/testAll.sh @@ -0,0 +1,38 @@ +#! /bin/sh + +DIR="$( cd "$( dirname "$0" )" && pwd )" + +mkdir -p $DIR/../test-compiled + +COMPILEDDIR="$(cd $DIR && cd ../test-compiled && pwd)" +export NODE_PATH="${DIR}:${DIR}/../../nodejs/lib:${NODE_PATH}" + +compile() +{ + #generating thrift code + ${DIR}/../../../compiler/cpp/thrift -o ${DIR} --gen js:node,ts ${DIR}/../../../test/ThriftTest.thrift + ${DIR}/../../../compiler/cpp/thrift -o ${COMPILEDDIR} --gen js:node,ts ${DIR}/../../../test/ThriftTest.thrift + + tsc --outDir $COMPILEDDIR --project $DIR/tsconfig.json +} +compile + +testServer() +{ + echo "start server $1" + RET=0 + node ${COMPILEDDIR}/server.js $1 & + SERVERPID=$! + sleep 1 + echo "start client $1" + node ${COMPILEDDIR}/client.js $1 || RET=1 + kill -2 $SERVERPID || RET=1 + return $RET +} + +#integration tests + +testServer || TESTOK=1 +testServer --promise || TESTOK=1 + +exit $TESTOK diff --git a/vendor/git.apache.org/thrift.git/lib/nodets/test/test_driver.ts b/vendor/git.apache.org/thrift.git/lib/nodets/test/test_driver.ts new file mode 100644 index 0000000..2c41526 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/nodets/test/test_driver.ts @@ -0,0 +1,278 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + + // This is the Node.js test driver for the standard Apache Thrift + // test service. The driver invokes every function defined in the + // Thrift Test service with a representative range of parameters. + // + // The ThriftTestDriver function requires a client object + // connected to a server hosting the Thrift Test service and + // supports an optional callback function which is called with + // a status message when the test is complete. + +import test = require("tape"); +import ttypes = require("./gen-nodejs/ThriftTest_types"); +import ThriftTest = require("./gen-nodejs/ThriftTest"); +import thrift = require("thrift"); +import Q = thrift.Q; +import TException = thrift.Thrift.TException; +var Int64 = require("node-int64"); +import testCases = require("./test-cases"); + +export function ThriftTestDriver(client: ThriftTest.Client, callback: (status: string) => void) { + + test("NodeJS Style Callback Client Tests", function(assert) { + + var checkRecursively = makeRecursiveCheck(assert); + + function makeAsserter(assertionFn: (a: any, b: any, msg?: string) => void) { + return function(c: (string | any)[]) { + var fnName = c[0]; + var expected = c[1]; + (client)[fnName](expected, function(err: any, actual: any) { + assert.error(err, fnName + ": no callback error"); + assertionFn(actual, expected, fnName); + }) + }; + } + + testCases.simple.forEach(makeAsserter(assert.equal)); + testCases.simpleLoose.forEach(makeAsserter(function(a, e, m){ + assert.ok(a == e, m); + })); + testCases.deep.forEach(makeAsserter(assert.deepEqual)); + + client.testMapMap(42, function(err, response) { + var expected: typeof response = { + "4": {"1":1, "2":2, "3":3, "4":4}, + "-4": {"-4":-4, "-3":-3, "-2":-2, "-1":-1} + }; + assert.error(err, 'testMapMap: no callback error'); + assert.deepEqual(expected, response, "testMapMap"); + }); + + client.testStruct(testCases.out, function(err, response) { + assert.error(err, "testStruct: no callback error"); + checkRecursively(testCases.out, response, "testStruct"); + }); + + client.testNest(testCases.out2, function(err, response) { + assert.error(err, "testNest: no callback error"); + checkRecursively(testCases.out2, response, "testNest"); + }); + + client.testInsanity(testCases.crazy, function(err, response) { + assert.error(err, "testInsanity: no callback error"); + checkRecursively(testCases.insanity, response, "testInsanity"); + }); + + client.testException("TException", function(err, response) { + assert.ok(err instanceof TException, 'testException: correct error type'); + assert.ok(!Boolean(response), 'testException: no response'); + }); + + client.testException("Xception", function(err, response) { + assert.ok(err instanceof ttypes.Xception, 'testException: correct error type'); + assert.ok(!Boolean(response), 'testException: no response'); + assert.equal(err.errorCode, 1001, 'testException: correct error code'); + assert.equal('Xception', err.message, 'testException: correct error message'); + }); + + client.testException("no Exception", function(err, response) { + assert.error(err, 'testException: no callback error'); + assert.ok(!Boolean(response), 'testException: no response'); + }); + + client.testOneway(0, function(err, response) { + assert.error(err, 'testOneway: no callback error'); + assert.strictEqual(response, undefined, 'testOneway: void response'); + }); + + checkOffByOne(function(done) { + client.testI32(-1, function(err, response) { + assert.error(err, "checkOffByOne: no callback error"); + assert.equal(-1, response); + assert.end(); + done(); + }); + }, callback); + + }); +}; + +export function ThriftTestDriverPromise(client: ThriftTest.Client, callback: (status: string) => void) { + + test("Q Promise Client Tests", function(assert) { + + var checkRecursively = makeRecursiveCheck(assert); + + function fail(msg: string) { + return function(error, response) { + if (error !== null) { + assert.fail(msg); + } + } + } + + function makeAsserter(assertionFn: (a: any, b: any, msg?: string) => void) { + return function(c: (string | any)[]) { + var fnName = c[0]; + var expected = c[1]; + (client)[fnName](expected) + .then(function(actual: any) { + assertionFn(actual, expected, fnName); + }) + .fail(fail("fnName")); + }; + } + + testCases.simple.forEach(makeAsserter(assert.equal)); + testCases.simpleLoose.forEach(makeAsserter(function(a, e, m){ + assert.ok(a == e, m); + })); + testCases.deep.forEach(makeAsserter(assert.deepEqual)); + + Q.resolve(client.testStruct(testCases.out)) + .then(function(response) { + checkRecursively(testCases.out, response, "testStruct"); + }) + .fail(fail("testStruct")); + + Q.resolve(client.testNest(testCases.out2)) + .then(function(response) { + checkRecursively(testCases.out2, response, "testNest"); + }) + .fail(fail("testNest")); + + Q.resolve(client.testInsanity(testCases.crazy)) + .then(function(response) { + checkRecursively(testCases.insanity, response, "testInsanity"); + }) + .fail(fail("testInsanity")); + + Q.resolve(client.testException("TException")) + .then(function(response) { + fail("testException: TException"); + }) + .fail(function(err) { + assert.ok(err instanceof TException); + }); + + Q.resolve(client.testException("Xception")) + .then(function(response) { + fail("testException: Xception"); + }) + .fail(function(err) { + assert.ok(err instanceof ttypes.Xception); + assert.equal(err.errorCode, 1001); + assert.equal("Xception", err.message); + }); + + Q.resolve(client.testException("no Exception")) + .then(function(response) { + assert.equal(undefined, response); //void + }) + .fail(fail("testException")); + + client.testOneway(0, fail("testOneway: should not answer")); + + checkOffByOne(function(done) { + Q.resolve(client.testI32(-1)) + .then(function(response) { + assert.equal(-1, response); + assert.end(); + done(); + }) + .fail(fail("checkOffByOne")); + }, callback); + }); +}; + + +// Helper Functions +// ========================================================= + +function makeRecursiveCheck(assert: test.Test) { + + return function (map1: any, map2: any, msg: string) { + var equal = true; + + var equal = checkRecursively(map1, map2); + + assert.ok(equal, msg); + + // deepEqual doesn't work with fields using node-int64 + function checkRecursively(map1: any, map2: any) : boolean { + if (!(typeof map1 !== "function" && typeof map2 !== "function")) { + return false; + } + if (!map1 || typeof map1 !== "object") { + //Handle int64 types (which use node-int64 in Node.js JavaScript) + if ((typeof map1 === "number") && (typeof map2 === "object") && + (map2.buffer) && (map2.buffer instanceof Buffer) && (map2.buffer.length === 8)) { + var n = new Int64(map2.buffer); + return map1 === n.toNumber(); + } else { + return map1 == map2; + } + } else { + return Object.keys(map1).every(function(key) { + return checkRecursively(map1[key], map2[key]); + }); + } + } + } +} + +function checkOffByOne(done: (callback: () => void) => void, callback: (message: string) => void) { + + var retry_limit = 30; + var retry_interval = 100; + var test_complete = false; + var retrys = 0; + + /** + * redo a simple test after the oneway to make sure we aren't "off by one" -- + * if the server treated oneway void like normal void, this next test will + * fail since it will get the void confirmation rather than the correct + * result. In this circumstance, the client will throw the exception: + * + * Because this is the last test against the server, when it completes + * the entire suite is complete by definition (the tests run serially). + */ + done(function() { + test_complete = true; + }); + + //We wait up to retry_limit * retry_interval for the test suite to complete + function TestForCompletion() { + if(test_complete && callback) { + callback("Server successfully tested!"); + } else { + if (++retrys < retry_limit) { + setTimeout(TestForCompletion, retry_interval); + } else if (callback) { + callback("Server test failed to complete after " + + (retry_limit * retry_interval / 1000) + " seconds"); + } + } + } + + setTimeout(TestForCompletion, retry_interval); +} diff --git a/vendor/git.apache.org/thrift.git/lib/nodets/test/test_handler.ts b/vendor/git.apache.org/thrift.git/lib/nodets/test/test_handler.ts new file mode 100644 index 0000000..1bc855a --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/nodets/test/test_handler.ts @@ -0,0 +1,299 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +//This is the server side Node test handler for the standard +// Apache Thrift test service. + +import ttypes = require("./gen-nodejs/ThriftTest_types"); +import thrift = require("thrift"); +import Thrift = thrift.Thrift; +import Q = require("q"); + + +export class SyncThriftTestHandler { + testVoid(): Q.IPromise { + //console.log('testVoid()'); + return Q.resolve(undefined); + } + testMapMap(hello: number) { + //console.log('testMapMap(' + hello + ')'); + + var mapmap: {[key: number]: {[key: number]: number; }} = []; + var pos: {[key: number]: number; } = []; + var neg: {[key: number]: number; } = []; + for (var i = 1; i < 5; i++) { + pos[i] = i; + neg[-i] = -i; + } + mapmap[4] = pos; + mapmap[-4] = neg; + + return Q.resolve(mapmap); + } + testInsanity(argument: ttypes.Insanity): Q.IPromise<{ [k: number]: any; }> { + const first_map: { [k: number]: any; } = []; + const second_map: { [k: number]: any; } = []; + + first_map[ttypes.Numberz.TWO] = argument; + first_map[ttypes.Numberz.THREE] = argument; + + const looney = new ttypes.Insanity(); + second_map[ttypes.Numberz.SIX] = looney; + + const insane: { [k: number]: any; } = []; + insane[1] = first_map; + insane[2] = second_map; + + return Q.resolve(insane); + } + testMulti(arg0: any, arg1: number, arg2: number, arg3: { [k: number]: string; }, arg4: ttypes.Numberz, arg5: number) { + var hello = new ttypes.Xtruct(); + hello.string_thing = 'Hello2'; + hello.byte_thing = arg0; + hello.i32_thing = arg1; + hello.i64_thing = arg2; + return Q.resolve(hello); + } + testException(arg: string): Q.IPromise { + if (arg === 'Xception') { + var x = new ttypes.Xception(); + x.errorCode = 1001; + x.message = arg; + throw x; + } else if (arg === 'TException') { + throw new Thrift.TException(arg); + } else { + return Q.resolve(); + } + } + testMultiException(arg0: string, arg1: string) { + if (arg0 === ('Xception')) { + var x = new ttypes.Xception(); + x.errorCode = 1001; + x.message = 'This is an Xception'; + throw x; + } else if (arg0 === ('Xception2')) { + var x2 = new ttypes.Xception2(); + x2.errorCode = 2002; + x2.struct_thing = new ttypes.Xtruct(); + x2.struct_thing.string_thing = 'This is an Xception2'; + throw x2; + } + + var res = new ttypes.Xtruct(); + res.string_thing = arg1; + return Q.resolve(res); + } + testOneway(sleepFor: number) { + } + + testString(thing: string) { + return Q.resolve(thing); + } + testBool(thing: boolean) { + return Q.resolve(thing); + } + testByte(thing: number) { + return Q.resolve(thing); + } + testI32(thing: number) { + return Q.resolve(thing); + } + testI64(thing: number) { + return Q.resolve(thing); + } + testDouble(thing: number) { + return Q.resolve(thing); + } + testBinary(thing: Buffer) { + return Q.resolve(thing); + } + testStruct(thing: ttypes.Xtruct) { + return Q.resolve(thing); + } + testNest(thing: ttypes.Xtruct2) { + return Q.resolve(thing); + } + testMap(thing: { [k: number]: number; }) { + return Q.resolve(thing); + } + testStringMap(thing: { [k: string]: string; }) { + return Q.resolve(thing); + } + testSet(thing: number[]) { + return Q.resolve(thing); + } + testList(thing: number[]) { + return Q.resolve(thing); + } + testEnum(thing: ttypes.Numberz) { + return Q.resolve(thing); + } + testTypedef(thing: number) { + return Q.resolve(thing); + } +} + +export class AsyncThriftTestHandler { + private syncHandler: SyncThriftTestHandler; + constructor() { + this.syncHandler = new SyncThriftTestHandler(); + } + + testVoid(callback: (result: void) => void): Q.IPromise { + callback(undefined); + return Q.resolve(); + } + testMapMap(hello: number, + callback: (err: any, result: { [k: number]: { [k: number]: number; }; }) => void): + Q.IPromise<{ [k: number]: { [k: number]: number; }; }> { + + var mapmap: {[key: number]: {[key: number]: number; }} = []; + var pos: {[key: number]: number; } = []; + var neg: {[key: number]: number; } = []; + for (var i = 1; i < 5; i++) { + pos[i] = i; + neg[-i] = -i; + } + mapmap[4] = pos; + mapmap[-4] = neg; + + callback(null, mapmap); + return Q.resolve(); + } + testInsanity(argument: ttypes.Insanity, callback?: (err: any, result: { [k: number]: any; }) => void): Q.IPromise<{ [k: number]: any; }> { + const first_map: { [k: number]: any; } = []; + const second_map: { [k: number]: any; } = []; + + first_map[ttypes.Numberz.TWO] = argument; + first_map[ttypes.Numberz.THREE] = argument; + + const looney = new ttypes.Insanity(); + second_map[ttypes.Numberz.SIX] = looney; + + const insane: { [k: number]: any; } = []; + insane[1] = first_map; + insane[2] = second_map; + + if (callback !== undefined){ + callback(null, insane); + } + return Q.resolve(); + } + testMulti(arg0: any, arg1: number, arg2: number, arg3: { [k: number]: string; }, arg4: ttypes.Numberz, arg5: number, result: Function): Q.IPromise { + var hello = this.syncHandler.testMulti(arg0, arg1, arg2, arg3, arg4, arg5); + hello.then(hello => result(null, hello)); + return Q.resolve(); + } + testException(arg: string, result: (err: any) => void): Q.IPromise { + if (arg === 'Xception') { + var x = new ttypes.Xception(); + x.errorCode = 1001; + x.message = arg; + result(x); + } else if (arg === 'TException') { + result(new Thrift.TException(arg)); + } else { + result(null); + } + return Q.resolve(); + } + testMultiException(arg0: string, arg1: string, result: (err: any, res?: ttypes.Xtruct) => void): Q.IPromise { + if (arg0 === ('Xception')) { + var x = new ttypes.Xception(); + x.errorCode = 1001; + x.message = 'This is an Xception'; + result(x); + } else if (arg0 === ('Xception2')) { + var x2 = new ttypes.Xception2(); + x2.errorCode = 2002; + x2.struct_thing = new ttypes.Xtruct(); + x2.struct_thing.string_thing = 'This is an Xception2'; + result(x2); + } else { + var res = new ttypes.Xtruct(); + res.string_thing = arg1; + result(null, res); + } + return Q.resolve(); + } + testOneway(sleepFor: number, result: Function) { + this.syncHandler.testOneway(sleepFor); + } + testString(thing: string, callback: (err: any, result: string) => void): Q.IPromise { + callback(null, thing); + return Q.resolve(); + } + testByte(thing: number, callback: (err: any, result: number) => void): Q.IPromise { + callback(null, thing); + return Q.resolve(); + } + testBool(thing: boolean, callback: (err: any, result: boolean) => void ): Q.IPromise { + callback(null, thing); + return Q.resolve(); + } + testI32(thing: number, callback: (err: any, result: number) => void): Q.IPromise { + callback(null, thing); + return Q.resolve(); + } + testI64(thing: number, callback: (err: any, result: number) => void): Q.IPromise { + callback(null, thing); + return Q.resolve(); + } + testDouble(thing: number, callback: (err: any, result: number) => void): Q.IPromise { + callback(null, thing); + return Q.resolve(); + } + testBinary(thing: Buffer, callback: (err: any, result: Buffer) => void): Q.IPromise { + callback(null, thing); + return Q.resolve(); + } + testStruct(thing: ttypes.Xtruct, callback: (err: any, result: ttypes.Xtruct) => void): Q.IPromise { + callback(null, thing); + return Q.resolve(); + } + testNest(thing: ttypes.Xtruct2, callback: (err: any, result: ttypes.Xtruct2) => void): Q.IPromise { + callback(null, thing); + return Q.resolve(); + } + testMap(thing: { [k: number]: number; }, callback: (err: any, result: { [k: number]: number; }) => void): Q.IPromise<{ [k: number]: number; }> { + callback(null, thing); + return Q.resolve(); + } + testStringMap(thing: { [k: string]: string; }, callback: (err: any, result: { [k: string]: string; }) => void): Q.IPromise<{ [k: string]: string; }> { + callback(null, thing); + return Q.resolve(); + } + testSet(thing: number[], callback: (err: any, result: number[]) => void): Q.IPromise { + callback(null, thing); + return Q.resolve(); + } + testList(thing: number[], callback: (err: any, result: number[]) => void): Q.IPromise { + callback(null, thing); + return Q.resolve(); + } + testEnum(thing: ttypes.Numberz, callback: (err: any, result: ttypes.Numberz) => void): Q.IPromise { + callback(null, thing); + return Q.resolve(); + } + testTypedef(thing: number, callback: (err: any, result: number) => void): Q.IPromise { + callback(null, thing); + return Q.resolve(); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/nodets/test/tsconfig.json b/vendor/git.apache.org/thrift.git/lib/nodets/test/tsconfig.json new file mode 100644 index 0000000..029d06d --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/nodets/test/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "allowJs": false, + "alwaysStrict": true, + "baseUrl": ".", + "declaration": true, + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "module": "commonjs", + "moduleResolution": "node", + "noImplicitThis": true, + "noUnusedLocals": true, + "preserveConstEnums": true, + "removeComments": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "target": "es6", + "paths": { + "thrift": ["../../nodejs/lib/thrift"] + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/ocaml/.gitignore b/vendor/git.apache.org/thrift.git/lib/ocaml/.gitignore new file mode 100644 index 0000000..0d9a6af --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/ocaml/.gitignore @@ -0,0 +1,11 @@ +_build/ +_tags +configure +setup.data +setup.ml +myocamlbuild.ml +*/META +*/*.mllib +*/*.mldylib +Makefile +OCamlMakefile diff --git a/vendor/git.apache.org/thrift.git/lib/ocaml/DEVELOPMENT b/vendor/git.apache.org/thrift.git/lib/ocaml/DEVELOPMENT new file mode 100644 index 0000000..3d5a03c --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/ocaml/DEVELOPMENT @@ -0,0 +1,76 @@ +Thrift OCaml Development +======================== + +Prerequisites +------------- + +In order to build this library, you must have the following installed: + + * The OCaml compiler, preferably >4.00 + * The Oasis build tool + +In addition you may want to install OPAM, which will allow you to setup an +OCaml development environment that's isolated from your system installation, +much like virutalenv for Python or the myriad systems available for Ruby. If +you have OPAM installed, then installing Oasis is as simple as running: + + $ opam install oasis + +Building +-------- + +Once all the prerequisites have been installed, run the following commands: + + $ oasis setup + $ ./configure + $ make + +The `oasis setup` command will generate the configure script and Makefile, +along with other files that opam will use to create an installable library. +The cofigure script will ensure that all build dependencies are installed, and +make will actually build the library. + +To remove files that the compiler geneates, run: + + $ make clean + +To remove those files _as well as_ files that the setup and configure process +generates, run: + + $ rm `cat .gitignore` + +Installing +---------- + +If you're using opam, simply run the following command: + + $ make install + +While development, you may want to install your latest build on the system to +test against other libraries or programs. To do this, use: + + $ make reinstall + +Distribution +------------ + +The de facto preferred method for distributing OCaml libraries is through the +OPAM package repository. To publish the latest package, issue a pull request +against the following github repository: + + https://github.com/ocaml/opam-repository + +The pull requestion should add the following directory structure and files: + + package + |__thrift + |__thrift. + |__ descr + |__ opam + |__ url + +Templates for the following files can be found in the opam/ subdirectory of +this library's root, with XXX(...) indicating fields that need to be filled +out. You can find further documentation here: + + http://opam.ocaml.org/doc/Packaging.html diff --git a/vendor/git.apache.org/thrift.git/lib/ocaml/OCamlMakefile b/vendor/git.apache.org/thrift.git/lib/ocaml/OCamlMakefile deleted file mode 100644 index b0b9252..0000000 --- a/vendor/git.apache.org/thrift.git/lib/ocaml/OCamlMakefile +++ /dev/null @@ -1,1231 +0,0 @@ -########################################################################### -# OCamlMakefile -# Copyright (C) 1999-2007 Markus Mottl -# -# For updates see: -# http://www.ocaml.info/home/ocaml_sources.html -# -########################################################################### - -# Modified by damien for .glade.ml compilation - -# Set these variables to the names of the sources to be processed and -# the result variable. Order matters during linkage! - -ifndef SOURCES - SOURCES := foo.ml -endif -export SOURCES - -ifndef RES_CLIB_SUF - RES_CLIB_SUF := _stubs -endif -export RES_CLIB_SUF - -ifndef RESULT - RESULT := foo -endif -export RESULT := $(strip $(RESULT)) - -export LIB_PACK_NAME - -ifndef DOC_FILES - DOC_FILES := $(filter %.mli, $(SOURCES)) -endif -export DOC_FILES -FIRST_DOC_FILE := $(firstword $(DOC_FILES)) - -export BCSUFFIX -export NCSUFFIX - -ifndef TOPSUFFIX - TOPSUFFIX := .top -endif -export TOPSUFFIX - -# Eventually set include- and library-paths, libraries to link, -# additional compilation-, link- and ocamlyacc-flags -# Path- and library information needs not be written with "-I" and such... -# Define THREADS if you need it, otherwise leave it unset (same for -# USE_CAMLP4)! - -export THREADS -export VMTHREADS -export ANNOTATE -export USE_CAMLP4 - -export INCDIRS -export LIBDIRS -export EXTLIBDIRS -export RESULTDEPS -export OCAML_DEFAULT_DIRS - -export LIBS -export CLIBS -export CFRAMEWORKS - -export OCAMLFLAGS -export OCAMLNCFLAGS -export OCAMLBCFLAGS - -export OCAMLLDFLAGS -export OCAMLNLDFLAGS -export OCAMLBLDFLAGS - -export OCAMLMKLIB_FLAGS - -ifndef OCAMLCPFLAGS - OCAMLCPFLAGS := a -endif -export OCAMLCPFLAGS - -ifndef DOC_DIR - DOC_DIR := doc -endif -export DOC_DIR - -export PPFLAGS - -export LFLAGS -export YFLAGS -export IDLFLAGS - -export OCAMLDOCFLAGS - -export OCAMLFIND_INSTFLAGS - -export DVIPSFLAGS - -export STATIC - -# Add a list of optional trash files that should be deleted by "make clean" -export TRASH - -ECHO := echo - -ifdef REALLY_QUIET - export REALLY_QUIET - ECHO := true - LFLAGS := $(LFLAGS) -q - YFLAGS := $(YFLAGS) -q -endif - -#################### variables depending on your OCaml-installation - -ifdef MINGW - export MINGW - WIN32 := 1 - CFLAGS_WIN32 := -mno-cygwin -endif -ifdef MSVC - export MSVC - WIN32 := 1 - ifndef STATIC - CPPFLAGS_WIN32 := -DCAML_DLL - endif - CFLAGS_WIN32 += -nologo - EXT_OBJ := obj - EXT_LIB := lib - ifeq ($(CC),gcc) - # work around GNU Make default value - ifdef THREADS - CC := cl -MT - else - CC := cl - endif - endif - ifeq ($(CXX),g++) - # work around GNU Make default value - CXX := $(CC) - endif - CFLAG_O := -Fo -endif -ifdef WIN32 - EXT_CXX := cpp - EXE := .exe -endif - -ifndef EXT_OBJ - EXT_OBJ := o -endif -ifndef EXT_LIB - EXT_LIB := a -endif -ifndef EXT_CXX - EXT_CXX := cc -endif -ifndef EXE - EXE := # empty -endif -ifndef CFLAG_O - CFLAG_O := -o # do not delete this comment (preserves trailing whitespace)! -endif - -export CC -export CXX -export CFLAGS -export CXXFLAGS -export LDFLAGS -export CPPFLAGS - -ifndef RPATH_FLAG - ifdef ELF_RPATH_FLAG - RPATH_FLAG := $(ELF_RPATH_FLAG) - else - RPATH_FLAG := -R - endif -endif -export RPATH_FLAG - -ifndef MSVC -ifndef PIC_CFLAGS - PIC_CFLAGS := -fPIC -endif -ifndef PIC_CPPFLAGS - PIC_CPPFLAGS := -DPIC -endif -endif - -export PIC_CFLAGS -export PIC_CPPFLAGS - -BCRESULT := $(addsuffix $(BCSUFFIX), $(RESULT)) -NCRESULT := $(addsuffix $(NCSUFFIX), $(RESULT)) -TOPRESULT := $(addsuffix $(TOPSUFFIX), $(RESULT)) - -ifndef OCAMLFIND - OCAMLFIND := ocamlfind -endif -export OCAMLFIND - -ifndef OCAMLC - OCAMLC := ocamlc -endif -export OCAMLC - -ifndef OCAMLOPT - OCAMLOPT := ocamlopt -endif -export OCAMLOPT - -ifndef OCAMLMKTOP - OCAMLMKTOP := ocamlmktop -endif -export OCAMLMKTOP - -ifndef OCAMLCP - OCAMLCP := ocamlcp -endif -export OCAMLCP - -ifndef OCAMLDEP - OCAMLDEP := ocamldep -endif -export OCAMLDEP - -ifndef OCAMLLEX - OCAMLLEX := ocamllex -endif -export OCAMLLEX - -ifndef OCAMLYACC - OCAMLYACC := ocamlyacc -endif -export OCAMLYACC - -ifndef OCAMLMKLIB - OCAMLMKLIB := ocamlmklib -endif -export OCAMLMKLIB - -ifndef OCAML_GLADECC - OCAML_GLADECC := lablgladecc2 -endif -export OCAML_GLADECC - -ifndef OCAML_GLADECC_FLAGS - OCAML_GLADECC_FLAGS := -endif -export OCAML_GLADECC_FLAGS - -ifndef CAMELEON_REPORT - CAMELEON_REPORT := report -endif -export CAMELEON_REPORT - -ifndef CAMELEON_REPORT_FLAGS - CAMELEON_REPORT_FLAGS := -endif -export CAMELEON_REPORT_FLAGS - -ifndef CAMELEON_ZOGGY - CAMELEON_ZOGGY := camlp4o pa_zog.cma pr_o.cmo -endif -export CAMELEON_ZOGGY - -ifndef CAMELEON_ZOGGY_FLAGS - CAMELEON_ZOGGY_FLAGS := -endif -export CAMELEON_ZOGGY_FLAGS - -ifndef OXRIDL - OXRIDL := oxridl -endif -export OXRIDL - -ifndef CAMLIDL - CAMLIDL := camlidl -endif -export CAMLIDL - -ifndef CAMLIDLDLL - CAMLIDLDLL := camlidldll -endif -export CAMLIDLDLL - -ifndef NOIDLHEADER - MAYBE_IDL_HEADER := -header -endif -export NOIDLHEADER - -export NO_CUSTOM - -ifndef CAMLP4 - CAMLP4 := camlp4 -endif -export CAMLP4 - -ifndef REAL_OCAMLFIND - ifdef PACKS - ifndef CREATE_LIB - ifdef THREADS - PACKS += threads - endif - endif - empty := - space := $(empty) $(empty) - comma := , - ifdef PREDS - PRE_OCAML_FIND_PREDICATES := $(subst $(space),$(comma),$(PREDS)) - PRE_OCAML_FIND_PACKAGES := $(subst $(space),$(comma),$(PACKS)) - OCAML_FIND_PREDICATES := -predicates $(PRE_OCAML_FIND_PREDICATES) - # OCAML_DEP_PREDICATES := -syntax $(PRE_OCAML_FIND_PREDICATES) - OCAML_FIND_PACKAGES := $(OCAML_FIND_PREDICATES) -package $(PRE_OCAML_FIND_PACKAGES) - OCAML_DEP_PACKAGES := $(OCAML_DEP_PREDICATES) -package $(PRE_OCAML_FIND_PACKAGES) - else - OCAML_FIND_PACKAGES := -package $(subst $(space),$(comma),$(PACKS)) - OCAML_DEP_PACKAGES := - endif - OCAML_FIND_LINKPKG := -linkpkg - REAL_OCAMLFIND := $(OCAMLFIND) - endif -endif - -export OCAML_FIND_PACKAGES -export OCAML_DEP_PACKAGES -export OCAML_FIND_LINKPKG -export REAL_OCAMLFIND - -ifndef OCAMLDOC - OCAMLDOC := ocamldoc -endif -export OCAMLDOC - -ifndef LATEX - LATEX := latex -endif -export LATEX - -ifndef DVIPS - DVIPS := dvips -endif -export DVIPS - -ifndef PS2PDF - PS2PDF := ps2pdf -endif -export PS2PDF - -ifndef OCAMLMAKEFILE - OCAMLMAKEFILE := OCamlMakefile -endif -export OCAMLMAKEFILE - -ifndef OCAMLLIBPATH - OCAMLLIBPATH := \ - $(shell $(OCAMLC) 2>/dev/null -where || echo /usr/local/lib/ocaml) -endif -export OCAMLLIBPATH - -ifndef OCAML_LIB_INSTALL - OCAML_LIB_INSTALL := $(OCAMLLIBPATH)/contrib -endif -export OCAML_LIB_INSTALL - -########################################################################### - -#################### change following sections only if -#################### you know what you are doing! - -# delete target files when a build command fails -.PHONY: .DELETE_ON_ERROR -.DELETE_ON_ERROR: - -# for pedants using "--warn-undefined-variables" -export MAYBE_IDL -export REAL_RESULT -export CAMLIDLFLAGS -export THREAD_FLAG -export RES_CLIB -export MAKEDLL -export ANNOT_FLAG -export C_OXRIDL -export SUBPROJS -export CFLAGS_WIN32 -export CPPFLAGS_WIN32 - -INCFLAGS := - -SHELL := /bin/sh - -MLDEPDIR := ._d -BCDIDIR := ._bcdi -NCDIDIR := ._ncdi - -FILTER_EXTNS := %.mli %.ml %.mll %.mly %.idl %.oxridl %.c %.m %.$(EXT_CXX) %.rep %.zog %.glade - -FILTERED := $(filter $(FILTER_EXTNS), $(SOURCES)) -SOURCE_DIRS := $(filter-out ./, $(sort $(dir $(FILTERED)))) - -FILTERED_REP := $(filter %.rep, $(FILTERED)) -DEP_REP := $(FILTERED_REP:%.rep=$(MLDEPDIR)/%.d) -AUTO_REP := $(FILTERED_REP:.rep=.ml) - -FILTERED_ZOG := $(filter %.zog, $(FILTERED)) -DEP_ZOG := $(FILTERED_ZOG:%.zog=$(MLDEPDIR)/%.d) -AUTO_ZOG := $(FILTERED_ZOG:.zog=.ml) - -FILTERED_GLADE := $(filter %.glade, $(FILTERED)) -DEP_GLADE := $(FILTERED_GLADE:%.glade=$(MLDEPDIR)/%.d) -AUTO_GLADE := $(FILTERED_GLADE:.glade=.ml) - -FILTERED_ML := $(filter %.ml, $(FILTERED)) -DEP_ML := $(FILTERED_ML:%.ml=$(MLDEPDIR)/%.d) - -FILTERED_MLI := $(filter %.mli, $(FILTERED)) -DEP_MLI := $(FILTERED_MLI:.mli=.di) - -FILTERED_MLL := $(filter %.mll, $(FILTERED)) -DEP_MLL := $(FILTERED_MLL:%.mll=$(MLDEPDIR)/%.d) -AUTO_MLL := $(FILTERED_MLL:.mll=.ml) - -FILTERED_MLY := $(filter %.mly, $(FILTERED)) -DEP_MLY := $(FILTERED_MLY:%.mly=$(MLDEPDIR)/%.d) $(FILTERED_MLY:.mly=.di) -AUTO_MLY := $(FILTERED_MLY:.mly=.mli) $(FILTERED_MLY:.mly=.ml) - -FILTERED_IDL := $(filter %.idl, $(FILTERED)) -DEP_IDL := $(FILTERED_IDL:%.idl=$(MLDEPDIR)/%.d) $(FILTERED_IDL:.idl=.di) -C_IDL := $(FILTERED_IDL:%.idl=%_stubs.c) -ifndef NOIDLHEADER - C_IDL += $(FILTERED_IDL:.idl=.h) -endif -OBJ_C_IDL := $(FILTERED_IDL:%.idl=%_stubs.$(EXT_OBJ)) -AUTO_IDL := $(FILTERED_IDL:.idl=.mli) $(FILTERED_IDL:.idl=.ml) $(C_IDL) - -FILTERED_OXRIDL := $(filter %.oxridl, $(FILTERED)) -DEP_OXRIDL := $(FILTERED_OXRIDL:%.oxridl=$(MLDEPDIR)/%.d) $(FILTERED_OXRIDL:.oxridl=.di) -AUTO_OXRIDL := $(FILTERED_OXRIDL:.oxridl=.mli) $(FILTERED_OXRIDL:.oxridl=.ml) $(C_OXRIDL) - -FILTERED_C_CXX := $(filter %.c %.m %.$(EXT_CXX), $(FILTERED)) -OBJ_C_CXX := $(FILTERED_C_CXX:.c=.$(EXT_OBJ)) -OBJ_C_CXX := $(OBJ_C_CXX:.m=.$(EXT_OBJ)) -OBJ_C_CXX := $(OBJ_C_CXX:.$(EXT_CXX)=.$(EXT_OBJ)) - -PRE_TARGETS += $(AUTO_MLL) $(AUTO_MLY) $(AUTO_IDL) $(AUTO_OXRIDL) $(AUTO_ZOG) $(AUTO_REP) $(AUTO_GLADE) - -ALL_DEPS := $(DEP_ML) $(DEP_MLI) $(DEP_MLL) $(DEP_MLY) $(DEP_IDL) $(DEP_OXRIDL) $(DEP_ZOG) $(DEP_REP) $(DEP_GLADE) - -MLDEPS := $(filter %.d, $(ALL_DEPS)) -MLIDEPS := $(filter %.di, $(ALL_DEPS)) -BCDEPIS := $(MLIDEPS:%.di=$(BCDIDIR)/%.di) -NCDEPIS := $(MLIDEPS:%.di=$(NCDIDIR)/%.di) - -ALLML := $(filter %.mli %.ml %.mll %.mly %.idl %.oxridl %.rep %.zog %.glade, $(FILTERED)) - -IMPLO_INTF := $(ALLML:%.mli=%.mli.__) -IMPLO_INTF := $(foreach file, $(IMPLO_INTF), \ - $(basename $(file)).cmi $(basename $(file)).cmo) -IMPLO_INTF := $(filter-out %.mli.cmo, $(IMPLO_INTF)) -IMPLO_INTF := $(IMPLO_INTF:%.mli.cmi=%.cmi) - -IMPLX_INTF := $(IMPLO_INTF:.cmo=.cmx) - -INTF := $(filter %.cmi, $(IMPLO_INTF)) -IMPL_CMO := $(filter %.cmo, $(IMPLO_INTF)) -IMPL_CMX := $(IMPL_CMO:.cmo=.cmx) -IMPL_ASM := $(IMPL_CMO:.cmo=.asm) -IMPL_S := $(IMPL_CMO:.cmo=.s) - -OBJ_LINK := $(OBJ_C_IDL) $(OBJ_C_CXX) -OBJ_FILES := $(IMPL_CMO:.cmo=.$(EXT_OBJ)) $(OBJ_LINK) - -EXECS := $(addsuffix $(EXE), \ - $(sort $(TOPRESULT) $(BCRESULT) $(NCRESULT))) -ifdef WIN32 - EXECS += $(BCRESULT).dll $(NCRESULT).dll -endif - -CLIB_BASE := $(RESULT)$(RES_CLIB_SUF) -ifneq ($(strip $(OBJ_LINK)),) - RES_CLIB := lib$(CLIB_BASE).$(EXT_LIB) -endif - -ifdef WIN32 -DLLSONAME := $(CLIB_BASE).dll -else -DLLSONAME := dll$(CLIB_BASE).so -endif - -NONEXECS := $(INTF) $(IMPL_CMO) $(IMPL_CMX) $(IMPL_ASM) $(IMPL_S) \ - $(OBJ_FILES) $(PRE_TARGETS) $(BCRESULT).cma $(NCRESULT).cmxa \ - $(NCRESULT).$(EXT_LIB) $(BCRESULT).cmi $(BCRESULT).cmo \ - $(NCRESULT).cmi $(NCRESULT).cmx $(NCRESULT).o \ - $(RES_CLIB) $(IMPL_CMO:.cmo=.annot) \ - $(LIB_PACK_NAME).cmi $(LIB_PACK_NAME).cmo $(LIB_PACK_NAME).cmx $(LIB_PACK_NAME).o - -ifndef STATIC - NONEXECS += $(DLLSONAME) -endif - -ifndef LIBINSTALL_FILES - LIBINSTALL_FILES := $(RESULT).mli $(RESULT).cmi $(RESULT).cma \ - $(RESULT).cmxa $(RESULT).$(EXT_LIB) $(RES_CLIB) - ifndef STATIC - ifneq ($(strip $(OBJ_LINK)),) - LIBINSTALL_FILES += $(DLLSONAME) - endif - endif -endif - -export LIBINSTALL_FILES - -ifdef WIN32 - # some extra stuff is created while linking DLLs - NONEXECS += $(BCRESULT).$(EXT_LIB) $(BCRESULT).exp $(NCRESULT).exp $(CLIB_BASE).exp $(CLIB_BASE).lib -endif - -TARGETS := $(EXECS) $(NONEXECS) - -# If there are IDL-files -ifneq ($(strip $(FILTERED_IDL)),) - MAYBE_IDL := -cclib -lcamlidl -endif - -ifdef USE_CAMLP4 - CAMLP4PATH := \ - $(shell $(CAMLP4) -where 2>/dev/null || echo /usr/local/lib/camlp4) - INCFLAGS := -I $(CAMLP4PATH) - CINCFLAGS := -I$(CAMLP4PATH) -endif - -DINCFLAGS := $(INCFLAGS) $(SOURCE_DIRS:%=-I %) $(OCAML_DEFAULT_DIRS:%=-I %) -INCFLAGS := $(DINCFLAGS) $(INCDIRS:%=-I %) -CINCFLAGS += $(SOURCE_DIRS:%=-I%) $(INCDIRS:%=-I%) $(OCAML_DEFAULT_DIRS:%=-I%) - -ifndef MSVC - CLIBFLAGS += $(SOURCE_DIRS:%=-L%) $(LIBDIRS:%=-L%) \ - $(EXTLIBDIRS:%=-L%) $(OCAML_DEFAULT_DIRS:%=-L%) - - ifeq ($(ELF_RPATH), yes) - CLIBFLAGS += $(EXTLIBDIRS:%=-Wl,$(RPATH_FLAG)%) - endif -endif - -ifndef PROFILING - INTF_OCAMLC := $(OCAMLC) -else - ifndef THREADS - INTF_OCAMLC := $(OCAMLCP) -p $(OCAMLCPFLAGS) - else - # OCaml does not support profiling byte code - # with threads (yet), therefore we force an error. - ifndef REAL_OCAMLC - $(error Profiling of multithreaded byte code not yet supported by OCaml) - endif - INTF_OCAMLC := $(OCAMLC) - endif -endif - -ifndef MSVC - COMMON_LDFLAGS := $(LDFLAGS:%=-ccopt %) $(SOURCE_DIRS:%=-ccopt -L%) \ - $(LIBDIRS:%=-ccopt -L%) $(EXTLIBDIRS:%=-ccopt -L%) \ - $(EXTLIBDIRS:%=-ccopt -Wl $(OCAML_DEFAULT_DIRS:%=-ccopt -L%)) - - ifeq ($(ELF_RPATH),yes) - COMMON_LDFLAGS += $(EXTLIBDIRS:%=-ccopt -Wl,$(RPATH_FLAG)%) - endif -else - COMMON_LDFLAGS := -ccopt "/link -NODEFAULTLIB:LIBC $(LDFLAGS:%=%) $(SOURCE_DIRS:%=-LIBPATH:%) \ - $(LIBDIRS:%=-LIBPATH:%) $(EXTLIBDIRS:%=-LIBPATH:%) \ - $(OCAML_DEFAULT_DIRS:%=-LIBPATH:%) " -endif - -CLIBS_OPTS := $(CLIBS:%=-cclib -l%) $(CFRAMEWORKS:%=-cclib '-framework %') -ifdef MSVC - ifndef STATIC - # MSVC libraries do not have 'lib' prefix - CLIBS_OPTS := $(CLIBS:%=-cclib %.lib) - endif -endif - -ifneq ($(strip $(OBJ_LINK)),) - ifdef CREATE_LIB - OBJS_LIBS := -cclib -l$(CLIB_BASE) $(CLIBS_OPTS) $(MAYBE_IDL) - else - OBJS_LIBS := $(OBJ_LINK) $(CLIBS_OPTS) $(MAYBE_IDL) - endif -else - OBJS_LIBS := $(CLIBS_OPTS) $(MAYBE_IDL) -endif - -# If we have to make byte-code -ifndef REAL_OCAMLC - BYTE_OCAML := y - - # EXTRADEPS is added dependencies we have to insert for all - # executable files we generate. Ideally it should be all of the - # libraries we use, but it's hard to find the ones that get searched on - # the path since I don't know the paths built into the compiler, so - # just include the ones with slashes in their names. - EXTRADEPS := $(addsuffix .cma,$(foreach i,$(LIBS),$(if $(findstring /,$(i)),$(i)))) - SPECIAL_OCAMLFLAGS := $(OCAMLBCFLAGS) - - REAL_OCAMLC := $(INTF_OCAMLC) - - REAL_IMPL := $(IMPL_CMO) - REAL_IMPL_INTF := $(IMPLO_INTF) - IMPL_SUF := .cmo - - DEPFLAGS := - MAKE_DEPS := $(MLDEPS) $(BCDEPIS) - - ifdef CREATE_LIB - override CFLAGS := $(PIC_CFLAGS) $(CFLAGS) - override CPPFLAGS := $(PIC_CPPFLAGS) $(CPPFLAGS) - ifndef STATIC - ifneq ($(strip $(OBJ_LINK)),) - MAKEDLL := $(DLLSONAME) - ALL_LDFLAGS := -dllib $(DLLSONAME) - endif - endif - endif - - ifndef NO_CUSTOM - ifneq "$(strip $(OBJ_LINK) $(THREADS) $(MAYBE_IDL) $(CLIBS) $(CFRAMEWORKS))" "" - ALL_LDFLAGS += -custom - endif - endif - - ALL_LDFLAGS += $(INCFLAGS) $(OCAMLLDFLAGS) $(OCAMLBLDFLAGS) \ - $(COMMON_LDFLAGS) $(LIBS:%=%.cma) - CAMLIDLDLLFLAGS := - - ifdef THREADS - ifdef VMTHREADS - THREAD_FLAG := -vmthread - else - THREAD_FLAG := -thread - endif - ALL_LDFLAGS := $(THREAD_FLAG) $(ALL_LDFLAGS) - ifndef CREATE_LIB - ifndef REAL_OCAMLFIND - ALL_LDFLAGS := unix.cma threads.cma $(ALL_LDFLAGS) - endif - endif - endif - -# we have to make native-code -else - EXTRADEPS := $(addsuffix .cmxa,$(foreach i,$(LIBS),$(if $(findstring /,$(i)),$(i)))) - ifndef PROFILING - SPECIAL_OCAMLFLAGS := $(OCAMLNCFLAGS) - PLDFLAGS := - else - SPECIAL_OCAMLFLAGS := -p $(OCAMLNCFLAGS) - PLDFLAGS := -p - endif - - REAL_IMPL := $(IMPL_CMX) - REAL_IMPL_INTF := $(IMPLX_INTF) - IMPL_SUF := .cmx - - override CPPFLAGS := -DNATIVE_CODE $(CPPFLAGS) - - DEPFLAGS := -native - MAKE_DEPS := $(MLDEPS) $(NCDEPIS) - - ALL_LDFLAGS := $(PLDFLAGS) $(INCFLAGS) $(OCAMLLDFLAGS) \ - $(OCAMLNLDFLAGS) $(COMMON_LDFLAGS) - CAMLIDLDLLFLAGS := -opt - - ifndef CREATE_LIB - ALL_LDFLAGS += $(LIBS:%=%.cmxa) - else - override CFLAGS := $(PIC_CFLAGS) $(CFLAGS) - override CPPFLAGS := $(PIC_CPPFLAGS) $(CPPFLAGS) - endif - - ifdef THREADS - THREAD_FLAG := -thread - ALL_LDFLAGS := $(THREAD_FLAG) $(ALL_LDFLAGS) - ifndef CREATE_LIB - ifndef REAL_OCAMLFIND - ALL_LDFLAGS := unix.cmxa threads.cmxa $(ALL_LDFLAGS) - endif - endif - endif -endif - -export MAKE_DEPS - -ifdef ANNOTATE - ANNOT_FLAG := -dtypes -else -endif - -ALL_OCAMLCFLAGS := $(THREAD_FLAG) $(ANNOT_FLAG) $(OCAMLFLAGS) \ - $(INCFLAGS) $(SPECIAL_OCAMLFLAGS) - -ifdef make_deps - -include $(MAKE_DEPS) - PRE_TARGETS := -endif - -########################################################################### -# USER RULES - -# Call "OCamlMakefile QUIET=" to get rid of all of the @'s. -QUIET=@ - -# generates byte-code (default) -byte-code: $(PRE_TARGETS) - $(QUIET)$(MAKE) -r -f $(OCAMLMAKEFILE) $(BCRESULT) \ - REAL_RESULT="$(BCRESULT)" make_deps=yes -bc: byte-code - -byte-code-nolink: $(PRE_TARGETS) - $(QUIET)$(MAKE) -r -f $(OCAMLMAKEFILE) nolink \ - REAL_RESULT="$(BCRESULT)" make_deps=yes -bcnl: byte-code-nolink - -top: $(PRE_TARGETS) - $(QUIET)$(MAKE) -r -f $(OCAMLMAKEFILE) $(TOPRESULT) \ - REAL_RESULT="$(BCRESULT)" make_deps=yes - -# generates native-code - -native-code: $(PRE_TARGETS) - $(QUIET)$(MAKE) -r -f $(OCAMLMAKEFILE) $(NCRESULT) \ - REAL_RESULT="$(NCRESULT)" \ - REAL_OCAMLC="$(OCAMLOPT)" \ - make_deps=yes -nc: native-code - -native-code-nolink: $(PRE_TARGETS) - $(QUIET)$(MAKE) -r -f $(OCAMLMAKEFILE) nolink \ - REAL_RESULT="$(NCRESULT)" \ - REAL_OCAMLC="$(OCAMLOPT)" \ - make_deps=yes -ncnl: native-code-nolink - -# generates byte-code libraries -byte-code-library: $(PRE_TARGETS) - $(QUIET)$(MAKE) -r -f $(OCAMLMAKEFILE) \ - $(RES_CLIB) $(BCRESULT).cma \ - REAL_RESULT="$(BCRESULT)" \ - CREATE_LIB=yes \ - make_deps=yes -bcl: byte-code-library - -# generates native-code libraries -native-code-library: $(PRE_TARGETS) - $(QUIET)$(MAKE) -r -f $(OCAMLMAKEFILE) \ - $(RES_CLIB) $(NCRESULT).cmxa \ - REAL_RESULT="$(NCRESULT)" \ - REAL_OCAMLC="$(OCAMLOPT)" \ - CREATE_LIB=yes \ - make_deps=yes -ncl: native-code-library - -ifdef WIN32 -# generates byte-code dll -byte-code-dll: $(PRE_TARGETS) - $(QUIET)$(MAKE) -r -f $(OCAMLMAKEFILE) \ - $(RES_CLIB) $(BCRESULT).dll \ - REAL_RESULT="$(BCRESULT)" \ - make_deps=yes -bcd: byte-code-dll - -# generates native-code dll -native-code-dll: $(PRE_TARGETS) - $(QUIET)$(MAKE) -r -f $(OCAMLMAKEFILE) \ - $(RES_CLIB) $(NCRESULT).dll \ - REAL_RESULT="$(NCRESULT)" \ - REAL_OCAMLC="$(OCAMLOPT)" \ - make_deps=yes -ncd: native-code-dll -endif - -# generates byte-code with debugging information -debug-code: $(PRE_TARGETS) - $(QUIET)$(MAKE) -r -f $(OCAMLMAKEFILE) $(BCRESULT) \ - REAL_RESULT="$(BCRESULT)" make_deps=yes \ - OCAMLFLAGS="-g $(OCAMLFLAGS)" \ - OCAMLLDFLAGS="-g $(OCAMLLDFLAGS)" -dc: debug-code - -debug-code-nolink: $(PRE_TARGETS) - $(QUIET)$(MAKE) -r -f $(OCAMLMAKEFILE) nolink \ - REAL_RESULT="$(BCRESULT)" make_deps=yes \ - OCAMLFLAGS="-g $(OCAMLFLAGS)" \ - OCAMLLDFLAGS="-g $(OCAMLLDFLAGS)" -dcnl: debug-code-nolink - -# generates byte-code with debugging information (native code) -debug-native-code: $(PRE_TARGETS) - $(QUIET)$(MAKE) -r -f $(OCAMLMAKEFILE) $(NCRESULT) \ - REAL_RESULT="$(NCRESULT)" make_deps=yes \ - REAL_OCAMLC="$(OCAMLOPT)" \ - OCAMLFLAGS="-g $(OCAMLFLAGS)" \ - OCAMLLDFLAGS="-g $(OCAMLLDFLAGS)" -dnc: debug-native-code - -debug-native-code-nolink: $(PRE_TARGETS) - $(QUIET)$(MAKE) -r -f $(OCAMLMAKEFILE) nolink \ - REAL_RESULT="$(NCRESULT)" make_deps=yes \ - REAL_OCAMLC="$(OCAMLOPT)" \ - OCAMLFLAGS="-g $(OCAMLFLAGS)" \ - OCAMLLDFLAGS="-g $(OCAMLLDFLAGS)" -dncnl: debug-native-code-nolink - -# generates byte-code libraries with debugging information -debug-code-library: $(PRE_TARGETS) - $(QUIET)$(MAKE) -r -f $(OCAMLMAKEFILE) \ - $(RES_CLIB) $(BCRESULT).cma \ - REAL_RESULT="$(BCRESULT)" make_deps=yes \ - CREATE_LIB=yes \ - OCAMLFLAGS="-g $(OCAMLFLAGS)" \ - OCAMLLDFLAGS="-g $(OCAMLLDFLAGS)" -dcl: debug-code-library - -# generates byte-code libraries with debugging information (native code) -debug-native-code-library: $(PRE_TARGETS) - $(QUIET)$(MAKE) -r -f $(OCAMLMAKEFILE) \ - $(RES_CLIB) $(NCRESULT).cma \ - REAL_RESULT="$(NCRESULT)" make_deps=yes \ - REAL_OCAMLC="$(OCAMLOPT)" \ - CREATE_LIB=yes \ - OCAMLFLAGS="-g $(OCAMLFLAGS)" \ - OCAMLLDFLAGS="-g $(OCAMLLDFLAGS)" -dncl: debug-native-code-library - -# generates byte-code for profiling -profiling-byte-code: $(PRE_TARGETS) - $(QUIET)$(MAKE) -r -f $(OCAMLMAKEFILE) $(BCRESULT) \ - REAL_RESULT="$(BCRESULT)" PROFILING="y" \ - make_deps=yes -pbc: profiling-byte-code - -# generates native-code - -profiling-native-code: $(PRE_TARGETS) - $(QUIET)$(MAKE) -r -f $(OCAMLMAKEFILE) $(NCRESULT) \ - REAL_RESULT="$(NCRESULT)" \ - REAL_OCAMLC="$(OCAMLOPT)" \ - PROFILING="y" \ - make_deps=yes -pnc: profiling-native-code - -# generates byte-code libraries -profiling-byte-code-library: $(PRE_TARGETS) - $(QUIET)$(MAKE) -r -f $(OCAMLMAKEFILE) \ - $(RES_CLIB) $(BCRESULT).cma \ - REAL_RESULT="$(BCRESULT)" PROFILING="y" \ - CREATE_LIB=yes \ - make_deps=yes -pbcl: profiling-byte-code-library - -# generates native-code libraries -profiling-native-code-library: $(PRE_TARGETS) - $(QUIET)$(MAKE) -r -f $(OCAMLMAKEFILE) \ - $(RES_CLIB) $(NCRESULT).cmxa \ - REAL_RESULT="$(NCRESULT)" PROFILING="y" \ - REAL_OCAMLC="$(OCAMLOPT)" \ - CREATE_LIB=yes \ - make_deps=yes -pncl: profiling-native-code-library - -# packs byte-code objects -pack-byte-code: $(PRE_TARGETS) - $(QUIET)$(MAKE) -r -f $(OCAMLMAKEFILE) $(BCRESULT).cmo \ - REAL_RESULT="$(BCRESULT)" \ - PACK_LIB=yes make_deps=yes -pabc: pack-byte-code - -# packs native-code objects -pack-native-code: $(PRE_TARGETS) - $(QUIET)$(MAKE) -r -f $(OCAMLMAKEFILE) \ - $(NCRESULT).cmx $(NCRESULT).o \ - REAL_RESULT="$(NCRESULT)" \ - REAL_OCAMLC="$(OCAMLOPT)" \ - PACK_LIB=yes make_deps=yes -panc: pack-native-code - -# generates HTML-documentation -htdoc: $(DOC_DIR)/$(RESULT)/html/index.html - -# generates Latex-documentation -ladoc: $(DOC_DIR)/$(RESULT)/latex/doc.tex - -# generates PostScript-documentation -psdoc: $(DOC_DIR)/$(RESULT)/latex/doc.ps - -# generates PDF-documentation -pdfdoc: $(DOC_DIR)/$(RESULT)/latex/doc.pdf - -# generates all supported forms of documentation -doc: htdoc ladoc psdoc pdfdoc - -########################################################################### -# LOW LEVEL RULES - -$(REAL_RESULT): $(REAL_IMPL_INTF) $(OBJ_LINK) $(EXTRADEPS) $(RESULTDEPS) - $(REAL_OCAMLFIND) $(REAL_OCAMLC) \ - $(OCAML_FIND_PACKAGES) $(OCAML_FIND_LINKPKG) \ - $(ALL_LDFLAGS) $(OBJS_LIBS) -o $@$(EXE) \ - $(REAL_IMPL) - -nolink: $(REAL_IMPL_INTF) $(OBJ_LINK) - -ifdef WIN32 -$(REAL_RESULT).dll: $(REAL_IMPL_INTF) $(OBJ_LINK) - $(CAMLIDLDLL) $(CAMLIDLDLLFLAGS) $(OBJ_LINK) $(CLIBS) \ - -o $@ $(REAL_IMPL) -endif - -%$(TOPSUFFIX): $(REAL_IMPL_INTF) $(OBJ_LINK) $(EXTRADEPS) - $(REAL_OCAMLFIND) $(OCAMLMKTOP) \ - $(OCAML_FIND_PACKAGES) $(OCAML_FIND_LINKPKG) \ - $(ALL_LDFLAGS) $(OBJS_LIBS) -o $@$(EXE) \ - $(REAL_IMPL) - -.SUFFIXES: .mli .ml .cmi .cmo .cmx .cma .cmxa .$(EXT_OBJ) \ - .mly .di .d .$(EXT_LIB) .idl %.oxridl .c .m .$(EXT_CXX) .h .so \ - .rep .zog .glade - -ifndef STATIC -ifdef MINGW -$(DLLSONAME): $(OBJ_LINK) - $(CC) $(CFLAGS) $(CFLAGS_WIN32) $(OBJ_LINK) -shared -o $@ \ - -Wl,--whole-archive $(wildcard $(foreach dir,$(LIBDIRS),$(CLIBS:%=$(dir)/lib%.a))) \ - $(OCAMLLIBPATH)/ocamlrun.a \ - -Wl,--export-all-symbols \ - -Wl,--no-whole-archive -else -ifdef MSVC -$(DLLSONAME): $(OBJ_LINK) - link /NOLOGO /DLL /OUT:$@ $(OBJ_LINK) \ - $(wildcard $(foreach dir,$(LIBDIRS),$(CLIBS:%=$(dir)/%.lib))) \ - $(OCAMLLIBPATH)/ocamlrun.lib - -else -$(DLLSONAME): $(OBJ_LINK) - $(OCAMLMKLIB) $(INCFLAGS) $(CLIBFLAGS) \ - -o $(CLIB_BASE) $(OBJ_LINK) $(CLIBS:%=-l%) $(CFRAMEWORKS:%=-framework %) \ - $(OCAMLMKLIB_FLAGS) -endif -endif -endif - -ifndef LIB_PACK_NAME -$(RESULT).cma: $(REAL_IMPL_INTF) $(MAKEDLL) $(EXTRADEPS) $(RESULTDEPS) - $(REAL_OCAMLFIND) $(REAL_OCAMLC) -a $(ALL_LDFLAGS) $(OBJS_LIBS) -o $@ $(REAL_IMPL) - -$(RESULT).cmxa $(RESULT).$(EXT_LIB): $(REAL_IMPL_INTF) $(EXTRADEPS) $(RESULTDEPS) - $(REAL_OCAMLFIND) $(OCAMLOPT) -a $(ALL_LDFLAGS) $(OBJS_LIBS) -o $@ $(REAL_IMPL) -else -ifdef BYTE_OCAML -$(LIB_PACK_NAME).cmi $(LIB_PACK_NAME).cmo: $(REAL_IMPL_INTF) - $(REAL_OCAMLFIND) $(REAL_OCAMLC) -pack -o $(LIB_PACK_NAME).cmo $(OCAMLLDFLAGS) $(REAL_IMPL) -else -$(LIB_PACK_NAME).cmi $(LIB_PACK_NAME).cmx: $(REAL_IMPL_INTF) - $(REAL_OCAMLFIND) $(OCAMLOPT) -pack -o $(LIB_PACK_NAME).cmx $(OCAMLLDFLAGS) $(REAL_IMPL) -endif - -$(RESULT).cma: $(LIB_PACK_NAME).cmi $(LIB_PACK_NAME).cmo $(MAKEDLL) $(EXTRADEPS) $(RESULTDEPS) - $(REAL_OCAMLFIND) $(REAL_OCAMLC) -a $(ALL_LDFLAGS) $(OBJS_LIBS) -o $@ $(LIB_PACK_NAME).cmo - -$(RESULT).cmxa $(RESULT).$(EXT_LIB): $(LIB_PACK_NAME).cmi $(LIB_PACK_NAME).cmx $(EXTRADEPS) $(RESULTDEPS) - $(REAL_OCAMLFIND) $(OCAMLOPT) -a $(filter-out -custom, $(ALL_LDFLAGS)) $(OBJS_LIBS) -o $@ $(LIB_PACK_NAME).cmx -endif - -$(RES_CLIB): $(OBJ_LINK) -ifndef MSVC - ifneq ($(strip $(OBJ_LINK)),) - $(AR) rcs $@ $(OBJ_LINK) - endif -else - ifneq ($(strip $(OBJ_LINK)),) - lib -nologo -debugtype:cv -out:$(RES_CLIB) $(OBJ_LINK) - endif -endif - -.mli.cmi: $(EXTRADEPS) - $(QUIET)pp=`sed -n -e '/^#/d' -e 's/(\*pp \([^*]*\) \*)/\1/p;q' $<`; \ - if [ -z "$$pp" ]; then \ - $(ECHO) $(REAL_OCAMLFIND) $(INTF_OCAMLC) $(OCAML_FIND_PACKAGES) \ - -c $(THREAD_FLAG) $(ANNOT_FLAG) \ - $(OCAMLFLAGS) $(INCFLAGS) $<; \ - $(REAL_OCAMLFIND) $(INTF_OCAMLC) $(OCAML_FIND_PACKAGES) \ - -c $(THREAD_FLAG) $(ANNOT_FLAG) \ - $(OCAMLFLAGS) $(INCFLAGS) $<; \ - else \ - $(ECHO) $(REAL_OCAMLFIND) $(INTF_OCAMLC) $(OCAML_FIND_PACKAGES) \ - -c -pp \"$$pp $(PPFLAGS)\" $(THREAD_FLAG) $(ANNOT_FLAG) \ - $(OCAMLFLAGS) $(INCFLAGS) $<; \ - $(REAL_OCAMLFIND) $(INTF_OCAMLC) $(OCAML_FIND_PACKAGES) \ - -c -pp "$$pp $(PPFLAGS)" $(THREAD_FLAG) $(ANNOT_FLAG) \ - $(OCAMLFLAGS) $(INCFLAGS) $<; \ - fi - -.ml.cmi .ml.$(EXT_OBJ) .ml.cmx .ml.cmo: $(EXTRADEPS) - $(QUIET)pp=`sed -n -e '/^#/d' -e 's/(\*pp \([^*]*\) \*)/\1/p;q' $<`; \ - if [ -z "$$pp" ]; then \ - $(ECHO) $(REAL_OCAMLFIND) $(REAL_OCAMLC) $(OCAML_FIND_PACKAGES) \ - -c $(ALL_OCAMLCFLAGS) $<; \ - $(REAL_OCAMLFIND) $(REAL_OCAMLC) $(OCAML_FIND_PACKAGES) \ - -c $(ALL_OCAMLCFLAGS) $<; \ - else \ - $(ECHO) $(REAL_OCAMLFIND) $(REAL_OCAMLC) $(OCAML_FIND_PACKAGES) \ - -c -pp \"$$pp $(PPFLAGS)\" $(ALL_OCAMLCFLAGS) $<; \ - $(REAL_OCAMLFIND) $(REAL_OCAMLC) $(OCAML_FIND_PACKAGES) \ - -c -pp "$$pp $(PPFLAGS)" $(ALL_OCAMLCFLAGS) $<; \ - fi - -ifdef PACK_LIB -$(REAL_RESULT).cmo $(REAL_RESULT).cmx $(REAL_RESULT).o: $(REAL_IMPL_INTF) $(OBJ_LINK) $(EXTRADEPS) - $(REAL_OCAMLFIND) $(REAL_OCAMLC) -pack $(ALL_LDFLAGS) \ - $(OBJS_LIBS) -o $@ $(REAL_IMPL) -endif - -.PRECIOUS: %.ml -%.ml: %.mll - $(OCAMLLEX) $(LFLAGS) $< - -.PRECIOUS: %.ml %.mli -%.ml %.mli: %.mly - $(OCAMLYACC) $(YFLAGS) $< - $(QUIET)pp=`sed -n -e 's/.*(\*pp \([^*]*\) \*).*/\1/p;q' $<`; \ - if [ ! -z "$$pp" ]; then \ - mv $*.ml $*.ml.temporary; \ - echo "(*pp $$pp $(PPFLAGS)*)" > $*.ml; \ - cat $*.ml.temporary >> $*.ml; \ - rm $*.ml.temporary; \ - mv $*.mli $*.mli.temporary; \ - echo "(*pp $$pp $(PPFLAGS)*)" > $*.mli; \ - cat $*.mli.temporary >> $*.mli; \ - rm $*.mli.temporary; \ - fi - - -.PRECIOUS: %.ml -%.ml: %.rep - $(CAMELEON_REPORT) $(CAMELEON_REPORT_FLAGS) -gen $< - -.PRECIOUS: %.ml -%.ml: %.zog - $(CAMELEON_ZOGGY) $(CAMELEON_ZOGGY_FLAGS) -impl $< > $@ - -.PRECIOUS: %.ml -%.ml: %.glade - $(OCAML_GLADECC) $(OCAML_GLADECC_FLAGS) $< > $@ - -.PRECIOUS: %.ml %.mli -%.ml %.mli: %.oxridl - $(OXRIDL) $< - -.PRECIOUS: %.ml %.mli %_stubs.c %.h -%.ml %.mli %_stubs.c %.h: %.idl - $(CAMLIDL) $(MAYBE_IDL_HEADER) $(IDLFLAGS) \ - $(CAMLIDLFLAGS) $< - $(QUIET)if [ $(NOIDLHEADER) ]; then touch $*.h; fi - -.c.$(EXT_OBJ): - $(OCAMLC) -c -cc "$(CC)" -ccopt "$(CFLAGS) \ - $(CPPFLAGS) $(CPPFLAGS_WIN32) \ - $(CFLAGS_WIN32) $(CINCFLAGS) $(CFLAG_O)$@ " $< - -.m.$(EXT_OBJ): - $(CC) -c $(CFLAGS) $(CINCFLAGS) $(CPPFLAGS) \ - -I'$(OCAMLLIBPATH)' \ - $< $(CFLAG_O)$@ - -.$(EXT_CXX).$(EXT_OBJ): - $(CXX) -c $(CXXFLAGS) $(CINCFLAGS) $(CPPFLAGS) \ - -I'$(OCAMLLIBPATH)' \ - $< $(CFLAG_O)$@ - -$(MLDEPDIR)/%.d: %.ml - $(QUIET)if [ ! -d $(@D) ]; then mkdir -p $(@D); fi - $(QUIET)pp=`sed -n -e '/^#/d' -e 's/(\*pp \([^*]*\) \*)/\1/p;q' $<`; \ - if [ -z "$$pp" ]; then \ - $(ECHO) $(REAL_OCAMLFIND) $(OCAMLDEP) $(OCAML_DEP_PACKAGES) \ - $(DINCFLAGS) $< \> $@; \ - $(REAL_OCAMLFIND) $(OCAMLDEP) $(OCAML_DEP_PACKAGES) \ - $(DINCFLAGS) $< > $@; \ - else \ - $(ECHO) $(REAL_OCAMLFIND) $(OCAMLDEP) $(OCAML_DEP_PACKAGES) \ - -pp \"$$pp $(PPFLAGS)\" $(DINCFLAGS) $< \> $@; \ - $(REAL_OCAMLFIND) $(OCAMLDEP) $(OCAML_DEP_PACKAGES) \ - -pp "$$pp $(PPFLAGS)" $(DINCFLAGS) $< > $@; \ - fi - -$(BCDIDIR)/%.di $(NCDIDIR)/%.di: %.mli - $(QUIET)if [ ! -d $(@D) ]; then mkdir -p $(@D); fi - $(QUIET)pp=`sed -n -e '/^#/d' -e 's/(\*pp \([^*]*\) \*)/\1/p;q' $<`; \ - if [ -z "$$pp" ]; then \ - $(ECHO) $(REAL_OCAMLFIND) $(OCAMLDEP) $(DEPFLAGS) $(DINCFLAGS) $< \> $@; \ - $(REAL_OCAMLFIND) $(OCAMLDEP) $(DEPFLAGS) $(DINCFLAGS) $< > $@; \ - else \ - $(ECHO) $(REAL_OCAMLFIND) $(OCAMLDEP) $(DEPFLAGS) \ - -pp \"$$pp $(PPFLAGS)\" $(DINCFLAGS) $< \> $@; \ - $(REAL_OCAMLFIND) $(OCAMLDEP) $(DEPFLAGS) \ - -pp "$$pp $(PPFLAGS)" $(DINCFLAGS) $< > $@; \ - fi - -$(DOC_DIR)/$(RESULT)/html: - mkdir -p $@ - -$(DOC_DIR)/$(RESULT)/html/index.html: $(DOC_DIR)/$(RESULT)/html $(DOC_FILES) - rm -rf $3.80 *** - ---------------------------------------------------------------------------- - - Contents of this distribution - -Changes - guess what? ;-) - -OCamlMakefile - Makefile for easy handling of compilation of not so easy - OCaml-projects. It generates dependencies of OCaml-files - automatically, is able to handle "ocamllex"-, - "ocamlyacc"-, IDL- and C-files, knows how to run - preprocessors and generates native- or byte-code, as - executable or as library - with thread-support if you - want! Profiling and debugging support can be added on - the fly! There is also support for installing libraries. - Ah, yes, and you can also create toplevels from any - sources: this allows you immediate interactive testing. - Automatic generation of documentation is easy due to - integration of support for OCamldoc. - -README - this file - -calc/ - Directory containing a quite fully-featured example - of what "OCamlMakefile" can do for you. This example - makes use of "ocamllex", "ocamlyacc", IDL + C and - threads. - -camlp4/ - This simple example demonstrates how to automatically - preprocess files with the camlp4-preprocessor. - -gtk/ - Demonstration of how to use OCamlMakefile with GTK - and threads. Courtesy of Tim Freeman . - -idl/ - Contains a very small example of how to use - "camlidl" together with "OCamlMakefile". Also intended - to show, how easy it is to interface OCaml and C. - -threads/ - Two examples of how to use threads (originally - posted by Xavier Leroy some time ago). Shows the use of - "OCamlMakefile" in an environment of multiple compilation - targets. - ---------------------------------------------------------------------------- - - Why should you use it? - -For several reasons: - - * It is well-tested (I use it in all of my projects). - - * In contrast to most other approaches it generates dependencies - correctly by ensuring that all automatically generated OCaml-files - exist before dependency calculation. This is the only way to - guarantee that "ocamldep" works correctly. - - * It is extremely convenient (at least I think so ;-). - Even quite complex compilation processes (see example "calc.ml") - need very little information to work correctly - actually just about - the minimum (file names of sources). - ---------------------------------------------------------------------------- - - When you shouldn't use it... - -In projects where every compilation unit needs different flags - but -in such complicated cases you will be on your own anyway. Luckily, -this doesn't happen too frequently... - ---------------------------------------------------------------------------- - - How to use "OCamlMakefile" in your own project - (Take a look at the examples for a quick introduction!) - -Create your project-specific "Makefile" in the appropriate directory. - -Now there are two ways of making use of "OCamlMakefile": - - 1) Have a look at the default settings in "OCamlMakefile" and set - them to the values that are vaild on your system - whether the - path to the standard libraries is ok, what executables shall be - used, etc... - - 2) Copy it into the directory of the project to be compiled. - Add "-include OCamlMakefile" as a last line of your "Makefile". - - 3) Put it somewhere else on the system. In this case you will have to - set a variable "OCAMLMAKEFILE" in your project-specific "Makefile". - This is the way in which the examples are written: so you need - only one version of "OCamlMakefile" to manage all your projects! - See the examples for details. - -You should usually specify two further variables for your project: - - * SOURCES (default: foo.ml) - * RESULT (default: foo) - -Put all the sources necessary for a target into variable "SOURCES". -Then set "RESULT" to the name of the target. If you want to generate -libraries, you should *not* specify the suffix (".cma", ".cmxa", ".a") -- it will be added automatically if you specify that you want to build -a library. - - ** Don't forget to add the ".mli"-files, too! ** - ** Don't forget that order of the source files matters! ** - -The order is important, because it matters during linking anyway -due to potential side effects caused at program startup. This is -why OCamlMakefile does not attempt to partially order dependencies by -itself, which might confuse users even more. It just compiles and links -OCaml-sources in the order specified by the user, even if it could -determine automatically that the order cannot be correct. - -The minimum of your "Makefile" looks like this (assuming that -"OCamlMakefile" is in the search path of "make"): - - -include OCamlMakefile - -This will assume that you want to compile a file "foo.ml" to a binary -"foo". - -Otherwise, your Makefile will probably contain something like this: - - SOURCES = foo.ml - RESULT = foo - -include OCamlMakefile - -Be careful with the names you put into these variables: if they are wrong, -a "make clean" might erase the wrong files - but I know you will not do -that ;-) - -A simple "make" will generate a byte-code executable. If you want to -change this, you may add an "all"-rule that generates something else. - -E.g.: - - SOURCES = foo.ml - RESULT = foo - all: native-code-library - -include OCamlMakefile - -This will build a native-code library "foo.cmxa" (+ "foo.a") from file -"foo.ml". - -You may even build several targets at once. To produce byte- and native-code -executables with one "make", add the following rule: - - all: byte-code native-code - -You will probably want to use a different suffix for each of these targets -so that the result will not be overwritten (see optional variables below -for details). - -You may also tell "make" at the command-line what kind of target to -produce (e.g. "make nc"). Here all the possibilities with shortcuts -between parenthesis: - - * byte-code (bc) - * byte-code-nolink (bcnl) - no linking stage - * byte-code-library (bcl) - * native-code (nc) - * native-code-nolink (ncnl) - no linking stage - * native-code-library (ncl) - * debug-code (dc) - * debug-code-nolink (dcnl) - no linking stage - * debug-code-library (dcl) - * profiling-byte-code (pbc) - * profiling-byte-code-library (pbcl) - * profiling-native-code (pnc) - * profiling-native-code-library (pncl) - * byte-code-dll (bcd) - * native-code-dll (ncd) - * pack-byte-code (pabc) - * pack-native-code (panc) - * toplevel interpreter (top) - * subprojs - -Here a short note concerning building and linking byte code libraries -with C-files: - - OCaml links C-object files only when they are used in an executable. - After compilation they should be placed in some directory that is in - your include path if you link your library against an executable. - - It is sometimes more convenient to link all C-object files into a - single C-library. Then you have to override the automatic link flags - of your library using "-noautolink" and add another linkflag that - links in your C-library explicitly. - -What concerns maintenance: - - "make clean" removes all (all!) automatically generated files - so - again: make sure your variables are ok! - - "make cleanup" is similar to "make clean" but leaves executables. - -Another way to destroy some important files is by having "OCamlMakefile" -automatically generate files with the same name. Read the documentation -about the tools in the OCaml-distribution to see what kind of files are -generated. "OCamlMakefile" additionally generates ('%' is basename of -source file): - - %_idl.c - "camlidl" generates a file "%.c" from "%.idl", but this is - not such a good idea, because when generating native-code, - both the file "%.c" and "%.ml" would generate files "%.o" - which would overwrite each other. Thus, "OCamlMakefile" - renames "%.c" to "%_idl.c" to work around this problem. - -The dependencies are stored in three different subdirectories (dot dirs): - - ._d - contains dependencies for .ml-files - ._bcdi - contains byte code dependencies for .mli-files - ._ncdi - contains native code dependencies for .mli-files - -The endings of the dependency files are: "%.d" for those generated from -"%.ml"-files, "%.di" for ones derived from "%.mli"-files. - ---------------------------------------------------------------------------- - - Debugging - - This is easy: if you discover a bug, just do a "make clean; make dc" - to recompile your project with debugging information. Then you can - immediately apply "ocamldebug" to the executable. - ---------------------------------------------------------------------------- - - Profiling - - For generating code that can be profiled with "ocamlprof" (byte code) - or "gprof" (native code), compile your project with one of the profiling - targets (see targets above). E.g.: - - * "make pbc" will build byte code that can be profiled with - "ocamlprof". - - * "make pnc" will build native code that can be profiled with - "gprof". - - Please note that it is not currently possible to profile byte code with - threads. OCamlMakefile will force an error if you try to do this. - - A short hint for DEC Alpha-users (under Digital Unix): you may also - compile your sources to native code without any further profiling - options/targets. Then call "pixie my_exec", "my_exec" being your - executable. This will produce (among other files) an executable - "my_exec.pixie". Call it and it will produce profiling information which - can be analysed using "prof -pixie my_exec". The resulting information - is extremely detailed and allows analysis up to the clock cycle level... - ---------------------------------------------------------------------------- - - Using Preprocessors - - Because one could employ any kind of program that reads from standard - input and prints to standard output as preprocessor, there cannot be any - default way to handle all of them correctly without further knowledge. - - Therefore you have to cooperate a bit with OCamlMakefile to let - preprocessing happen automatically. Basically, this only requires - that you put a comment into the first line of files that should be - preprocessed, e.g.: - - (*pp cat *) - ... rest of program ... - - OCamlMakefile looks at the first line of your files, and if it finds - a comment that starts with "(*pp", then it will assume that the - rest of the comment tells it how to correctly call the appropriate - preprocessor. In this case the program "cat" will be called, which will, - of course, just output the source text again without changing it. - - If you are, for example, an advocate of the new "revised syntax", - which is supported by the camlp4 preprocessor, you could simply write: - - (*pp camlp4r *) - ... rest of program in revised syntax ... - - Simple, isn't it? - - If you want to write your own syntax extensions, just take a look at the - example in the directory "camlp4": it implements the "repeat ... until" - extension as described in the camlp4-tutorial. - ---------------------------------------------------------------------------- - - Library (Un-)Installation Support - - OCamlMakefile contains two targets using "ocamlfind" for this purpose: - - * libinstall - * libuninstall - - These two targets require the existence of the variable - "LIBINSTALL_FILES", which should be set to all the files that you - want to install in the library directory (usually %.mli, %.cmi, %.cma, - %.cmxa, %.a and possibly further C-libraries). The target "libinstall" - has the dependency "all" to force compilation of the library so make - sure you define target "all" in your Makefile appropriately. - - The targets inform the user about the configured install path and ask - for confirmation to (un)install there. If you want to use them, it - is often a good idea to just alias them in your Makefile to "install" - and "uninstall" respectively. - - Two other targets allow installation of files into a particular - directory (without using ocamlfind): - - * rawinstall - * rawuninstall - ---------------------------------------------------------------------------- - - Building toplevels - - There is just one target for this: - - * top - - The generated file can be used immediately for interactive sessions - - even with scanners, parsers, C-files, etc.! - ---------------------------------------------------------------------------- - - Generating documentation - - The following targets are supported: - - * htdoc - generates HTML-documentation - * ladoc - generates Latex-documentation - * psdoc - generates PostScript-documentation - * pdfdoc - generates PDF-documentation - * doc - generates all supported forms of documentation - * clean-doc - generates all supported forms of documentation - - All of them generate a sub-directory "doc". More precisely, for HTML it - is "doc/$(RESULT)/html" and for Latex, PostScript and PDF the directory - "doc/$(RESULT)/latex". See the OCamldoc-manual for details and the - optional variables below for settings you can control. - ---------------------------------------------------------------------------- - - Handling subprojects - - You can have several targets in the same directory and manage them - from within an single Makefile. - - Give each subproject a name, e.g. "p1", "p2", etc. Then you export - settings specific to each project by using variables of the form - "PROJ_p1", "PROJ_p2", etc. E.g.: - - define PROJ_p1 - SOURCES="foo.ml main.ml" - RESULT="p1" - OCAMLFLAGS="-unsafe" - endef - export PROJ_p1 - - define PROJ_p2 - ... - endef - export PROJ_p2 - - You may also export common settings used by all projects directly, e.g. - "export THREADS = y". - - Now it is a good idea to define, which projects should be affected by - commands by default. E.g.: - - ifndef SUBPROJS - export SUBPROJS = p1 p2 - endif - - This will automatically generate a given target for all those - subprojects if this variable has not been defined in the shell - environment or in the command line of the make-invocation by the user. - E.g., "make dc" will generate debug code for all subprojects. - - Then you need to define a default action for your subprojects if "make" - has been called without arguments: - - all: bc - - This will build byte code by default for all subprojects. - - Finally, you'll have to define a catch-all target that uses the target - provided by the user for all subprojects. Just add (assuming that - OCAMLMAKEFILE has been defined appropriately): - - %: - @make -f $(OCAMLMAKEFILE) subprojs SUBTARGET=$@ - - See the "threads"-directory in the distribution for a short example! - ---------------------------------------------------------------------------- - - Optional variables that may be passed to "OCamlMakefile" - - * LIB_PACK_NAME - packs all modules of a library into a module whose - name is given in variable "LIB_PACK_NAME". - - * RES_CLIB_SUF - when building a library that contains C-stubs, this - variable controls the suffix appended to the name - of the C-library (default: "_stubs"). - - * THREADS - say "THREADS = yes" if you need thread support compiled in, - otherwise leave it away. - - * VMTHREADS - say "VMTHREADS = yes" if you want to force VM-level - scheduling of threads (byte-code only). - - * ANNOTATE - say "ANNOTATE = yes" to generate type annotation files - (.annot) to support displaying of type information - in editors. - - * USE_CAMLP4 - say "USE_CAMLP4 = yes" in your "Makefile" if you - want to include the camlp4 directory during the - build process, otherwise leave it away. - - * INCDIRS - directories that should be searched for ".cmi"- and - ".cmo"-files. You need not write "-I ..." - just the - plain names. - * LIBDIRS - directories that should be searched for libraries - Also just put the plain paths into this variable - * EXTLIBDIRS - Same as "LIBDIRS", but paths in this variable are - also added to the binary via the "-R"-flag so that - dynamic libraries in non-standard places can be found. - * RESULTDEPS - Targets on which results (executables or libraries) - should additionally depend. - - * PACKS - adds packages under control of "findlib". - - * PREDS - specifies "findlib"-predicates. - - * LIBS - OCaml-libraries that should be linked (just plain names). - E.g. if you want to link the Str-library, just write - "str" (without quotes). - The new OCaml-compiler handles libraries in such - a way that they "remember" whether they have to - be linked against a C-library and it gets linked - in automatically. - If there is a slash in the library name (such as - "./str" or "lib/foo") then make is told that the - generated files depend on the library. This - helps to ensure that changes to your libraries are - taken into account, which is important if you are - regenerating your libraries frequently. - * CLIBS - C-libraries that should be linked (just plain names). - - * PRE_TARGETS - set this to a list of target files that you want - to have buildt before dependency calculation actually - takes place. E.g. use this to automatically compile - modules needed by camlp4, which have to be available - before other modules can be parsed at all. - - ** WARNING **: the files mentioned in this variable - will be removed when "make clean" is executed! - - * LIBINSTALL_FILES - the files of a library that should be installed - using "findlib". Default: - - $(RESULT).mli $(RESULT).cmi $(RESULT).cma - $(RESULT).cmxa $(RESULT).a lib$(RESULT).a - - * OCAML_LIB_INSTALL - target directory for "rawinstall/rawuninstall". - (default: $(OCAMLLIBPATH)/contrib) - - * DOC_FILES - names of files from which documentation is generated. - (default: all .mli-files in your $(SOURCES)). - - * DOC_DIR - name of directory where documentation should be stored. - - * OCAMLFLAGS - flags passed to the compilers - * OCAMLBCFLAGS - flags passed to the byte code compiler only - * OCAMLNCFLAGS - flags passed to the native code compiler only - - * OCAMLLDFLAGS - flags passed to the OCaml-linker - * OCAMLBLDFLAGS - flags passed to the OCaml-linker when linking byte code - * OCAMLNLDFLAGS - flags passed to the OCaml-linker when linking - native code - - * OCAMLMKLIB_FLAGS - flags passed to the OCaml library tool - - * OCAMLCPFLAGS - profiling flags passed to "ocamlcp" (default: "a") - - * PPFLAGS - additional flags passed to the preprocessor (default: none) - - * LFLAGS - flags passed to "ocamllex" - * YFLAGS - flags passed to "ocamlyacc" - * IDLFLAGS - flags passed to "camlidl" - - * OCAMLDOCFLAGS - flags passed to "ocamldoc" - - * OCAMLFIND_INSTFLAGS - flags passed to "ocamlfind" during installation - (default: none) - - * DVIPSFLAGS - flags passed to dvips - (when generating documentation in PostScript). - - * STATIC - set this variable if you want to force creation - of static libraries - - * CC - the C-compiler to be used - * CXX - the C++-compiler to be used - - * CFLAGS - additional flags passed to the C-compiler. - The flag "-DNATIVE_CODE" will be passed automatically - if you choose to build native code. This allows you - to compile your C-files conditionally. But please - note: You should do a "make clean" or remove the - object files manually or touch the %.c-files: - otherwise, they may not be correctly recompiled - between different builds. - - * CXXFLAGS - additional flags passed to the C++-compiler. - - * CPPFLAGS - additional flags passed to the C-preprocessor. - - * CFRAMEWORKS - Objective-C framework to pass to linker on MacOS X. - - * LDFLAGS - additional flags passed to the C-linker - - * RPATH_FLAG - flag passed through to the C-linker to set a path for - dynamic libraries. May need to be set by user on - exotic platforms. (default: "-R"). - - * ELF_RPATH_FLAG - this flag is used to set the rpath on ELF-platforms. - (default: "-R") - - * ELF_RPATH - if this flag is "yes", then the RPATH_FLAG will be - passed by "-Wl" to the linker as normal on - ELF-platforms. - - * OCAMLLIBPATH - path to the OCaml-standard-libraries - (first default: `$(OCAMLC) -where`) - (second default: "/usr/local/lib/ocaml") - - * OCAML_DEFAULT_DIRS - additional path in which the user can supply - default directories to his own collection of - libraries. The idea is to pass this as an environment - variable so that the Makefiles do not have to contain - this path all the time. - - * OCAMLFIND - ocamlfind from findlib (default: "ocamlfind") - * OCAMLC - byte-code compiler (default: "ocamlc") - * OCAMLOPT - native-code compiler (default: "ocamlopt") - * OCAMLMKTOP - top-level compiler (default: "ocamlmktop") - * OCAMLCP - profiling byte-code compiler (default: "ocamlcp") - * OCAMLDEP - dependency generator (default: "ocamldep") - * OCAMLLEX - scanner generator (default: "ocamllex") - * OCAMLYACC - parser generator (default: "ocamlyacc") - * OCAMLMKLIB - tool to create libraries (default: "ocamlmklib") - * CAMLIDL - IDL-code generator (default: "camlidl") - * CAMLIDLDLL - IDL-utility (default: "camlidldll") - * CAMLP4 - camlp4 preprocessor (default: "camlp4") - * OCAMLDOC - OCamldoc-command (default: "ocamldoc") - - * LATEX - Latex-processor (default: "latex") - * DVIPS - dvips-command (default: "dvips") - * PS2PDF - PostScript-to-PDF converter (default: "ps2pdf") - - * CAMELEON_REPORT - report tool of Cameleon (default: "report") - * CAMELEON_REPORT_FLAGS - flags for the report tool of Cameleon - - * CAMELEON_ZOGGY - zoggy tool of Cameleon - (default: "camlp4o pa_zog.cma pr_o.cmo") - * CAMELEON_ZOGGY_FLAGS - flags for the zoggy tool of Cameleon - - * OCAML_GLADECC - Glade compiler for OCaml (default: "lablgladecc2") - * OCAML_GLADECC_FLAGS - flags for the Glade compiler - - * OXRIDL - OXRIDL-generator (default: "oxridl") - - * NOIDLHEADER - set to "yes" to prohibit "OCamlMakefile" from using - the default camlidl-flag "-header". - - * NO_CUSTOM - Prevent linking in custom mode. - - * QUIET - unsetting this variable (e.g. "make QUIET=") - will print all executed commands, including - intermediate ones. This allows more comfortable - debugging when things go wrong during a build. - - * REALLY_QUIET - when set this flag turns off output from some commands. - - * OCAMLMAKEFILE - location of (=path to) this "OCamlMakefile". - Because it calles itself recursively, it has to - know where it is. (default: "OCamlMakefile" = - local directory) - - * BCSUFFIX - Suffix for all byte-code files. E.g.: - - RESULT = foo - BCSUFFIX = _bc - - This will produce byte-code executables/libraries - with basename "foo_bc". - - * NCSUFFIX - Similar to "BCSUFFIX", but for native-code files. - * TOPSUFFIX - Suffix added to toplevel interpreters (default: ".top") - - * SUBPROJS - variable containing the names of subprojects to be - compiled. - - * SUBTARGET - target to be built for all projects in variable - SUBPROJS. - ---------------------------------------------------------------------------- - - Optional variables for Windows users - - * MINGW - variable to detect the MINGW-environment - * MSVC - variable to detect the MSVC-compiler - ---------------------------------------------------------------------------- - -Up-to-date information (newest release of distribution) can always be -found at: - - http://www.ocaml.info/home/ocaml_sources.html - ---------------------------------------------------------------------------- - -Enjoy! - -New York, 2007-04-22 -Markus Mottl - -e-mail: markus.mottl@gmail.com -WWW: http://www.ocaml.info diff --git a/vendor/git.apache.org/thrift.git/lib/ocaml/_oasis b/vendor/git.apache.org/thrift.git/lib/ocaml/_oasis index 95536f0..315183f 100644 --- a/vendor/git.apache.org/thrift.git/lib/ocaml/_oasis +++ b/vendor/git.apache.org/thrift.git/lib/ocaml/_oasis @@ -1,5 +1,5 @@ Name: libthrift-ocaml -Version: 0.10.0 +Version: 0.12.0 OASISFormat: 0.3 Synopsis: OCaml bindings for the Apache Thrift RPC system Authors: Apache Thrift Developers diff --git a/vendor/git.apache.org/thrift.git/lib/ocaml/descr b/vendor/git.apache.org/thrift.git/lib/ocaml/descr new file mode 100644 index 0000000..a41749d --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/ocaml/descr @@ -0,0 +1 @@ +OCaml bindings for the Apache Thrift RPC system diff --git a/vendor/git.apache.org/thrift.git/lib/ocaml/opam b/vendor/git.apache.org/thrift.git/lib/ocaml/opam new file mode 100644 index 0000000..9dbc3d9 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/ocaml/opam @@ -0,0 +1,8 @@ +opam-version: "1" +maintainer: "XXX(FILL ME IN WITH EMAIL)" +build: [ + [make] + [make "install"] +] +remove: [["ocamlfind" "remove" "thrift"]] +depends: ["ocamlfind"] diff --git a/vendor/git.apache.org/thrift.git/lib/ocaml/url b/vendor/git.apache.org/thrift.git/lib/ocaml/url new file mode 100644 index 0000000..fe4d604 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/ocaml/url @@ -0,0 +1,2 @@ +archive: "XXX(FILL ME IN WITH URL)" +checksum: "XXX(FILL ME IN WITH MD5)" diff --git a/vendor/git.apache.org/thrift.git/lib/perl/MANIFEST.SKIP b/vendor/git.apache.org/thrift.git/lib/perl/MANIFEST.SKIP new file mode 100644 index 0000000..7963b42 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/perl/MANIFEST.SKIP @@ -0,0 +1,13 @@ +blib/.*$ +build-cpan-dist.sh +FixupDist.pl +MANIFEST.bak +MANIFEST.SKIP +MYMETA.json +Makefile +Makefile.am +Makefile.in +pm_to_blib +test/Makefile.am +test/Makefile.in +tools/FixupDist.pl diff --git a/vendor/git.apache.org/thrift.git/lib/perl/Makefile.PL b/vendor/git.apache.org/thrift.git/lib/perl/Makefile.PL index ceca86f..bdeaad2 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/Makefile.PL +++ b/vendor/git.apache.org/thrift.git/lib/perl/Makefile.PL @@ -17,13 +17,20 @@ # under the License. # +use 5.10.0; +use strict; +use warnings; + use ExtUtils::MakeMaker; -WriteMakefile( 'NAME' => 'Thrift', - 'VERSION_FROM' => 'lib/Thrift.pm', - 'PREREQ_PM' => { - 'Bit::Vector' => 0, + +WriteMakefile( ABSTRACT => 'Apache Thrift is a software framework for scalable cross-language services development.', + AUTHOR => 'Apache Thrift ', + LICENSE => 'apache_2_0', + MIN_PERL_VERSION => '5.010000', + NAME => 'Thrift', + NEEDS_LINKING => 0, + PREREQ_PM => { + 'Bit::Vector' => 0, 'Class::Accessor' => 0 }, - ($] >= 5.005 ? - ( AUTHOR => 'Apache Thrift ') : ()), - ); + VERSION_FROM => 'lib/Thrift.pm' ); diff --git a/vendor/git.apache.org/thrift.git/lib/perl/Makefile.am b/vendor/git.apache.org/thrift.git/lib/perl/Makefile.am index 0d2c8d3..fa0f16b 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/Makefile.am +++ b/vendor/git.apache.org/thrift.git/lib/perl/Makefile.am @@ -38,12 +38,14 @@ clean-local: EXTRA_DIST = \ coding_standards.md \ + build-cpan-dist.sh \ Makefile.PL \ test.pl \ lib/Thrift.pm \ lib/Thrift.pm \ lib/Thrift/BinaryProtocol.pm \ lib/Thrift/BufferedTransport.pm \ + lib/Thrift/Exception.pm \ lib/Thrift/FramedTransport.pm \ lib/Thrift/HttpClient.pm \ lib/Thrift/MemoryBuffer.pm \ @@ -59,6 +61,7 @@ EXTRA_DIST = \ lib/Thrift/SSLServerSocket.pm \ lib/Thrift/UnixServerSocket.pm \ lib/Thrift/UnixSocket.pm \ + lib/Thrift/Type.pm \ lib/Thrift/Transport.pm \ README.md diff --git a/vendor/git.apache.org/thrift.git/lib/perl/README.md b/vendor/git.apache.org/thrift.git/lib/perl/README.md index 51247e0..bd1e5b2 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/README.md +++ b/vendor/git.apache.org/thrift.git/lib/perl/README.md @@ -1,7 +1,13 @@ Thrift Perl Software Library -License -======= +# Summary + +Apache Thrift is a software framework for scalable cross-language services development. +It combines a software stack with a code generation engine to build services that work +efficiently and seamlessly between many programming languages. A language-neutral IDL +is used to generate functioning client libraries and server-side handling frameworks. + +# License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file @@ -20,10 +26,13 @@ KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -Using Thrift with Perl -===================== +# For More Information -Thrift requires Perl >= 5.6.0 +See the [Apache Thrift Web Site](http://thrift.apache.org/) for more information. + +# Using Thrift with Perl + +Thrift requires Perl >= 5.10.0 Unexpected exceptions in a service handler are converted to TApplicationException with type INTERNAL ERROR and the string @@ -34,12 +43,82 @@ to wrap eval{} statments around any code that contains exceptions. Please see tutoral and test dirs for examples. -Dependencies -============ +The Perl ForkingServer ignores SIGCHLD allowing the forks to be +reaped by the operating system naturally when they exit. This means +one cannot use a custom SIGCHLD handler in the consuming perl +implementation that calls serve(). It is acceptable to use +a custom SIGCHLD handler within a thrift handler implementation +as the ForkingServer resets the forked child process to use +default signal handling. + +# Dependencies + +The following modules are not provided by Perl 5.10.0 but are required +to use Thrift. + +## Runtime + + * Bit::Vector + * Class::Accessor + +### HttpClient Transport + +These are only required if using Thrift::HttpClient: + + * HTTP::Request + * IO::String + * LWP::UserAgent + +### SSL/TLS + +These are only required if using Thrift::SSLSocket or Thrift::SSLServerSocket: + + * IO::Socket::SSL + +# Breaking Changes + +## 0.10.0 + +The socket classes were refactored in 0.10.0 so that there is one package per +file. This means `use Socket;` no longer defines SSLSocket. You can use this +technique to make your application run against 0.10.0 as well as earlier versions: + +`eval { require Thrift::SSLSocket; } or do { require Thrift::Socket; }` + +## 0.11.0 + + * Namespaces of packages that were not scoped within Thrift have been fixed. + ** TApplicationException is now Thrift::TApplicationException + ** TException is now Thrift::TException + ** TMessageType is now Thrift::TMessageType + ** TProtocolException is now Thrift::TProtocolException + ** TProtocolFactory is now Thrift::TProtocolFactory + ** TTransportException is now Thrift::TTransportException + ** TType is now Thrift::TType + +If you need a single version of your code to work with both older and newer thrift +namespace changes, you can make the new, correct namespaces behave like the old ones +in your files with this technique to create an alias, which will allow you code to +run against either version of the perl runtime for thrift: + +`BEGIN {*TType:: = *Thrift::TType::}` + + * Packages found in Thrift.pm were moved into the Thrift/ directory in separate files: + ** Thrift::TApplicationException is now in Thrift/Exception.pm + ** Thrift::TException is now in Thrift/Exception.pm + ** Thrift::TMessageType is now in Thrift/MessageType.pm + ** Thrift::TType is now in Thrift/Type.pm + +If you need to modify your code to work against both older or newer thrift versions, +you can deal with these changes in a backwards compatible way in your projects using eval: + +`eval { require Thrift::Exception; require Thrift::MessageType; require Thrift::Type; } + or do { require Thrift; }` + +# Deprecations + +## 0.11.0 + +Thrift::HttpClient setRecvTimeout() and setSendTimeout() are deprecated. +Use setTimeout instead. -Bit::Vector - comes with modern perl installations. -Class::Accessor -IO::Socket::INET - comes with modern perl installations. -IO::Socket::SSL - required if using SSL/TLS. -NET::SSLeay -Crypt::SSLeay - for make cross diff --git a/vendor/git.apache.org/thrift.git/lib/perl/build-cpan-dist.sh b/vendor/git.apache.org/thrift.git/lib/perl/build-cpan-dist.sh new file mode 100755 index 0000000..ae22e7e --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/perl/build-cpan-dist.sh @@ -0,0 +1,53 @@ +#!/bin/bash +# +# This script is intended to be used after tagging the repository and updating +# the version files for a release. It will create a CPAN archive. Run this +# from inside a docker image like ubuntu-xenial. +# + +set -e + +rm -f MANIFEST +rm -rf Thrift-* + +# setup cpan without a prompt +echo | cpan +cpan install HTTP::Date +cpan install CPAN +cpan install CPAN::Meta ExtUtils::MakeMaker JSON::PP + +perl Makefile.PL +rm MYMETA.yml +make manifest +make dist + +# +# We unpack the archive so we can add version metadata for CPAN +# so that it properly indexes Thrift and remove unnecessary files. +# + +echo '-----------------------------------------------------------' +set -x + +DISTFILE=$(ls Thrift*.gz) +NEWFILE=${DISTFILE/t-v/t-} +if [[ "$DISTFILE" != "$NEWFILE" ]]; then + mv $DISTFILE $NEWFILE + DISTFILE="$NEWFILE" +fi +tar xzf $DISTFILE +rm $DISTFILE +DISTDIR=$(ls -d Thrift*) +# cpan doesn't like "Thrift-v0.nn.0 as a directory name +# needs to be Thrift-0.nn.0 +NEWDIR=${DISTDIR/t-v/t-} +if [[ "$DISTDIR" != "$NEWDIR" ]]; then + mv $DISTDIR $NEWDIR + DISTDIR="$NEWDIR" +fi +cd $DISTDIR +cp -p ../Makefile.PL . +perl ../tools/FixupDist.pl +cd .. +tar cvzf $DISTFILE $DISTDIR +rm -r $DISTDIR diff --git a/vendor/git.apache.org/thrift.git/lib/perl/coding_standards.md b/vendor/git.apache.org/thrift.git/lib/perl/coding_standards.md index fa0390b..e4e8255 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/coding_standards.md +++ b/vendor/git.apache.org/thrift.git/lib/perl/coding_standards.md @@ -1 +1,2 @@ -Please follow [General Coding Standards](/doc/coding_standards.md) +Please follow [General Coding Standards](/doc/coding_standards.md). +Additional perl coding standards can be found in [perlstyle](http://perldoc.perl.org/perlstyle.html). diff --git a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift.pm b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift.pm index 152d223..107b2a2 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift.pm +++ b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift.pm @@ -17,177 +17,20 @@ # under the License. # -package Thrift; - -our $VERSION = '0.10.0'; - -require 5.6.0; +use 5.10.0; use strict; use warnings; # -# Data types that can be sent via Thrift +# Versioning # -package TType; -use constant STOP => 0; -use constant VOID => 1; -use constant BOOL => 2; -use constant BYTE => 3; -use constant I08 => 3; -use constant DOUBLE => 4; -use constant I16 => 6; -use constant I32 => 8; -use constant I64 => 10; -use constant STRING => 11; -use constant UTF7 => 11; -use constant STRUCT => 12; -use constant MAP => 13; -use constant SET => 14; -use constant LIST => 15; -use constant UTF8 => 16; -use constant UTF16 => 17; -1; - +# Every perl module for Thrift will have the same version +# declaration. For a production build, change it below to +# something like "v0.11.0" and all of the packages in all +# of the files will pick it up from here. # -# Message types for RPC -# -package TMessageType; -use constant CALL => 1; -use constant REPLY => 2; -use constant EXCEPTION => 3; -use constant ONEWAY => 4; -1; -package Thrift::TException; - -use overload '""' => sub { - return - ref( $_[0] ) - . " error: " - . ( $_[0]->{message} || 'empty message' ) - . " (code " - . ( defined $_[0]->{code} ? $_[0]->{code} : 'undefined' ) . ")"; - }; - -sub new { - my $classname = shift; - my $self = {message => shift, code => shift || 0}; - - return bless($self,$classname); -} -1; - -package TApplicationException; -use base('Thrift::TException'); - -use constant UNKNOWN => 0; -use constant UNKNOWN_METHOD => 1; -use constant INVALID_MESSAGE_TYPE => 2; -use constant WRONG_METHOD_NAME => 3; -use constant BAD_SEQUENCE_ID => 4; -use constant MISSING_RESULT => 5; -use constant INTERNAL_ERROR => 6; -use constant PROTOCOL_ERROR => 7; -use constant INVALID_TRANSFORM => 8; -use constant INVALID_PROTOCOL => 9; -use constant UNSUPPORTED_CLIENT_TYPE => 10; - -sub new { - my $classname = shift; - - my $self = $classname->SUPER::new(@_); - - return bless($self,$classname); -} - -sub read { - my $self = shift; - my $input = shift; - - my $xfer = 0; - my $fname = undef; - my $ftype = 0; - my $fid = 0; - - $xfer += $input->readStructBegin(\$fname); - - while (1) - { - $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); - if ($ftype == TType::STOP) { - last; next; - } - - SWITCH: for($fid) - { - /1/ && do{ - - if ($ftype == TType::STRING) { - $xfer += $input->readString(\$self->{message}); - } else { - $xfer += $input->skip($ftype); - } - - last; - }; - - /2/ && do{ - if ($ftype == TType::I32) { - $xfer += $input->readI32(\$self->{code}); - } else { - $xfer += $input->skip($ftype); - } - last; - }; - - $xfer += $input->skip($ftype); - } - - $xfer += $input->readFieldEnd(); - } - $xfer += $input->readStructEnd(); - - return $xfer; -} - -sub write { - my $self = shift; - my $output = shift; - - my $xfer = 0; - - $xfer += $output->writeStructBegin('TApplicationException'); - - if ($self->getMessage()) { - $xfer += $output->writeFieldBegin('message', TType::STRING, 1); - $xfer += $output->writeString($self->getMessage()); - $xfer += $output->writeFieldEnd(); - } - - if ($self->getCode()) { - $xfer += $output->writeFieldBegin('type', TType::I32, 2); - $xfer += $output->writeI32($self->getCode()); - $xfer += $output->writeFieldEnd(); - } - - $xfer += $output->writeFieldStop(); - $xfer += $output->writeStructEnd(); - - return $xfer; -} - -sub getMessage -{ - my $self = shift; - - return $self->{message}; -} - -sub getCode -{ - my $self = shift; - - return $self->{code}; -} +package Thrift; +use version 0.77; our $VERSION = version->declare("v0.12.0_0"); 1; diff --git a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/BinaryProtocol.pm b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/BinaryProtocol.pm index c638ead..d62509a 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/BinaryProtocol.pm +++ b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/BinaryProtocol.pm @@ -17,28 +17,29 @@ # under the License. # -require 5.6.0; - +use 5.10.0; use strict; use warnings; -use utf8; -use Encode; - -use Thrift; -use Thrift::Protocol; - use Bit::Vector; +use Encode; +use Thrift; +use Thrift::Exception; +use Thrift::MessageType; +use Thrift::Protocol; +use Thrift::Type; +use utf8; # # Binary implementation of the Thrift protocol. # package Thrift::BinaryProtocol; use base('Thrift::Protocol'); +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); use constant VERSION_MASK => 0xffff0000; use constant VERSION_1 => 0x80010000; -use constant IS_BIG_ENDIAN => unpack("h*", pack("s", 1)) =~ /01/; +use constant IS_BIG_ENDIAN => unpack('h*', pack('s', 1)) =~ m/01/; sub new { @@ -66,7 +67,8 @@ sub writeMessageEnd return 0; } -sub writeStructBegin{ +sub writeStructBegin +{ my $self = shift; my $name = shift; return 0; @@ -97,7 +99,7 @@ sub writeFieldEnd sub writeFieldStop { my $self = shift; - return $self->writeByte(TType::STOP); + return $self->writeByte(Thrift::TType::STOP); } sub writeMapBegin @@ -252,14 +254,16 @@ sub readMessageBegin my $result = $self->readI32(\$version); if (($version & VERSION_MASK) > 0) { if (($version & VERSION_MASK) != VERSION_1) { - die new Thrift::TException('Missing version identifier') + die Thrift::TProtocolException->new('Missing version identifier', + Thrift::TProtocolException::BAD_VERSION); } $$type = $version & 0x000000ff; return $result + $self->readString($name) + $self->readI32($seqid); - } else { # old client support code + } + else { # old client support code return $result + $self->readStringBody($name, $version) + # version here holds the size of the string @@ -297,7 +301,7 @@ sub readFieldBegin my $result = $self->readByte($fieldType); - if ($$fieldType == TType::STOP) { + if ($$fieldType == Thrift::TType::STOP) { $$fieldId = 0; return $result; } @@ -425,7 +429,7 @@ sub readI64 my ($hi,$lo)=unpack('NN',$data); - my $vec = new Bit::Vector(64); + my $vec = Bit::Vector->new(64); $vec->Chunk_Store(32,32,$hi); $vec->Chunk_Store(32,0,$lo); @@ -447,7 +451,7 @@ sub readDouble else { $data = scalar reverse($self->{trans}->readAll(8)); } - + my @arr = unpack('d', $data); $$value = $arr[0]; @@ -465,7 +469,8 @@ sub readString if ($len) { $$value = $self->{trans}->readAll($len); - } else { + } + else { $$value = ''; } @@ -480,7 +485,8 @@ sub readStringBody if ($len) { $$value = $self->{trans}->readAll($len); - } else { + } + else { $$value = ''; } @@ -491,7 +497,8 @@ sub readStringBody # Binary Protocol Factory # package Thrift::BinaryProtocolFactory; -use base('TProtocolFactory'); +use base('Thrift::TProtocolFactory'); +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); sub new { @@ -505,7 +512,7 @@ sub getProtocol{ my $self = shift; my $trans = shift; - return new Thrift::BinaryProtocol($trans); + return Thrift::BinaryProtocol->new($trans); } 1; diff --git a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/BufferedTransport.pm b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/BufferedTransport.pm index 3868ca2..6b5bf7a 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/BufferedTransport.pm +++ b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/BufferedTransport.pm @@ -17,15 +17,17 @@ # under the License. # -require 5.6.0; +use 5.10.0; use strict; use warnings; use Thrift; +use Thrift::Exception; use Thrift::Transport; package Thrift::BufferedTransport; use base('Thrift::Transport'); +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); sub new { @@ -110,6 +112,7 @@ sub flush # BufferedTransport factory creates buffered transport objects from transports # package Thrift::BufferedTransportFactory; +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); sub new { my $classname = shift; diff --git a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Exception.pm b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Exception.pm new file mode 100644 index 0000000..e404068 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Exception.pm @@ -0,0 +1,161 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +use 5.10.0; +use strict; +use warnings; + +use Thrift; +use Thrift::Type; + +package Thrift::TException; +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); + +use overload '""' => sub { + return + sprintf '%s error: %s (code %s)', + ref( $_[0] ), + ( $_[0]->{message} || 'empty message' ), + ( defined $_[0]->{code} ? $_[0]->{code} : 'undefined' ); + }; + +sub new { + my $classname = shift; + my $self = {message => shift, code => shift || 0}; + + return bless($self,$classname); +} + +package Thrift::TApplicationException; +use parent -norequire, 'Thrift::TException'; +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); + +use constant UNKNOWN => 0; +use constant UNKNOWN_METHOD => 1; +use constant INVALID_MESSAGE_TYPE => 2; +use constant WRONG_METHOD_NAME => 3; +use constant BAD_SEQUENCE_ID => 4; +use constant MISSING_RESULT => 5; +use constant INTERNAL_ERROR => 6; +use constant PROTOCOL_ERROR => 7; +use constant INVALID_TRANSFORM => 8; +use constant INVALID_PROTOCOL => 9; +use constant UNSUPPORTED_CLIENT_TYPE => 10; + +sub new { + my $classname = shift; + + my $self = $classname->SUPER::new(@_); + + return bless($self,$classname); +} + +sub read { + my $self = shift; + my $input = shift; + + my $xfer = 0; + my $fname = undef; + my $ftype = 0; + my $fid = 0; + + $xfer += $input->readStructBegin(\$fname); + + while (1) + { + $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); + if ($ftype == Thrift::TType::STOP) { + last; next; + } + + SWITCH: for($fid) + { + /1/ && do{ + + if ($ftype == Thrift::TType::STRING) { + $xfer += $input->readString(\$self->{message}); + } + else { + $xfer += $input->skip($ftype); + } + + last; + }; + + /2/ && do{ + if ($ftype == Thrift::TType::I32) { + $xfer += $input->readI32(\$self->{code}); + } + else { + $xfer += $input->skip($ftype); + } + last; + }; + + $xfer += $input->skip($ftype); + } + + $xfer += $input->readFieldEnd(); + } + $xfer += $input->readStructEnd(); + + return $xfer; +} + +sub write { + my $self = shift; + my $output = shift; + + my $xfer = 0; + + $xfer += $output->writeStructBegin('TApplicationException'); + + if ($self->getMessage()) { + $xfer += $output->writeFieldBegin('message', Thrift::TType::STRING, 1); + $xfer += $output->writeString($self->getMessage()); + $xfer += $output->writeFieldEnd(); + } + + if ($self->getCode()) { + $xfer += $output->writeFieldBegin('type', Thrift::TType::I32, 2); + $xfer += $output->writeI32($self->getCode()); + $xfer += $output->writeFieldEnd(); + } + + $xfer += $output->writeFieldStop(); + $xfer += $output->writeStructEnd(); + + return $xfer; +} + +sub getMessage +{ + my $self = shift; + + return $self->{message}; +} + +sub getCode +{ + my $self = shift; + + return $self->{code}; +} + +1; diff --git a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/FramedTransport.pm b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/FramedTransport.pm index 6f2d2cf..ba89ba3 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/FramedTransport.pm +++ b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/FramedTransport.pm @@ -17,6 +17,7 @@ # under the License. # +use 5.10.0; use strict; use warnings; @@ -30,8 +31,8 @@ use Thrift::Transport; # @package thrift.transport # package Thrift::FramedTransport; - use base('Thrift::Transport'); +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); sub new { @@ -69,7 +70,7 @@ sub close my $self = shift; if (defined $self->{transport}) { - $self->{transport}->close(); + $self->{transport}->close(); } } @@ -167,6 +168,7 @@ sub flush # FramedTransport factory creates framed transport objects from transports # package Thrift::FramedTransportFactory; +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); sub new { my $classname = shift; @@ -189,5 +191,4 @@ sub getTransport return $buffered; } - 1; diff --git a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/HttpClient.pm b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/HttpClient.pm index d6fc8be..40ec9ce 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/HttpClient.pm +++ b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/HttpClient.pm @@ -17,26 +17,25 @@ # under the License. # -require 5.6.0; +use 5.10.0; use strict; use warnings; +use HTTP::Request; +use IO::String; +use LWP::UserAgent; use Thrift; +use Thrift::Exception; use Thrift::Transport; -use HTTP::Request; -use LWP::UserAgent; -use IO::String; - package Thrift::HttpClient; - use base('Thrift::Transport'); +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); sub new { my $classname = shift; my $url = shift || 'http://localhost:9090'; - my $debugHandler = shift; my $out = IO::String->new; binmode($out); @@ -44,44 +43,44 @@ sub new my $self = { url => $url, out => $out, - debugHandler => $debugHandler, - debug => 0, - sendTimeout => 100, - recvTimeout => 750, + timeout => 100, handle => undef, + headers => {}, }; return bless($self,$classname); } +sub setTimeout +{ + my $self = shift; + my $timeout = shift; + + $self->{timeout} = $timeout; +} + +sub setRecvTimeout +{ + warn 'setRecvTimeout is deprecated - use setTimeout instead'; + # note: recvTimeout was never used so we do not need to do anything here +} + sub setSendTimeout { my $self = shift; my $timeout = shift; - $self->{sendTimeout} = $timeout; + warn 'setSendTimeout is deprecated - use setTimeout instead'; + + $self->setTimeout($timeout); } -sub setRecvTimeout +sub setHeader { - my $self = shift; - my $timeout = shift; + my $self = shift; + my ($name, $value) = @_; - $self->{recvTimeout} = $timeout; -} - - -# -#Sets debugging output on or off -# -# @param bool $debug -# -sub setDebug -{ - my $self = shift; - my $debug = shift; - - $self->{debug} = $debug; + $self->{headers}->{$name} = $value; } # @@ -103,8 +102,8 @@ sub close { my $self = shift; if (defined($self->{io})) { - close($self->{io}); - $self->{io} = undef; + close($self->{io}); + $self->{io} = undef; } } @@ -122,7 +121,8 @@ sub readAll my $buf = $self->read($len); if (!defined($buf)) { - die new Thrift::TException('TSocket: Could not read '.$len.' bytes from input buffer'); + die Thrift::TTransportException->new("TSocket: Could not read $len bytes from input buffer", + Thrift::TTransportException::END_OF_FILE); } return $buf; } @@ -140,15 +140,18 @@ sub read my $in = $self->{in}; if (!defined($in)) { - die new Thrift::TException("Response buffer is empty, no request."); + die Thrift::TTransportException->new('Response buffer is empty, no request.', + Thrift::TTransportException::END_OF_FILE); } eval { - my $ret = sysread($in, $buf, $len); - if (! defined($ret)) { - die new Thrift::TException("No more data available."); - } - }; if($@){ - die new Thrift::TException($@); + my $ret = sysread($in, $buf, $len); + if (! defined($ret)) { + die Thrift::TTransportException->new('No more data available.', + Thrift::TTransportException::TIMED_OUT); + } + }; + if($@){ + die Thrift::TTransportException->new("$@", Thrift::TTransportException::UNKNOWN); } return $buf; @@ -171,8 +174,9 @@ sub flush { my $self = shift; - my $ua = LWP::UserAgent->new('timeout' => ($self->{sendTimeout} / 1000), - 'agent' => 'Perl/THttpClient' + my $ua = LWP::UserAgent->new( + 'timeout' => ($self->{timeout} / 1000), + 'agent' => 'Perl/THttpClient' ); $ua->default_header('Accept' => 'application/x-thrift'); $ua->default_header('Content-Type' => 'application/x-thrift'); @@ -182,7 +186,7 @@ sub flush $out->setpos(0); # rewind my $buf = join('', <$out>); - my $request = new HTTP::Request(POST => $self->{url}, undef, $buf); + my $request = HTTP::Request->new(POST => $self->{url}, ($self->{headers} || undef), $buf); my $response = $ua->request($request); my $content_ref = $response->content_ref; diff --git a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/MemoryBuffer.pm b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/MemoryBuffer.pm index 0b28687..be97ce4 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/MemoryBuffer.pm +++ b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/MemoryBuffer.pm @@ -17,7 +17,7 @@ # under the License. # -require 5.6.0; +use 5.10.0; use strict; use warnings; @@ -26,6 +26,7 @@ use Thrift::Transport; package Thrift::MemoryBuffer; use base('Thrift::Transport'); +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); sub new { @@ -34,10 +35,10 @@ sub new my $bufferSize= shift || 1024; my $self = { - buffer => '', - bufferSize=> $bufferSize, - wPos => 0, - rPos => 0, + buffer => '', + bufferSize => $bufferSize, + wPos => 0, + rPos => 0, }; return bless($self,$classname); @@ -116,7 +117,8 @@ sub readAll my $avail = ($self->{wPos} - $self->{rPos}); if ($avail < $len) { - die new TTransportException("Attempt to readAll($len) found only $avail available"); + die TTransportException->new("Attempt to readAll($len) found only $avail available", + Thrift::TTransportException::END_OF_FILE); } my $data = ''; diff --git a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/MessageType.pm b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/MessageType.pm index c8902cc..d25c2f7 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/MessageType.pm +++ b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/MessageType.pm @@ -17,16 +17,21 @@ # under the License. # +use 5.10.0; use strict; use warnings; -package Thrift::MessageType; +use Thrift; -use strict; +# +# Message types for RPC +# +package Thrift::TMessageType; +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); -use constant CALL => 1; -use constant REPLY => 2; -use constant EXCEPTION => 3; -use constant ONEWAY => 4; +use constant CALL => 1; +use constant REPLY => 2; +use constant EXCEPTION => 3; +use constant ONEWAY => 4; -1; \ No newline at end of file +1; diff --git a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/MultiplexedProcessor.pm b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/MultiplexedProcessor.pm index 421bf73..ae925d7 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/MultiplexedProcessor.pm +++ b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/MultiplexedProcessor.pm @@ -17,19 +17,19 @@ # under the License. # +use 5.10.0; use strict; use warnings; use Thrift; -use Thrift::Protocol; -use Thrift::MultiplexedProtocol; -use Thrift::ProtocolDecorator; use Thrift::MessageType; +use Thrift::MultiplexedProtocol; +use Thrift::Protocol; +use Thrift::ProtocolDecorator; package Thrift::StoredMessageProtocol; use base qw(Thrift::ProtocolDecorator); - -use strict; +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); sub new { my $classname = shift; @@ -46,7 +46,7 @@ sub new { return bless($self,$classname); } -sub readMessageBegin +sub readMessageBegin { my $self = shift; my $name = shift; @@ -59,27 +59,34 @@ sub readMessageBegin } package Thrift::MultiplexedProcessor; - -use strict; +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); sub new { my $classname = shift; my $self = {}; - + $self->{serviceProcessorMap} = {}; + $self->{defaultProcessor} = undef; return bless($self,$classname); } +sub defaultProcessor { + my $self = shift; + my $processor = shift; + + $self->{defaultProcessor} = $processor; +} + sub registerProcessor { my $self = shift; my $serviceName = shift; my $processor = shift; - + $self->{serviceProcessorMap}->{$serviceName} = $processor; } -sub process{ +sub process { my $self = shift; my $input = shift; my $output = shift; @@ -92,30 +99,35 @@ sub process{ my ($fname, $mtype, $rseqid); $input->readMessageBegin(\$fname, \$mtype, \$rseqid); - - if ($mtype ne Thrift::MessageType::CALL && $mtype ne Thrift::MessageType::ONEWAY) { - die new Thrift::TException("This should not have happened!?"); + if ($mtype ne Thrift::TMessageType::CALL && $mtype ne Thrift::TMessageType::ONEWAY) { + die Thrift::TException->new('This should not have happened!?'); } - + # Extract the service name and the new Message name. if (index($fname, Thrift::MultiplexedProtocol::SEPARATOR) == -1) { - die new Thrift::TException("Service name not found in message name: {$fname}. Did you " . - "forget to use a MultiplexProtocol in your client?"); + if (defined $self->{defaultProcessor}) { + return $self->{defaultProcessor}->process( + Thrift::StoredMessageProtocol->new($input, $fname, $mtype, $rseqid), $output + ); + } else { + die Thrift::TException->new("Service name not found in message name: {$fname} and no default processor defined. Did you " . + 'forget to use a MultiplexProtocol in your client?'); + } } - + (my $serviceName, my $messageName) = split(':', $fname, 2); - + if (!exists($self->{serviceProcessorMap}->{$serviceName})) { - die new Thrift::TException("Service name not found: {$serviceName}. Did you forget " . - "to call registerProcessor()?"); + die Thrift::TException->new("Service name not found: {$serviceName}. Did you forget " . + 'to call registerProcessor()?'); } - - #Dispatch processing to the stored processor - my $processor = $self->{serviceProcessorMap}->{$serviceName}; - return $processor->process( - new Thrift::StoredMessageProtocol($input, $messageName, $mtype, $rseqid), $output - ); + + # Dispatch processing to the stored processor + my $processor = $self->{serviceProcessorMap}->{$serviceName}; + return $processor->process( + Thrift::StoredMessageProtocol->new($input, $messageName, $mtype, $rseqid), $output + ); } -1; \ No newline at end of file +1; diff --git a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/MultiplexedProtocol.pm b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/MultiplexedProtocol.pm index 83a4eaf..5b5b60b 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/MultiplexedProtocol.pm +++ b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/MultiplexedProtocol.pm @@ -17,26 +17,27 @@ # under the License. # +use 5.10.0; use strict; use warnings; +use Thrift; +use Thrift::MessageType; use Thrift::Protocol; use Thrift::ProtocolDecorator; -use Thrift::MessageType; package Thrift::MultiplexedProtocol; use base qw(Thrift::ProtocolDecorator); +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); -use strict; - -use constant SEPARATOR => ':'; +use constant SEPARATOR => ':'; sub new { my $classname = shift; my $protocol = shift; my $serviceName = shift; my $self = $classname->SUPER::new($protocol); - + $self->{serviceName} = $serviceName; return bless($self,$classname); @@ -50,18 +51,18 @@ sub new { # @param int $type Message type. # @param int $seqid The sequence id of this message. # -sub writeMessageBegin +sub writeMessageBegin { - my $self = shift; + my $self = shift; my ($name, $type, $seqid) = @_; - if ($type == Thrift::MessageType::CALL || $type == Thrift::MessageType::ONEWAY) { + if ($type == Thrift::TMessageType::CALL || $type == Thrift::TMessageType::ONEWAY) { my $nameWithService = $self->{serviceName}.SEPARATOR.$name; $self->SUPER::writeMessageBegin($nameWithService, $type, $seqid); } else { - $self->SUPER::writeMessageBegin($name, $type, $seqid); + $self->SUPER::writeMessageBegin($name, $type, $seqid); } } -1; \ No newline at end of file +1; diff --git a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Protocol.pm b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Protocol.pm index 3e9f0dd..26ef46a 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Protocol.pm +++ b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Protocol.pm @@ -17,26 +17,28 @@ # under the License. # -require 5.6.0; +use 5.10.0; use strict; use warnings; use Thrift; +use Thrift::Exception; +use Thrift::Type; # # Protocol exceptions # -package TProtocolException; +package Thrift::TProtocolException; use base('Thrift::TException'); +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); -use constant UNKNOWN => 0; -use constant INVALID_DATA => 1; -use constant NEGATIVE_SIZE => 2; -use constant SIZE_LIMIT => 3; -use constant BAD_VERSION => 4; +use constant UNKNOWN => 0; +use constant INVALID_DATA => 1; +use constant NEGATIVE_SIZE => 2; +use constant SIZE_LIMIT => 3; +use constant BAD_VERSION => 4; use constant NOT_IMPLEMENTED => 5; -use constant DEPTH_LIMIT => 6; - +use constant DEPTH_LIMIT => 6; sub new { my $classname = shift; @@ -50,6 +52,7 @@ sub new { # Protocol base class module. # package Thrift::Protocol; +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); sub new { my $classname = shift; @@ -78,37 +81,37 @@ sub getTransport sub writeMessageBegin { my ($name, $type, $seqid); - die "abstract"; + die 'abstract'; } # # Close the message # sub writeMessageEnd { - die "abstract"; + die 'abstract'; } # # Writes a struct header. # # @param string $name Struct name -# @throws TException on write error +# @throws TProtocolException on write error # @return int How many bytes written # sub writeStructBegin { my ($name); - die "abstract"; + die 'abstract'; } # # Close a struct. # -# @throws TException on write error +# @throws TProtocolException on write error # @return int How many bytes written # sub writeStructEnd { - die "abstract"; + die 'abstract'; } # @@ -117,85 +120,85 @@ sub writeStructEnd { # @param string $name Field name # @param int $type Field type # @param int $fid Field id -# @throws TException on write error +# @throws TProtocolException on write error # @return int How many bytes written # sub writeFieldBegin { my ($fieldName, $fieldType, $fieldId); - die "abstract"; + die 'abstract'; } sub writeFieldEnd { - die "abstract"; + die 'abstract'; } sub writeFieldStop { - die "abstract"; + die 'abstract'; } sub writeMapBegin { my ($keyType, $valType, $size); - die "abstract"; + die 'abstract'; } sub writeMapEnd { - die "abstract"; + die 'abstract'; } sub writeListBegin { my ($elemType, $size); - die "abstract"; + die 'abstract'; } sub writeListEnd { - die "abstract"; + die 'abstract'; } sub writeSetBegin { my ($elemType, $size); - die "abstract"; + die 'abstract'; } sub writeSetEnd { - die "abstract"; + die 'abstract'; } sub writeBool { my ($bool); - die "abstract"; + die 'abstract'; } sub writeByte { my ($byte); - die "abstract"; + die 'abstract'; } sub writeI16 { my ($i16); - die "abstract"; + die 'abstract'; } sub writeI32 { my ($i32); - die "abstract"; + die 'abstract'; } sub writeI64 { my ($i64); - die "abstract"; + die 'abstract'; } sub writeDouble { my ($dub); - die "abstract"; + die 'abstract'; } sub writeString { my ($str); - die "abstract"; + die 'abstract'; } # @@ -208,7 +211,7 @@ sub writeString sub readMessageBegin { my ($name, $type, $seqid); - die "abstract"; + die 'abstract'; } # @@ -216,105 +219,105 @@ sub readMessageBegin # sub readMessageEnd { - die "abstract"; + die 'abstract'; } sub readStructBegin { my($name); - die "abstract"; + die 'abstract'; } sub readStructEnd { - die "abstract"; + die 'abstract'; } sub readFieldBegin { my ($name, $fieldType, $fieldId); - die "abstract"; + die 'abstract'; } sub readFieldEnd { - die "abstract"; + die 'abstract'; } sub readMapBegin { my ($keyType, $valType, $size); - die "abstract"; + die 'abstract'; } sub readMapEnd { - die "abstract"; + die 'abstract'; } sub readListBegin { my ($elemType, $size); - die "abstract"; + die 'abstract'; } sub readListEnd { - die "abstract"; + die 'abstract'; } sub readSetBegin { my ($elemType, $size); - die "abstract"; + die 'abstract'; } sub readSetEnd { - die "abstract"; + die 'abstract'; } sub readBool { my ($bool); - die "abstract"; + die 'abstract'; } sub readByte { my ($byte); - die "abstract"; + die 'abstract'; } sub readI16 { my ($i16); - die "abstract"; + die 'abstract'; } sub readI32 { my ($i32); - die "abstract"; + die 'abstract'; } sub readI64 { my ($i64); - die "abstract"; + die 'abstract'; } sub readDouble { my ($dub); - die "abstract"; + die 'abstract'; } sub readString { my ($str); - die "abstract"; + die 'abstract'; } # @@ -332,36 +335,36 @@ sub skip my $result; my $i; - if($type == TType::BOOL) + if($type == Thrift::TType::BOOL) { return $self->readBool(\$ref); } - elsif($type == TType::BYTE){ + elsif($type == Thrift::TType::BYTE){ return $self->readByte(\$ref); } - elsif($type == TType::I16){ + elsif($type == Thrift::TType::I16){ return $self->readI16(\$ref); } - elsif($type == TType::I32){ + elsif($type == Thrift::TType::I32){ return $self->readI32(\$ref); } - elsif($type == TType::I64){ + elsif($type == Thrift::TType::I64){ return $self->readI64(\$ref); } - elsif($type == TType::DOUBLE){ + elsif($type == Thrift::TType::DOUBLE){ return $self->readDouble(\$ref); } - elsif($type == TType::STRING) + elsif($type == Thrift::TType::STRING) { return $self->readString(\$ref); } - elsif($type == TType::STRUCT) + elsif($type == Thrift::TType::STRUCT) { $result = $self->readStructBegin(\$ref); while (1) { my ($ftype,$fid); $result += $self->readFieldBegin(\$ref, \$ftype, \$fid); - if ($ftype == TType::STOP) { + if ($ftype == Thrift::TType::STOP) { last; } $result += $self->skip($ftype); @@ -370,7 +373,7 @@ sub skip $result += $self->readStructEnd(); return $result; } - elsif($type == TType::MAP) + elsif($type == Thrift::TType::MAP) { my($keyType,$valType,$size); $result = $self->readMapBegin(\$keyType, \$valType, \$size); @@ -381,7 +384,7 @@ sub skip $result += $self->readMapEnd(); return $result; } - elsif($type == TType::SET) + elsif($type == Thrift::TType::SET) { my ($elemType,$size); $result = $self->readSetBegin(\$elemType, \$size); @@ -391,7 +394,7 @@ sub skip $result += $self->readSetEnd(); return $result; } - elsif($type == TType::LIST) + elsif($type == Thrift::TType::LIST) { my ($elemType,$size); $result = $self->readListBegin(\$elemType, \$size); @@ -402,7 +405,8 @@ sub skip return $result; } - die new Thrift::TException("Type $type not recognised --- corrupt data?"); + die Thrift::TProtocolException->new("Type $type not recognized --- corrupt data?", + Thrift::TProtocolException::INVALID_DATA); } @@ -418,31 +422,31 @@ sub skipBinary my $itrans = shift; my $type = shift; - if($type == TType::BOOL) - { - return $itrans->readAll(1); - } - elsif($type == TType::BYTE) + if($type == Thrift::TType::BOOL) { return $itrans->readAll(1); } - elsif($type == TType::I16) + elsif($type == Thrift::TType::BYTE) + { + return $itrans->readAll(1); + } + elsif($type == Thrift::TType::I16) { return $itrans->readAll(2); } - elsif($type == TType::I32) + elsif($type == Thrift::TType::I32) { return $itrans->readAll(4); } - elsif($type == TType::I64) + elsif($type == Thrift::TType::I64) { return $itrans->readAll(8); } - elsif($type == TType::DOUBLE) + elsif($type == Thrift::TType::DOUBLE) { return $itrans->readAll(8); } - elsif( $type == TType::STRING ) + elsif( $type == Thrift::TType::STRING ) { my @len = unpack('N', $itrans->readAll(4)); my $len = $len[0]; @@ -451,25 +455,25 @@ sub skipBinary } return 4 + $itrans->readAll($len); } - elsif( $type == TType::STRUCT ) + elsif( $type == Thrift::TType::STRUCT ) { my $result = 0; while (1) { - my $ftype = 0; - my $fid = 0; - my $data = $itrans->readAll(1); - my @arr = unpack('c', $data); - $ftype = $arr[0]; - if ($ftype == TType::STOP) { - last; - } - # I16 field id - $result += $itrans->readAll(2); - $result += $self->skipBinary($itrans, $ftype); + my $ftype = 0; + my $fid = 0; + my $data = $itrans->readAll(1); + my @arr = unpack('c', $data); + $ftype = $arr[0]; + if ($ftype == Thrift::TType::STOP) { + last; + } + # I16 field id + $result += $itrans->readAll(2); + $result += $self->skipBinary($itrans, $ftype); } return $result; } - elsif($type == TType::MAP) + elsif($type == Thrift::TType::MAP) { # Ktype my $data = $itrans->readAll(1); @@ -493,7 +497,7 @@ sub skipBinary } return $result; } - elsif($type == TType::SET || $type == TType::LIST) + elsif($type == Thrift::TType::SET || $type == Thrift::TType::LIST) { # Vtype my $data = $itrans->readAll(1); @@ -513,14 +517,15 @@ sub skipBinary return $result; } - die new Thrift::TException("Type $type not recognised --- corrupt data?"); + die Thrift::TProtocolException->new("Type $type not recognized --- corrupt data?", + Thrift::TProtocolException::INVALID_DATA); } # # Protocol factory creates protocol objects from transports # -package TProtocolFactory; - +package Thrift::TProtocolFactory; +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); sub new { my $classname = shift; @@ -537,7 +542,7 @@ sub new { sub getProtocol { my ($trans); - die "interface"; + die 'interface'; } diff --git a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/ProtocolDecorator.pm b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/ProtocolDecorator.pm index 8120200..cc5c9da 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/ProtocolDecorator.pm +++ b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/ProtocolDecorator.pm @@ -17,19 +17,22 @@ # under the License. # +use 5.10.0; use strict; use warnings; +use Thrift; use Thrift::Protocol; package Thrift::ProtocolDecorator; use base qw(Thrift::Protocol); +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); sub new { my $classname = shift; my $protocol = shift; my $self = $classname->SUPER::new($protocol->getTransport()); - + $self->{concreteProtocol} = $protocol; return bless($self,$classname); @@ -45,7 +48,7 @@ sub new { sub writeMessageBegin { my $self = shift; my ($name, $type, $seqid) = @_; - + return $self->{concreteProtocol}->writeMessageBegin($name, $type, $seqid); } @@ -54,7 +57,7 @@ sub writeMessageBegin { # sub writeMessageEnd { my $self = shift; - + return $self->{concreteProtocol}->writeMessageEnd(); } @@ -79,7 +82,7 @@ sub writeStructBegin { # @return int How many bytes written # sub writeStructEnd { - my $self = shift; + my $self = shift; return $self->{concreteProtocol}->writeStructEnd(); } @@ -101,13 +104,13 @@ sub writeFieldBegin { } sub writeFieldEnd { - my $self = shift; + my $self = shift; return $self->{concreteProtocol}->writeFieldEnd(); } sub writeFieldStop { - my $self = shift; + my $self = shift; return $self->{concreteProtocol}->writeFieldStop(); } @@ -121,7 +124,7 @@ sub writeMapBegin { sub writeMapEnd { my $self = shift; - + return $self->{concreteProtocol}->writeMapEnd(); } @@ -134,7 +137,7 @@ sub writeListBegin { sub writeListEnd { my $self = shift; - + return $self->{concreteProtocol}->writeListEnd(); } @@ -147,7 +150,7 @@ sub writeSetBegin { sub writeSetEnd { my $self = shift; - + return $self->{concreteProtocol}->writeListEnd(); } @@ -177,7 +180,7 @@ sub writeI32 { my ($i32) = @_; return $self->{concreteProtocol}->writeI32($i32); - + } sub writeI64 { @@ -221,7 +224,7 @@ sub readMessageBegin # sub readMessageEnd { - my $self = shift; + my $self = shift; return $self->{concreteProtocol}->readMessageEnd(); } @@ -236,7 +239,7 @@ sub readStructBegin sub readStructEnd { - my $self = shift; + my $self = shift; return $self->{concreteProtocol}->readStructEnd(); } @@ -251,7 +254,7 @@ sub readFieldBegin sub readFieldEnd { - my $self = shift; + my $self = shift; return $self->{concreteProtocol}->readFieldEnd(); } @@ -266,7 +269,7 @@ sub readMapBegin sub readMapEnd { - my $self = shift; + my $self = shift; return $self->{concreteProtocol}->readMapEnd(); } @@ -281,7 +284,7 @@ sub readListBegin sub readListEnd { - my $self = shift; + my $self = shift; return $self->{concreteProtocol}->readListEnd(); } @@ -296,7 +299,7 @@ sub readSetBegin sub readSetEnd { - my $self = shift; + my $self = shift; return $self->{concreteProtocol}->readSetEnd(); } diff --git a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/SSLServerSocket.pm b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/SSLServerSocket.pm index 2efdfff..7b06431 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/SSLServerSocket.pm +++ b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/SSLServerSocket.pm @@ -17,24 +17,24 @@ # under the License. # -require 5.6.0; +use 5.10.0; use strict; use warnings; use Thrift; use Thrift::SSLSocket; +use Thrift::ServerSocket; use IO::Socket::SSL; -use IO::Select; package Thrift::SSLServerSocket; - use base qw( Thrift::ServerSocket ); +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); # # Constructor. # Takes a hash: -# See Thirft::Socket for base class parameters. +# See Thrift::Socket for base class parameters. # @param[in] ca certificate authority filename - not required # @param[in] cert certificate filename; may contain key in which case key is not required # @param[in] key private key filename for the certificate if it is not inside the cert file @@ -48,21 +48,29 @@ sub new sub __client { - return new Thrift::SSLSocket(); + return Thrift::SSLSocket->new(); } sub __listen { my $self = shift; - return IO::Socket::SSL->new(LocalAddr => $self->{host}, - LocalPort => $self->{port}, - Proto => 'tcp', - Listen => $self->{queue}, - ReuseAddr => 1, - SSL_cert_file => $self->{cert}, - SSL_key_file => $self->{key}, - SSL_ca_file => $self->{ca}); + my $opts = {Listen => $self->{queue}, + LocalAddr => $self->{host}, + LocalPort => $self->{port}, + Proto => 'tcp', + ReuseAddr => 1}; + + my $verify = IO::Socket::SSL::SSL_VERIFY_PEER | IO::Socket::SSL::SSL_VERIFY_FAIL_IF_NO_PEER_CERT | IO::Socket::SSL::SSL_VERIFY_CLIENT_ONCE; + + $opts->{SSL_ca_file} = $self->{ca} if defined $self->{ca}; + $opts->{SSL_cert_file} = $self->{cert} if defined $self->{cert}; + $opts->{SSL_cipher_list} = $self->{ciphers} if defined $self->{ciphers}; + $opts->{SSL_key_file} = $self->{key} if defined $self->{key}; + $opts->{SSL_use_cert} = (defined $self->{cert}) ? 1 : 0; + $opts->{SSL_verify_mode} = (defined $self->{ca}) ? $verify : IO::Socket::SSL::SSL_VERIFY_NONE; + $opts->{SSL_version} = (defined $self->{version}) ? $self->{version} : 'SSLv23:!SSLv3:!SSLv2'; + + return IO::Socket::SSL->new(%$opts); } - 1; diff --git a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/SSLSocket.pm b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/SSLSocket.pm index 0d2edf8..e34924d 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/SSLSocket.pm +++ b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/SSLSocket.pm @@ -17,21 +17,42 @@ # under the License. # -require 5.6.0; +use 5.10.0; use strict; use warnings; use Thrift; -use Thrift::Transport; +use Thrift::Socket; use IO::Socket::SSL; -use IO::Select; package Thrift::SSLSocket; - -# TODO: Does not provide cipher selection or authentication hooks yet. - use base qw( Thrift::Socket ); +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); + +# +# Construction and usage +# +# my $opts = {} +# my $socket = Thrift::SSLSocket->new(\%opts); +# +# options: +# +# Any option from Socket.pm is valid, and then: +# +# ca => certificate authority file (PEM file) to authenticate the +# server against; if not specified then the server is not +# authenticated +# cert => certificate to use as the client; if not specified then +# the client does not present one but still connects using +# secure protocol +# ciphers => allowed cipher list +# (see http://www.openssl.org/docs/apps/ciphers.html#CIPHER_STRINGS) +# key => certificate key for "cert" option +# version => acceptable SSL/TLS versions - if not specified then the +# default is to use SSLv23 handshake but only negotiate +# at TLSv1.0 or later +# sub new { @@ -44,10 +65,22 @@ sub new sub __open { my $self = shift; - return IO::Socket::SSL->new(PeerAddr => $self->{host}, - PeerPort => $self->{port}, - Proto => 'tcp', - Timeout => $self->{sendTimeout} / 1000); + my $opts = {PeerAddr => $self->{host}, + PeerPort => $self->{port}, + Proto => 'tcp', + Timeout => $self->{sendTimeout} / 1000}; + + my $verify = IO::Socket::SSL::SSL_VERIFY_PEER | IO::Socket::SSL::SSL_VERIFY_FAIL_IF_NO_PEER_CERT | IO::Socket::SSL::SSL_VERIFY_CLIENT_ONCE; + + $opts->{SSL_ca_file} = $self->{ca} if defined $self->{ca}; + $opts->{SSL_cert_file} = $self->{cert} if defined $self->{cert}; + $opts->{SSL_cipher_list} = $self->{ciphers} if defined $self->{ciphers}; + $opts->{SSL_key_file} = $self->{key} if defined $self->{key}; + $opts->{SSL_use_cert} = (defined $self->{cert}) ? 1 : 0; + $opts->{SSL_verify_mode} = (defined $self->{ca}) ? $verify : IO::Socket::SSL::SSL_VERIFY_NONE; + $opts->{SSL_version} = (defined $self->{version}) ? $self->{version} : 'SSLv23:!SSLv3:!SSLv2'; + + return IO::Socket::SSL->new(%$opts); } sub __close @@ -61,10 +94,10 @@ sub __close sub __recv { - my $self = shift; - my $sock = shift; - my $len = shift; - my $buf = undef; + my $self = shift; + my $sock = shift; + my $len = shift; + my $buf = undef; if ($sock) { sysread($sock, $buf, $len); } diff --git a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Server.pm b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Server.pm index ac1e17d..28822e8 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Server.pm +++ b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Server.pm @@ -17,25 +17,31 @@ # under the License. # -require 5.6.0; +use 5.10.0; use strict; use warnings; use Thrift; -use Thrift::BufferedTransport; use Thrift::BinaryProtocol; +use Thrift::BufferedTransport; +use Thrift::Exception; # # Server base class module # package Thrift::Server; +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); +# # 3 possible constructors: # 1. (processor, serverTransport) +# Uses a BufferedTransportFactory and a BinaryProtocolFactory. # 2. (processor, serverTransport, transportFactory, protocolFactory) +# Uses the same factory for input and output of each type. # 3. (processor, serverTransport, # inputTransportFactory, outputTransportFactory, # inputProtocolFactory, outputProtocolFactory) +# sub new { my $classname = shift; @@ -45,7 +51,7 @@ sub new if (scalar @args == 2) { - $self = _init($args[0], $args[1], + $self = _init($args[0], $args[1], Thrift::BufferedTransportFactory->new(), Thrift::BufferedTransportFactory->new(), Thrift::BinaryProtocolFactory->new(), @@ -61,7 +67,7 @@ sub new } else { - die "Thrift::Server expects exactly 2, 4, or 6 args"; + die Thrift::TException->new('Thrift::Server expects exactly 2, 4, or 6 args'); } return bless($self,$classname); @@ -88,7 +94,7 @@ sub _init sub serve { - die "abstract"; + die 'abstract'; } sub _clientBegin @@ -109,7 +115,7 @@ sub _handleException my $self = shift; my $e = shift; - if ($e =~ m/TException/ and exists $e->{message}) { + if ($e->isa('Thrift::TException') and exists $e->{message}) { my $message = $e->{message}; my $code = $e->{code}; my $out = $code . ':' . $message; @@ -117,10 +123,12 @@ sub _handleException $message =~ m/TTransportException/ and die $out; if ($message =~ m/Socket/) { # suppress Socket messages - } else { + } + else { warn $out; } - } else { + } + else { warn $e; } } @@ -129,41 +137,46 @@ sub _handleException # SimpleServer from the Server base class that handles one connection at a time # package Thrift::SimpleServer; -use base qw( Thrift::Server ); +use parent -norequire, 'Thrift::Server'; +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); sub new { my $classname = shift; - my @args = @_; - my $self = $classname->SUPER::new(@args); + my $self = $classname->SUPER::new(@_); + return bless($self,$classname); } sub serve { my $self = shift; + my $stop = 0; $self->{serverTransport}->listen(); - while (1) - { + while (!$stop) { my $client = $self->{serverTransport}->accept(); - my $itrans = $self->{inputTransportFactory}->getTransport($client); - my $otrans = $self->{outputTransportFactory}->getTransport($client); - my $iprot = $self->{inputProtocolFactory}->getProtocol($itrans); - my $oprot = $self->{outputProtocolFactory}->getProtocol($otrans); - eval { - $self->_clientBegin($iprot, $oprot); - while (1) - { - $self->{processor}->process($iprot, $oprot); + if (defined $client) { + my $itrans = $self->{inputTransportFactory}->getTransport($client); + my $otrans = $self->{outputTransportFactory}->getTransport($client); + my $iprot = $self->{inputProtocolFactory}->getProtocol($itrans); + my $oprot = $self->{outputProtocolFactory}->getProtocol($otrans); + eval { + $self->_clientBegin($iprot, $oprot); + while (1) + { + $self->{processor}->process($iprot, $oprot); + } + }; + if($@) { + $self->_handleException($@); } - }; if($@) { - $self->_handleException($@); + $itrans->close(); + $otrans->close(); + } else { + $stop = 1; } - - $itrans->close(); - $otrans->close(); } } @@ -172,9 +185,9 @@ sub serve # ForkingServer that forks a new process for each request # package Thrift::ForkingServer; -use base qw( Thrift::Server ); - -use POSIX ":sys_wait_h"; +use parent -norequire, 'Thrift::Server'; +use POSIX ':sys_wait_h'; +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); sub new { @@ -217,13 +230,15 @@ sub _client my $pid = fork(); - if ($pid) #parent + if ($pid) { $self->_parent($pid, $itrans, $otrans); - } else { + } + else { $self->_child($itrans, $otrans, $iprot, $oprot); } - }; if($@) { + }; + if($@) { $self->_handleException($@); } } @@ -235,10 +250,6 @@ sub _parent my $itrans = shift; my $otrans = shift; - # add before collect, otherwise you race w/ waitpid - $self->{children}->{$pid} = 1; - $self->_collectChildren(); - # Parent must close socket or the connection may not get closed promptly $self->tryClose($itrans); $self->tryClose($otrans); @@ -254,11 +265,14 @@ sub _child my $ecode = 0; eval { + # THRIFT-4065 ensure child process has normal signal handling in case thrift handler uses it + $SIG{CHLD} = 'DEFAULT'; while (1) { $self->{processor}->process($iprot, $oprot); } - }; if($@) { + }; + if($@) { $ecode = 1; $self->_handleException($@); } @@ -279,37 +293,19 @@ sub tryClose { $file->close(); } - }; if($@) { - if ($@ =~ m/TException/ and exists $@->{message}) { + }; + if($@) { + if ($@->isa('Thrift::TException') and exists $@->{message}) { my $message = $@->{message}; my $code = $@->{code}; my $out = $code . ':' . $message; warn $out; - } else { + } + else { warn $@; } } } -sub _collectChildren -{ - my $self = shift; - - while (scalar keys %{$self->{children}}) - { - my $pid = waitpid(-1, WNOHANG); - - if ($pid>0) - { - delete $self->{children}->{$pid}; - } - else - { - last; - } - } -} - - 1; diff --git a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/ServerSocket.pm b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/ServerSocket.pm index 89664f6..3972643 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/ServerSocket.pm +++ b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/ServerSocket.pm @@ -17,18 +17,19 @@ # under the License. # -require 5.6.0; +use 5.10.0; use strict; use warnings; use IO::Socket::INET; use IO::Select; use Thrift; +use Thrift::Transport; use Thrift::Socket; package Thrift::ServerSocket; - use base qw( Thrift::ServerTransport ); +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); # # Constructor. @@ -37,25 +38,26 @@ use base qw( Thrift::ServerTransport ); # @param[in] host host interface to listen on (undef = all interfaces) # @param[in] port port number to listen on (required) # @param[in] queue the listen queue size (default if not specified is 128) -# @example my $serversock = new Thrift::ServerSocket(host => undef, port => port) +# @example my $serversock = Thrift::ServerSocket->new(host => undef, port => port) # sub new { my $classname = shift; my $args = shift; my $self; - + # Support both old-style "port number" construction and newer... if (ref($args) eq 'HASH') { $self = $args; - } else { + } + else { $self = { port => $args }; } if (not defined $self->{queue}) { $self->{queue} = 128; } - + return bless($self, $classname); } @@ -70,7 +72,7 @@ sub listen $self->{debugHandler}->($error); } - die new Thrift::TException($error); + die Thrift::TTransportException->new($error, Thrift::TTransportException::NOT_OPEN); }; $self->{handle} = $sock; @@ -80,15 +82,24 @@ sub accept { my $self = shift; - if ( exists $self->{handle} and defined $self->{handle} ) - { + if ( exists $self->{handle} and defined $self->{handle} ) { my $client = $self->{handle}->accept(); my $result = $self->__client(); - $result->{handle} = new IO::Select($client); + $result->{handle} = IO::Select->new($client); return $result; } - return 0; + return undef; +} + +sub close +{ + my $self = shift; + + if ( exists $self->{handle} and defined $self->{handle} ) + { + $self->{handle}->close(); + } } ### @@ -97,7 +108,7 @@ sub accept sub __client { - return new Thrift::Socket(); + return Thrift::Socket->new(); } sub __listen diff --git a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Socket.pm b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Socket.pm index eaf8b9e..ba0db5e 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Socket.pm +++ b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Socket.pm @@ -17,37 +17,63 @@ # under the License. # -require 5.6.0; +use 5.10.0; use strict; use warnings; use Thrift; +use Thrift::Exception; use Thrift::Transport; use IO::Socket::INET; use IO::Select; package Thrift::Socket; - use base qw( Thrift::Transport ); +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); + +# +# Construction and usage +# +# my $opts = {} +# my $socket = Thrift::Socket->new(\%opts); +# +# options: +# +# host => host to connect to +# port => port to connect to +# sendTimeout => timeout used for send and for connect +# recvTimeout => timeout used for recv +# sub new { - my $classname = shift; - my $host = shift || "localhost"; - my $port = shift || 9090; - my $debugHandler = shift; + my $classname = shift; + my $opts = shift; + # default settings: my $self = { - host => $host, - port => $port, - debugHandler => $debugHandler, - debug => 0, - sendTimeout => 10000, + host => 'localhost', + port => 9090, recvTimeout => 10000, - handle => undef, + sendTimeout => 10000, + + handle => undef }; + if (defined $opts and ref $opts eq ref {}) { + + # argument is a hash of options so override the defaults + $self->{$_} = $opts->{$_} for keys %$opts; + + } else { + + # older style constructor takes 3 arguments, none of which are required + $self->{host} = $opts || 'localhost'; + $self->{port} = shift || 9090; + + } + return bless($self,$classname); } @@ -69,19 +95,6 @@ sub setRecvTimeout } -# -#Sets debugging output on or off -# -# @param bool $debug -# -sub setDebug -{ - my $self = shift; - my $debug = shift; - - $self->{debug} = $debug; -} - # # Tests whether this is open # @@ -107,15 +120,10 @@ sub open my $sock = $self->__open() || do { my $error = ref($self).': Could not connect to '.$self->{host}.':'.$self->{port}.' ('.$!.')'; - - if ($self->{debug}) { - $self->{debugHandler}->($error); - } - - die new Thrift::TException($error); + die Thrift::TTransportException->new($error, Thrift::TTransportException::NOT_OPEN); }; - $self->{handle} = new IO::Select( $sock ); + $self->{handle} = IO::Select->new( $sock ); } # @@ -125,7 +133,7 @@ sub close { my $self = shift; if( defined $self->{handle} ) { - $self->__close(); + $self->__close(); } } @@ -151,15 +159,17 @@ sub readAll if (!defined $buf || $buf eq '') { - die new Thrift::TException(ref($self).': Could not read '.$len.' bytes from '. - $self->{host}.':'.$self->{port}); + die Thrift::TTransportException->new(ref($self).': Could not read '.$len.' bytes from '. + $self->{host}.':'.$self->{port}, Thrift::TTransportException::END_OF_FILE); - } elsif ((my $sz = length($buf)) < $len) { + } + elsif ((my $sz = length($buf)) < $len) { $pre .= $buf; $len -= $sz; - } else { + } + else { return $pre.$buf; } } @@ -183,8 +193,8 @@ sub read if (!defined $buf || $buf eq '') { - die new TException(ref($self).': Could not read '.$len.' bytes from '. - $self->{host}.':'.$self->{port}); + die Thrift::TTransportException->new(ref($self).': Could not read '.$len.' bytes from '. + $self->{host}.':'.$self->{port}, Thrift::TTransportException::END_OF_FILE); } @@ -209,16 +219,16 @@ sub write my @sockets = $self->{handle}->can_write( $self->{sendTimeout} / 1000 ); if(@sockets == 0){ - die new Thrift::TException(ref($self).': timed out writing to bytes from '. - $self->{host}.':'.$self->{port}); + die Thrift::TTransportException->new(ref($self).': timed out writing to bytes from '. + $self->{host}.':'.$self->{port}, Thrift::TTransportException::TIMED_OUT); } my $sent = $self->__send($sockets[0], $buf); if (!defined $sent || $sent == 0 ) { - - die new Thrift::TException(ref($self).': Could not write '.length($buf).' bytes '. - $self->{host}.':'.$self->{host}); + + die Thrift::TTransportException->new(ref($self).': Could not write '.length($buf).' bytes '. + $self->{host}.':'.$self->{host}, Thrift::TTransportException::END_OF_FILE); } @@ -259,7 +269,7 @@ sub __open # sub __close { - my $self = shift; + my $self = shift; CORE::close(($self->{handle}->handles())[0]); } @@ -272,12 +282,12 @@ sub __close # sub __recv { - my $self = shift; - my $sock = shift; - my $len = shift; - my $buf = undef; - $sock->recv($buf, $len); - return $buf; + my $self = shift; + my $sock = shift; + my $len = shift; + my $buf = undef; + $sock->recv($buf, $len); + return $buf; } # @@ -306,8 +316,8 @@ sub __wait my @sockets = $self->{handle}->can_read( $self->{recvTimeout} / 1000 ); if (@sockets == 0) { - die new Thrift::TException(ref($self).': timed out reading from '. - $self->{host}.':'.$self->{port}); + die Thrift::TTransportException->new(ref($self).': timed out reading from '. + $self->{host}.':'.$self->{port}, Thrift::TTransportException::TIMED_OUT); } return $sockets[0]; diff --git a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Transport.pm b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Transport.pm index 5ec6fee..41b7e15 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Transport.pm +++ b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Transport.pm @@ -17,17 +17,19 @@ # under the License. # -require 5.6.0; +use 5.10.0; use strict; use warnings; use Thrift; +use Thrift::Exception; # # Transport exceptions # -package TTransportException; +package Thrift::TTransportException; use base('Thrift::TException'); +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); use constant UNKNOWN => 0; use constant NOT_OPEN => 1; @@ -35,7 +37,7 @@ use constant ALREADY_OPEN => 2; use constant TIMED_OUT => 3; use constant END_OF_FILE => 4; -sub new{ +sub new { my $classname = shift; my $self = $classname->SUPER::new(@_); @@ -43,6 +45,7 @@ sub new{ } package Thrift::Transport; +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); # # Whether this transport is open. @@ -51,7 +54,7 @@ package Thrift::Transport; # sub isOpen { - die "abstract"; + die 'abstract'; } # @@ -61,7 +64,7 @@ sub isOpen # sub open { - die "abstract"; + die 'abstract'; } # @@ -69,7 +72,7 @@ sub open # sub close { - die "abstract"; + die 'abstract'; } # @@ -81,8 +84,7 @@ sub close # sub read { - my ($len); - die("abstract"); + die 'abstract'; } # @@ -114,8 +116,7 @@ sub readAll # sub write { - my ($buf); - die "abstract"; + die 'abstract'; } # @@ -130,6 +131,7 @@ sub flush {} # TransportFactory creates transport objects from transports # package Thrift::TransportFactory; +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); sub new { my $classname = shift; @@ -156,20 +158,21 @@ sub getTransport # ServerTransport base class module # package Thrift::ServerTransport; +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); sub listen { - die "abstract"; + die 'abstract'; } sub accept { - die "abstract"; + die 'abstract'; } sub close { - die "abstract"; + die 'abstract'; } diff --git a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Type.pm b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Type.pm new file mode 100644 index 0000000..ad8da3b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/Type.pm @@ -0,0 +1,50 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +use 5.10.0; +use strict; +use warnings; + +use Thrift; + +# +# Data types that can be sent via Thrift +# +package Thrift::TType; +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); + +use constant STOP => 0; +use constant VOID => 1; +use constant BOOL => 2; +use constant BYTE => 3; +use constant I08 => 3; +use constant DOUBLE => 4; +use constant I16 => 6; +use constant I32 => 8; +use constant I64 => 10; +use constant STRING => 11; +use constant UTF7 => 11; +use constant STRUCT => 12; +use constant MAP => 13; +use constant SET => 14; +use constant LIST => 15; +use constant UTF8 => 16; +use constant UTF16 => 17; + +1; diff --git a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/UnixServerSocket.pm b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/UnixServerSocket.pm index 3251a00..875e804 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/UnixServerSocket.pm +++ b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/UnixServerSocket.pm @@ -17,19 +17,19 @@ # under the License. # -require 5.6.0; +use 5.10.0; use strict; use warnings; use Thrift; +use Thrift::ServerSocket; use Thrift::UnixSocket; use IO::Socket::UNIX; -use IO::Select; package Thrift::UnixServerSocket; - use base qw( Thrift::ServerSocket ); +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); # # Constructor. @@ -37,8 +37,8 @@ use base qw( Thrift::ServerSocket ); # If a single argument is given that is a hash: # @param[in] path unix domain socket file name # @param[in] queue the listen queue size (default is not specified is supplied by ServerSocket) -# @example my $serversock = new Thrift::UnixServerSocket($path); -# @example my $serversock = new Thrift::UnixServerSocket(path => "somepath", queue => 64); +# @example my $serversock = Thrift::UnixServerSocket->new($path); +# @example my $serversock = Thrift::UnixServerSocket->new(path => "somepath", queue => 64); # sub new { @@ -58,7 +58,7 @@ sub new sub __client { - return new Thrift::UnixSocket(); + return Thrift::UnixSocket->new(); } sub __listen @@ -75,7 +75,7 @@ sub __listen if ($self->{debug}) { $self->{debugHandler}->($error); } - die new Thrift::TException($error); + die Thrift::TTransportException->new($error, Thrift::TTransportException::NOT_OPEN); }; return $sock; diff --git a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/UnixSocket.pm b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/UnixSocket.pm index e8317b6..ba386d1 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/UnixSocket.pm +++ b/vendor/git.apache.org/thrift.git/lib/perl/lib/Thrift/UnixSocket.pm @@ -17,32 +17,31 @@ # under the License. # -require 5.6.0; +use 5.10.0; use strict; use warnings; use Thrift; -use Thrift::Transport; +use Thrift::Socket; use IO::Socket::UNIX; -use IO::Select; package Thrift::UnixSocket; - use base qw( Thrift::Socket ); +use version 0.77; our $VERSION = version->declare("$Thrift::VERSION"); # # Constructor. # Takes a unix domain socket filename. -# See Thirft::Socket for base class parameters. +# See Thrift::Socket for base class parameters. # @param[in] path path to unix socket file -# @example my $sock = new Thrift::UnixSocket($path); +# @example my $sock = Thrift::UnixSocket->new($path); # sub new { my $classname = shift; my $self = $classname->SUPER::new(); - $self->{path} = shift; + $self->{path} = shift; return bless($self, $classname); } @@ -59,7 +58,7 @@ sub __open if ($self->{debug}) { $self->{debugHandler}->($error); } - die new Thrift::TException($error); + die Thrift::TTransportException->new($error, Thrift::TTransportException::NOT_OPEN); }; return $sock; diff --git a/vendor/git.apache.org/thrift.git/lib/perl/test/multiplex.t b/vendor/git.apache.org/thrift.git/lib/perl/test/multiplex.t index 76f2706..90a9b4d 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/test/multiplex.t +++ b/vendor/git.apache.org/thrift.git/lib/perl/test/multiplex.t @@ -22,15 +22,13 @@ use Test::More tests => 6; use strict; use warnings; -use Thrift; -use Thrift::Socket; -use Thrift::Server; -use Thrift::MultiplexedProcessor; use Thrift::BinaryProtocol; -use Thrift::MemoryBuffer; use Thrift::FramedTransport; use Thrift::MemoryBuffer; - +use Thrift::MessageType; +use Thrift::MultiplexedProcessor; +use Thrift::Server; +use Thrift::Socket; use BenchmarkService; use Aggr; @@ -103,7 +101,7 @@ for(my $i = 1; $i <= 5; $i++) { $aggr_protocol->readMessageBegin(\$function_name, \$message_type, \$sequence_id); - if ($message_type == TMessageType::EXCEPTION) { + if ($message_type == Thrift::TMessageType::EXCEPTION) { die; } @@ -116,7 +114,7 @@ my ($function_name, $message_type, $sequence_id); $aggr_protocol->readMessageBegin(\$function_name, \$message_type, \$sequence_id); -if ($message_type == TMessageType::EXCEPTION) { +if ($message_type == Thrift::TMessageType::EXCEPTION) { die; } @@ -132,7 +130,7 @@ foreach my $val((1,2,3,5,8)) { $benchmark_protocol->readMessageBegin(\$function_name, \$message_type, \$sequence_id); - if ($message_type == TMessageType::EXCEPTION) { + if ($message_type == Thrift::TMessageType::EXCEPTION) { die; } my $benchmark_result = BenchmarkService_fibonacci_result->new(); diff --git a/vendor/git.apache.org/thrift.git/lib/perl/test/processor.t b/vendor/git.apache.org/thrift.git/lib/perl/test/processor.t index 1d8be73..f833035 100644 --- a/vendor/git.apache.org/thrift.git/lib/perl/test/processor.t +++ b/vendor/git.apache.org/thrift.git/lib/perl/test/processor.t @@ -22,9 +22,9 @@ use Test::More tests => 2; use strict; use warnings; -use Thrift; use Thrift::BinaryProtocol; use Thrift::MemoryBuffer; +use Thrift::MessageType; use ThriftTest::ThriftTest; use ThriftTest::Types; @@ -72,7 +72,7 @@ foreach my $val (("got foo","got bar")){ $protocol->readMessageBegin(\$function_name, \$message_type, \$sequence_id); print " $function_name, $message_type, $sequence_id\n"; - if ($message_type == TMessageType::EXCEPTION) { + if ($message_type == Thrift::TMessageType::EXCEPTION) { die; } diff --git a/vendor/git.apache.org/thrift.git/lib/perl/tools/FixupDist.pl b/vendor/git.apache.org/thrift.git/lib/perl/tools/FixupDist.pl new file mode 100644 index 0000000..24a2b20 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/perl/tools/FixupDist.pl @@ -0,0 +1,35 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +# +# This will fix up the distribution so that CPAN properly +# indexes Thrift. +# + +use 5.10.0; +use strict; +use warnings; +use utf8; + +use Data::Dumper; +use CPAN::Meta; + +my $meta = CPAN::Meta->load_file('META.json'); +$meta->{'provides'} = { 'Thrift' => { 'file' => 'lib/Thrift.pm', 'version' => $meta->version() } }; +$meta->save('META.json'); diff --git a/vendor/git.apache.org/thrift.git/lib/php/Makefile.am b/vendor/git.apache.org/thrift.git/lib/php/Makefile.am index 8e62960..8d9050a 100755 --- a/vendor/git.apache.org/thrift.git/lib/php/Makefile.am +++ b/vendor/git.apache.org/thrift.git/lib/php/Makefile.am @@ -37,103 +37,102 @@ distclean-local: endif -phpdir = $(PHP_PREFIX)/Thrift +phpdir = $(PHP_PREFIX)/ php_DATA = \ - lib/Thrift/TMultiplexedProcessor.php + lib/TMultiplexedProcessor.php phpbasedir = $(phpdir)/Base phpbase_DATA = \ - lib/Thrift/Base/TBase.php + lib/Base/TBase.php phpclassloaderdir = $(phpdir)/ClassLoader phpclassloader_DATA = \ - lib/Thrift/ClassLoader/ThriftClassLoader.php + lib/ClassLoader/ThriftClassLoader.php phpexceptiondir = $(phpdir)/Exception phpexception_DATA = \ - lib/Thrift/Exception/TApplicationException.php \ - lib/Thrift/Exception/TException.php \ - lib/Thrift/Exception/TProtocolException.php \ - lib/Thrift/Exception/TTransportException.php + lib/Exception/TApplicationException.php \ + lib/Exception/TException.php \ + lib/Exception/TProtocolException.php \ + lib/Exception/TTransportException.php phpfactorydir = $(phpdir)/Factory phpfactory_DATA = \ - lib/Thrift/Factory/TBinaryProtocolFactory.php \ - lib/Thrift/Factory/TCompactProtocolFactory.php \ - lib/Thrift/Factory/TJSONProtocolFactory.php \ - lib/Thrift/Factory/TProtocolFactory.php \ - lib/Thrift/Factory/TStringFuncFactory.php \ - lib/Thrift/Factory/TTransportFactory.php + lib/Factory/TBinaryProtocolFactory.php \ + lib/Factory/TCompactProtocolFactory.php \ + lib/Factory/TJSONProtocolFactory.php \ + lib/Factory/TProtocolFactory.php \ + lib/Factory/TStringFuncFactory.php \ + lib/Factory/TTransportFactory.php phpprotocoldir = $(phpdir)/Protocol phpprotocol_DATA = \ - lib/Thrift/Protocol/TBinaryProtocolAccelerated.php \ - lib/Thrift/Protocol/TBinaryProtocol.php \ - lib/Thrift/Protocol/TCompactProtocol.php \ - lib/Thrift/Protocol/TJSONProtocol.php \ - lib/Thrift/Protocol/TMultiplexedProtocol.php \ - lib/Thrift/Protocol/TProtocol.php \ - lib/Thrift/Protocol/TProtocolDecorator.php \ - lib/Thrift/Protocol/TSimpleJSONProtocol.php + lib/Protocol/TBinaryProtocolAccelerated.php \ + lib/Protocol/TBinaryProtocol.php \ + lib/Protocol/TCompactProtocol.php \ + lib/Protocol/TJSONProtocol.php \ + lib/Protocol/TMultiplexedProtocol.php \ + lib/Protocol/TProtocol.php \ + lib/Protocol/TProtocolDecorator.php \ + lib/Protocol/TSimpleJSONProtocol.php phpprotocoljsondir = $(phpprotocoldir)/JSON phpprotocoljson_DATA = \ - lib/Thrift/Protocol/JSON/BaseContext.php \ - lib/Thrift/Protocol/JSON/ListContext.php \ - lib/Thrift/Protocol/JSON/LookaheadReader.php \ - lib/Thrift/Protocol/JSON/PairContext.php + lib/Protocol/JSON/BaseContext.php \ + lib/Protocol/JSON/ListContext.php \ + lib/Protocol/JSON/LookaheadReader.php \ + lib/Protocol/JSON/PairContext.php phpprotocolsimplejsondir = $(phpprotocoldir)/SimpleJSON phpprotocolsimplejson_DATA = \ - lib/Thrift/Protocol/SimpleJSON/CollectionMapKeyException.php \ - lib/Thrift/Protocol/SimpleJSON/Context.php \ - lib/Thrift/Protocol/SimpleJSON/ListContext.php \ - lib/Thrift/Protocol/SimpleJSON/MapContext.php \ - lib/Thrift/Protocol/SimpleJSON/StructContext.php + lib/Protocol/SimpleJSON/CollectionMapKeyException.php \ + lib/Protocol/SimpleJSON/Context.php \ + lib/Protocol/SimpleJSON/ListContext.php \ + lib/Protocol/SimpleJSON/MapContext.php \ + lib/Protocol/SimpleJSON/StructContext.php phpserializerdir = $(phpdir)/Serializer phpserializer_DATA = \ - lib/Thrift/Serializer/TBinarySerializer.php + lib/Serializer/TBinarySerializer.php phpserverdir = $(phpdir)/Server phpserver_DATA = \ - lib/Thrift/Server/TServerSocket.php \ - lib/Thrift/Server/TForkingServer.php \ - lib/Thrift/Server/TServer.php \ - lib/Thrift/Server/TServerTransport.php \ - lib/Thrift/Server/TSimpleServer.php + lib/Server/TServerSocket.php \ + lib/Server/TForkingServer.php \ + lib/Server/TServer.php \ + lib/Server/TServerTransport.php \ + lib/Server/TSimpleServer.php phpstringfuncdir = $(phpdir)/StringFunc phpstringfunc_DATA = \ - lib/Thrift/StringFunc/Mbstring.php \ - lib/Thrift/StringFunc/Core.php \ - lib/Thrift/StringFunc/TStringFunc.php + lib/StringFunc/Mbstring.php \ + lib/StringFunc/Core.php \ + lib/StringFunc/TStringFunc.php phptransportdir = $(phpdir)/Transport phptransport_DATA = \ - lib/Thrift/Transport/TBufferedTransport.php \ - lib/Thrift/Transport/TCurlClient.php \ - lib/Thrift/Transport/TFramedTransport.php \ - lib/Thrift/Transport/THttpClient.php \ - lib/Thrift/Transport/TMemoryBuffer.php \ - lib/Thrift/Transport/TNullTransport.php \ - lib/Thrift/Transport/TPhpStream.php \ - lib/Thrift/Transport/TSocket.php \ - lib/Thrift/Transport/TSocketPool.php \ - lib/Thrift/Transport/TTransport.php + lib/Transport/TBufferedTransport.php \ + lib/Transport/TCurlClient.php \ + lib/Transport/TFramedTransport.php \ + lib/Transport/THttpClient.php \ + lib/Transport/TMemoryBuffer.php \ + lib/Transport/TNullTransport.php \ + lib/Transport/TPhpStream.php \ + lib/Transport/TSocket.php \ + lib/Transport/TSocketPool.php \ + lib/Transport/TTransport.php phptypedir = $(phpdir)/Type phptype_DATA = \ - lib/Thrift/Type/TMessageType.php \ - lib/Thrift/Type/TType.php \ - lib/Thrift/Type/TConstant.php + lib/Type/TMessageType.php \ + lib/Type/TType.php \ + lib/Type/TConstant.php EXTRA_DIST = \ lib \ src/autoload.php \ src/ext/thrift_protocol/config.m4 \ src/ext/thrift_protocol/config.w32 \ - src/ext/thrift_protocol/php_thrift_protocol7.cpp \ src/ext/thrift_protocol/php_thrift_protocol.cpp \ src/ext/thrift_protocol/php_thrift_protocol.h \ src/ext/thrift_protocol/run-tests.php \ diff --git a/vendor/git.apache.org/thrift.git/lib/php/README.md b/vendor/git.apache.org/thrift.git/lib/php/README.md index c24ee2c..7170104 100644 --- a/vendor/git.apache.org/thrift.git/lib/php/README.md +++ b/vendor/git.apache.org/thrift.git/lib/php/README.md @@ -1,7 +1,6 @@ Thrift PHP Software Library -License -======= +# License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file @@ -20,8 +19,7 @@ KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -Using Thrift with PHP -===================== +# Using Thrift with PHP Thrift requires PHP 5. Thrift makes as few assumptions about your PHP environment as possible while trying to make some more advanced PHP @@ -29,25 +27,34 @@ features (i.e. APC cacheing using asbolute path URLs) as simple as possible. To use Thrift in your PHP codebase, take the following steps: -#1) Copy all of thrift/lib/php/lib into your PHP codebase -#2) Configure Symfony Autoloader (or whatever you usually use) +1. Copy all of thrift/lib/php/lib into your PHP codebase +2. Configure Symfony Autoloader (or whatever you usually use) After that, you have to manually include the Thrift package created by the compiler: +``` require_once 'packages/Service/Service.php'; require_once 'packages/Service/Types.php'; +``` -Dependencies -============ +# Dependencies PHP_INT_SIZE - This built-in signals whether your architecture is 32 or 64 bit and is - used by the TBinaryProtocol to properly use pack() and unpack() to - serialize data. + This built-in signals whether your architecture is 32 or 64 bit and is + used by the TBinaryProtocol to properly use pack() and unpack() to + serialize data. apc_fetch(), apc_store() - APC cache is used by the TSocketPool class. If you do not have APC installed, - Thrift will fill in null stub function definitions. + APC cache is used by the TSocketPool class. If you do not have APC installed, + Thrift will fill in null stub function definitions. + +# Breaking Changes + +## 0.12.0 + +1. [PSR-4](https://www.php-fig.org/psr/psr-4/) loader is now the default. If you want to use class maps instead, use `-gen php:classmap`. + +2. If using PSR-4, use `$thriftClassLoader->registerNamespace('namespace', '')` instead of `$thriftClassLoader->registerDefinition('namespace', '')`. diff --git a/vendor/git.apache.org/thrift.git/lib/php/coding_standards.md b/vendor/git.apache.org/thrift.git/lib/php/coding_standards.md index fa0390b..e217539 100644 --- a/vendor/git.apache.org/thrift.git/lib/php/coding_standards.md +++ b/vendor/git.apache.org/thrift.git/lib/php/coding_standards.md @@ -1 +1,5 @@ -Please follow [General Coding Standards](/doc/coding_standards.md) +## PHP Coding Standards + +Please follow: + * [Thrift General Coding Standards](/doc/coding_standards.md) + * [PSR-2](http://www.php-fig.org/psr/psr-2/) diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Base/TBase.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Base/TBase.php new file mode 100644 index 0000000..c61b631 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Base/TBase.php @@ -0,0 +1,382 @@ + 'Bool', + TType::BYTE => 'Byte', + TType::I16 => 'I16', + TType::I32 => 'I32', + TType::I64 => 'I64', + TType::DOUBLE => 'Double', + TType::STRING => 'String' + ); + + abstract public function read($input); + + abstract public function write($output); + + public function __construct($spec = null, $vals = null) + { + if (is_array($spec) && is_array($vals)) { + foreach ($spec as $fid => $fspec) { + $var = $fspec['var']; + if (isset($vals[$var])) { + $this->$var = $vals[$var]; + } + } + } + } + + public function __wakeup() + { + $this->__construct(get_object_vars($this)); + } + + private function _readMap(&$var, $spec, $input) + { + $xfer = 0; + $ktype = $spec['ktype']; + $vtype = $spec['vtype']; + $kread = $vread = null; + if (isset(TBase::$tmethod[$ktype])) { + $kread = 'read' . TBase::$tmethod[$ktype]; + } else { + $kspec = $spec['key']; + } + if (isset(TBase::$tmethod[$vtype])) { + $vread = 'read' . TBase::$tmethod[$vtype]; + } else { + $vspec = $spec['val']; + } + $var = array(); + $_ktype = $_vtype = $size = 0; + $xfer += $input->readMapBegin($_ktype, $_vtype, $size); + for ($i = 0; $i < $size; ++$i) { + $key = $val = null; + if ($kread !== null) { + $xfer += $input->$kread($key); + } else { + switch ($ktype) { + case TType::STRUCT: + $class = $kspec['class']; + $key = new $class(); + $xfer += $key->read($input); + break; + case TType::MAP: + $xfer += $this->_readMap($key, $kspec, $input); + break; + case TType::LST: + $xfer += $this->_readList($key, $kspec, $input, false); + break; + case TType::SET: + $xfer += $this->_readList($key, $kspec, $input, true); + break; + } + } + if ($vread !== null) { + $xfer += $input->$vread($val); + } else { + switch ($vtype) { + case TType::STRUCT: + $class = $vspec['class']; + $val = new $class(); + $xfer += $val->read($input); + break; + case TType::MAP: + $xfer += $this->_readMap($val, $vspec, $input); + break; + case TType::LST: + $xfer += $this->_readList($val, $vspec, $input, false); + break; + case TType::SET: + $xfer += $this->_readList($val, $vspec, $input, true); + break; + } + } + $var[$key] = $val; + } + $xfer += $input->readMapEnd(); + + return $xfer; + } + + private function _readList(&$var, $spec, $input, $set = false) + { + $xfer = 0; + $etype = $spec['etype']; + $eread = $vread = null; + if (isset(TBase::$tmethod[$etype])) { + $eread = 'read' . TBase::$tmethod[$etype]; + } else { + $espec = $spec['elem']; + } + $var = array(); + $_etype = $size = 0; + if ($set) { + $xfer += $input->readSetBegin($_etype, $size); + } else { + $xfer += $input->readListBegin($_etype, $size); + } + for ($i = 0; $i < $size; ++$i) { + $elem = null; + if ($eread !== null) { + $xfer += $input->$eread($elem); + } else { + $espec = $spec['elem']; + switch ($etype) { + case TType::STRUCT: + $class = $espec['class']; + $elem = new $class(); + $xfer += $elem->read($input); + break; + case TType::MAP: + $xfer += $this->_readMap($elem, $espec, $input); + break; + case TType::LST: + $xfer += $this->_readList($elem, $espec, $input, false); + break; + case TType::SET: + $xfer += $this->_readList($elem, $espec, $input, true); + break; + } + } + if ($set) { + $var[$elem] = true; + } else { + $var [] = $elem; + } + } + if ($set) { + $xfer += $input->readSetEnd(); + } else { + $xfer += $input->readListEnd(); + } + + return $xfer; + } + + protected function _read($class, $spec, $input) + { + $xfer = 0; + $fname = null; + $ftype = 0; + $fid = 0; + $xfer += $input->readStructBegin($fname); + while (true) { + $xfer += $input->readFieldBegin($fname, $ftype, $fid); + if ($ftype == TType::STOP) { + break; + } + if (isset($spec[$fid])) { + $fspec = $spec[$fid]; + $var = $fspec['var']; + if ($ftype == $fspec['type']) { + $xfer = 0; + if (isset(TBase::$tmethod[$ftype])) { + $func = 'read' . TBase::$tmethod[$ftype]; + $xfer += $input->$func($this->$var); + } else { + switch ($ftype) { + case TType::STRUCT: + $class = $fspec['class']; + $this->$var = new $class(); + $xfer += $this->$var->read($input); + break; + case TType::MAP: + $xfer += $this->_readMap($this->$var, $fspec, $input); + break; + case TType::LST: + $xfer += $this->_readList($this->$var, $fspec, $input, false); + break; + case TType::SET: + $xfer += $this->_readList($this->$var, $fspec, $input, true); + break; + } + } + } else { + $xfer += $input->skip($ftype); + } + } else { + $xfer += $input->skip($ftype); + } + $xfer += $input->readFieldEnd(); + } + $xfer += $input->readStructEnd(); + + return $xfer; + } + + private function _writeMap($var, $spec, $output) + { + $xfer = 0; + $ktype = $spec['ktype']; + $vtype = $spec['vtype']; + $kwrite = $vwrite = null; + if (isset(TBase::$tmethod[$ktype])) { + $kwrite = 'write' . TBase::$tmethod[$ktype]; + } else { + $kspec = $spec['key']; + } + if (isset(TBase::$tmethod[$vtype])) { + $vwrite = 'write' . TBase::$tmethod[$vtype]; + } else { + $vspec = $spec['val']; + } + $xfer += $output->writeMapBegin($ktype, $vtype, count($var)); + foreach ($var as $key => $val) { + if (isset($kwrite)) { + $xfer += $output->$kwrite($key); + } else { + switch ($ktype) { + case TType::STRUCT: + $xfer += $key->write($output); + break; + case TType::MAP: + $xfer += $this->_writeMap($key, $kspec, $output); + break; + case TType::LST: + $xfer += $this->_writeList($key, $kspec, $output, false); + break; + case TType::SET: + $xfer += $this->_writeList($key, $kspec, $output, true); + break; + } + } + if (isset($vwrite)) { + $xfer += $output->$vwrite($val); + } else { + switch ($vtype) { + case TType::STRUCT: + $xfer += $val->write($output); + break; + case TType::MAP: + $xfer += $this->_writeMap($val, $vspec, $output); + break; + case TType::LST: + $xfer += $this->_writeList($val, $vspec, $output, false); + break; + case TType::SET: + $xfer += $this->_writeList($val, $vspec, $output, true); + break; + } + } + } + $xfer += $output->writeMapEnd(); + + return $xfer; + } + + private function _writeList($var, $spec, $output, $set = false) + { + $xfer = 0; + $etype = $spec['etype']; + $ewrite = null; + if (isset(TBase::$tmethod[$etype])) { + $ewrite = 'write' . TBase::$tmethod[$etype]; + } else { + $espec = $spec['elem']; + } + if ($set) { + $xfer += $output->writeSetBegin($etype, count($var)); + } else { + $xfer += $output->writeListBegin($etype, count($var)); + } + foreach ($var as $key => $val) { + $elem = $set ? $key : $val; + if (isset($ewrite)) { + $xfer += $output->$ewrite($elem); + } else { + switch ($etype) { + case TType::STRUCT: + $xfer += $elem->write($output); + break; + case TType::MAP: + $xfer += $this->_writeMap($elem, $espec, $output); + break; + case TType::LST: + $xfer += $this->_writeList($elem, $espec, $output, false); + break; + case TType::SET: + $xfer += $this->_writeList($elem, $espec, $output, true); + break; + } + } + } + if ($set) { + $xfer += $output->writeSetEnd(); + } else { + $xfer += $output->writeListEnd(); + } + + return $xfer; + } + + protected function _write($class, $spec, $output) + { + $xfer = 0; + $xfer += $output->writeStructBegin($class); + foreach ($spec as $fid => $fspec) { + $var = $fspec['var']; + if ($this->$var !== null) { + $ftype = $fspec['type']; + $xfer += $output->writeFieldBegin($var, $ftype, $fid); + if (isset(TBase::$tmethod[$ftype])) { + $func = 'write' . TBase::$tmethod[$ftype]; + $xfer += $output->$func($this->$var); + } else { + switch ($ftype) { + case TType::STRUCT: + $xfer += $this->$var->write($output); + break; + case TType::MAP: + $xfer += $this->_writeMap($this->$var, $fspec, $output); + break; + case TType::LST: + $xfer += $this->_writeList($this->$var, $fspec, $output, false); + break; + case TType::SET: + $xfer += $this->_writeList($this->$var, $fspec, $output, true); + break; + } + } + $xfer += $output->writeFieldEnd(); + } + } + $xfer += $output->writeFieldStop(); + $xfer += $output->writeStructEnd(); + + return $xfer; + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/ClassLoader/ThriftClassLoader.php b/vendor/git.apache.org/thrift.git/lib/php/lib/ClassLoader/ThriftClassLoader.php similarity index 78% rename from vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/ClassLoader/ThriftClassLoader.php rename to vendor/git.apache.org/thrift.git/lib/php/lib/ClassLoader/ThriftClassLoader.php index 67575ce..4361bd8 100644 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/ClassLoader/ThriftClassLoader.php +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/ClassLoader/ThriftClassLoader.php @@ -54,7 +54,7 @@ class ThriftClassLoader /** * Set autoloader to use APC cache * @param boolean $apc - * @param string $apc_prefix + * @param string $apc_prefix */ public function __construct($apc = false, $apc_prefix = null) { @@ -65,23 +65,23 @@ class ThriftClassLoader /** * Registers a namespace. * - * @param string $namespace The namespace - * @param array|string $paths The location(s) of the namespace + * @param string $namespace The namespace + * @param array|string $paths The location(s) of the namespace */ public function registerNamespace($namespace, $paths) { - $this->namespaces[$namespace] = (array) $paths; + $this->namespaces[$namespace] = (array)$paths; } /** * Registers a Thrift definition namespace. * - * @param string $namespace The definition namespace - * @param array|string $paths The location(s) of the definition namespace + * @param string $namespace The definition namespace + * @param array|string $paths The location(s) of the definition namespace */ public function registerDefinition($namespace, $paths) { - $this->definitions[$namespace] = (array) $paths; + $this->definitions[$namespace] = (array)$paths; } /** @@ -101,11 +101,9 @@ class ThriftClassLoader */ public function loadClass($class) { - if ( - (true === $this->apc && ($file = $this->findFileInApc($class))) or + if ((true === $this->apc && ($file = $this->findFileInApc($class))) or ($file = $this->findFile($class)) - ) - { + ) { require_once $file; } } @@ -117,8 +115,8 @@ class ThriftClassLoader */ protected function findFileInApc($class) { - if (false === $file = apc_fetch($this->apc_prefix.$class)) { - apc_store($this->apc_prefix.$class, $file = $this->findFile($class)); + if (false === $file = apc_fetch($this->apc_prefix . $class)) { + apc_store($this->apc_prefix . $class, $file = $this->findFile($class)); } return $file; @@ -150,10 +148,10 @@ class ThriftClassLoader foreach ($dirs as $dir) { $className = substr($class, $pos + 1); - $file = $dir.DIRECTORY_SEPARATOR. - str_replace('\\', DIRECTORY_SEPARATOR, $namespace). - DIRECTORY_SEPARATOR. - $className.'.php'; + $file = $dir . DIRECTORY_SEPARATOR . + str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . + DIRECTORY_SEPARATOR . + $className . '.php'; if (file_exists($file)) { return $file; @@ -185,20 +183,18 @@ class ThriftClassLoader * Available in service: Interface, Client, Processor, Rest * And every service methods (_.+) */ - if( - 0 === preg_match('#(.+)(if|client|processor|rest)$#i', $class, $n) and + if (0 === preg_match('#(.+)(if|client|processor|rest)$#i', $class, $n) and 0 === preg_match('#(.+)_[a-z0-9]+_(args|result)$#i', $class, $n) - ) - { + ) { $className = 'Types'; } else { $className = $n[1]; } - $file = $dir.DIRECTORY_SEPARATOR . - str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . - DIRECTORY_SEPARATOR . - $className . '.php'; + $file = $dir . DIRECTORY_SEPARATOR . + str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . + DIRECTORY_SEPARATOR . + $className . '.php'; if (file_exists($file)) { return $file; diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Exception/TApplicationException.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Exception/TApplicationException.php new file mode 100644 index 0000000..ebb6a6a --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Exception/TApplicationException.php @@ -0,0 +1,76 @@ + array('var' => 'message', + 'type' => TType::STRING), + 2 => array('var' => 'code', + 'type' => TType::I32)); + + const UNKNOWN = 0; + const UNKNOWN_METHOD = 1; + const INVALID_MESSAGE_TYPE = 2; + const WRONG_METHOD_NAME = 3; + const BAD_SEQUENCE_ID = 4; + const MISSING_RESULT = 5; + const INTERNAL_ERROR = 6; + const PROTOCOL_ERROR = 7; + const INVALID_TRANSFORM = 8; + const INVALID_PROTOCOL = 9; + const UNSUPPORTED_CLIENT_TYPE = 10; + + public function __construct($message = null, $code = 0) + { + parent::__construct($message, $code); + } + + public function read($output) + { + return $this->_read('TApplicationException', self::$_TSPEC, $output); + } + + public function write($output) + { + $xfer = 0; + $xfer += $output->writeStructBegin('TApplicationException'); + if ($message = $this->getMessage()) { + $xfer += $output->writeFieldBegin('message', TType::STRING, 1); + $xfer += $output->writeString($message); + $xfer += $output->writeFieldEnd(); + } + if ($code = $this->getCode()) { + $xfer += $output->writeFieldBegin('type', TType::I32, 2); + $xfer += $output->writeI32($code); + $xfer += $output->writeFieldEnd(); + } + $xfer += $output->writeFieldStop(); + $xfer += $output->writeStructEnd(); + + return $xfer; + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Exception/TException.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Exception/TException.php new file mode 100644 index 0000000..7dbf832 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Exception/TException.php @@ -0,0 +1,384 @@ + $fspec) { + $var = $fspec['var']; + if (isset($vals[$var])) { + $this->$var = $vals[$var]; + } + } + } else { + parent::__construct($p1, $p2); + } + } + + public static $tmethod = array( + TType::BOOL => 'Bool', + TType::BYTE => 'Byte', + TType::I16 => 'I16', + TType::I32 => 'I32', + TType::I64 => 'I64', + TType::DOUBLE => 'Double', + TType::STRING => 'String' + ); + + private function _readMap(&$var, $spec, $input) + { + $xfer = 0; + $ktype = $spec['ktype']; + $vtype = $spec['vtype']; + $kread = $vread = null; + if (isset(TBase::$tmethod[$ktype])) { + $kread = 'read' . TBase::$tmethod[$ktype]; + } else { + $kspec = $spec['key']; + } + if (isset(TBase::$tmethod[$vtype])) { + $vread = 'read' . TBase::$tmethod[$vtype]; + } else { + $vspec = $spec['val']; + } + $var = array(); + $_ktype = $_vtype = $size = 0; + $xfer += $input->readMapBegin($_ktype, $_vtype, $size); + for ($i = 0; $i < $size; ++$i) { + $key = $val = null; + if ($kread !== null) { + $xfer += $input->$kread($key); + } else { + switch ($ktype) { + case TType::STRUCT: + $class = $kspec['class']; + $key = new $class(); + $xfer += $key->read($input); + break; + case TType::MAP: + $xfer += $this->_readMap($key, $kspec, $input); + break; + case TType::LST: + $xfer += $this->_readList($key, $kspec, $input, false); + break; + case TType::SET: + $xfer += $this->_readList($key, $kspec, $input, true); + break; + } + } + if ($vread !== null) { + $xfer += $input->$vread($val); + } else { + switch ($vtype) { + case TType::STRUCT: + $class = $vspec['class']; + $val = new $class(); + $xfer += $val->read($input); + break; + case TType::MAP: + $xfer += $this->_readMap($val, $vspec, $input); + break; + case TType::LST: + $xfer += $this->_readList($val, $vspec, $input, false); + break; + case TType::SET: + $xfer += $this->_readList($val, $vspec, $input, true); + break; + } + } + $var[$key] = $val; + } + $xfer += $input->readMapEnd(); + + return $xfer; + } + + private function _readList(&$var, $spec, $input, $set = false) + { + $xfer = 0; + $etype = $spec['etype']; + $eread = $vread = null; + if (isset(TBase::$tmethod[$etype])) { + $eread = 'read' . TBase::$tmethod[$etype]; + } else { + $espec = $spec['elem']; + } + $var = array(); + $_etype = $size = 0; + if ($set) { + $xfer += $input->readSetBegin($_etype, $size); + } else { + $xfer += $input->readListBegin($_etype, $size); + } + for ($i = 0; $i < $size; ++$i) { + $elem = null; + if ($eread !== null) { + $xfer += $input->$eread($elem); + } else { + $espec = $spec['elem']; + switch ($etype) { + case TType::STRUCT: + $class = $espec['class']; + $elem = new $class(); + $xfer += $elem->read($input); + break; + case TType::MAP: + $xfer += $this->_readMap($elem, $espec, $input); + break; + case TType::LST: + $xfer += $this->_readList($elem, $espec, $input, false); + break; + case TType::SET: + $xfer += $this->_readList($elem, $espec, $input, true); + break; + } + } + if ($set) { + $var[$elem] = true; + } else { + $var [] = $elem; + } + } + if ($set) { + $xfer += $input->readSetEnd(); + } else { + $xfer += $input->readListEnd(); + } + + return $xfer; + } + + protected function _read($class, $spec, $input) + { + $xfer = 0; + $fname = null; + $ftype = 0; + $fid = 0; + $xfer += $input->readStructBegin($fname); + while (true) { + $xfer += $input->readFieldBegin($fname, $ftype, $fid); + if ($ftype == TType::STOP) { + break; + } + if (isset($spec[$fid])) { + $fspec = $spec[$fid]; + $var = $fspec['var']; + if ($ftype == $fspec['type']) { + $xfer = 0; + if (isset(TBase::$tmethod[$ftype])) { + $func = 'read' . TBase::$tmethod[$ftype]; + $xfer += $input->$func($this->$var); + } else { + switch ($ftype) { + case TType::STRUCT: + $class = $fspec['class']; + $this->$var = new $class(); + $xfer += $this->$var->read($input); + break; + case TType::MAP: + $xfer += $this->_readMap($this->$var, $fspec, $input); + break; + case TType::LST: + $xfer += $this->_readList($this->$var, $fspec, $input, false); + break; + case TType::SET: + $xfer += $this->_readList($this->$var, $fspec, $input, true); + break; + } + } + } else { + $xfer += $input->skip($ftype); + } + } else { + $xfer += $input->skip($ftype); + } + $xfer += $input->readFieldEnd(); + } + $xfer += $input->readStructEnd(); + + return $xfer; + } + + private function _writeMap($var, $spec, $output) + { + $xfer = 0; + $ktype = $spec['ktype']; + $vtype = $spec['vtype']; + $kwrite = $vwrite = null; + if (isset(TBase::$tmethod[$ktype])) { + $kwrite = 'write' . TBase::$tmethod[$ktype]; + } else { + $kspec = $spec['key']; + } + if (isset(TBase::$tmethod[$vtype])) { + $vwrite = 'write' . TBase::$tmethod[$vtype]; + } else { + $vspec = $spec['val']; + } + $xfer += $output->writeMapBegin($ktype, $vtype, count($var)); + foreach ($var as $key => $val) { + if (isset($kwrite)) { + $xfer += $output->$kwrite($key); + } else { + switch ($ktype) { + case TType::STRUCT: + $xfer += $key->write($output); + break; + case TType::MAP: + $xfer += $this->_writeMap($key, $kspec, $output); + break; + case TType::LST: + $xfer += $this->_writeList($key, $kspec, $output, false); + break; + case TType::SET: + $xfer += $this->_writeList($key, $kspec, $output, true); + break; + } + } + if (isset($vwrite)) { + $xfer += $output->$vwrite($val); + } else { + switch ($vtype) { + case TType::STRUCT: + $xfer += $val->write($output); + break; + case TType::MAP: + $xfer += $this->_writeMap($val, $vspec, $output); + break; + case TType::LST: + $xfer += $this->_writeList($val, $vspec, $output, false); + break; + case TType::SET: + $xfer += $this->_writeList($val, $vspec, $output, true); + break; + } + } + } + $xfer += $output->writeMapEnd(); + + return $xfer; + } + + private function _writeList($var, $spec, $output, $set = false) + { + $xfer = 0; + $etype = $spec['etype']; + $ewrite = null; + if (isset(TBase::$tmethod[$etype])) { + $ewrite = 'write' . TBase::$tmethod[$etype]; + } else { + $espec = $spec['elem']; + } + if ($set) { + $xfer += $output->writeSetBegin($etype, count($var)); + } else { + $xfer += $output->writeListBegin($etype, count($var)); + } + foreach ($var as $key => $val) { + $elem = $set ? $key : $val; + if (isset($ewrite)) { + $xfer += $output->$ewrite($elem); + } else { + switch ($etype) { + case TType::STRUCT: + $xfer += $elem->write($output); + break; + case TType::MAP: + $xfer += $this->_writeMap($elem, $espec, $output); + break; + case TType::LST: + $xfer += $this->_writeList($elem, $espec, $output, false); + break; + case TType::SET: + $xfer += $this->_writeList($elem, $espec, $output, true); + break; + } + } + } + if ($set) { + $xfer += $output->writeSetEnd(); + } else { + $xfer += $output->writeListEnd(); + } + + return $xfer; + } + + protected function _write($class, $spec, $output) + { + $xfer = 0; + $xfer += $output->writeStructBegin($class); + foreach ($spec as $fid => $fspec) { + $var = $fspec['var']; + if ($this->$var !== null) { + $ftype = $fspec['type']; + $xfer += $output->writeFieldBegin($var, $ftype, $fid); + if (isset(TBase::$tmethod[$ftype])) { + $func = 'write' . TBase::$tmethod[$ftype]; + $xfer += $output->$func($this->$var); + } else { + switch ($ftype) { + case TType::STRUCT: + $xfer += $this->$var->write($output); + break; + case TType::MAP: + $xfer += $this->_writeMap($this->$var, $fspec, $output); + break; + case TType::LST: + $xfer += $this->_writeList($this->$var, $fspec, $output, false); + break; + case TType::SET: + $xfer += $this->_writeList($this->$var, $fspec, $output, true); + break; + } + } + $xfer += $output->writeFieldEnd(); + } + } + $xfer += $output->writeFieldStop(); + $xfer += $output->writeStructEnd(); + + return $xfer; + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Exception/TProtocolException.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Exception/TProtocolException.php similarity index 78% rename from vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Exception/TProtocolException.php rename to vendor/git.apache.org/thrift.git/lib/php/lib/Exception/TProtocolException.php index ba7135c..3a55d45 100644 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Exception/TProtocolException.php +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Exception/TProtocolException.php @@ -35,16 +35,16 @@ namespace Thrift\Exception; */ class TProtocolException extends TException { - const UNKNOWN = 0; - const INVALID_DATA = 1; - const NEGATIVE_SIZE = 2; - const SIZE_LIMIT = 3; - const BAD_VERSION = 4; - const NOT_IMPLEMENTED = 5; - const DEPTH_LIMIT = 6; + const UNKNOWN = 0; + const INVALID_DATA = 1; + const NEGATIVE_SIZE = 2; + const SIZE_LIMIT = 3; + const BAD_VERSION = 4; + const NOT_IMPLEMENTED = 5; + const DEPTH_LIMIT = 6; - public function __construct($message=null, $code=0) - { - parent::__construct($message, $code); - } + public function __construct($message = null, $code = 0) + { + parent::__construct($message, $code); + } } diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Exception/TTransportException.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Exception/TTransportException.php similarity index 79% rename from vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Exception/TTransportException.php rename to vendor/git.apache.org/thrift.git/lib/php/lib/Exception/TTransportException.php index 0074467..7d8d567 100644 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Exception/TTransportException.php +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Exception/TTransportException.php @@ -27,14 +27,14 @@ namespace Thrift\Exception; */ class TTransportException extends TException { - const UNKNOWN = 0; - const NOT_OPEN = 1; - const ALREADY_OPEN = 2; - const TIMED_OUT = 3; - const END_OF_FILE = 4; + const UNKNOWN = 0; + const NOT_OPEN = 1; + const ALREADY_OPEN = 2; + const TIMED_OUT = 3; + const END_OF_FILE = 4; - public function __construct($message=null, $code=0) - { - parent::__construct($message, $code); - } + public function __construct($message = null, $code = 0) + { + parent::__construct($message, $code); + } } diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Factory/TBinaryProtocolFactory.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Factory/TBinaryProtocolFactory.php similarity index 72% rename from vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Factory/TBinaryProtocolFactory.php rename to vendor/git.apache.org/thrift.git/lib/php/lib/Factory/TBinaryProtocolFactory.php index 0c1c4a7..2519183 100644 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Factory/TBinaryProtocolFactory.php +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Factory/TBinaryProtocolFactory.php @@ -29,17 +29,17 @@ use Thrift\Protocol\TBinaryProtocol; */ class TBinaryProtocolFactory implements TProtocolFactory { - private $strictRead_ = false; - private $strictWrite_ = false; + private $strictRead_ = false; + private $strictWrite_ = false; - public function __construct($strictRead=false, $strictWrite=false) - { - $this->strictRead_ = $strictRead; - $this->strictWrite_ = $strictWrite; - } + public function __construct($strictRead = false, $strictWrite = false) + { + $this->strictRead_ = $strictRead; + $this->strictWrite_ = $strictWrite; + } - public function getProtocol($trans) - { - return new TBinaryProtocol($trans, $this->strictRead_, $this->strictWrite_); - } + public function getProtocol($trans) + { + return new TBinaryProtocol($trans, $this->strictRead_, $this->strictWrite_); + } } diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Factory/TCompactProtocolFactory.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Factory/TCompactProtocolFactory.php similarity index 87% rename from vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Factory/TCompactProtocolFactory.php rename to vendor/git.apache.org/thrift.git/lib/php/lib/Factory/TCompactProtocolFactory.php index f4b4fe3..11fb8ff 100644 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Factory/TCompactProtocolFactory.php +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Factory/TCompactProtocolFactory.php @@ -29,12 +29,12 @@ use Thrift\Protocol\TCompactProtocol; */ class TCompactProtocolFactory implements TProtocolFactory { - public function __construct() - { - } + public function __construct() + { + } - public function getProtocol($trans) - { - return new TCompactProtocol($trans); - } + public function getProtocol($trans) + { + return new TCompactProtocol($trans); + } } diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Factory/TJSONProtocolFactory.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Factory/TJSONProtocolFactory.php similarity index 100% rename from vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Factory/TJSONProtocolFactory.php rename to vendor/git.apache.org/thrift.git/lib/php/lib/Factory/TJSONProtocolFactory.php diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Factory/TProtocolFactory.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Factory/TProtocolFactory.php similarity index 85% rename from vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Factory/TProtocolFactory.php rename to vendor/git.apache.org/thrift.git/lib/php/lib/Factory/TProtocolFactory.php index 4c9562d..d3066c8 100644 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Factory/TProtocolFactory.php +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Factory/TProtocolFactory.php @@ -27,10 +27,10 @@ namespace Thrift\Factory; */ interface TProtocolFactory { - /** - * Build a protocol from the base transport - * - * @return Thrift\Protocol\TProtocol protocol - */ - public function getProtocol($trans); + /** + * Build a protocol from the base transport + * + * @return Thrift\Protocol\TProtocol protocol + */ + public function getProtocol($trans); } diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Factory/TStringFuncFactory.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Factory/TStringFuncFactory.php similarity index 83% rename from vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Factory/TStringFuncFactory.php rename to vendor/git.apache.org/thrift.git/lib/php/lib/Factory/TStringFuncFactory.php index 6ad6839..30de4d7 100644 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Factory/TStringFuncFactory.php +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Factory/TStringFuncFactory.php @@ -21,8 +21,9 @@ namespace Thrift\Factory; -use Thrift\StringFunc\Mbstring; use Thrift\StringFunc\Core; +use Thrift\StringFunc\Mbstring; +use Thrift\StringFunc\TStringFunc; class TStringFuncFactory { @@ -49,17 +50,16 @@ class TStringFuncFactory * Cannot use str* functions for byte counting because multibyte * characters will be read a single bytes. * - * See: http://us.php.net/manual/en/mbstring.overload.php + * See: http://php.net/manual/en/mbstring.overload.php */ if (ini_get('mbstring.func_overload') & 2) { self::$_instance = new Mbstring(); - } - /** - * mbstring is not installed or does not have function overloading - * of the str* functions enabled so use PHP core str* functions for - * byte counting. - */ - else { + } else { + /** + * mbstring is not installed or does not have function overloading + * of the str* functions enabled so use PHP core str* functions for + * byte counting. + */ self::$_instance = new Core(); } } diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Factory/TTransportFactory.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Factory/TTransportFactory.php new file mode 100644 index 0000000..43f2eec --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Factory/TTransportFactory.php @@ -0,0 +1,18 @@ +isKey; } } - - diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/SimpleJSON/StructContext.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/SimpleJSON/StructContext.php similarity index 93% rename from vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/SimpleJSON/StructContext.php rename to vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/SimpleJSON/StructContext.php index 8162f2b..38a62d1 100644 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/SimpleJSON/StructContext.php +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/SimpleJSON/StructContext.php @@ -43,11 +43,10 @@ class StructContext extends Context } else { $this->p_->getTransport()->write( $this->colon_ ? - TSimpleJSONProtocol::COLON : - TSimpleJSONProtocol::COMMA + TSimpleJSONProtocol::COLON : + TSimpleJSONProtocol::COMMA ); $this->colon_ = !$this->colon_; } } } - diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TBinaryProtocol.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TBinaryProtocol.php new file mode 100644 index 0000000..cda5c0d --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TBinaryProtocol.php @@ -0,0 +1,453 @@ +strictRead_ = $strictRead; + $this->strictWrite_ = $strictWrite; + } + + public function writeMessageBegin($name, $type, $seqid) + { + if ($this->strictWrite_) { + $version = self::VERSION_1 | $type; + + return + $this->writeI32($version) + + $this->writeString($name) + + $this->writeI32($seqid); + } else { + return + $this->writeString($name) + + $this->writeByte($type) + + $this->writeI32($seqid); + } + } + + public function writeMessageEnd() + { + return 0; + } + + public function writeStructBegin($name) + { + return 0; + } + + public function writeStructEnd() + { + return 0; + } + + public function writeFieldBegin($fieldName, $fieldType, $fieldId) + { + return + $this->writeByte($fieldType) + + $this->writeI16($fieldId); + } + + public function writeFieldEnd() + { + return 0; + } + + public function writeFieldStop() + { + return + $this->writeByte(TType::STOP); + } + + public function writeMapBegin($keyType, $valType, $size) + { + return + $this->writeByte($keyType) + + $this->writeByte($valType) + + $this->writeI32($size); + } + + public function writeMapEnd() + { + return 0; + } + + public function writeListBegin($elemType, $size) + { + return + $this->writeByte($elemType) + + $this->writeI32($size); + } + + public function writeListEnd() + { + return 0; + } + + public function writeSetBegin($elemType, $size) + { + return + $this->writeByte($elemType) + + $this->writeI32($size); + } + + public function writeSetEnd() + { + return 0; + } + + public function writeBool($value) + { + $data = pack('c', $value ? 1 : 0); + $this->trans_->write($data, 1); + + return 1; + } + + public function writeByte($value) + { + $data = pack('c', $value); + $this->trans_->write($data, 1); + + return 1; + } + + public function writeI16($value) + { + $data = pack('n', $value); + $this->trans_->write($data, 2); + + return 2; + } + + public function writeI32($value) + { + $data = pack('N', $value); + $this->trans_->write($data, 4); + + return 4; + } + + public function writeI64($value) + { + // If we are on a 32bit architecture we have to explicitly deal with + // 64-bit twos-complement arithmetic since PHP wants to treat all ints + // as signed and any int over 2^31 - 1 as a float + if (PHP_INT_SIZE == 4) { + $neg = $value < 0; + + if ($neg) { + $value *= -1; + } + + $hi = (int)($value / 4294967296); + $lo = (int)$value; + + if ($neg) { + $hi = ~$hi; + $lo = ~$lo; + if (($lo & (int)0xffffffff) == (int)0xffffffff) { + $lo = 0; + $hi++; + } else { + $lo++; + } + } + $data = pack('N2', $hi, $lo); + } else { + $hi = $value >> 32; + $lo = $value & 0xFFFFFFFF; + $data = pack('N2', $hi, $lo); + } + + $this->trans_->write($data, 8); + + return 8; + } + + public function writeDouble($value) + { + $data = pack('d', $value); + $this->trans_->write(strrev($data), 8); + + return 8; + } + + public function writeString($value) + { + $len = TStringFuncFactory::create()->strlen($value); + $result = $this->writeI32($len); + if ($len) { + $this->trans_->write($value, $len); + } + + return $result + $len; + } + + public function readMessageBegin(&$name, &$type, &$seqid) + { + $result = $this->readI32($sz); + if ($sz < 0) { + $version = (int)($sz & self::VERSION_MASK); + if ($version != (int)self::VERSION_1) { + throw new TProtocolException('Bad version identifier: ' . $sz, TProtocolException::BAD_VERSION); + } + $type = $sz & 0x000000ff; + $result += + $this->readString($name) + + $this->readI32($seqid); + } else { + if ($this->strictRead_) { + throw new TProtocolException( + 'No version identifier, old protocol client?', + TProtocolException::BAD_VERSION + ); + } else { + // Handle pre-versioned input + $name = $this->trans_->readAll($sz); + $result += + $sz + + $this->readByte($type) + + $this->readI32($seqid); + } + } + + return $result; + } + + public function readMessageEnd() + { + return 0; + } + + public function readStructBegin(&$name) + { + $name = ''; + + return 0; + } + + public function readStructEnd() + { + return 0; + } + + public function readFieldBegin(&$name, &$fieldType, &$fieldId) + { + $result = $this->readByte($fieldType); + if ($fieldType == TType::STOP) { + $fieldId = 0; + + return $result; + } + $result += $this->readI16($fieldId); + + return $result; + } + + public function readFieldEnd() + { + return 0; + } + + public function readMapBegin(&$keyType, &$valType, &$size) + { + return + $this->readByte($keyType) + + $this->readByte($valType) + + $this->readI32($size); + } + + public function readMapEnd() + { + return 0; + } + + public function readListBegin(&$elemType, &$size) + { + return + $this->readByte($elemType) + + $this->readI32($size); + } + + public function readListEnd() + { + return 0; + } + + public function readSetBegin(&$elemType, &$size) + { + return + $this->readByte($elemType) + + $this->readI32($size); + } + + public function readSetEnd() + { + return 0; + } + + public function readBool(&$value) + { + $data = $this->trans_->readAll(1); + $arr = unpack('c', $data); + $value = $arr[1] == 1; + + return 1; + } + + public function readByte(&$value) + { + $data = $this->trans_->readAll(1); + $arr = unpack('c', $data); + $value = $arr[1]; + + return 1; + } + + public function readI16(&$value) + { + $data = $this->trans_->readAll(2); + $arr = unpack('n', $data); + $value = $arr[1]; + if ($value > 0x7fff) { + $value = 0 - (($value - 1) ^ 0xffff); + } + + return 2; + } + + public function readI32(&$value) + { + $data = $this->trans_->readAll(4); + $arr = unpack('N', $data); + $value = $arr[1]; + if ($value > 0x7fffffff) { + $value = 0 - (($value - 1) ^ 0xffffffff); + } + + return 4; + } + + public function readI64(&$value) + { + $data = $this->trans_->readAll(8); + + $arr = unpack('N2', $data); + + // If we are on a 32bit architecture we have to explicitly deal with + // 64-bit twos-complement arithmetic since PHP wants to treat all ints + // as signed and any int over 2^31 - 1 as a float + if (PHP_INT_SIZE == 4) { + $hi = $arr[1]; + $lo = $arr[2]; + $isNeg = $hi < 0; + + // Check for a negative + if ($isNeg) { + $hi = ~$hi & (int)0xffffffff; + $lo = ~$lo & (int)0xffffffff; + + if ($lo == (int)0xffffffff) { + $hi++; + $lo = 0; + } else { + $lo++; + } + } + + // Force 32bit words in excess of 2G to pe positive - we deal wigh sign + // explicitly below + + if ($hi & (int)0x80000000) { + $hi &= (int)0x7fffffff; + $hi += 0x80000000; + } + + if ($lo & (int)0x80000000) { + $lo &= (int)0x7fffffff; + $lo += 0x80000000; + } + + $value = $hi * 4294967296 + $lo; + + if ($isNeg) { + $value = 0 - $value; + } + } else { + // Upcast negatives in LSB bit + if ($arr[2] & 0x80000000) { + $arr[2] = $arr[2] & 0xffffffff; + } + + // Check for a negative + if ($arr[1] & 0x80000000) { + $arr[1] = $arr[1] & 0xffffffff; + $arr[1] = $arr[1] ^ 0xffffffff; + $arr[2] = $arr[2] ^ 0xffffffff; + $value = 0 - $arr[1] * 4294967296 - $arr[2] - 1; + } else { + $value = $arr[1] * 4294967296 + $arr[2]; + } + } + + return 8; + } + + public function readDouble(&$value) + { + $data = strrev($this->trans_->readAll(8)); + $arr = unpack('d', $data); + $value = $arr[1]; + + return 8; + } + + public function readString(&$value) + { + $result = $this->readI32($len); + if ($len) { + $value = $this->trans_->readAll($len); + } else { + $value = ''; + } + + return $result + $len; + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TBinaryProtocolAccelerated.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TBinaryProtocolAccelerated.php new file mode 100644 index 0000000..ff799a6 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TBinaryProtocolAccelerated.php @@ -0,0 +1,67 @@ +strictRead_; + } + + public function isStrictWrite() + { + return $this->strictWrite_; + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TCompactProtocol.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TCompactProtocol.php new file mode 100644 index 0000000..1af2a27 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TCompactProtocol.php @@ -0,0 +1,739 @@ + TCompactProtocol::COMPACT_STOP, + TType::BOOL => TCompactProtocol::COMPACT_TRUE, // used for collection + TType::BYTE => TCompactProtocol::COMPACT_BYTE, + TType::I16 => TCompactProtocol::COMPACT_I16, + TType::I32 => TCompactProtocol::COMPACT_I32, + TType::I64 => TCompactProtocol::COMPACT_I64, + TType::DOUBLE => TCompactProtocol::COMPACT_DOUBLE, + TType::STRING => TCompactProtocol::COMPACT_BINARY, + TType::STRUCT => TCompactProtocol::COMPACT_STRUCT, + TType::LST => TCompactProtocol::COMPACT_LIST, + TType::SET => TCompactProtocol::COMPACT_SET, + TType::MAP => TCompactProtocol::COMPACT_MAP, + ); + + protected static $ttypes = array( + TCompactProtocol::COMPACT_STOP => TType::STOP, + TCompactProtocol::COMPACT_TRUE => TType::BOOL, // used for collection + TCompactProtocol::COMPACT_FALSE => TType::BOOL, + TCompactProtocol::COMPACT_BYTE => TType::BYTE, + TCompactProtocol::COMPACT_I16 => TType::I16, + TCompactProtocol::COMPACT_I32 => TType::I32, + TCompactProtocol::COMPACT_I64 => TType::I64, + TCompactProtocol::COMPACT_DOUBLE => TType::DOUBLE, + TCompactProtocol::COMPACT_BINARY => TType::STRING, + TCompactProtocol::COMPACT_STRUCT => TType::STRUCT, + TCompactProtocol::COMPACT_LIST => TType::LST, + TCompactProtocol::COMPACT_SET => TType::SET, + TCompactProtocol::COMPACT_MAP => TType::MAP, + ); + + protected $state = TCompactProtocol::STATE_CLEAR; + protected $lastFid = 0; + protected $boolFid = null; + protected $boolValue = null; + protected $structs = array(); + protected $containers = array(); + + // Some varint / zigzag helper methods + public function toZigZag($n, $bits) + { + return ($n << 1) ^ ($n >> ($bits - 1)); + } + + public function fromZigZag($n) + { + return ($n >> 1) ^ -($n & 1); + } + + public function getVarint($data) + { + $out = ""; + while (true) { + if (($data & ~0x7f) === 0) { + $out .= chr($data); + break; + } else { + $out .= chr(($data & 0xff) | 0x80); + $data = $data >> 7; + } + } + + return $out; + } + + public function writeVarint($data) + { + $out = $this->getVarint($data); + $result = TStringFuncFactory::create()->strlen($out); + $this->trans_->write($out, $result); + + return $result; + } + + public function readVarint(&$result) + { + $idx = 0; + $shift = 0; + $result = 0; + while (true) { + $x = $this->trans_->readAll(1); + $arr = unpack('C', $x); + $byte = $arr[1]; + $idx += 1; + $result |= ($byte & 0x7f) << $shift; + if (($byte >> 7) === 0) { + return $idx; + } + $shift += 7; + } + + return $idx; + } + + public function __construct($trans) + { + parent::__construct($trans); + } + + public function writeMessageBegin($name, $type, $seqid) + { + $written = + $this->writeUByte(TCompactProtocol::PROTOCOL_ID) + + $this->writeUByte(TCompactProtocol::VERSION | + ($type << TCompactProtocol::TYPE_SHIFT_AMOUNT)) + + $this->writeVarint($seqid) + + $this->writeString($name); + $this->state = TCompactProtocol::STATE_VALUE_WRITE; + + return $written; + } + + public function writeMessageEnd() + { + $this->state = TCompactProtocol::STATE_CLEAR; + + return 0; + } + + public function writeStructBegin($name) + { + $this->structs[] = array($this->state, $this->lastFid); + $this->state = TCompactProtocol::STATE_FIELD_WRITE; + $this->lastFid = 0; + + return 0; + } + + public function writeStructEnd() + { + $old_values = array_pop($this->structs); + $this->state = $old_values[0]; + $this->lastFid = $old_values[1]; + + return 0; + } + + public function writeFieldStop() + { + return $this->writeByte(0); + } + + public function writeFieldHeader($type, $fid) + { + $written = 0; + $delta = $fid - $this->lastFid; + if (0 < $delta && $delta <= 15) { + $written = $this->writeUByte(($delta << 4) | $type); + } else { + $written = $this->writeByte($type) + + $this->writeI16($fid); + } + $this->lastFid = $fid; + + return $written; + } + + public function writeFieldBegin($field_name, $field_type, $field_id) + { + if ($field_type == TTYPE::BOOL) { + $this->state = TCompactProtocol::STATE_BOOL_WRITE; + $this->boolFid = $field_id; + + return 0; + } else { + $this->state = TCompactProtocol::STATE_VALUE_WRITE; + + return $this->writeFieldHeader(self::$ctypes[$field_type], $field_id); + } + } + + public function writeFieldEnd() + { + $this->state = TCompactProtocol::STATE_FIELD_WRITE; + + return 0; + } + + public function writeCollectionBegin($etype, $size) + { + $written = 0; + if ($size <= 14) { + $written = $this->writeUByte($size << 4 | + self::$ctypes[$etype]); + } else { + $written = $this->writeUByte(0xf0 | + self::$ctypes[$etype]) + + $this->writeVarint($size); + } + $this->containers[] = $this->state; + $this->state = TCompactProtocol::STATE_CONTAINER_WRITE; + + return $written; + } + + public function writeMapBegin($key_type, $val_type, $size) + { + $written = 0; + if ($size == 0) { + $written = $this->writeByte(0); + } else { + $written = $this->writeVarint($size) + + $this->writeUByte(self::$ctypes[$key_type] << 4 | + self::$ctypes[$val_type]); + } + $this->containers[] = $this->state; + + return $written; + } + + public function writeCollectionEnd() + { + $this->state = array_pop($this->containers); + + return 0; + } + + public function writeMapEnd() + { + return $this->writeCollectionEnd(); + } + + public function writeListBegin($elem_type, $size) + { + return $this->writeCollectionBegin($elem_type, $size); + } + + public function writeListEnd() + { + return $this->writeCollectionEnd(); + } + + public function writeSetBegin($elem_type, $size) + { + return $this->writeCollectionBegin($elem_type, $size); + } + + public function writeSetEnd() + { + return $this->writeCollectionEnd(); + } + + public function writeBool($value) + { + if ($this->state == TCompactProtocol::STATE_BOOL_WRITE) { + $ctype = TCompactProtocol::COMPACT_FALSE; + if ($value) { + $ctype = TCompactProtocol::COMPACT_TRUE; + } + + return $this->writeFieldHeader($ctype, $this->boolFid); + } elseif ($this->state == TCompactProtocol::STATE_CONTAINER_WRITE) { + return $this->writeByte($value ? 1 : 0); + } else { + throw new TProtocolException('Invalid state in compact protocol'); + } + } + + public function writeByte($value) + { + $data = pack('c', $value); + $this->trans_->write($data, 1); + + return 1; + } + + public function writeUByte($byte) + { + $this->trans_->write(pack('C', $byte), 1); + + return 1; + } + + public function writeI16($value) + { + $thing = $this->toZigZag($value, 16); + + return $this->writeVarint($thing); + } + + public function writeI32($value) + { + $thing = $this->toZigZag($value, 32); + + return $this->writeVarint($thing); + } + + public function writeDouble($value) + { + $data = pack('d', $value); + $this->trans_->write($data, 8); + + return 8; + } + + public function writeString($value) + { + $len = TStringFuncFactory::create()->strlen($value); + $result = $this->writeVarint($len); + if ($len) { + $this->trans_->write($value, $len); + } + + return $result + $len; + } + + public function readFieldBegin(&$name, &$field_type, &$field_id) + { + $result = $this->readUByte($compact_type_and_delta); + + $compact_type = $compact_type_and_delta & 0x0f; + + if ($compact_type == TType::STOP) { + $field_type = $compact_type; + $field_id = 0; + + return $result; + } + $delta = $compact_type_and_delta >> 4; + if ($delta == 0) { + $result += $this->readI16($field_id); + } else { + $field_id = $this->lastFid + $delta; + } + $this->lastFid = $field_id; + $field_type = $this->getTType($compact_type); + + if ($compact_type == TCompactProtocol::COMPACT_TRUE) { + $this->state = TCompactProtocol::STATE_BOOL_READ; + $this->boolValue = true; + } elseif ($compact_type == TCompactProtocol::COMPACT_FALSE) { + $this->state = TCompactProtocol::STATE_BOOL_READ; + $this->boolValue = false; + } else { + $this->state = TCompactProtocol::STATE_VALUE_READ; + } + + return $result; + } + + public function readFieldEnd() + { + $this->state = TCompactProtocol::STATE_FIELD_READ; + + return 0; + } + + public function readUByte(&$value) + { + $data = $this->trans_->readAll(1); + $arr = unpack('C', $data); + $value = $arr[1]; + + return 1; + } + + public function readByte(&$value) + { + $data = $this->trans_->readAll(1); + $arr = unpack('c', $data); + $value = $arr[1]; + + return 1; + } + + public function readZigZag(&$value) + { + $result = $this->readVarint($value); + $value = $this->fromZigZag($value); + + return $result; + } + + public function readMessageBegin(&$name, &$type, &$seqid) + { + $protoId = 0; + $result = $this->readUByte($protoId); + if ($protoId != TCompactProtocol::PROTOCOL_ID) { + throw new TProtocolException('Bad protocol id in TCompact message'); + } + $verType = 0; + $result += $this->readUByte($verType); + $type = ($verType >> TCompactProtocol::TYPE_SHIFT_AMOUNT) & TCompactProtocol::TYPE_BITS; + $version = $verType & TCompactProtocol::VERSION_MASK; + if ($version != TCompactProtocol::VERSION) { + throw new TProtocolException('Bad version in TCompact message'); + } + $result += $this->readVarint($seqid); + $result += $this->readString($name); + + return $result; + } + + public function readMessageEnd() + { + return 0; + } + + public function readStructBegin(&$name) + { + $name = ''; // unused + $this->structs[] = array($this->state, $this->lastFid); + $this->state = TCompactProtocol::STATE_FIELD_READ; + $this->lastFid = 0; + + return 0; + } + + public function readStructEnd() + { + $last = array_pop($this->structs); + $this->state = $last[0]; + $this->lastFid = $last[1]; + + return 0; + } + + public function readCollectionBegin(&$type, &$size) + { + $sizeType = 0; + $result = $this->readUByte($sizeType); + $size = $sizeType >> 4; + $type = $this->getTType($sizeType); + if ($size == 15) { + $result += $this->readVarint($size); + } + $this->containers[] = $this->state; + $this->state = TCompactProtocol::STATE_CONTAINER_READ; + + return $result; + } + + public function readMapBegin(&$key_type, &$val_type, &$size) + { + $result = $this->readVarint($size); + $types = 0; + if ($size > 0) { + $result += $this->readUByte($types); + } + $val_type = $this->getTType($types); + $key_type = $this->getTType($types >> 4); + $this->containers[] = $this->state; + $this->state = TCompactProtocol::STATE_CONTAINER_READ; + + return $result; + } + + public function readCollectionEnd() + { + $this->state = array_pop($this->containers); + + return 0; + } + + public function readMapEnd() + { + return $this->readCollectionEnd(); + } + + public function readListBegin(&$elem_type, &$size) + { + return $this->readCollectionBegin($elem_type, $size); + } + + public function readListEnd() + { + return $this->readCollectionEnd(); + } + + public function readSetBegin(&$elem_type, &$size) + { + return $this->readCollectionBegin($elem_type, $size); + } + + public function readSetEnd() + { + return $this->readCollectionEnd(); + } + + public function readBool(&$value) + { + if ($this->state == TCompactProtocol::STATE_BOOL_READ) { + $value = $this->boolValue; + + return 0; + } elseif ($this->state == TCompactProtocol::STATE_CONTAINER_READ) { + return $this->readByte($value); + } else { + throw new TProtocolException('Invalid state in compact protocol'); + } + } + + public function readI16(&$value) + { + return $this->readZigZag($value); + } + + public function readI32(&$value) + { + return $this->readZigZag($value); + } + + public function readDouble(&$value) + { + $data = $this->trans_->readAll(8); + $arr = unpack('d', $data); + $value = $arr[1]; + + return 8; + } + + public function readString(&$value) + { + $result = $this->readVarint($len); + if ($len) { + $value = $this->trans_->readAll($len); + } else { + $value = ''; + } + + return $result + $len; + } + + public function getTType($byte) + { + return self::$ttypes[$byte & 0x0f]; + } + + // If we are on a 32bit architecture we have to explicitly deal with + // 64-bit twos-complement arithmetic since PHP wants to treat all ints + // as signed and any int over 2^31 - 1 as a float + + // Read and write I64 as two 32 bit numbers $hi and $lo + + public function readI64(&$value) + { + // Read varint from wire + $hi = 0; + $lo = 0; + + $idx = 0; + $shift = 0; + + while (true) { + $x = $this->trans_->readAll(1); + $arr = unpack('C', $x); + $byte = $arr[1]; + $idx += 1; + // Shift hi and lo together. + if ($shift < 28) { + $lo |= (($byte & 0x7f) << $shift); + } elseif ($shift == 28) { + $lo |= (($byte & 0x0f) << 28); + $hi |= (($byte & 0x70) >> 4); + } else { + $hi |= (($byte & 0x7f) << ($shift - 32)); + } + if (($byte >> 7) === 0) { + break; + } + $shift += 7; + } + + // Now, unzig it. + $xorer = 0; + if ($lo & 1) { + $xorer = 0xffffffff; + } + $lo = ($lo >> 1) & 0x7fffffff; + $lo = $lo | (($hi & 1) << 31); + $hi = ($hi >> 1) ^ $xorer; + $lo = $lo ^ $xorer; + + // Now put $hi and $lo back together + $isNeg = $hi < 0 || $hi & 0x80000000; + + // Check for a negative + if ($isNeg) { + $hi = ~$hi & (int)0xffffffff; + $lo = ~$lo & (int)0xffffffff; + + if ($lo == (int)0xffffffff) { + $hi++; + $lo = 0; + } else { + $lo++; + } + } + + // Force 32bit words in excess of 2G to be positive - we deal with sign + // explicitly below + + if ($hi & (int)0x80000000) { + $hi &= (int)0x7fffffff; + $hi += 0x80000000; + } + + if ($lo & (int)0x80000000) { + $lo &= (int)0x7fffffff; + $lo += 0x80000000; + } + + // Create as negative value first, since we can store -2^63 but not 2^63 + $value = -$hi * 4294967296 - $lo; + + if (!$isNeg) { + $value = -$value; + } + + return $idx; + } + + public function writeI64($value) + { + // If we are in an I32 range, use the easy method below. + if (($value > 4294967296) || ($value < -4294967296)) { + // Convert $value to $hi and $lo + $neg = $value < 0; + + if ($neg) { + $value *= -1; + } + + $hi = (int)$value >> 32; + $lo = (int)$value & 0xffffffff; + + if ($neg) { + $hi = ~$hi; + $lo = ~$lo; + if (($lo & (int)0xffffffff) == (int)0xffffffff) { + $lo = 0; + $hi++; + } else { + $lo++; + } + } + + // Now do the zigging and zagging. + $xorer = 0; + if ($neg) { + $xorer = 0xffffffff; + } + $lowbit = ($lo >> 31) & 1; + $hi = ($hi << 1) | $lowbit; + $lo = ($lo << 1); + $lo = ($lo ^ $xorer) & 0xffffffff; + $hi = ($hi ^ $xorer) & 0xffffffff; + + // now write out the varint, ensuring we shift both hi and lo + $out = ""; + while (true) { + if (($lo & ~0x7f) === 0 && + $hi === 0) { + $out .= chr($lo); + break; + } else { + $out .= chr(($lo & 0xff) | 0x80); + $lo = $lo >> 7; + $lo = $lo | ($hi << 25); + $hi = $hi >> 7; + // Right shift carries sign, but we don't want it to. + $hi = $hi & (127 << 25); + } + } + + $ret = TStringFuncFactory::create()->strlen($out); + $this->trans_->write($out, $ret); + + return $ret; + } else { + return $this->writeVarint($this->toZigZag($value, 64)); + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TJSONProtocol.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TJSONProtocol.php similarity index 90% rename from vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TJSONProtocol.php rename to vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TJSONProtocol.php index 6d8e81f..9144884 100644 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TJSONProtocol.php +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TJSONProtocol.php @@ -217,9 +217,9 @@ class TJSONProtocol extends TProtocol private function hasJSONUnescapedUnicode() { - if (PHP_MAJOR_VERSION > 5 - || (PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION >= 4)) + if (PHP_MAJOR_VERSION > 5 || (PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION >= 4)) { return true; + } return false; } @@ -237,18 +237,24 @@ class TJSONProtocol extends TProtocol * High surrogate: 0xD800 - 0xDBFF * Low surrogate: 0xDC00 - 0xDFFF */ - $json = preg_replace_callback('/\\\\u(d[89ab][0-9a-f]{2})\\\\u(d[cdef][0-9a-f]{2})/i', + $json = preg_replace_callback( + '/\\\\u(d[89ab][0-9a-f]{2})\\\\u(d[cdef][0-9a-f]{2})/i', function ($matches) { - return mb_convert_encoding(pack('H*', $matches[1].$matches[2]), 'UTF-8', 'UTF-16BE'); - }, $json); + return mb_convert_encoding(pack('H*', $matches[1] . $matches[2]), 'UTF-8', 'UTF-16BE'); + }, + $json + ); /* * Unescaped characters within the Basic Multilingual Plane */ - $json = preg_replace_callback('/\\\\u([0-9a-f]{4})/i', + $json = preg_replace_callback( + '/\\\\u([0-9a-f]{4})/i', function ($matches) { return mb_convert_encoding(pack('H*', $matches[1]), 'UTF-8', 'UTF-16BE'); - }, $json); + }, + $json + ); return $json; } @@ -308,54 +314,54 @@ class TJSONProtocol extends TProtocol private function writeJSONObjectStart() { - $this->context_->write(); - $this->trans_->write(self::LBRACE); - $this->pushContext(new PairContext($this)); + $this->context_->write(); + $this->trans_->write(self::LBRACE); + $this->pushContext(new PairContext($this)); } private function writeJSONObjectEnd() { - $this->popContext(); - $this->trans_->write(self::RBRACE); + $this->popContext(); + $this->trans_->write(self::RBRACE); } private function writeJSONArrayStart() { - $this->context_->write(); - $this->trans_->write(self::LBRACKET); - $this->pushContext(new ListContext($this)); + $this->context_->write(); + $this->trans_->write(self::LBRACKET); + $this->pushContext(new ListContext($this)); } private function writeJSONArrayEnd() { - $this->popContext(); - $this->trans_->write(self::RBRACKET); + $this->popContext(); + $this->trans_->write(self::RBRACKET); } private function readJSONString($skipContext) { - if (!$skipContext) { - $this->context_->read(); - } - - $jsonString = ''; - $lastChar = null; - while (true) { - $ch = $this->reader_->read(); - $jsonString .= $ch; - if ($ch == self::QUOTE && - $lastChar !== NULL && - $lastChar !== self::ESCSEQ) { - break; + if (!$skipContext) { + $this->context_->read(); } - if ($ch == self::ESCSEQ && $lastChar == self::ESCSEQ) { - $lastChar = self::DOUBLEESC; - } else { - $lastChar = $ch; - } - } - return json_decode($jsonString); + $jsonString = ''; + $lastChar = null; + while (true) { + $ch = $this->reader_->read(); + $jsonString .= $ch; + if ($ch == self::QUOTE && + $lastChar !== null && + $lastChar !== self::ESCSEQ) { + break; + } + if ($ch == self::ESCSEQ && $lastChar == self::ESCSEQ) { + $lastChar = self::DOUBLEESC; + } else { + $lastChar = $ch; + } + } + + return json_decode($jsonString); } private function isJSONNumeric($b) @@ -376,8 +382,8 @@ class TJSONProtocol extends TProtocol case '9': case 'E': case 'e': - return true; - } + return true; + } return false; } @@ -459,8 +465,10 @@ class TJSONProtocol extends TProtocol } elseif ($arr == "Infinity") { return INF; } elseif (!$this->context_->escapeNum()) { - throw new TProtocolException("Numeric data unexpectedly quoted " . $arr, - TProtocolException::INVALID_DATA); + throw new TProtocolException( + "Numeric data unexpectedly quoted " . $arr, + TProtocolException::INVALID_DATA + ); } return floatval($arr); @@ -514,9 +522,9 @@ class TJSONProtocol extends TProtocol /** * Writes the message header * - * @param string $name Function name - * @param int $type message type TMessageType::CALL or TMessageType::REPLY - * @param int $seqid The sequence id of this message + * @param string $name Function name + * @param int $type message type TMessageType::CALL or TMessageType::REPLY + * @param int $seqid The sequence id of this message */ public function writeMessageBegin($name, $type, $seqid) { @@ -538,7 +546,7 @@ class TJSONProtocol extends TProtocol /** * Writes a struct header. * - * @param string $name Struct name + * @param string $name Struct name * @throws TException on write error * @return int How many bytes written */ @@ -652,7 +660,7 @@ class TJSONProtocol extends TProtocol * Reads the message header * * @param string $name Function name - * @param int $type message type TMessageType::CALL or TMessageType::REPLY + * @param int $type message type TMessageType::CALL or TMessageType::REPLY * @parem int $seqid The sequence id of this message */ public function readMessageBegin(&$name, &$type, &$seqid) diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TMultiplexedProtocol.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TMultiplexedProtocol.php similarity index 100% rename from vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TMultiplexedProtocol.php rename to vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TMultiplexedProtocol.php diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TProtocol.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TProtocol.php new file mode 100644 index 0000000..81aceb6 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TProtocol.php @@ -0,0 +1,350 @@ +trans_ = $trans; + } + + /** + * Accessor for transport + * + * @return TTransport + */ + public function getTransport() + { + return $this->trans_; + } + + /** + * Writes the message header + * + * @param string $name Function name + * @param int $type message type TMessageType::CALL or TMessageType::REPLY + * @param int $seqid The sequence id of this message + */ + abstract public function writeMessageBegin($name, $type, $seqid); + + /** + * Close the message + */ + abstract public function writeMessageEnd(); + + /** + * Writes a struct header. + * + * @param string $name Struct name + * @throws TException on write error + * @return int How many bytes written + */ + abstract public function writeStructBegin($name); + + /** + * Close a struct. + * + * @throws TException on write error + * @return int How many bytes written + */ + abstract public function writeStructEnd(); + + /* + * Starts a field. + * + * @param string $name Field name + * @param int $type Field type + * @param int $fid Field id + * @throws TException on write error + * @return int How many bytes written + */ + abstract public function writeFieldBegin($fieldName, $fieldType, $fieldId); + + abstract public function writeFieldEnd(); + + abstract public function writeFieldStop(); + + abstract public function writeMapBegin($keyType, $valType, $size); + + abstract public function writeMapEnd(); + + abstract public function writeListBegin($elemType, $size); + + abstract public function writeListEnd(); + + abstract public function writeSetBegin($elemType, $size); + + abstract public function writeSetEnd(); + + abstract public function writeBool($bool); + + abstract public function writeByte($byte); + + abstract public function writeI16($i16); + + abstract public function writeI32($i32); + + abstract public function writeI64($i64); + + abstract public function writeDouble($dub); + + abstract public function writeString($str); + + /** + * Reads the message header + * + * @param string $name Function name + * @param int $type message type TMessageType::CALL or TMessageType::REPLY + * @parem int $seqid The sequence id of this message + */ + abstract public function readMessageBegin(&$name, &$type, &$seqid); + + /** + * Read the close of message + */ + abstract public function readMessageEnd(); + + abstract public function readStructBegin(&$name); + + abstract public function readStructEnd(); + + abstract public function readFieldBegin(&$name, &$fieldType, &$fieldId); + + abstract public function readFieldEnd(); + + abstract public function readMapBegin(&$keyType, &$valType, &$size); + + abstract public function readMapEnd(); + + abstract public function readListBegin(&$elemType, &$size); + + abstract public function readListEnd(); + + abstract public function readSetBegin(&$elemType, &$size); + + abstract public function readSetEnd(); + + abstract public function readBool(&$bool); + + abstract public function readByte(&$byte); + + abstract public function readI16(&$i16); + + abstract public function readI32(&$i32); + + abstract public function readI64(&$i64); + + abstract public function readDouble(&$dub); + + abstract public function readString(&$str); + + /** + * The skip function is a utility to parse over unrecognized date without + * causing corruption. + * + * @param TType $type What type is it + */ + public function skip($type) + { + switch ($type) { + case TType::BOOL: + return $this->readBool($bool); + case TType::BYTE: + return $this->readByte($byte); + case TType::I16: + return $this->readI16($i16); + case TType::I32: + return $this->readI32($i32); + case TType::I64: + return $this->readI64($i64); + case TType::DOUBLE: + return $this->readDouble($dub); + case TType::STRING: + return $this->readString($str); + case TType::STRUCT: + $result = $this->readStructBegin($name); + while (true) { + $result += $this->readFieldBegin($name, $ftype, $fid); + if ($ftype == TType::STOP) { + break; + } + $result += $this->skip($ftype); + $result += $this->readFieldEnd(); + } + $result += $this->readStructEnd(); + + return $result; + + case TType::MAP: + $result = $this->readMapBegin($keyType, $valType, $size); + for ($i = 0; $i < $size; $i++) { + $result += $this->skip($keyType); + $result += $this->skip($valType); + } + $result += $this->readMapEnd(); + + return $result; + + case TType::SET: + $result = $this->readSetBegin($elemType, $size); + for ($i = 0; $i < $size; $i++) { + $result += $this->skip($elemType); + } + $result += $this->readSetEnd(); + + return $result; + + case TType::LST: + $result = $this->readListBegin($elemType, $size); + for ($i = 0; $i < $size; $i++) { + $result += $this->skip($elemType); + } + $result += $this->readListEnd(); + + return $result; + + default: + throw new TProtocolException( + 'Unknown field type: ' . $type, + TProtocolException::INVALID_DATA + ); + } + } + + /** + * Utility for skipping binary data + * + * @param TTransport $itrans TTransport object + * @param int $type Field type + */ + public static function skipBinary($itrans, $type) + { + switch ($type) { + case TType::BOOL: + return $itrans->readAll(1); + case TType::BYTE: + return $itrans->readAll(1); + case TType::I16: + return $itrans->readAll(2); + case TType::I32: + return $itrans->readAll(4); + case TType::I64: + return $itrans->readAll(8); + case TType::DOUBLE: + return $itrans->readAll(8); + case TType::STRING: + $len = unpack('N', $itrans->readAll(4)); + $len = $len[1]; + if ($len > 0x7fffffff) { + $len = 0 - (($len - 1) ^ 0xffffffff); + } + + return 4 + $itrans->readAll($len); + + case TType::STRUCT: + $result = 0; + while (true) { + $ftype = 0; + $fid = 0; + $data = $itrans->readAll(1); + $arr = unpack('c', $data); + $ftype = $arr[1]; + if ($ftype == TType::STOP) { + break; + } + // I16 field id + $result += $itrans->readAll(2); + $result += self::skipBinary($itrans, $ftype); + } + + return $result; + + case TType::MAP: + // Ktype + $data = $itrans->readAll(1); + $arr = unpack('c', $data); + $ktype = $arr[1]; + // Vtype + $data = $itrans->readAll(1); + $arr = unpack('c', $data); + $vtype = $arr[1]; + // Size + $data = $itrans->readAll(4); + $arr = unpack('N', $data); + $size = $arr[1]; + if ($size > 0x7fffffff) { + $size = 0 - (($size - 1) ^ 0xffffffff); + } + $result = 6; + for ($i = 0; $i < $size; $i++) { + $result += self::skipBinary($itrans, $ktype); + $result += self::skipBinary($itrans, $vtype); + } + + return $result; + + case TType::SET: + case TType::LST: + // Vtype + $data = $itrans->readAll(1); + $arr = unpack('c', $data); + $vtype = $arr[1]; + // Size + $data = $itrans->readAll(4); + $arr = unpack('N', $data); + $size = $arr[1]; + if ($size > 0x7fffffff) { + $size = 0 - (($size - 1) ^ 0xffffffff); + } + $result = 5; + for ($i = 0; $i < $size; $i++) { + $result += self::skipBinary($itrans, $vtype); + } + + return $result; + + default: + throw new TProtocolException( + 'Unknown field type: ' . $type, + TProtocolException::INVALID_DATA + ); + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TProtocolDecorator.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TProtocolDecorator.php similarity index 99% rename from vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TProtocolDecorator.php rename to vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TProtocolDecorator.php index c08c4d5..a85e0b8 100644 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TProtocolDecorator.php +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TProtocolDecorator.php @@ -21,6 +21,7 @@ */ namespace Thrift\Protocol; + use Thrift\Exception\TException; /** diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TSimpleJSONProtocol.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TSimpleJSONProtocol.php similarity index 98% rename from vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TSimpleJSONProtocol.php rename to vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TSimpleJSONProtocol.php index 9cf90bd..1cf1f64 100644 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TSimpleJSONProtocol.php +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Protocol/TSimpleJSONProtocol.php @@ -54,7 +54,8 @@ class TSimpleJSONProtocol extends TProtocol /** * Push a new write context onto the stack. */ - protected function pushWriteContext(Context $c) { + protected function pushWriteContext(Context $c) + { $this->writeContextStack_[] = $this->writeContext_; $this->writeContext_ = $c; } @@ -62,14 +63,16 @@ class TSimpleJSONProtocol extends TProtocol /** * Pop the last write context off the stack */ - protected function popWriteContext() { + protected function popWriteContext() + { $this->writeContext_ = array_pop($this->writeContextStack_); } /** * Used to make sure that we are not encountering a map whose keys are containers */ - protected function assertContextIsNotMapKey($invalidKeyType) { + protected function assertContextIsNotMapKey($invalidKeyType) + { if ($this->writeContext_->isMapKey()) { throw new CollectionMapKeyException( "Cannot serialize a map with keys that are of type " . diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Serializer/TBinarySerializer.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Serializer/TBinarySerializer.php new file mode 100644 index 0000000..9d2b147 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Serializer/TBinarySerializer.php @@ -0,0 +1,87 @@ +getName(), + TMessageType::REPLY, + $object, + 0, + $protocol->isStrictWrite() + ); + + $protocol->readMessageBegin($unused_name, $unused_type, $unused_seqid); + } else { + $object->write($protocol); + } + $protocol->getTransport()->flush(); + + return $transport->getBuffer(); + } + + public static function deserialize($string_object, $class_name, $buffer_size = 8192) + { + $transport = new TMemoryBuffer(); + $protocol = new TBinaryProtocolAccelerated($transport); + if (function_exists('thrift_protocol_read_binary')) { + // NOTE (t.heintz) TBinaryProtocolAccelerated internally wraps our TMemoryBuffer in a + // TBufferedTransport, so we have to retrieve it again or risk losing data when writing + // less than 512 bytes to the transport (see the comment there as well). + // @see THRIFT-1579 + $protocol->writeMessageBegin('', TMessageType::REPLY, 0); + $protocolTransport = $protocol->getTransport(); + $protocolTransport->write($string_object); + $protocolTransport->flush(); + + return thrift_protocol_read_binary($protocol, $class_name, $protocol->isStrictRead(), $buffer_size); + } else { + $transport->write($string_object); + $object = new $class_name(); + $object->read($protocol); + + return $object; + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Server/TForkingServer.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Server/TForkingServer.php new file mode 100644 index 0000000..0bb6e91 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Server/TForkingServer.php @@ -0,0 +1,125 @@ +transport_->listen(); + + while (!$this->stop_) { + try { + $transport = $this->transport_->accept(); + + if ($transport != null) { + $pid = pcntl_fork(); + + if ($pid > 0) { + $this->handleParent($transport, $pid); + } elseif ($pid === 0) { + $this->handleChild($transport); + } else { + throw new TException('Failed to fork'); + } + } + } catch (TTransportException $e) { + } + + $this->collectChildren(); + } + } + + /** + * Code run by the parent + * + * @param TTransport $transport + * @param int $pid + * @return void + */ + private function handleParent(TTransport $transport, $pid) + { + $this->children_[$pid] = $transport; + } + + /** + * Code run by the child. + * + * @param TTransport $transport + * @return void + */ + private function handleChild(TTransport $transport) + { + try { + $inputTransport = $this->inputTransportFactory_->getTransport($transport); + $outputTransport = $this->outputTransportFactory_->getTransport($transport); + $inputProtocol = $this->inputProtocolFactory_->getProtocol($inputTransport); + $outputProtocol = $this->outputProtocolFactory_->getProtocol($outputTransport); + while ($this->processor_->process($inputProtocol, $outputProtocol)) { + } + @$transport->close(); + } catch (TTransportException $e) { + } + + exit(0); + } + + /** + * Collects any children we may have + * + * @return void + */ + private function collectChildren() + { + foreach ($this->children_ as $pid => $transport) { + if (pcntl_waitpid($pid, $status, WNOHANG) > 0) { + unset($this->children_[$pid]); + if ($transport) { + @$transport->close(); + } + } + } + } + + /** + * Stops the server running. Kills the transport + * and then stops the main serving loop + * + * @return void + */ + public function stop() + { + $this->transport_->close(); + $this->stop_ = true; + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Server/TSSLServerSocket.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Server/TSSLServerSocket.php new file mode 100644 index 0000000..ac589b7 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Server/TSSLServerSocket.php @@ -0,0 +1,97 @@ +getSSLHost($host); + parent::__construct($ssl_host, $port); + $this->context_ = $context; + } + + public function getSSLHost($host) + { + $transport_protocol_loc = strpos($host, "://"); + if ($transport_protocol_loc === false) { + $host = 'ssl://' . $host; + } + return $host; + } + + /** + * Opens a new socket server handle + * + * @return void + */ + public function listen() + { + $this->listener_ = @stream_socket_server( + $this->host_ . ':' . $this->port_, + $errno, + $errstr, + STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, + $this->context_ + ); + } + + /** + * Implementation of accept. If not client is accepted in the given time + * + * @return TSocket + */ + protected function acceptImpl() + { + $handle = @stream_socket_accept($this->listener_, $this->acceptTimeout_ / 1000.0); + if (!$handle) { + return null; + } + + $socket = new TSSLSocket(); + $socket->setHandle($handle); + + return $socket; + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Server/TServer.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Server/TServer.php new file mode 100644 index 0000000..268c378 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Server/TServer.php @@ -0,0 +1,102 @@ +processor_ = $processor; + $this->transport_ = $transport; + $this->inputTransportFactory_ = $inputTransportFactory; + $this->outputTransportFactory_ = $outputTransportFactory; + $this->inputProtocolFactory_ = $inputProtocolFactory; + $this->outputProtocolFactory_ = $outputProtocolFactory; + } + + /** + * Serves the server. This should never return + * unless a problem permits it to do so or it + * is interrupted intentionally + * + * @abstract + * @return void + */ + abstract public function serve(); + + /** + * Stops the server serving + * + * @abstract + * @return void + */ + abstract public function stop(); +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Server/TServerSocket.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Server/TServerSocket.php new file mode 100644 index 0000000..8f38fb2 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Server/TServerSocket.php @@ -0,0 +1,124 @@ +host_ = $host; + $this->port_ = $port; + } + + /** + * Sets the accept timeout + * + * @param int $acceptTimeout + * @return void + */ + public function setAcceptTimeout($acceptTimeout) + { + $this->acceptTimeout_ = $acceptTimeout; + } + + /** + * Opens a new socket server handle + * + * @return void + */ + public function listen() + { + $this->listener_ = stream_socket_server('tcp://' . $this->host_ . ':' . $this->port_); + } + + /** + * Closes the socket server handle + * + * @return void + */ + public function close() + { + @fclose($this->listener_); + $this->listener_ = null; + } + + /** + * Implementation of accept. If not client is accepted in the given time + * + * @return TSocket + */ + protected function acceptImpl() + { + $handle = @stream_socket_accept($this->listener_, $this->acceptTimeout_ / 1000.0); + if (!$handle) { + return null; + } + + $socket = new TSocket(); + $socket->setHandle($handle); + + return $socket; + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Server/TServerTransport.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Server/TServerTransport.php new file mode 100644 index 0000000..15a27af --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Server/TServerTransport.php @@ -0,0 +1,56 @@ +acceptImpl(); + + if ($transport == null) { + throw new TTransportException("accept() may not return NULL"); + } + + return $transport; + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Server/TSimpleServer.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Server/TSimpleServer.php new file mode 100644 index 0000000..4c1dda5 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Server/TSimpleServer.php @@ -0,0 +1,60 @@ +transport_->listen(); + + while (!$this->stop_) { + try { + $transport = $this->transport_->accept(); + + if ($transport != null) { + $inputTransport = $this->inputTransportFactory_->getTransport($transport); + $outputTransport = $this->outputTransportFactory_->getTransport($transport); + $inputProtocol = $this->inputProtocolFactory_->getProtocol($inputTransport); + $outputProtocol = $this->outputProtocolFactory_->getProtocol($outputTransport); + while ($this->processor_->process($inputProtocol, $outputProtocol)) { + } + } + } catch (TTransportException $e) { + } + } + } + + /** + * Stops the server running. Kills the transport + * and then stops the main serving loop + * + * @return void + */ + public function stop() + { + $this->transport_->close(); + $this->stop_ = true; + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/StoredMessageProtocol.php b/vendor/git.apache.org/thrift.git/lib/php/lib/StoredMessageProtocol.php new file mode 100644 index 0000000..c4aaaa9 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/StoredMessageProtocol.php @@ -0,0 +1,53 @@ +fname_ = $fname; + $this->mtype_ = $mtype; + $this->rseqid_ = $rseqid; + } + + public function readMessageBegin(&$name, &$type, &$seqid) + { + $name = $this->fname_; + $type = $this->mtype_; + $seqid = $this->rseqid_; + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/StringFunc/Core.php b/vendor/git.apache.org/thrift.git/lib/php/lib/StringFunc/Core.php similarity index 100% rename from vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/StringFunc/Core.php rename to vendor/git.apache.org/thrift.git/lib/php/lib/StringFunc/Core.php diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/StringFunc/Mbstring.php b/vendor/git.apache.org/thrift.git/lib/php/lib/StringFunc/Mbstring.php similarity index 100% rename from vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/StringFunc/Mbstring.php rename to vendor/git.apache.org/thrift.git/lib/php/lib/StringFunc/Mbstring.php diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/StringFunc/TStringFunc.php b/vendor/git.apache.org/thrift.git/lib/php/lib/StringFunc/TStringFunc.php similarity index 100% rename from vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/StringFunc/TStringFunc.php rename to vendor/git.apache.org/thrift.git/lib/php/lib/StringFunc/TStringFunc.php diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/TMultiplexedProcessor.php b/vendor/git.apache.org/thrift.git/lib/php/lib/TMultiplexedProcessor.php similarity index 84% rename from vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/TMultiplexedProcessor.php rename to vendor/git.apache.org/thrift.git/lib/php/lib/TMultiplexedProcessor.php index 138f95b..a64a968 100644 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/TMultiplexedProcessor.php +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/TMultiplexedProcessor.php @@ -25,7 +25,6 @@ namespace Thrift; use Thrift\Exception\TException; use Thrift\Protocol\TProtocol; use Thrift\Protocol\TMultiplexedProtocol; -use Thrift\Protocol\TProtocolDecorator; use Thrift\Type\TMessageType; /** @@ -112,32 +111,8 @@ class TMultiplexedProcessor $processor = $this->serviceProcessorMap_[$serviceName]; return $processor->process( - new StoredMessageProtocol($input, $messageName, $mtype, $rseqid), $output + new StoredMessageProtocol($input, $messageName, $mtype, $rseqid), + $output ); } } - -/** - * Our goal was to work with any protocol. In order to do that, we needed - * to allow them to call readMessageBegin() and get the Message in exactly - * the standard format, without the service name prepended to the Message name. - */ -class StoredMessageProtocol extends TProtocolDecorator -{ - private $fname_, $mtype_, $rseqid_; - - public function __construct(TProtocol $protocol, $fname, $mtype, $rseqid) - { - parent::__construct($protocol); - $this->fname_ = $fname; - $this->mtype_ = $mtype; - $this->rseqid_ = $rseqid; - } - - public function readMessageBegin(&$name, &$type, &$seqid) - { - $name = $this->fname_; - $type = $this->mtype_; - $seqid = $this->rseqid_; - } -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Base/TBase.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Base/TBase.php deleted file mode 100644 index 4195f75..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Base/TBase.php +++ /dev/null @@ -1,380 +0,0 @@ - 'Bool', - TType::BYTE => 'Byte', - TType::I16 => 'I16', - TType::I32 => 'I32', - TType::I64 => 'I64', - TType::DOUBLE => 'Double', - TType::STRING => 'String'); - - abstract public function read($input); - - abstract public function write($output); - - public function __construct($spec=null, $vals=null) - { - if (is_array($spec) && is_array($vals)) { - foreach ($spec as $fid => $fspec) { - $var = $fspec['var']; - if (isset($vals[$var])) { - $this->$var = $vals[$var]; - } - } - } - } - - public function __wakeup() - { - $this->__construct(get_object_vars($this)); - } - - private function _readMap(&$var, $spec, $input) - { - $xfer = 0; - $ktype = $spec['ktype']; - $vtype = $spec['vtype']; - $kread = $vread = null; - if (isset(TBase::$tmethod[$ktype])) { - $kread = 'read'.TBase::$tmethod[$ktype]; - } else { - $kspec = $spec['key']; - } - if (isset(TBase::$tmethod[$vtype])) { - $vread = 'read'.TBase::$tmethod[$vtype]; - } else { - $vspec = $spec['val']; - } - $var = array(); - $_ktype = $_vtype = $size = 0; - $xfer += $input->readMapBegin($_ktype, $_vtype, $size); - for ($i = 0; $i < $size; ++$i) { - $key = $val = null; - if ($kread !== null) { - $xfer += $input->$kread($key); - } else { - switch ($ktype) { - case TType::STRUCT: - $class = $kspec['class']; - $key = new $class(); - $xfer += $key->read($input); - break; - case TType::MAP: - $xfer += $this->_readMap($key, $kspec, $input); - break; - case TType::LST: - $xfer += $this->_readList($key, $kspec, $input, false); - break; - case TType::SET: - $xfer += $this->_readList($key, $kspec, $input, true); - break; - } - } - if ($vread !== null) { - $xfer += $input->$vread($val); - } else { - switch ($vtype) { - case TType::STRUCT: - $class = $vspec['class']; - $val = new $class(); - $xfer += $val->read($input); - break; - case TType::MAP: - $xfer += $this->_readMap($val, $vspec, $input); - break; - case TType::LST: - $xfer += $this->_readList($val, $vspec, $input, false); - break; - case TType::SET: - $xfer += $this->_readList($val, $vspec, $input, true); - break; - } - } - $var[$key] = $val; - } - $xfer += $input->readMapEnd(); - - return $xfer; - } - - private function _readList(&$var, $spec, $input, $set=false) - { - $xfer = 0; - $etype = $spec['etype']; - $eread = $vread = null; - if (isset(TBase::$tmethod[$etype])) { - $eread = 'read'.TBase::$tmethod[$etype]; - } else { - $espec = $spec['elem']; - } - $var = array(); - $_etype = $size = 0; - if ($set) { - $xfer += $input->readSetBegin($_etype, $size); - } else { - $xfer += $input->readListBegin($_etype, $size); - } - for ($i = 0; $i < $size; ++$i) { - $elem = null; - if ($eread !== null) { - $xfer += $input->$eread($elem); - } else { - $espec = $spec['elem']; - switch ($etype) { - case TType::STRUCT: - $class = $espec['class']; - $elem = new $class(); - $xfer += $elem->read($input); - break; - case TType::MAP: - $xfer += $this->_readMap($elem, $espec, $input); - break; - case TType::LST: - $xfer += $this->_readList($elem, $espec, $input, false); - break; - case TType::SET: - $xfer += $this->_readList($elem, $espec, $input, true); - break; - } - } - if ($set) { - $var[$elem] = true; - } else { - $var []= $elem; - } - } - if ($set) { - $xfer += $input->readSetEnd(); - } else { - $xfer += $input->readListEnd(); - } - - return $xfer; - } - - protected function _read($class, $spec, $input) - { - $xfer = 0; - $fname = null; - $ftype = 0; - $fid = 0; - $xfer += $input->readStructBegin($fname); - while (true) { - $xfer += $input->readFieldBegin($fname, $ftype, $fid); - if ($ftype == TType::STOP) { - break; - } - if (isset($spec[$fid])) { - $fspec = $spec[$fid]; - $var = $fspec['var']; - if ($ftype == $fspec['type']) { - $xfer = 0; - if (isset(TBase::$tmethod[$ftype])) { - $func = 'read'.TBase::$tmethod[$ftype]; - $xfer += $input->$func($this->$var); - } else { - switch ($ftype) { - case TType::STRUCT: - $class = $fspec['class']; - $this->$var = new $class(); - $xfer += $this->$var->read($input); - break; - case TType::MAP: - $xfer += $this->_readMap($this->$var, $fspec, $input); - break; - case TType::LST: - $xfer += $this->_readList($this->$var, $fspec, $input, false); - break; - case TType::SET: - $xfer += $this->_readList($this->$var, $fspec, $input, true); - break; - } - } - } else { - $xfer += $input->skip($ftype); - } - } else { - $xfer += $input->skip($ftype); - } - $xfer += $input->readFieldEnd(); - } - $xfer += $input->readStructEnd(); - - return $xfer; - } - - private function _writeMap($var, $spec, $output) - { - $xfer = 0; - $ktype = $spec['ktype']; - $vtype = $spec['vtype']; - $kwrite = $vwrite = null; - if (isset(TBase::$tmethod[$ktype])) { - $kwrite = 'write'.TBase::$tmethod[$ktype]; - } else { - $kspec = $spec['key']; - } - if (isset(TBase::$tmethod[$vtype])) { - $vwrite = 'write'.TBase::$tmethod[$vtype]; - } else { - $vspec = $spec['val']; - } - $xfer += $output->writeMapBegin($ktype, $vtype, count($var)); - foreach ($var as $key => $val) { - if (isset($kwrite)) { - $xfer += $output->$kwrite($key); - } else { - switch ($ktype) { - case TType::STRUCT: - $xfer += $key->write($output); - break; - case TType::MAP: - $xfer += $this->_writeMap($key, $kspec, $output); - break; - case TType::LST: - $xfer += $this->_writeList($key, $kspec, $output, false); - break; - case TType::SET: - $xfer += $this->_writeList($key, $kspec, $output, true); - break; - } - } - if (isset($vwrite)) { - $xfer += $output->$vwrite($val); - } else { - switch ($vtype) { - case TType::STRUCT: - $xfer += $val->write($output); - break; - case TType::MAP: - $xfer += $this->_writeMap($val, $vspec, $output); - break; - case TType::LST: - $xfer += $this->_writeList($val, $vspec, $output, false); - break; - case TType::SET: - $xfer += $this->_writeList($val, $vspec, $output, true); - break; - } - } - } - $xfer += $output->writeMapEnd(); - - return $xfer; - } - - private function _writeList($var, $spec, $output, $set=false) - { - $xfer = 0; - $etype = $spec['etype']; - $ewrite = null; - if (isset(TBase::$tmethod[$etype])) { - $ewrite = 'write'.TBase::$tmethod[$etype]; - } else { - $espec = $spec['elem']; - } - if ($set) { - $xfer += $output->writeSetBegin($etype, count($var)); - } else { - $xfer += $output->writeListBegin($etype, count($var)); - } - foreach ($var as $key => $val) { - $elem = $set ? $key : $val; - if (isset($ewrite)) { - $xfer += $output->$ewrite($elem); - } else { - switch ($etype) { - case TType::STRUCT: - $xfer += $elem->write($output); - break; - case TType::MAP: - $xfer += $this->_writeMap($elem, $espec, $output); - break; - case TType::LST: - $xfer += $this->_writeList($elem, $espec, $output, false); - break; - case TType::SET: - $xfer += $this->_writeList($elem, $espec, $output, true); - break; - } - } - } - if ($set) { - $xfer += $output->writeSetEnd(); - } else { - $xfer += $output->writeListEnd(); - } - - return $xfer; - } - - protected function _write($class, $spec, $output) - { - $xfer = 0; - $xfer += $output->writeStructBegin($class); - foreach ($spec as $fid => $fspec) { - $var = $fspec['var']; - if ($this->$var !== null) { - $ftype = $fspec['type']; - $xfer += $output->writeFieldBegin($var, $ftype, $fid); - if (isset(TBase::$tmethod[$ftype])) { - $func = 'write'.TBase::$tmethod[$ftype]; - $xfer += $output->$func($this->$var); - } else { - switch ($ftype) { - case TType::STRUCT: - $xfer += $this->$var->write($output); - break; - case TType::MAP: - $xfer += $this->_writeMap($this->$var, $fspec, $output); - break; - case TType::LST: - $xfer += $this->_writeList($this->$var, $fspec, $output, false); - break; - case TType::SET: - $xfer += $this->_writeList($this->$var, $fspec, $output, true); - break; - } - } - $xfer += $output->writeFieldEnd(); - } - } - $xfer += $output->writeFieldStop(); - $xfer += $output->writeStructEnd(); - - return $xfer; - } -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Exception/TApplicationException.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Exception/TApplicationException.php deleted file mode 100644 index b1689fc..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Exception/TApplicationException.php +++ /dev/null @@ -1,76 +0,0 @@ - array('var' => 'message', - 'type' => TType::STRING), - 2 => array('var' => 'code', - 'type' => TType::I32)); - - const UNKNOWN = 0; - const UNKNOWN_METHOD = 1; - const INVALID_MESSAGE_TYPE = 2; - const WRONG_METHOD_NAME = 3; - const BAD_SEQUENCE_ID = 4; - const MISSING_RESULT = 5; - const INTERNAL_ERROR = 6; - const PROTOCOL_ERROR = 7; - const INVALID_TRANSFORM = 8; - const INVALID_PROTOCOL = 9; - const UNSUPPORTED_CLIENT_TYPE = 10; - - public function __construct($message=null, $code=0) - { - parent::__construct($message, $code); - } - - public function read($output) - { - return $this->_read('TApplicationException', self::$_TSPEC, $output); - } - - public function write($output) - { - $xfer = 0; - $xfer += $output->writeStructBegin('TApplicationException'); - if ($message = $this->getMessage()) { - $xfer += $output->writeFieldBegin('message', TType::STRING, 1); - $xfer += $output->writeString($message); - $xfer += $output->writeFieldEnd(); - } - if ($code = $this->getCode()) { - $xfer += $output->writeFieldBegin('type', TType::I32, 2); - $xfer += $output->writeI32($code); - $xfer += $output->writeFieldEnd(); - } - $xfer += $output->writeFieldStop(); - $xfer += $output->writeStructEnd(); - - return $xfer; - } -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Exception/TException.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Exception/TException.php deleted file mode 100644 index 5c06843..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Exception/TException.php +++ /dev/null @@ -1,383 +0,0 @@ - $fspec) { - $var = $fspec['var']; - if (isset($vals[$var])) { - $this->$var = $vals[$var]; - } - } - } else { - parent::__construct($p1, $p2); - } - } - - static $tmethod = array(TType::BOOL => 'Bool', - TType::BYTE => 'Byte', - TType::I16 => 'I16', - TType::I32 => 'I32', - TType::I64 => 'I64', - TType::DOUBLE => 'Double', - TType::STRING => 'String'); - - private function _readMap(&$var, $spec, $input) - { - $xfer = 0; - $ktype = $spec['ktype']; - $vtype = $spec['vtype']; - $kread = $vread = null; - if (isset(TBase::$tmethod[$ktype])) { - $kread = 'read'.TBase::$tmethod[$ktype]; - } else { - $kspec = $spec['key']; - } - if (isset(TBase::$tmethod[$vtype])) { - $vread = 'read'.TBase::$tmethod[$vtype]; - } else { - $vspec = $spec['val']; - } - $var = array(); - $_ktype = $_vtype = $size = 0; - $xfer += $input->readMapBegin($_ktype, $_vtype, $size); - for ($i = 0; $i < $size; ++$i) { - $key = $val = null; - if ($kread !== null) { - $xfer += $input->$kread($key); - } else { - switch ($ktype) { - case TType::STRUCT: - $class = $kspec['class']; - $key = new $class(); - $xfer += $key->read($input); - break; - case TType::MAP: - $xfer += $this->_readMap($key, $kspec, $input); - break; - case TType::LST: - $xfer += $this->_readList($key, $kspec, $input, false); - break; - case TType::SET: - $xfer += $this->_readList($key, $kspec, $input, true); - break; - } - } - if ($vread !== null) { - $xfer += $input->$vread($val); - } else { - switch ($vtype) { - case TType::STRUCT: - $class = $vspec['class']; - $val = new $class(); - $xfer += $val->read($input); - break; - case TType::MAP: - $xfer += $this->_readMap($val, $vspec, $input); - break; - case TType::LST: - $xfer += $this->_readList($val, $vspec, $input, false); - break; - case TType::SET: - $xfer += $this->_readList($val, $vspec, $input, true); - break; - } - } - $var[$key] = $val; - } - $xfer += $input->readMapEnd(); - - return $xfer; - } - - private function _readList(&$var, $spec, $input, $set=false) - { - $xfer = 0; - $etype = $spec['etype']; - $eread = $vread = null; - if (isset(TBase::$tmethod[$etype])) { - $eread = 'read'.TBase::$tmethod[$etype]; - } else { - $espec = $spec['elem']; - } - $var = array(); - $_etype = $size = 0; - if ($set) { - $xfer += $input->readSetBegin($_etype, $size); - } else { - $xfer += $input->readListBegin($_etype, $size); - } - for ($i = 0; $i < $size; ++$i) { - $elem = null; - if ($eread !== null) { - $xfer += $input->$eread($elem); - } else { - $espec = $spec['elem']; - switch ($etype) { - case TType::STRUCT: - $class = $espec['class']; - $elem = new $class(); - $xfer += $elem->read($input); - break; - case TType::MAP: - $xfer += $this->_readMap($elem, $espec, $input); - break; - case TType::LST: - $xfer += $this->_readList($elem, $espec, $input, false); - break; - case TType::SET: - $xfer += $this->_readList($elem, $espec, $input, true); - break; - } - } - if ($set) { - $var[$elem] = true; - } else { - $var []= $elem; - } - } - if ($set) { - $xfer += $input->readSetEnd(); - } else { - $xfer += $input->readListEnd(); - } - - return $xfer; - } - - protected function _read($class, $spec, $input) - { - $xfer = 0; - $fname = null; - $ftype = 0; - $fid = 0; - $xfer += $input->readStructBegin($fname); - while (true) { - $xfer += $input->readFieldBegin($fname, $ftype, $fid); - if ($ftype == TType::STOP) { - break; - } - if (isset($spec[$fid])) { - $fspec = $spec[$fid]; - $var = $fspec['var']; - if ($ftype == $fspec['type']) { - $xfer = 0; - if (isset(TBase::$tmethod[$ftype])) { - $func = 'read'.TBase::$tmethod[$ftype]; - $xfer += $input->$func($this->$var); - } else { - switch ($ftype) { - case TType::STRUCT: - $class = $fspec['class']; - $this->$var = new $class(); - $xfer += $this->$var->read($input); - break; - case TType::MAP: - $xfer += $this->_readMap($this->$var, $fspec, $input); - break; - case TType::LST: - $xfer += $this->_readList($this->$var, $fspec, $input, false); - break; - case TType::SET: - $xfer += $this->_readList($this->$var, $fspec, $input, true); - break; - } - } - } else { - $xfer += $input->skip($ftype); - } - } else { - $xfer += $input->skip($ftype); - } - $xfer += $input->readFieldEnd(); - } - $xfer += $input->readStructEnd(); - - return $xfer; - } - - private function _writeMap($var, $spec, $output) - { - $xfer = 0; - $ktype = $spec['ktype']; - $vtype = $spec['vtype']; - $kwrite = $vwrite = null; - if (isset(TBase::$tmethod[$ktype])) { - $kwrite = 'write'.TBase::$tmethod[$ktype]; - } else { - $kspec = $spec['key']; - } - if (isset(TBase::$tmethod[$vtype])) { - $vwrite = 'write'.TBase::$tmethod[$vtype]; - } else { - $vspec = $spec['val']; - } - $xfer += $output->writeMapBegin($ktype, $vtype, count($var)); - foreach ($var as $key => $val) { - if (isset($kwrite)) { - $xfer += $output->$kwrite($key); - } else { - switch ($ktype) { - case TType::STRUCT: - $xfer += $key->write($output); - break; - case TType::MAP: - $xfer += $this->_writeMap($key, $kspec, $output); - break; - case TType::LST: - $xfer += $this->_writeList($key, $kspec, $output, false); - break; - case TType::SET: - $xfer += $this->_writeList($key, $kspec, $output, true); - break; - } - } - if (isset($vwrite)) { - $xfer += $output->$vwrite($val); - } else { - switch ($vtype) { - case TType::STRUCT: - $xfer += $val->write($output); - break; - case TType::MAP: - $xfer += $this->_writeMap($val, $vspec, $output); - break; - case TType::LST: - $xfer += $this->_writeList($val, $vspec, $output, false); - break; - case TType::SET: - $xfer += $this->_writeList($val, $vspec, $output, true); - break; - } - } - } - $xfer += $output->writeMapEnd(); - - return $xfer; - } - - private function _writeList($var, $spec, $output, $set=false) - { - $xfer = 0; - $etype = $spec['etype']; - $ewrite = null; - if (isset(TBase::$tmethod[$etype])) { - $ewrite = 'write'.TBase::$tmethod[$etype]; - } else { - $espec = $spec['elem']; - } - if ($set) { - $xfer += $output->writeSetBegin($etype, count($var)); - } else { - $xfer += $output->writeListBegin($etype, count($var)); - } - foreach ($var as $key => $val) { - $elem = $set ? $key : $val; - if (isset($ewrite)) { - $xfer += $output->$ewrite($elem); - } else { - switch ($etype) { - case TType::STRUCT: - $xfer += $elem->write($output); - break; - case TType::MAP: - $xfer += $this->_writeMap($elem, $espec, $output); - break; - case TType::LST: - $xfer += $this->_writeList($elem, $espec, $output, false); - break; - case TType::SET: - $xfer += $this->_writeList($elem, $espec, $output, true); - break; - } - } - } - if ($set) { - $xfer += $output->writeSetEnd(); - } else { - $xfer += $output->writeListEnd(); - } - - return $xfer; - } - - protected function _write($class, $spec, $output) - { - $xfer = 0; - $xfer += $output->writeStructBegin($class); - foreach ($spec as $fid => $fspec) { - $var = $fspec['var']; - if ($this->$var !== null) { - $ftype = $fspec['type']; - $xfer += $output->writeFieldBegin($var, $ftype, $fid); - if (isset(TBase::$tmethod[$ftype])) { - $func = 'write'.TBase::$tmethod[$ftype]; - $xfer += $output->$func($this->$var); - } else { - switch ($ftype) { - case TType::STRUCT: - $xfer += $this->$var->write($output); - break; - case TType::MAP: - $xfer += $this->_writeMap($this->$var, $fspec, $output); - break; - case TType::LST: - $xfer += $this->_writeList($this->$var, $fspec, $output, false); - break; - case TType::SET: - $xfer += $this->_writeList($this->$var, $fspec, $output, true); - break; - } - } - $xfer += $output->writeFieldEnd(); - } - } - $xfer += $output->writeFieldStop(); - $xfer += $output->writeStructEnd(); - - return $xfer; - } - -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Factory/TTransportFactory.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Factory/TTransportFactory.php deleted file mode 100644 index b32b5f4..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Factory/TTransportFactory.php +++ /dev/null @@ -1,18 +0,0 @@ -strictRead_ = $strictRead; - $this->strictWrite_ = $strictWrite; - } - - public function writeMessageBegin($name, $type, $seqid) - { - if ($this->strictWrite_) { - $version = self::VERSION_1 | $type; - - return - $this->writeI32($version) + - $this->writeString($name) + - $this->writeI32($seqid); - } else { - return - $this->writeString($name) + - $this->writeByte($type) + - $this->writeI32($seqid); - } - } - - public function writeMessageEnd() - { - return 0; - } - - public function writeStructBegin($name) - { - return 0; - } - - public function writeStructEnd() - { - return 0; - } - - public function writeFieldBegin($fieldName, $fieldType, $fieldId) - { - return - $this->writeByte($fieldType) + - $this->writeI16($fieldId); - } - - public function writeFieldEnd() - { - return 0; - } - - public function writeFieldStop() - { - return - $this->writeByte(TType::STOP); - } - - public function writeMapBegin($keyType, $valType, $size) - { - return - $this->writeByte($keyType) + - $this->writeByte($valType) + - $this->writeI32($size); - } - - public function writeMapEnd() - { - return 0; - } - - public function writeListBegin($elemType, $size) - { - return - $this->writeByte($elemType) + - $this->writeI32($size); - } - - public function writeListEnd() - { - return 0; - } - - public function writeSetBegin($elemType, $size) - { - return - $this->writeByte($elemType) + - $this->writeI32($size); - } - - public function writeSetEnd() - { - return 0; - } - - public function writeBool($value) - { - $data = pack('c', $value ? 1 : 0); - $this->trans_->write($data, 1); - - return 1; - } - - public function writeByte($value) - { - $data = pack('c', $value); - $this->trans_->write($data, 1); - - return 1; - } - - public function writeI16($value) - { - $data = pack('n', $value); - $this->trans_->write($data, 2); - - return 2; - } - - public function writeI32($value) - { - $data = pack('N', $value); - $this->trans_->write($data, 4); - - return 4; - } - - public function writeI64($value) - { - // If we are on a 32bit architecture we have to explicitly deal with - // 64-bit twos-complement arithmetic since PHP wants to treat all ints - // as signed and any int over 2^31 - 1 as a float - if (PHP_INT_SIZE == 4) { - $neg = $value < 0; - - if ($neg) { - $value *= -1; - } - - $hi = (int) ($value / 4294967296); - $lo = (int) $value; - - if ($neg) { - $hi = ~$hi; - $lo = ~$lo; - if (($lo & (int) 0xffffffff) == (int) 0xffffffff) { - $lo = 0; - $hi++; - } else { - $lo++; - } - } - $data = pack('N2', $hi, $lo); - - } else { - $hi = $value >> 32; - $lo = $value & 0xFFFFFFFF; - $data = pack('N2', $hi, $lo); - } - - $this->trans_->write($data, 8); - - return 8; - } - - public function writeDouble($value) - { - $data = pack('d', $value); - $this->trans_->write(strrev($data), 8); - - return 8; - } - - public function writeString($value) - { - $len = TStringFuncFactory::create()->strlen($value); - $result = $this->writeI32($len); - if ($len) { - $this->trans_->write($value, $len); - } - - return $result + $len; - } - - public function readMessageBegin(&$name, &$type, &$seqid) - { - $result = $this->readI32($sz); - if ($sz < 0) { - $version = (int) ($sz & self::VERSION_MASK); - if ($version != (int) self::VERSION_1) { - throw new TProtocolException('Bad version identifier: '.$sz, TProtocolException::BAD_VERSION); - } - $type = $sz & 0x000000ff; - $result += - $this->readString($name) + - $this->readI32($seqid); - } else { - if ($this->strictRead_) { - throw new TProtocolException('No version identifier, old protocol client?', TProtocolException::BAD_VERSION); - } else { - // Handle pre-versioned input - $name = $this->trans_->readAll($sz); - $result += - $sz + - $this->readByte($type) + - $this->readI32($seqid); - } - } - - return $result; - } - - public function readMessageEnd() - { - return 0; - } - - public function readStructBegin(&$name) - { - $name = ''; - - return 0; - } - - public function readStructEnd() - { - return 0; - } - - public function readFieldBegin(&$name, &$fieldType, &$fieldId) - { - $result = $this->readByte($fieldType); - if ($fieldType == TType::STOP) { - $fieldId = 0; - - return $result; - } - $result += $this->readI16($fieldId); - - return $result; - } - - public function readFieldEnd() - { - return 0; - } - - public function readMapBegin(&$keyType, &$valType, &$size) - { - return - $this->readByte($keyType) + - $this->readByte($valType) + - $this->readI32($size); - } - - public function readMapEnd() - { - return 0; - } - - public function readListBegin(&$elemType, &$size) - { - return - $this->readByte($elemType) + - $this->readI32($size); - } - - public function readListEnd() - { - return 0; - } - - public function readSetBegin(&$elemType, &$size) - { - return - $this->readByte($elemType) + - $this->readI32($size); - } - - public function readSetEnd() - { - return 0; - } - - public function readBool(&$value) - { - $data = $this->trans_->readAll(1); - $arr = unpack('c', $data); - $value = $arr[1] == 1; - - return 1; - } - - public function readByte(&$value) - { - $data = $this->trans_->readAll(1); - $arr = unpack('c', $data); - $value = $arr[1]; - - return 1; - } - - public function readI16(&$value) - { - $data = $this->trans_->readAll(2); - $arr = unpack('n', $data); - $value = $arr[1]; - if ($value > 0x7fff) { - $value = 0 - (($value - 1) ^ 0xffff); - } - - return 2; - } - - public function readI32(&$value) - { - $data = $this->trans_->readAll(4); - $arr = unpack('N', $data); - $value = $arr[1]; - if ($value > 0x7fffffff) { - $value = 0 - (($value - 1) ^ 0xffffffff); - } - - return 4; - } - - public function readI64(&$value) - { - $data = $this->trans_->readAll(8); - - $arr = unpack('N2', $data); - - // If we are on a 32bit architecture we have to explicitly deal with - // 64-bit twos-complement arithmetic since PHP wants to treat all ints - // as signed and any int over 2^31 - 1 as a float - if (PHP_INT_SIZE == 4) { - - $hi = $arr[1]; - $lo = $arr[2]; - $isNeg = $hi < 0; - - // Check for a negative - if ($isNeg) { - $hi = ~$hi & (int) 0xffffffff; - $lo = ~$lo & (int) 0xffffffff; - - if ($lo == (int) 0xffffffff) { - $hi++; - $lo = 0; - } else { - $lo++; - } - } - - // Force 32bit words in excess of 2G to pe positive - we deal wigh sign - // explicitly below - - if ($hi & (int) 0x80000000) { - $hi &= (int) 0x7fffffff; - $hi += 0x80000000; - } - - if ($lo & (int) 0x80000000) { - $lo &= (int) 0x7fffffff; - $lo += 0x80000000; - } - - $value = $hi * 4294967296 + $lo; - - if ($isNeg) { - $value = 0 - $value; - } - } else { - - // Upcast negatives in LSB bit - if ($arr[2] & 0x80000000) { - $arr[2] = $arr[2] & 0xffffffff; - } - - // Check for a negative - if ($arr[1] & 0x80000000) { - $arr[1] = $arr[1] & 0xffffffff; - $arr[1] = $arr[1] ^ 0xffffffff; - $arr[2] = $arr[2] ^ 0xffffffff; - $value = 0 - $arr[1]*4294967296 - $arr[2] - 1; - } else { - $value = $arr[1]*4294967296 + $arr[2]; - } - } - - return 8; - } - - public function readDouble(&$value) - { - $data = strrev($this->trans_->readAll(8)); - $arr = unpack('d', $data); - $value = $arr[1]; - - return 8; - } - - public function readString(&$value) - { - $result = $this->readI32($len); - if ($len) { - $value = $this->trans_->readAll($len); - } else { - $value = ''; - } - - return $result + $len; - } -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TBinaryProtocolAccelerated.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TBinaryProtocolAccelerated.php deleted file mode 100644 index f0e0bb9..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TBinaryProtocolAccelerated.php +++ /dev/null @@ -1,65 +0,0 @@ -strictRead_; - } - public function isStrictWrite() - { - return $this->strictWrite_; - } -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TCompactProtocol.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TCompactProtocol.php deleted file mode 100644 index c25b050..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TCompactProtocol.php +++ /dev/null @@ -1,739 +0,0 @@ - TCompactProtocol::COMPACT_STOP, - TType::BOOL => TCompactProtocol::COMPACT_TRUE, // used for collection - TType::BYTE => TCompactProtocol::COMPACT_BYTE, - TType::I16 => TCompactProtocol::COMPACT_I16, - TType::I32 => TCompactProtocol::COMPACT_I32, - TType::I64 => TCompactProtocol::COMPACT_I64, - TType::DOUBLE => TCompactProtocol::COMPACT_DOUBLE, - TType::STRING => TCompactProtocol::COMPACT_BINARY, - TType::STRUCT => TCompactProtocol::COMPACT_STRUCT, - TType::LST => TCompactProtocol::COMPACT_LIST, - TType::SET => TCompactProtocol::COMPACT_SET, - TType::MAP => TCompactProtocol::COMPACT_MAP, - ); - - protected static $ttypes = array( - TCompactProtocol::COMPACT_STOP => TType::STOP , - TCompactProtocol::COMPACT_TRUE => TType::BOOL, // used for collection - TCompactProtocol::COMPACT_FALSE => TType::BOOL, - TCompactProtocol::COMPACT_BYTE => TType::BYTE, - TCompactProtocol::COMPACT_I16 => TType::I16, - TCompactProtocol::COMPACT_I32 => TType::I32, - TCompactProtocol::COMPACT_I64 => TType::I64, - TCompactProtocol::COMPACT_DOUBLE => TType::DOUBLE, - TCompactProtocol::COMPACT_BINARY => TType::STRING, - TCompactProtocol::COMPACT_STRUCT => TType::STRUCT, - TCompactProtocol::COMPACT_LIST => TType::LST, - TCompactProtocol::COMPACT_SET => TType::SET, - TCompactProtocol::COMPACT_MAP => TType::MAP, - ); - - protected $state = TCompactProtocol::STATE_CLEAR; - protected $lastFid = 0; - protected $boolFid = null; - protected $boolValue = null; - protected $structs = array(); - protected $containers = array(); - - // Some varint / zigzag helper methods - public function toZigZag($n, $bits) - { - return ($n << 1) ^ ($n >> ($bits - 1)); - } - - public function fromZigZag($n) - { - return ($n >> 1) ^ -($n & 1); - } - - public function getVarint($data) - { - $out = ""; - while (true) { - if (($data & ~0x7f) === 0) { - $out .= chr($data); - break; - } else { - $out .= chr(($data & 0xff) | 0x80); - $data = $data >> 7; - } - } - - return $out; - } - - public function writeVarint($data) - { - $out = $this->getVarint($data); - $result = TStringFuncFactory::create()->strlen($out); - $this->trans_->write($out, $result); - - return $result; - } - - public function readVarint(&$result) - { - $idx = 0; - $shift = 0; - $result = 0; - while (true) { - $x = $this->trans_->readAll(1); - $arr = unpack('C', $x); - $byte = $arr[1]; - $idx += 1; - $result |= ($byte & 0x7f) << $shift; - if (($byte >> 7) === 0) { - return $idx; - } - $shift += 7; - } - - return $idx; - } - - public function __construct($trans) - { - parent::__construct($trans); - } - - public function writeMessageBegin($name, $type, $seqid) - { - $written = - $this->writeUByte(TCompactProtocol::PROTOCOL_ID) + - $this->writeUByte(TCompactProtocol::VERSION | - ($type << TCompactProtocol::TYPE_SHIFT_AMOUNT)) + - $this->writeVarint($seqid) + - $this->writeString($name); - $this->state = TCompactProtocol::STATE_VALUE_WRITE; - - return $written; - } - - public function writeMessageEnd() - { - $this->state = TCompactProtocol::STATE_CLEAR; - - return 0; - } - - public function writeStructBegin($name) - { - $this->structs[] = array($this->state, $this->lastFid); - $this->state = TCompactProtocol::STATE_FIELD_WRITE; - $this->lastFid = 0; - - return 0; - } - - public function writeStructEnd() - { - $old_values = array_pop($this->structs); - $this->state = $old_values[0]; - $this->lastFid = $old_values[1]; - - return 0; - } - - public function writeFieldStop() - { - return $this->writeByte(0); - } - - public function writeFieldHeader($type, $fid) - { - $written = 0; - $delta = $fid - $this->lastFid; - if (0 < $delta && $delta <= 15) { - $written = $this->writeUByte(($delta << 4) | $type); - } else { - $written = $this->writeByte($type) + - $this->writeI16($fid); - } - $this->lastFid = $fid; - - return $written; - } - - public function writeFieldBegin($field_name, $field_type, $field_id) - { - if ($field_type == TTYPE::BOOL) { - $this->state = TCompactProtocol::STATE_BOOL_WRITE; - $this->boolFid = $field_id; - - return 0; - } else { - $this->state = TCompactProtocol::STATE_VALUE_WRITE; - - return $this->writeFieldHeader(self::$ctypes[$field_type], $field_id); - } - } - - public function writeFieldEnd() - { - $this->state = TCompactProtocol::STATE_FIELD_WRITE; - - return 0; - } - - public function writeCollectionBegin($etype, $size) - { - $written = 0; - if ($size <= 14) { - $written = $this->writeUByte($size << 4 | - self::$ctypes[$etype]); - } else { - $written = $this->writeUByte(0xf0 | - self::$ctypes[$etype]) + - $this->writeVarint($size); - } - $this->containers[] = $this->state; - $this->state = TCompactProtocol::STATE_CONTAINER_WRITE; - - return $written; - } - - public function writeMapBegin($key_type, $val_type, $size) - { - $written = 0; - if ($size == 0) { - $written = $this->writeByte(0); - } else { - $written = $this->writeVarint($size) + - $this->writeUByte(self::$ctypes[$key_type] << 4 | - self::$ctypes[$val_type]); - } - $this->containers[] = $this->state; - - return $written; - } - - public function writeCollectionEnd() - { - $this->state = array_pop($this->containers); - - return 0; - } - - public function writeMapEnd() - { - return $this->writeCollectionEnd(); - } - - public function writeListBegin($elem_type, $size) - { - return $this->writeCollectionBegin($elem_type, $size); - } - - public function writeListEnd() - { - return $this->writeCollectionEnd(); - } - - public function writeSetBegin($elem_type, $size) - { - return $this->writeCollectionBegin($elem_type, $size); - } - - public function writeSetEnd() - { - return $this->writeCollectionEnd(); - } - - public function writeBool($value) - { - if ($this->state == TCompactProtocol::STATE_BOOL_WRITE) { - $ctype = TCompactProtocol::COMPACT_FALSE; - if ($value) { - $ctype = TCompactProtocol::COMPACT_TRUE; - } - - return $this->writeFieldHeader($ctype, $this->boolFid); - } elseif ($this->state == TCompactProtocol::STATE_CONTAINER_WRITE) { - return $this->writeByte($value ? 1 : 0); - } else { - throw new TProtocolException('Invalid state in compact protocol'); - } - } - - public function writeByte($value) - { - $data = pack('c', $value); - $this->trans_->write($data, 1); - - return 1; - } - - public function writeUByte($byte) - { - $this->trans_->write(pack('C', $byte), 1); - - return 1; - } - - public function writeI16($value) - { - $thing = $this->toZigZag($value, 16); - - return $this->writeVarint($thing); - } - - public function writeI32($value) - { - $thing = $this->toZigZag($value, 32); - - return $this->writeVarint($thing); - } - - public function writeDouble($value) - { - $data = pack('d', $value); - $this->trans_->write($data, 8); - - return 8; - } - - public function writeString($value) - { - $len = TStringFuncFactory::create()->strlen($value); - $result = $this->writeVarint($len); - if ($len) { - $this->trans_->write($value, $len); - } - - return $result + $len; - } - - public function readFieldBegin(&$name, &$field_type, &$field_id) - { - $result = $this->readUByte($compact_type_and_delta); - - $compact_type = $compact_type_and_delta & 0x0f; - - if ($compact_type == TType::STOP) { - $field_type = $compact_type; - $field_id = 0; - - return $result; - } - $delta = $compact_type_and_delta >> 4; - if ($delta == 0) { - $result += $this->readI16($field_id); - } else { - $field_id = $this->lastFid + $delta; - } - $this->lastFid = $field_id; - $field_type = $this->getTType($compact_type); - - if ($compact_type == TCompactProtocol::COMPACT_TRUE) { - $this->state = TCompactProtocol::STATE_BOOL_READ; - $this->boolValue = true; - } elseif ($compact_type == TCompactProtocol::COMPACT_FALSE) { - $this->state = TCompactProtocol::STATE_BOOL_READ; - $this->boolValue = false; - } else { - $this->state = TCompactProtocol::STATE_VALUE_READ; - } - - return $result; - } - - public function readFieldEnd() - { - $this->state = TCompactProtocol::STATE_FIELD_READ; - - return 0; - } - - public function readUByte(&$value) - { - $data = $this->trans_->readAll(1); - $arr = unpack('C', $data); - $value = $arr[1]; - - return 1; - } - - public function readByte(&$value) - { - $data = $this->trans_->readAll(1); - $arr = unpack('c', $data); - $value = $arr[1]; - - return 1; - } - - public function readZigZag(&$value) - { - $result = $this->readVarint($value); - $value = $this->fromZigZag($value); - - return $result; - } - - public function readMessageBegin(&$name, &$type, &$seqid) - { - $protoId = 0; - $result = $this->readUByte($protoId); - if ($protoId != TCompactProtocol::PROTOCOL_ID) { - throw new TProtocolException('Bad protocol id in TCompact message'); - } - $verType = 0; - $result += $this->readUByte($verType); - $type = ($verType >> TCompactProtocol::TYPE_SHIFT_AMOUNT) & TCompactProtocol::TYPE_BITS; - $version = $verType & TCompactProtocol::VERSION_MASK; - if ($version != TCompactProtocol::VERSION) { - throw new TProtocolException('Bad version in TCompact message'); - } - $result += $this->readVarint($seqid); - $result += $this->readString($name); - - return $result; - } - - public function readMessageEnd() - { - return 0; - } - - public function readStructBegin(&$name) - { - $name = ''; // unused - $this->structs[] = array($this->state, $this->lastFid); - $this->state = TCompactProtocol::STATE_FIELD_READ; - $this->lastFid = 0; - - return 0; - } - - public function readStructEnd() - { - $last = array_pop($this->structs); - $this->state = $last[0]; - $this->lastFid = $last[1]; - - return 0; - } - - public function readCollectionBegin(&$type, &$size) - { - $sizeType = 0; - $result = $this->readUByte($sizeType); - $size = $sizeType >> 4; - $type = $this->getTType($sizeType); - if ($size == 15) { - $result += $this->readVarint($size); - } - $this->containers[] = $this->state; - $this->state = TCompactProtocol::STATE_CONTAINER_READ; - - return $result; - } - - public function readMapBegin(&$key_type, &$val_type, &$size) - { - $result = $this->readVarint($size); - $types = 0; - if ($size > 0) { - $result += $this->readUByte($types); - } - $val_type = $this->getTType($types); - $key_type = $this->getTType($types >> 4); - $this->containers[] = $this->state; - $this->state = TCompactProtocol::STATE_CONTAINER_READ; - - return $result; - } - - public function readCollectionEnd() - { - $this->state = array_pop($this->containers); - - return 0; - } - - public function readMapEnd() - { - return $this->readCollectionEnd(); - } - - public function readListBegin(&$elem_type, &$size) - { - return $this->readCollectionBegin($elem_type, $size); - } - - public function readListEnd() - { - return $this->readCollectionEnd(); - } - - public function readSetBegin(&$elem_type, &$size) - { - return $this->readCollectionBegin($elem_type, $size); - } - - public function readSetEnd() - { - return $this->readCollectionEnd(); - } - - public function readBool(&$value) - { - if ($this->state == TCompactProtocol::STATE_BOOL_READ) { - $value = $this->boolValue; - - return 0; - } elseif ($this->state == TCompactProtocol::STATE_CONTAINER_READ) { - return $this->readByte($value); - } else { - throw new TProtocolException('Invalid state in compact protocol'); - } - } - - public function readI16(&$value) - { - return $this->readZigZag($value); - } - - public function readI32(&$value) - { - return $this->readZigZag($value); - } - - public function readDouble(&$value) - { - $data = $this->trans_->readAll(8); - $arr = unpack('d', $data); - $value = $arr[1]; - - return 8; - } - - public function readString(&$value) - { - $result = $this->readVarint($len); - if ($len) { - $value = $this->trans_->readAll($len); - } else { - $value = ''; - } - - return $result + $len; - } - - public function getTType($byte) - { - return self::$ttypes[$byte & 0x0f]; - } - - // If we are on a 32bit architecture we have to explicitly deal with - // 64-bit twos-complement arithmetic since PHP wants to treat all ints - // as signed and any int over 2^31 - 1 as a float - - // Read and write I64 as two 32 bit numbers $hi and $lo - - public function readI64(&$value) - { - // Read varint from wire - $hi = 0; - $lo = 0; - - $idx = 0; - $shift = 0; - - while (true) { - $x = $this->trans_->readAll(1); - $arr = unpack('C', $x); - $byte = $arr[1]; - $idx += 1; - // Shift hi and lo together. - if ($shift < 28) { - $lo |= (($byte & 0x7f) << $shift); - } elseif ($shift == 28) { - $lo |= (($byte & 0x0f) << 28); - $hi |= (($byte & 0x70) >> 4); - } else { - $hi |= (($byte & 0x7f) << ($shift - 32)); - } - if (($byte >> 7) === 0) { - break; - } - $shift += 7; - } - - // Now, unzig it. - $xorer = 0; - if ($lo & 1) { - $xorer = 0xffffffff; - } - $lo = ($lo >> 1) & 0x7fffffff; - $lo = $lo | (($hi & 1) << 31); - $hi = ($hi >> 1) ^ $xorer; - $lo = $lo ^ $xorer; - - // Now put $hi and $lo back together - $isNeg = $hi < 0 || $hi & 0x80000000; - - // Check for a negative - if ($isNeg) { - $hi = ~$hi & (int) 0xffffffff; - $lo = ~$lo & (int) 0xffffffff; - - if ($lo == (int) 0xffffffff) { - $hi++; - $lo = 0; - } else { - $lo++; - } - } - - // Force 32bit words in excess of 2G to be positive - we deal with sign - // explicitly below - - if ($hi & (int) 0x80000000) { - $hi &= (int) 0x7fffffff; - $hi += 0x80000000; - } - - if ($lo & (int) 0x80000000) { - $lo &= (int) 0x7fffffff; - $lo += 0x80000000; - } - - // Create as negative value first, since we can store -2^63 but not 2^63 - $value = -$hi * 4294967296 - $lo; - - if (!$isNeg) { - $value = -$value; - } - - return $idx; - } - - public function writeI64($value) - { - // If we are in an I32 range, use the easy method below. - if (($value > 4294967296) || ($value < -4294967296)) { - // Convert $value to $hi and $lo - $neg = $value < 0; - - if ($neg) { - $value *= -1; - } - - $hi = (int) $value >> 32; - $lo = (int) $value & 0xffffffff; - - if ($neg) { - $hi = ~$hi; - $lo = ~$lo; - if (($lo & (int) 0xffffffff) == (int) 0xffffffff) { - $lo = 0; - $hi++; - } else { - $lo++; - } - } - - // Now do the zigging and zagging. - $xorer = 0; - if ($neg) { - $xorer = 0xffffffff; - } - $lowbit = ($lo >> 31) & 1; - $hi = ($hi << 1) | $lowbit; - $lo = ($lo << 1); - $lo = ($lo ^ $xorer) & 0xffffffff; - $hi = ($hi ^ $xorer) & 0xffffffff; - - // now write out the varint, ensuring we shift both hi and lo - $out = ""; - while (true) { - if (($lo & ~0x7f) === 0 && - $hi === 0) { - $out .= chr($lo); - break; - } else { - $out .= chr(($lo & 0xff) | 0x80); - $lo = $lo >> 7; - $lo = $lo | ($hi << 25); - $hi = $hi >> 7; - // Right shift carries sign, but we don't want it to. - $hi = $hi & (127 << 25); - } - } - - $ret = TStringFuncFactory::create()->strlen($out); - $this->trans_->write($out, $ret); - - return $ret; - } else { - return $this->writeVarint($this->toZigZag($value, 64)); - } - } -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TProtocol.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TProtocol.php deleted file mode 100644 index 0e3bc0d..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Protocol/TProtocol.php +++ /dev/null @@ -1,352 +0,0 @@ -trans_ = $trans; - } - - /** - * Accessor for transport - * - * @return TTransport - */ - public function getTransport() - { - return $this->trans_; - } - - /** - * Writes the message header - * - * @param string $name Function name - * @param int $type message type TMessageType::CALL or TMessageType::REPLY - * @param int $seqid The sequence id of this message - */ - abstract public function writeMessageBegin($name, $type, $seqid); - - /** - * Close the message - */ - abstract public function writeMessageEnd(); - - /** - * Writes a struct header. - * - * @param string $name Struct name - * @throws TException on write error - * @return int How many bytes written - */ - abstract public function writeStructBegin($name); - - /** - * Close a struct. - * - * @throws TException on write error - * @return int How many bytes written - */ - abstract public function writeStructEnd(); - - /* - * Starts a field. - * - * @param string $name Field name - * @param int $type Field type - * @param int $fid Field id - * @throws TException on write error - * @return int How many bytes written - */ - abstract public function writeFieldBegin($fieldName, $fieldType, $fieldId); - - abstract public function writeFieldEnd(); - - abstract public function writeFieldStop(); - - abstract public function writeMapBegin($keyType, $valType, $size); - - abstract public function writeMapEnd(); - - abstract public function writeListBegin($elemType, $size); - - abstract public function writeListEnd(); - - abstract public function writeSetBegin($elemType, $size); - - abstract public function writeSetEnd(); - - abstract public function writeBool($bool); - - abstract public function writeByte($byte); - - abstract public function writeI16($i16); - - abstract public function writeI32($i32); - - abstract public function writeI64($i64); - - abstract public function writeDouble($dub); - - abstract public function writeString($str); - - /** - * Reads the message header - * - * @param string $name Function name - * @param int $type message type TMessageType::CALL or TMessageType::REPLY - * @parem int $seqid The sequence id of this message - */ - abstract public function readMessageBegin(&$name, &$type, &$seqid); - - /** - * Read the close of message - */ - abstract public function readMessageEnd(); - - abstract public function readStructBegin(&$name); - - abstract public function readStructEnd(); - - abstract public function readFieldBegin(&$name, &$fieldType, &$fieldId); - - abstract public function readFieldEnd(); - - abstract public function readMapBegin(&$keyType, &$valType, &$size); - - abstract public function readMapEnd(); - - abstract public function readListBegin(&$elemType, &$size); - - abstract public function readListEnd(); - - abstract public function readSetBegin(&$elemType, &$size); - - abstract public function readSetEnd(); - - abstract public function readBool(&$bool); - - abstract public function readByte(&$byte); - - abstract public function readI16(&$i16); - - abstract public function readI32(&$i32); - - abstract public function readI64(&$i64); - - abstract public function readDouble(&$dub); - - abstract public function readString(&$str); - - /** - * The skip function is a utility to parse over unrecognized date without - * causing corruption. - * - * @param TType $type What type is it - */ - public function skip($type) - { - switch ($type) { - case TType::BOOL: - return $this->readBool($bool); - case TType::BYTE: - return $this->readByte($byte); - case TType::I16: - return $this->readI16($i16); - case TType::I32: - return $this->readI32($i32); - case TType::I64: - return $this->readI64($i64); - case TType::DOUBLE: - return $this->readDouble($dub); - case TType::STRING: - return $this->readString($str); - case TType::STRUCT: - { - $result = $this->readStructBegin($name); - while (true) { - $result += $this->readFieldBegin($name, $ftype, $fid); - if ($ftype == TType::STOP) { - break; - } - $result += $this->skip($ftype); - $result += $this->readFieldEnd(); - } - $result += $this->readStructEnd(); - - return $result; - } - case TType::MAP: - { - $result = $this->readMapBegin($keyType, $valType, $size); - for ($i = 0; $i < $size; $i++) { - $result += $this->skip($keyType); - $result += $this->skip($valType); - } - $result += $this->readMapEnd(); - - return $result; - } - case TType::SET: - { - $result = $this->readSetBegin($elemType, $size); - for ($i = 0; $i < $size; $i++) { - $result += $this->skip($elemType); - } - $result += $this->readSetEnd(); - - return $result; - } - case TType::LST: - { - $result = $this->readListBegin($elemType, $size); - for ($i = 0; $i < $size; $i++) { - $result += $this->skip($elemType); - } - $result += $this->readListEnd(); - - return $result; - } - default: - throw new TProtocolException('Unknown field type: '.$type, - TProtocolException::INVALID_DATA); - } - } - - /** - * Utility for skipping binary data - * - * @param TTransport $itrans TTransport object - * @param int $type Field type - */ - public static function skipBinary($itrans, $type) - { - switch ($type) { - case TType::BOOL: - return $itrans->readAll(1); - case TType::BYTE: - return $itrans->readAll(1); - case TType::I16: - return $itrans->readAll(2); - case TType::I32: - return $itrans->readAll(4); - case TType::I64: - return $itrans->readAll(8); - case TType::DOUBLE: - return $itrans->readAll(8); - case TType::STRING: - $len = unpack('N', $itrans->readAll(4)); - $len = $len[1]; - if ($len > 0x7fffffff) { - $len = 0 - (($len - 1) ^ 0xffffffff); - } - - return 4 + $itrans->readAll($len); - case TType::STRUCT: - { - $result = 0; - while (true) { - $ftype = 0; - $fid = 0; - $data = $itrans->readAll(1); - $arr = unpack('c', $data); - $ftype = $arr[1]; - if ($ftype == TType::STOP) { - break; - } - // I16 field id - $result += $itrans->readAll(2); - $result += self::skipBinary($itrans, $ftype); - } - - return $result; - } - case TType::MAP: - { - // Ktype - $data = $itrans->readAll(1); - $arr = unpack('c', $data); - $ktype = $arr[1]; - // Vtype - $data = $itrans->readAll(1); - $arr = unpack('c', $data); - $vtype = $arr[1]; - // Size - $data = $itrans->readAll(4); - $arr = unpack('N', $data); - $size = $arr[1]; - if ($size > 0x7fffffff) { - $size = 0 - (($size - 1) ^ 0xffffffff); - } - $result = 6; - for ($i = 0; $i < $size; $i++) { - $result += self::skipBinary($itrans, $ktype); - $result += self::skipBinary($itrans, $vtype); - } - - return $result; - } - case TType::SET: - case TType::LST: - { - // Vtype - $data = $itrans->readAll(1); - $arr = unpack('c', $data); - $vtype = $arr[1]; - // Size - $data = $itrans->readAll(4); - $arr = unpack('N', $data); - $size = $arr[1]; - if ($size > 0x7fffffff) { - $size = 0 - (($size - 1) ^ 0xffffffff); - } - $result = 5; - for ($i = 0; $i < $size; $i++) { - $result += self::skipBinary($itrans, $vtype); - } - - return $result; - } - default: - throw new TProtocolException('Unknown field type: '.$type, - TProtocolException::INVALID_DATA); - } - } -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Serializer/TBinarySerializer.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Serializer/TBinarySerializer.php deleted file mode 100644 index aa2f71b..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Serializer/TBinarySerializer.php +++ /dev/null @@ -1,85 +0,0 @@ -getName(), - TMessageType::REPLY, $object, - 0, $protocol->isStrictWrite()); - - $protocol->readMessageBegin($unused_name, $unused_type, - $unused_seqid); - } else { - $object->write($protocol); - } - $protocol->getTransport()->flush(); - - return $transport->getBuffer(); - } - - public static function deserialize($string_object, $class_name, $buffer_size = 8192) - { - $transport = new TMemoryBuffer(); - $protocol = new TBinaryProtocolAccelerated($transport); - if (function_exists('thrift_protocol_read_binary')) { - // NOTE (t.heintz) TBinaryProtocolAccelerated internally wraps our TMemoryBuffer in a - // TBufferedTransport, so we have to retrieve it again or risk losing data when writing - // less than 512 bytes to the transport (see the comment there as well). - // @see THRIFT-1579 - $protocol->writeMessageBegin('', TMessageType::REPLY, 0); - $protocolTransport = $protocol->getTransport(); - $protocolTransport->write($string_object); - $protocolTransport->flush(); - - return thrift_protocol_read_binary($protocol, $class_name, - $protocol->isStrictRead(), - $buffer_size); - } else { - $transport->write($string_object); - $object = new $class_name(); - $object->read($protocol); - - return $object; - } - } -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TForkingServer.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TForkingServer.php deleted file mode 100644 index 7f6e541..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TForkingServer.php +++ /dev/null @@ -1,120 +0,0 @@ -transport_->listen(); - - while (!$this->stop_) { - try { - $transport = $this->transport_->accept(); - - if ($transport != null) { - $pid = pcntl_fork(); - - if ($pid > 0) { - $this->handleParent($transport, $pid); - } elseif ($pid === 0) { - $this->handleChild($transport); - } else { - throw new TException('Failed to fork'); - } - } - } catch (TTransportException $e) { } - - $this->collectChildren(); - } - } - - /** - * Code run by the parent - * - * @param TTransport $transport - * @param int $pid - * @return void - */ - private function handleParent(TTransport $transport, $pid) - { - $this->children_[$pid] = $transport; - } - - /** - * Code run by the child. - * - * @param TTransport $transport - * @return void - */ - private function handleChild(TTransport $transport) - { - try { - $inputTransport = $this->inputTransportFactory_->getTransport($transport); - $outputTransport = $this->outputTransportFactory_->getTransport($transport); - $inputProtocol = $this->inputProtocolFactory_->getProtocol($inputTransport); - $outputProtocol = $this->outputProtocolFactory_->getProtocol($outputTransport); - while ($this->processor_->process($inputProtocol, $outputProtocol)) { } - @$transport->close(); - } catch (TTransportException $e) { } - - exit(0); - } - - /** - * Collects any children we may have - * - * @return void - */ - private function collectChildren() - { - foreach ($this->children_ as $pid => $transport) { - if (pcntl_waitpid($pid, $status, WNOHANG) > 0) { - unset($this->children_[$pid]); - if ($transport) @$transport->close(); - } - } - } - - /** - * Stops the server running. Kills the transport - * and then stops the main serving loop - * - * @return void - */ - public function stop() - { - $this->transport_->close(); - $this->stop_ = true; - } -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TSSLServerSocket.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TSSLServerSocket.php deleted file mode 100644 index dfc4704..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TSSLServerSocket.php +++ /dev/null @@ -1,94 +0,0 @@ -getSSLHost($host); - parent::__construct($ssl_host, $port); - $this->context_ = $context; - } - - public function getSSLHost($host) - { - $transport_protocol_loc = strpos($host, "://"); - if ($transport_protocol_loc === false) { - $host = 'ssl://'.$host; - } - return $host; - } - - /** - * Opens a new socket server handle - * - * @return void - */ - public function listen() - { - $this->listener_ = @stream_socket_server( - $this->host_ . ':' . $this->port_, - $errno, - $errstr, - STREAM_SERVER_BIND|STREAM_SERVER_LISTEN, - $this->context_); - } - - /** - * Implementation of accept. If not client is accepted in the given time - * - * @return TSocket - */ - protected function acceptImpl() - { - $handle = @stream_socket_accept($this->listener_, $this->acceptTimeout_ / 1000.0); - if(!$handle) return null; - - $socket = new TSSLSocket(); - $socket->setHandle($handle); - - return $socket; - } -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TServer.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TServer.php deleted file mode 100644 index f4d76cc..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TServer.php +++ /dev/null @@ -1,100 +0,0 @@ -processor_ = $processor; - $this->transport_ = $transport; - $this->inputTransportFactory_ = $inputTransportFactory; - $this->outputTransportFactory_ = $outputTransportFactory; - $this->inputProtocolFactory_ = $inputProtocolFactory; - $this->outputProtocolFactory_ = $outputProtocolFactory; - } - - /** - * Serves the server. This should never return - * unless a problem permits it to do so or it - * is interrupted intentionally - * - * @abstract - * @return void - */ - abstract public function serve(); - - /** - * Stops the server serving - * - * @abstract - * @return void - */ - abstract public function stop(); -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TServerSocket.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TServerSocket.php deleted file mode 100644 index da8e226..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TServerSocket.php +++ /dev/null @@ -1,122 +0,0 @@ -host_ = $host; - $this->port_ = $port; - } - - /** - * Sets the accept timeout - * - * @param int $acceptTimeout - * @return void - */ - public function setAcceptTimeout($acceptTimeout) - { - $this->acceptTimeout_ = $acceptTimeout; - } - - /** - * Opens a new socket server handle - * - * @return void - */ - public function listen() - { - $this->listener_ = stream_socket_server('tcp://' . $this->host_ . ':' . $this->port_); - } - - /** - * Closes the socket server handle - * - * @return void - */ - public function close() - { - @fclose($this->listener_); - $this->listener_ = null; - } - - /** - * Implementation of accept. If not client is accepted in the given time - * - * @return TSocket - */ - protected function acceptImpl() - { - $handle = @stream_socket_accept($this->listener_, $this->acceptTimeout_ / 1000.0); - if(!$handle) return null; - - $socket = new TSocket(); - $socket->setHandle($handle); - - return $socket; - } -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TServerTransport.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TServerTransport.php deleted file mode 100644 index f82d06d..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TServerTransport.php +++ /dev/null @@ -1,56 +0,0 @@ -acceptImpl(); - - if ($transport == null) { - throw new TTransportException("accept() may not return NULL"); - } - - return $transport; - } -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TSimpleServer.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TSimpleServer.php deleted file mode 100644 index e277700..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Server/TSimpleServer.php +++ /dev/null @@ -1,58 +0,0 @@ -transport_->listen(); - - while (!$this->stop_) { - try { - $transport = $this->transport_->accept(); - - if ($transport != null) { - $inputTransport = $this->inputTransportFactory_->getTransport($transport); - $outputTransport = $this->outputTransportFactory_->getTransport($transport); - $inputProtocol = $this->inputProtocolFactory_->getProtocol($inputTransport); - $outputProtocol = $this->outputProtocolFactory_->getProtocol($outputTransport); - while ($this->processor_->process($inputProtocol, $outputProtocol)) { } - } - } catch (TTransportException $e) { } - } - } - - /** - * Stops the server running. Kills the transport - * and then stops the main serving loop - * - * @return void - */ - public function stop() - { - $this->transport_->close(); - $this->stop_ = true; - } -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TBufferedTransport.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TBufferedTransport.php deleted file mode 100644 index f654ad3..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TBufferedTransport.php +++ /dev/null @@ -1,181 +0,0 @@ -transport_ = $transport; - $this->rBufSize_ = $rBufSize; - $this->wBufSize_ = $wBufSize; - } - - /** - * The underlying transport - * - * @var TTransport - */ - protected $transport_ = null; - - /** - * The receive buffer size - * - * @var int - */ - protected $rBufSize_ = 512; - - /** - * The write buffer size - * - * @var int - */ - protected $wBufSize_ = 512; - - /** - * The write buffer. - * - * @var string - */ - protected $wBuf_ = ''; - - /** - * The read buffer. - * - * @var string - */ - protected $rBuf_ = ''; - - public function isOpen() - { - return $this->transport_->isOpen(); - } - - public function open() - { - $this->transport_->open(); - } - - public function close() - { - $this->transport_->close(); - } - - public function putBack($data) - { - if (TStringFuncFactory::create()->strlen($this->rBuf_) === 0) { - $this->rBuf_ = $data; - } else { - $this->rBuf_ = ($data . $this->rBuf_); - } - } - - /** - * The reason that we customize readAll here is that the majority of PHP - * streams are already internally buffered by PHP. The socket stream, for - * example, buffers internally and blocks if you call read with $len greater - * than the amount of data available, unlike recv() in C. - * - * Therefore, use the readAll method of the wrapped transport inside - * the buffered readAll. - */ - public function readAll($len) - { - $have = TStringFuncFactory::create()->strlen($this->rBuf_); - if ($have == 0) { - $data = $this->transport_->readAll($len); - } elseif ($have < $len) { - $data = $this->rBuf_; - $this->rBuf_ = ''; - $data .= $this->transport_->readAll($len - $have); - } elseif ($have == $len) { - $data = $this->rBuf_; - $this->rBuf_ = ''; - } elseif ($have > $len) { - $data = TStringFuncFactory::create()->substr($this->rBuf_, 0, $len); - $this->rBuf_ = TStringFuncFactory::create()->substr($this->rBuf_, $len); - } - - return $data; - } - - public function read($len) - { - if (TStringFuncFactory::create()->strlen($this->rBuf_) === 0) { - $this->rBuf_ = $this->transport_->read($this->rBufSize_); - } - - if (TStringFuncFactory::create()->strlen($this->rBuf_) <= $len) { - $ret = $this->rBuf_; - $this->rBuf_ = ''; - - return $ret; - } - - $ret = TStringFuncFactory::create()->substr($this->rBuf_, 0, $len); - $this->rBuf_ = TStringFuncFactory::create()->substr($this->rBuf_, $len); - - return $ret; - } - - public function write($buf) - { - $this->wBuf_ .= $buf; - if (TStringFuncFactory::create()->strlen($this->wBuf_) >= $this->wBufSize_) { - $out = $this->wBuf_; - - // Note that we clear the internal wBuf_ prior to the underlying write - // to ensure we're in a sane state (i.e. internal buffer cleaned) - // if the underlying write throws up an exception - $this->wBuf_ = ''; - $this->transport_->write($out); - } - } - - public function flush() - { - if (TStringFuncFactory::create()->strlen($this->wBuf_) > 0) { - $out = $this->wBuf_; - - // Note that we clear the internal wBuf_ prior to the underlying write - // to ensure we're in a sane state (i.e. internal buffer cleaned) - // if the underlying write throws up an exception - $this->wBuf_ = ''; - $this->transport_->write($out); - } - $this->transport_->flush(); - } - -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TCurlClient.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TCurlClient.php deleted file mode 100644 index 4b3e694..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TCurlClient.php +++ /dev/null @@ -1,231 +0,0 @@ -strlen($uri) > 0) && ($uri{0} != '/')) { - $uri = '/'.$uri; - } - $this->scheme_ = $scheme; - $this->host_ = $host; - $this->port_ = $port; - $this->uri_ = $uri; - $this->request_ = ''; - $this->response_ = null; - $this->timeout_ = null; - } - - /** - * Set read timeout - * - * @param float $timeout - */ - public function setTimeoutSecs($timeout) - { - $this->timeout_ = $timeout; - } - - /** - * Whether this transport is open. - * - * @return boolean true if open - */ - public function isOpen() - { - return true; - } - - /** - * Open the transport for reading/writing - * - * @throws TTransportException if cannot open - */ - public function open() - { - } - - /** - * Close the transport. - */ - public function close() - { - $this->request_ = ''; - $this->response_ = null; - } - - /** - * Read some data into the array. - * - * @param int $len How much to read - * @return string The data that has been read - * @throws TTransportException if cannot read any more data - */ - public function read($len) - { - if ($len >= strlen($this->response_)) { - return $this->response_; - } else { - $ret = substr($this->response_, 0, $len); - $this->response_ = substr($this->response_, $len); - - return $ret; - } - } - - /** - * Writes some data into the pending buffer - * - * @param string $buf The data to write - * @throws TTransportException if writing fails - */ - public function write($buf) - { - $this->request_ .= $buf; - } - - /** - * Opens and sends the actual request over the HTTP connection - * - * @throws TTransportException if a writing error occurs - */ - public function flush() - { - if (!self::$curlHandle) { - register_shutdown_function(array('Thrift\\Transport\\TCurlClient', 'closeCurlHandle')); - self::$curlHandle = curl_init(); - curl_setopt(self::$curlHandle, CURLOPT_RETURNTRANSFER, true); - curl_setopt(self::$curlHandle, CURLOPT_BINARYTRANSFER, true); - curl_setopt(self::$curlHandle, CURLOPT_USERAGENT, 'PHP/TCurlClient'); - curl_setopt(self::$curlHandle, CURLOPT_CUSTOMREQUEST, 'POST'); - curl_setopt(self::$curlHandle, CURLOPT_FOLLOWLOCATION, true); - curl_setopt(self::$curlHandle, CURLOPT_MAXREDIRS, 1); - } - // God, PHP really has some esoteric ways of doing simple things. - $host = $this->host_.($this->port_ != 80 ? ':'.$this->port_ : ''); - $fullUrl = $this->scheme_."://".$host.$this->uri_; - - $headers = array('Accept: application/x-thrift', - 'Content-Type: application/x-thrift', - 'Content-Length: '.TStringFuncFactory::create()->strlen($this->request_)); - curl_setopt(self::$curlHandle, CURLOPT_HTTPHEADER, $headers); - - if ($this->timeout_ > 0) { - curl_setopt(self::$curlHandle, CURLOPT_TIMEOUT, $this->timeout_); - } - curl_setopt(self::$curlHandle, CURLOPT_POSTFIELDS, $this->request_); - $this->request_ = ''; - - curl_setopt(self::$curlHandle, CURLOPT_URL, $fullUrl); - $this->response_ = curl_exec(self::$curlHandle); - - // Connect failed? - if (!$this->response_) { - curl_close(self::$curlHandle); - self::$curlHandle = null; - $error = 'TCurlClient: Could not connect to '.$fullUrl; - throw new TTransportException($error, TTransportException::NOT_OPEN); - } - } - - public static function closeCurlHandle() - { - try { - if (self::$curlHandle) { - curl_close(self::$curlHandle); - self::$curlHandle = null; - } - } catch (\Exception $x) { - error_log('There was an error closing the curl handle: ' . $x->getMessage()); - } - } - -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TFramedTransport.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TFramedTransport.php deleted file mode 100644 index b8a64a9..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TFramedTransport.php +++ /dev/null @@ -1,193 +0,0 @@ -transport_ = $transport; - $this->read_ = $read; - $this->write_ = $write; - } - - public function isOpen() - { - return $this->transport_->isOpen(); - } - - public function open() - { - $this->transport_->open(); - } - - public function close() - { - $this->transport_->close(); - } - - /** - * Reads from the buffer. When more data is required reads another entire - * chunk and serves future reads out of that. - * - * @param int $len How much data - */ - public function read($len) - { - if (!$this->read_) { - return $this->transport_->read($len); - } - - if (TStringFuncFactory::create()->strlen($this->rBuf_) === 0) { - $this->readFrame(); - } - - // Just return full buff - if ($len >= TStringFuncFactory::create()->strlen($this->rBuf_)) { - $out = $this->rBuf_; - $this->rBuf_ = null; - - return $out; - } - - // Return TStringFuncFactory::create()->substr - $out = TStringFuncFactory::create()->substr($this->rBuf_, 0, $len); - $this->rBuf_ = TStringFuncFactory::create()->substr($this->rBuf_, $len); - - return $out; - } - - /** - * Put previously read data back into the buffer - * - * @param string $data data to return - */ - public function putBack($data) - { - if (TStringFuncFactory::create()->strlen($this->rBuf_) === 0) { - $this->rBuf_ = $data; - } else { - $this->rBuf_ = ($data . $this->rBuf_); - } - } - - /** - * Reads a chunk of data into the internal read buffer. - */ - private function readFrame() - { - $buf = $this->transport_->readAll(4); - $val = unpack('N', $buf); - $sz = $val[1]; - - $this->rBuf_ = $this->transport_->readAll($sz); - } - - /** - * Writes some data to the pending output buffer. - * - * @param string $buf The data - * @param int $len Limit of bytes to write - */ - public function write($buf, $len=null) - { - if (!$this->write_) { - return $this->transport_->write($buf, $len); - } - - if ($len !== null && $len < TStringFuncFactory::create()->strlen($buf)) { - $buf = TStringFuncFactory::create()->substr($buf, 0, $len); - } - $this->wBuf_ .= $buf; - } - - /** - * Writes the output buffer to the stream in the format of a 4-byte length - * followed by the actual data. - */ - public function flush() - { - if (!$this->write_ || TStringFuncFactory::create()->strlen($this->wBuf_) == 0) { - return $this->transport_->flush(); - } - - $out = pack('N', TStringFuncFactory::create()->strlen($this->wBuf_)); - $out .= $this->wBuf_; - - // Note that we clear the internal wBuf_ prior to the underlying write - // to ensure we're in a sane state (i.e. internal buffer cleaned) - // if the underlying write throws up an exception - $this->wBuf_ = ''; - $this->transport_->write($out); - $this->transport_->flush(); - } - -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/THttpClient.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/THttpClient.php deleted file mode 100644 index b372ab7..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/THttpClient.php +++ /dev/null @@ -1,229 +0,0 @@ -strlen($uri) > 0) && ($uri{0} != '/')) { - $uri = '/'.$uri; - } - $this->scheme_ = $scheme; - $this->host_ = $host; - $this->port_ = $port; - $this->uri_ = $uri; - $this->buf_ = ''; - $this->handle_ = null; - $this->timeout_ = null; - $this->headers_ = array(); - } - - /** - * Set read timeout - * - * @param float $timeout - */ - public function setTimeoutSecs($timeout) - { - $this->timeout_ = $timeout; - } - - /** - * Whether this transport is open. - * - * @return boolean true if open - */ - public function isOpen() - { - return true; - } - - /** - * Open the transport for reading/writing - * - * @throws TTransportException if cannot open - */ - public function open() {} - - /** - * Close the transport. - */ - public function close() - { - if ($this->handle_) { - @fclose($this->handle_); - $this->handle_ = null; - } - } - - /** - * Read some data into the array. - * - * @param int $len How much to read - * @return string The data that has been read - * @throws TTransportException if cannot read any more data - */ - public function read($len) - { - $data = @fread($this->handle_, $len); - if ($data === FALSE || $data === '') { - $md = stream_get_meta_data($this->handle_); - if ($md['timed_out']) { - throw new TTransportException('THttpClient: timed out reading '.$len.' bytes from '.$this->host_.':'.$this->port_.$this->uri_, TTransportException::TIMED_OUT); - } else { - throw new TTransportException('THttpClient: Could not read '.$len.' bytes from '.$this->host_.':'.$this->port_.$this->uri_, TTransportException::UNKNOWN); - } - } - - return $data; - } - - /** - * Writes some data into the pending buffer - * - * @param string $buf The data to write - * @throws TTransportException if writing fails - */ - public function write($buf) - { - $this->buf_ .= $buf; - } - - /** - * Opens and sends the actual request over the HTTP connection - * - * @throws TTransportException if a writing error occurs - */ - public function flush() - { - // God, PHP really has some esoteric ways of doing simple things. - $host = $this->host_.($this->port_ != 80 ? ':'.$this->port_ : ''); - - $headers = array(); - $defaultHeaders = array('Host' => $host, - 'Accept' => 'application/x-thrift', - 'User-Agent' => 'PHP/THttpClient', - 'Content-Type' => 'application/x-thrift', - 'Content-Length' => TStringFuncFactory::create()->strlen($this->buf_)); - foreach (array_merge($defaultHeaders, $this->headers_) as $key => $value) { - $headers[] = "$key: $value"; - } - - $options = array('method' => 'POST', - 'header' => implode("\r\n", $headers), - 'max_redirects' => 1, - 'content' => $this->buf_); - if ($this->timeout_ > 0) { - $options['timeout'] = $this->timeout_; - } - $this->buf_ = ''; - - $contextid = stream_context_create(array('http' => $options)); - $this->handle_ = @fopen($this->scheme_.'://'.$host.$this->uri_, 'r', false, $contextid); - - // Connect failed? - if ($this->handle_ === FALSE) { - $this->handle_ = null; - $error = 'THttpClient: Could not connect to '.$host.$this->uri_; - throw new TTransportException($error, TTransportException::NOT_OPEN); - } - } - - public function addHeaders($headers) - { - $this->headers_ = array_merge($this->headers_, $headers); - } - -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TMemoryBuffer.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TMemoryBuffer.php deleted file mode 100644 index ca31c57..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TMemoryBuffer.php +++ /dev/null @@ -1,100 +0,0 @@ -buf_ = $buf; - } - - protected $buf_ = ''; - - public function isOpen() - { - return true; - } - - public function open() {} - - public function close() {} - - public function write($buf) - { - $this->buf_ .= $buf; - } - - public function read($len) - { - $bufLength = TStringFuncFactory::create()->strlen($this->buf_); - - if ($bufLength === 0) { - throw new TTransportException('TMemoryBuffer: Could not read ' . - $len . ' bytes from buffer.', - TTransportException::UNKNOWN); - } - - if ($bufLength <= $len) { - $ret = $this->buf_; - $this->buf_ = ''; - - return $ret; - } - - $ret = TStringFuncFactory::create()->substr($this->buf_, 0, $len); - $this->buf_ = TStringFuncFactory::create()->substr($this->buf_, $len); - - return $ret; - } - - public function getBuffer() - { - return $this->buf_; - } - - public function available() - { - return TStringFuncFactory::create()->strlen($this->buf_); - } - - public function putBack($data) - { - $this->buf_ = $data.$this->buf_; - } -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TPhpStream.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TPhpStream.php deleted file mode 100644 index 4c14cdf..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TPhpStream.php +++ /dev/null @@ -1,123 +0,0 @@ -read_ = $mode & self::MODE_R; - $this->write_ = $mode & self::MODE_W; - } - - public function open() - { - if ($this->read_) { - $this->inStream_ = @fopen(self::inStreamName(), 'r'); - if (!is_resource($this->inStream_)) { - throw new TException('TPhpStream: Could not open php://input'); - } - } - if ($this->write_) { - $this->outStream_ = @fopen('php://output', 'w'); - if (!is_resource($this->outStream_)) { - throw new TException('TPhpStream: Could not open php://output'); - } - } - } - - public function close() - { - if ($this->read_) { - @fclose($this->inStream_); - $this->inStream_ = null; - } - if ($this->write_) { - @fclose($this->outStream_); - $this->outStream_ = null; - } - } - - public function isOpen() - { - return - (!$this->read_ || is_resource($this->inStream_)) && - (!$this->write_ || is_resource($this->outStream_)); - } - - public function read($len) - { - $data = @fread($this->inStream_, $len); - if ($data === FALSE || $data === '') { - throw new TException('TPhpStream: Could not read '.$len.' bytes'); - } - - return $data; - } - - public function write($buf) - { - while (TStringFuncFactory::create()->strlen($buf) > 0) { - $got = @fwrite($this->outStream_, $buf); - if ($got === 0 || $got === FALSE) { - throw new TException('TPhpStream: Could not write '.TStringFuncFactory::create()->strlen($buf).' bytes'); - } - $buf = TStringFuncFactory::create()->substr($buf, $got); - } - } - - public function flush() - { - @fflush($this->outStream_); - } - - private static function inStreamName() - { - if (php_sapi_name() == 'cli') { - return 'php://stdin'; - } - - return 'php://input'; - } - -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TSSLSocket.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TSSLSocket.php deleted file mode 100644 index 533b7bb..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TSSLSocket.php +++ /dev/null @@ -1,112 +0,0 @@ -host_ = $this->getSSLHost($host); - $this->port_ = $port; - $this->context_ = $context; - $this->debugHandler_ = $debugHandler ? $debugHandler : 'error_log'; - } - - /** - * Creates a host name with SSL transport protocol - * if no transport protocol already specified in - * the host name. - * - * @param string $host Host to listen on - * @return string $host Host name with transport protocol - */ - private function getSSLHost($host) - { - $transport_protocol_loc = strpos($host, "://"); - if ($transport_protocol_loc === false) { - $host = 'ssl://'.$host; - } - return $host; - } - - /** - * Connects the socket. - */ - public function open() - { - if ($this->isOpen()) { - throw new TTransportException('Socket already connected', TTransportException::ALREADY_OPEN); - } - - if (empty($this->host_)) { - throw new TTransportException('Cannot open null host', TTransportException::NOT_OPEN); - } - - if ($this->port_ <= 0) { - throw new TTransportException('Cannot open without port', TTransportException::NOT_OPEN); - } - - $this->handle_ = @stream_socket_client($this->host_.':'.$this->port_, - $errno, - $errstr, - $this->sendTimeoutSec_ + ($this->sendTimeoutUsec_ / 1000000), - STREAM_CLIENT_CONNECT, - $this->context_); - - // Connect failed? - if ($this->handle_ === FALSE) { - $error = 'TSocket: Could not connect to '.$this->host_.':'.$this->port_.' ('.$errstr.' ['.$errno.'])'; - if ($this->debug_) { - call_user_func($this->debugHandler_, $error); - } - throw new TException($error); - } - } -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TSocket.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TSocket.php deleted file mode 100644 index 10d5115..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TSocket.php +++ /dev/null @@ -1,337 +0,0 @@ -host_ = $host; - $this->port_ = $port; - $this->persist_ = $persist; - $this->debugHandler_ = $debugHandler ? $debugHandler : 'error_log'; - } - - /** - * @param resource $handle - * @return void - */ - public function setHandle($handle) - { - $this->handle_ = $handle; - } - - /** - * Sets the send timeout. - * - * @param int $timeout Timeout in milliseconds. - */ - public function setSendTimeout($timeout) - { - $this->sendTimeoutSec_ = floor($timeout / 1000); - $this->sendTimeoutUsec_ = - ($timeout - ($this->sendTimeoutSec_ * 1000)) * 1000; - } - - /** - * Sets the receive timeout. - * - * @param int $timeout Timeout in milliseconds. - */ - public function setRecvTimeout($timeout) - { - $this->recvTimeoutSec_ = floor($timeout / 1000); - $this->recvTimeoutUsec_ = - ($timeout - ($this->recvTimeoutSec_ * 1000)) * 1000; - } - - /** - * Sets debugging output on or off - * - * @param bool $debug - */ - public function setDebug($debug) - { - $this->debug_ = $debug; - } - - /** - * Get the host that this socket is connected to - * - * @return string host - */ - public function getHost() - { - return $this->host_; - } - - /** - * Get the remote port that this socket is connected to - * - * @return int port - */ - public function getPort() - { - return $this->port_; - } - - /** - * Tests whether this is open - * - * @return bool true if the socket is open - */ - public function isOpen() - { - return is_resource($this->handle_); - } - - /** - * Connects the socket. - */ - public function open() - { - if ($this->isOpen()) { - throw new TTransportException('Socket already connected', TTransportException::ALREADY_OPEN); - } - - if (empty($this->host_)) { - throw new TTransportException('Cannot open null host', TTransportException::NOT_OPEN); - } - - if ($this->port_ <= 0) { - throw new TTransportException('Cannot open without port', TTransportException::NOT_OPEN); - } - - if ($this->persist_) { - $this->handle_ = @pfsockopen($this->host_, - $this->port_, - $errno, - $errstr, - $this->sendTimeoutSec_ + ($this->sendTimeoutUsec_ / 1000000)); - } else { - $this->handle_ = @fsockopen($this->host_, - $this->port_, - $errno, - $errstr, - $this->sendTimeoutSec_ + ($this->sendTimeoutUsec_ / 1000000)); - } - - // Connect failed? - if ($this->handle_ === FALSE) { - $error = 'TSocket: Could not connect to '.$this->host_.':'.$this->port_.' ('.$errstr.' ['.$errno.'])'; - if ($this->debug_) { - call_user_func($this->debugHandler_, $error); - } - throw new TException($error); - } - } - - /** - * Closes the socket. - */ - public function close() - { - if (!$this->persist_) { - @fclose($this->handle_); - $this->handle_ = null; - } - } - - /** - * Read from the socket at most $len bytes. - * - * This method will not wait for all the requested data, it will return as - * soon as any data is received. - * - * @param int $len Maximum number of bytes to read. - * @return string Binary data - */ - public function read($len) - { - $null = null; - $read = array($this->handle_); - $readable = @stream_select($read, $null, $null, $this->recvTimeoutSec_, $this->recvTimeoutUsec_); - - if ($readable > 0) { - $data = fread($this->handle_, $len); - if ($data === false) { - throw new TTransportException('TSocket: Could not read '.$len.' bytes from '. - $this->host_.':'.$this->port_); - } elseif ($data == '' && feof($this->handle_)) { - throw new TTransportException('TSocket read 0 bytes'); - } - - return $data; - } elseif ($readable === 0) { - throw new TTransportException('TSocket: timed out reading '.$len.' bytes from '. - $this->host_.':'.$this->port_); - } else { - throw new TTransportException('TSocket: Could not read '.$len.' bytes from '. - $this->host_.':'.$this->port_); - } - } - - /** - * Write to the socket. - * - * @param string $buf The data to write - */ - public function write($buf) - { - $null = null; - $write = array($this->handle_); - - // keep writing until all the data has been written - while (TStringFuncFactory::create()->strlen($buf) > 0) { - // wait for stream to become available for writing - $writable = @stream_select($null, $write, $null, $this->sendTimeoutSec_, $this->sendTimeoutUsec_); - if ($writable > 0) { - // write buffer to stream - $written = fwrite($this->handle_, $buf); - if ($written === -1 || $written === false) { - throw new TTransportException('TSocket: Could not write '.TStringFuncFactory::create()->strlen($buf).' bytes '. - $this->host_.':'.$this->port_); - } - // determine how much of the buffer is left to write - $buf = TStringFuncFactory::create()->substr($buf, $written); - } elseif ($writable === 0) { - throw new TTransportException('TSocket: timed out writing '.TStringFuncFactory::create()->strlen($buf).' bytes from '. - $this->host_.':'.$this->port_); - } else { - throw new TTransportException('TSocket: Could not write '.TStringFuncFactory::create()->strlen($buf).' bytes '. - $this->host_.':'.$this->port_); - } - } - } - - /** - * Flush output to the socket. - * - * Since read(), readAll() and write() operate on the sockets directly, - * this is a no-op - * - * If you wish to have flushable buffering behaviour, wrap this TSocket - * in a TBufferedTransport. - */ - public function flush() - { - // no-op - } - } diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TSocketPool.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TSocketPool.php deleted file mode 100644 index 18ffd8d..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TSocketPool.php +++ /dev/null @@ -1,300 +0,0 @@ - $val) { - $ports[$key] = $port; - } - } - - foreach ($hosts as $key => $host) { - $this->servers_ []= array('host' => $host, - 'port' => $ports[$key]); - } - } - - /** - * Add a server to the pool - * - * This function does not prevent you from adding a duplicate server entry. - * - * @param string $host hostname or IP - * @param int $port port - */ - public function addServer($host, $port) - { - $this->servers_[] = array('host' => $host, 'port' => $port); - } - - /** - * Sets how many time to keep retrying a host in the connect function. - * - * @param int $numRetries - */ - public function setNumRetries($numRetries) - { - $this->numRetries_ = $numRetries; - } - - /** - * Sets how long to wait until retrying a host if it was marked down - * - * @param int $numRetries - */ - public function setRetryInterval($retryInterval) - { - $this->retryInterval_ = $retryInterval; - } - - /** - * Sets how many time to keep retrying a host before marking it as down. - * - * @param int $numRetries - */ - public function setMaxConsecutiveFailures($maxConsecutiveFailures) - { - $this->maxConsecutiveFailures_ = $maxConsecutiveFailures; - } - - /** - * Turns randomization in connect order on or off. - * - * @param bool $randomize - */ - public function setRandomize($randomize) - { - $this->randomize_ = $randomize; - } - - /** - * Whether to always try the last server. - * - * @param bool $alwaysTryLast - */ - public function setAlwaysTryLast($alwaysTryLast) - { - $this->alwaysTryLast_ = $alwaysTryLast; - } - - /** - * Connects the socket by iterating through all the servers in the pool - * and trying to find one that works. - */ - public function open() - { - // Check if we want order randomization - if ($this->randomize_) { - shuffle($this->servers_); - } - - // Count servers to identify the "last" one - $numServers = count($this->servers_); - - for ($i = 0; $i < $numServers; ++$i) { - - // This extracts the $host and $port variables - extract($this->servers_[$i]); - - // Check APC cache for a record of this server being down - $failtimeKey = 'thrift_failtime:'.$host.':'.$port.'~'; - - // Cache miss? Assume it's OK - $lastFailtime = apc_fetch($failtimeKey); - if ($lastFailtime === FALSE) { - $lastFailtime = 0; - } - - $retryIntervalPassed = false; - - // Cache hit...make sure enough the retry interval has elapsed - if ($lastFailtime > 0) { - $elapsed = time() - $lastFailtime; - if ($elapsed > $this->retryInterval_) { - $retryIntervalPassed = true; - if ($this->debug_) { - call_user_func($this->debugHandler_, - 'TSocketPool: retryInterval '. - '('.$this->retryInterval_.') '. - 'has passed for host '.$host.':'.$port); - } - } - } - - // Only connect if not in the middle of a fail interval, OR if this - // is the LAST server we are trying, just hammer away on it - $isLastServer = false; - if ($this->alwaysTryLast_) { - $isLastServer = ($i == ($numServers - 1)); - } - - if (($lastFailtime === 0) || - ($isLastServer) || - ($lastFailtime > 0 && $retryIntervalPassed)) { - - // Set underlying TSocket params to this one - $this->host_ = $host; - $this->port_ = $port; - - // Try up to numRetries_ connections per server - for ($attempt = 0; $attempt < $this->numRetries_; $attempt++) { - try { - // Use the underlying TSocket open function - parent::open(); - - // Only clear the failure counts if required to do so - if ($lastFailtime > 0) { - apc_store($failtimeKey, 0); - } - - // Successful connection, return now - return; - - } catch (TException $tx) { - // Connection failed - } - } - - // Mark failure of this host in the cache - $consecfailsKey = 'thrift_consecfails:'.$host.':'.$port.'~'; - - // Ignore cache misses - $consecfails = apc_fetch($consecfailsKey); - if ($consecfails === FALSE) { - $consecfails = 0; - } - - // Increment by one - $consecfails++; - - // Log and cache this failure - if ($consecfails >= $this->maxConsecutiveFailures_) { - if ($this->debug_) { - call_user_func($this->debugHandler_, - 'TSocketPool: marking '.$host.':'.$port. - ' as down for '.$this->retryInterval_.' secs '. - 'after '.$consecfails.' failed attempts.'); - } - // Store the failure time - apc_store($failtimeKey, time()); - - // Clear the count of consecutive failures - apc_store($consecfailsKey, 0); - } else { - apc_store($consecfailsKey, $consecfails); - } - } - } - - // Oh no; we failed them all. The system is totally ill! - $error = 'TSocketPool: All hosts in pool are down. '; - $hosts = array(); - foreach ($this->servers_ as $server) { - $hosts []= $server['host'].':'.$server['port']; - } - $hostlist = implode(',', $hosts); - $error .= '('.$hostlist.')'; - if ($this->debug_) { - call_user_func($this->debugHandler_, $error); - } - throw new TException($error); - } -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TTransport.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TTransport.php deleted file mode 100644 index 99c39ff..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TTransport.php +++ /dev/null @@ -1,95 +0,0 @@ -read($len); - - $data = ''; - $got = 0; - while (($got = TStringFuncFactory::create()->strlen($data)) < $len) { - $data .= $this->read($len - $got); - } - - return $data; - } - - /** - * Writes the given data out. - * - * @param string $buf The data to write - * @throws TTransportException if writing fails - */ - abstract public function write($buf); - - /** - * Flushes any pending data out of a buffer - * - * @throws TTransportException if a writing error occurs - */ - public function flush() {} -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TBufferedTransport.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TBufferedTransport.php new file mode 100644 index 0000000..253c5ac --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TBufferedTransport.php @@ -0,0 +1,206 @@ +transport_ = $transport; + $this->rBufSize_ = $rBufSize; + $this->wBufSize_ = $wBufSize; + } + + public function isOpen() + { + return $this->transport_->isOpen(); + } + + /** + * @inheritdoc + * + * @throws TTransportException + */ + public function open() + { + $this->transport_->open(); + } + + public function close() + { + $this->transport_->close(); + } + + public function putBack($data) + { + if (TStringFuncFactory::create()->strlen($this->rBuf_) === 0) { + $this->rBuf_ = $data; + } else { + $this->rBuf_ = ($data . $this->rBuf_); + } + } + + /** + * The reason that we customize readAll here is that the majority of PHP + * streams are already internally buffered by PHP. The socket stream, for + * example, buffers internally and blocks if you call read with $len greater + * than the amount of data available, unlike recv() in C. + * + * Therefore, use the readAll method of the wrapped transport inside + * the buffered readAll. + * + * @throws TTransportException + */ + public function readAll($len) + { + $have = TStringFuncFactory::create()->strlen($this->rBuf_); + if ($have == 0) { + $data = $this->transport_->readAll($len); + } elseif ($have < $len) { + $data = $this->rBuf_; + $this->rBuf_ = ''; + $data .= $this->transport_->readAll($len - $have); + } elseif ($have == $len) { + $data = $this->rBuf_; + $this->rBuf_ = ''; + } elseif ($have > $len) { + $data = TStringFuncFactory::create()->substr($this->rBuf_, 0, $len); + $this->rBuf_ = TStringFuncFactory::create()->substr($this->rBuf_, $len); + } + + return $data; + } + + /** + * @inheritdoc + * + * @param int $len + * @return string + * @throws TTransportException + */ + public function read($len) + { + if (TStringFuncFactory::create()->strlen($this->rBuf_) === 0) { + $this->rBuf_ = $this->transport_->read($this->rBufSize_); + } + + if (TStringFuncFactory::create()->strlen($this->rBuf_) <= $len) { + $ret = $this->rBuf_; + $this->rBuf_ = ''; + + return $ret; + } + + $ret = TStringFuncFactory::create()->substr($this->rBuf_, 0, $len); + $this->rBuf_ = TStringFuncFactory::create()->substr($this->rBuf_, $len); + + return $ret; + } + + /** + * @inheritdoc + * + * @param string $buf + * @throws TTransportException + */ + public function write($buf) + { + $this->wBuf_ .= $buf; + if (TStringFuncFactory::create()->strlen($this->wBuf_) >= $this->wBufSize_) { + $out = $this->wBuf_; + + // Note that we clear the internal wBuf_ prior to the underlying write + // to ensure we're in a sane state (i.e. internal buffer cleaned) + // if the underlying write throws up an exception + $this->wBuf_ = ''; + $this->transport_->write($out); + } + } + + /** + * @inheritdoc + * + * @throws TTransportException + */ + public function flush() + { + if (TStringFuncFactory::create()->strlen($this->wBuf_) > 0) { + $out = $this->wBuf_; + + // Note that we clear the internal wBuf_ prior to the underlying write + // to ensure we're in a sane state (i.e. internal buffer cleaned) + // if the underlying write throws up an exception + $this->wBuf_ = ''; + $this->transport_->write($out); + } + $this->transport_->flush(); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TCurlClient.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TCurlClient.php new file mode 100644 index 0000000..482b43b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TCurlClient.php @@ -0,0 +1,276 @@ +strlen($uri) > 0) && ($uri{0} != '/')) { + $uri = '/' . $uri; + } + $this->scheme_ = $scheme; + $this->host_ = $host; + $this->port_ = $port; + $this->uri_ = $uri; + $this->request_ = ''; + $this->response_ = null; + $this->timeout_ = null; + $this->headers_ = array(); + } + + /** + * Set read timeout + * + * @param float $timeout + */ + public function setTimeoutSecs($timeout) + { + $this->timeout_ = $timeout; + } + + /** + * Whether this transport is open. + * + * @return boolean true if open + */ + public function isOpen() + { + return true; + } + + /** + * Open the transport for reading/writing + * + * @throws TTransportException if cannot open + */ + public function open() + { + } + + /** + * Close the transport. + */ + public function close() + { + $this->request_ = ''; + $this->response_ = null; + } + + /** + * Read some data into the array. + * + * @param int $len How much to read + * @return string The data that has been read + * @throws TTransportException if cannot read any more data + */ + public function read($len) + { + if ($len >= strlen($this->response_)) { + return $this->response_; + } else { + $ret = substr($this->response_, 0, $len); + $this->response_ = substr($this->response_, $len); + + return $ret; + } + } + + /** + * Guarantees that the full amount of data is read. Since TCurlClient gets entire payload at + * once, parent readAll cannot be used. + * + * @return string The data, of exact length + * @throws TTransportException if cannot read data + */ + public function readAll($len) + { + $data = $this->read($len); + + if (TStringFuncFactory::create()->strlen($data) !== $len) { + throw new TTransportException('TCurlClient could not read '.$len.' bytes'); + } + + return $data; + } + + /** + * Writes some data into the pending buffer + * + * @param string $buf The data to write + * @throws TTransportException if writing fails + */ + public function write($buf) + { + $this->request_ .= $buf; + } + + /** + * Opens and sends the actual request over the HTTP connection + * + * @throws TTransportException if a writing error occurs + */ + public function flush() + { + if (!self::$curlHandle) { + register_shutdown_function(array('Thrift\\Transport\\TCurlClient', 'closeCurlHandle')); + self::$curlHandle = curl_init(); + curl_setopt(self::$curlHandle, CURLOPT_RETURNTRANSFER, true); + curl_setopt(self::$curlHandle, CURLOPT_BINARYTRANSFER, true); + curl_setopt(self::$curlHandle, CURLOPT_USERAGENT, 'PHP/TCurlClient'); + curl_setopt(self::$curlHandle, CURLOPT_CUSTOMREQUEST, 'POST'); + curl_setopt(self::$curlHandle, CURLOPT_FOLLOWLOCATION, true); + curl_setopt(self::$curlHandle, CURLOPT_MAXREDIRS, 1); + } + // God, PHP really has some esoteric ways of doing simple things. + $host = $this->host_ . ($this->port_ != 80 ? ':' . $this->port_ : ''); + $fullUrl = $this->scheme_ . "://" . $host . $this->uri_; + + $headers = array(); + $defaultHeaders = array('Accept' => 'application/x-thrift', + 'Content-Type' => 'application/x-thrift', + 'Content-Length' => TStringFuncFactory::create()->strlen($this->request_)); + foreach (array_merge($defaultHeaders, $this->headers_) as $key => $value) { + $headers[] = "$key: $value"; + } + + curl_setopt(self::$curlHandle, CURLOPT_HTTPHEADER, $headers); + + if ($this->timeout_ > 0) { + curl_setopt(self::$curlHandle, CURLOPT_TIMEOUT, $this->timeout_); + } + curl_setopt(self::$curlHandle, CURLOPT_POSTFIELDS, $this->request_); + $this->request_ = ''; + + curl_setopt(self::$curlHandle, CURLOPT_URL, $fullUrl); + $this->response_ = curl_exec(self::$curlHandle); + $responseError = curl_error(self::$curlHandle); + + $code = curl_getinfo(self::$curlHandle, CURLINFO_HTTP_CODE); + + // Handle non 200 status code / connect failure + if ($this->response_ === false || $code !== 200) { + curl_close(self::$curlHandle); + self::$curlHandle = null; + $this->response_ = null; + $error = 'TCurlClient: Could not connect to ' . $fullUrl; + if ($responseError) { + $error .= ', ' . $responseError; + } + if ($code) { + $error .= ', HTTP status code: ' . $code; + } + throw new TTransportException($error, TTransportException::UNKNOWN); + } + } + + public static function closeCurlHandle() + { + try { + if (self::$curlHandle) { + curl_close(self::$curlHandle); + self::$curlHandle = null; + } + } catch (\Exception $x) { + error_log('There was an error closing the curl handle: ' . $x->getMessage()); + } + } + + public function addHeaders($headers) + { + $this->headers_ = array_merge($this->headers_, $headers); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TFramedTransport.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TFramedTransport.php new file mode 100644 index 0000000..39d1869 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TFramedTransport.php @@ -0,0 +1,192 @@ +transport_ = $transport; + $this->read_ = $read; + $this->write_ = $write; + } + + public function isOpen() + { + return $this->transport_->isOpen(); + } + + public function open() + { + $this->transport_->open(); + } + + public function close() + { + $this->transport_->close(); + } + + /** + * Reads from the buffer. When more data is required reads another entire + * chunk and serves future reads out of that. + * + * @param int $len How much data + */ + public function read($len) + { + if (!$this->read_) { + return $this->transport_->read($len); + } + + if (TStringFuncFactory::create()->strlen($this->rBuf_) === 0) { + $this->readFrame(); + } + + // Just return full buff + if ($len >= TStringFuncFactory::create()->strlen($this->rBuf_)) { + $out = $this->rBuf_; + $this->rBuf_ = null; + + return $out; + } + + // Return TStringFuncFactory::create()->substr + $out = TStringFuncFactory::create()->substr($this->rBuf_, 0, $len); + $this->rBuf_ = TStringFuncFactory::create()->substr($this->rBuf_, $len); + + return $out; + } + + /** + * Put previously read data back into the buffer + * + * @param string $data data to return + */ + public function putBack($data) + { + if (TStringFuncFactory::create()->strlen($this->rBuf_) === 0) { + $this->rBuf_ = $data; + } else { + $this->rBuf_ = ($data . $this->rBuf_); + } + } + + /** + * Reads a chunk of data into the internal read buffer. + */ + private function readFrame() + { + $buf = $this->transport_->readAll(4); + $val = unpack('N', $buf); + $sz = $val[1]; + + $this->rBuf_ = $this->transport_->readAll($sz); + } + + /** + * Writes some data to the pending output buffer. + * + * @param string $buf The data + * @param int $len Limit of bytes to write + */ + public function write($buf, $len = null) + { + if (!$this->write_) { + return $this->transport_->write($buf, $len); + } + + if ($len !== null && $len < TStringFuncFactory::create()->strlen($buf)) { + $buf = TStringFuncFactory::create()->substr($buf, 0, $len); + } + $this->wBuf_ .= $buf; + } + + /** + * Writes the output buffer to the stream in the format of a 4-byte length + * followed by the actual data. + */ + public function flush() + { + if (!$this->write_ || TStringFuncFactory::create()->strlen($this->wBuf_) == 0) { + return $this->transport_->flush(); + } + + $out = pack('N', TStringFuncFactory::create()->strlen($this->wBuf_)); + $out .= $this->wBuf_; + + // Note that we clear the internal wBuf_ prior to the underlying write + // to ensure we're in a sane state (i.e. internal buffer cleaned) + // if the underlying write throws up an exception + $this->wBuf_ = ''; + $this->transport_->write($out); + $this->transport_->flush(); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/THttpClient.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/THttpClient.php new file mode 100644 index 0000000..0158809 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/THttpClient.php @@ -0,0 +1,258 @@ +strlen($uri) > 0) && ($uri{0} != '/')) { + $uri = '/' . $uri; + } + $this->scheme_ = $scheme; + $this->host_ = $host; + $this->port_ = $port; + $this->uri_ = $uri; + $this->buf_ = ''; + $this->handle_ = null; + $this->timeout_ = null; + $this->headers_ = array(); + $this->context_ = $context; + } + + /** + * Set read timeout + * + * @param float $timeout + */ + public function setTimeoutSecs($timeout) + { + $this->timeout_ = $timeout; + } + + /** + * Whether this transport is open. + * + * @return boolean true if open + */ + public function isOpen() + { + return true; + } + + /** + * Open the transport for reading/writing + * + * @throws TTransportException if cannot open + */ + public function open() + { + } + + /** + * Close the transport. + */ + public function close() + { + if ($this->handle_) { + @fclose($this->handle_); + $this->handle_ = null; + } + } + + /** + * Read some data into the array. + * + * @param int $len How much to read + * @return string The data that has been read + * @throws TTransportException if cannot read any more data + */ + public function read($len) + { + $data = @fread($this->handle_, $len); + if ($data === false || $data === '') { + $md = stream_get_meta_data($this->handle_); + if ($md['timed_out']) { + throw new TTransportException( + 'THttpClient: timed out reading ' . $len . ' bytes from ' . + $this->host_ . ':' . $this->port_ . $this->uri_, + TTransportException::TIMED_OUT + ); + } else { + throw new TTransportException( + 'THttpClient: Could not read ' . $len . ' bytes from ' . + $this->host_ . ':' . $this->port_ . $this->uri_, + TTransportException::UNKNOWN + ); + } + } + + return $data; + } + + /** + * Writes some data into the pending buffer + * + * @param string $buf The data to write + * @throws TTransportException if writing fails + */ + public function write($buf) + { + $this->buf_ .= $buf; + } + + /** + * Opens and sends the actual request over the HTTP connection + * + * @throws TTransportException if a writing error occurs + */ + public function flush() + { + // God, PHP really has some esoteric ways of doing simple things. + $host = $this->host_ . ($this->port_ != 80 ? ':' . $this->port_ : ''); + + $headers = array(); + $defaultHeaders = array('Host' => $host, + 'Accept' => 'application/x-thrift', + 'User-Agent' => 'PHP/THttpClient', + 'Content-Type' => 'application/x-thrift', + 'Content-Length' => TStringFuncFactory::create()->strlen($this->buf_)); + foreach (array_merge($defaultHeaders, $this->headers_) as $key => $value) { + $headers[] = "$key: $value"; + } + + $options = $this->context_; + + $baseHttpOptions = isset($options["http"]) ? $options["http"] : array(); + + $httpOptions = $baseHttpOptions + array('method' => 'POST', + 'header' => implode("\r\n", $headers), + 'max_redirects' => 1, + 'content' => $this->buf_); + if ($this->timeout_ > 0) { + $httpOptions['timeout'] = $this->timeout_; + } + $this->buf_ = ''; + + $options["http"] = $httpOptions; + $contextid = stream_context_create($options); + $this->handle_ = @fopen( + $this->scheme_ . '://' . $host . $this->uri_, + 'r', + false, + $contextid + ); + + // Connect failed? + if ($this->handle_ === false) { + $this->handle_ = null; + $error = 'THttpClient: Could not connect to ' . $host . $this->uri_; + throw new TTransportException($error, TTransportException::NOT_OPEN); + } + } + + public function addHeaders($headers) + { + $this->headers_ = array_merge($this->headers_, $headers); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TMemoryBuffer.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TMemoryBuffer.php new file mode 100644 index 0000000..fee03a2 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TMemoryBuffer.php @@ -0,0 +1,106 @@ +buf_ = $buf; + } + + protected $buf_ = ''; + + public function isOpen() + { + return true; + } + + public function open() + { + } + + public function close() + { + } + + public function write($buf) + { + $this->buf_ .= $buf; + } + + public function read($len) + { + $bufLength = TStringFuncFactory::create()->strlen($this->buf_); + + if ($bufLength === 0) { + throw new TTransportException( + 'TMemoryBuffer: Could not read ' . + $len . ' bytes from buffer.', + TTransportException::UNKNOWN + ); + } + + if ($bufLength <= $len) { + $ret = $this->buf_; + $this->buf_ = ''; + + return $ret; + } + + $ret = TStringFuncFactory::create()->substr($this->buf_, 0, $len); + $this->buf_ = TStringFuncFactory::create()->substr($this->buf_, $len); + + return $ret; + } + + public function getBuffer() + { + return $this->buf_; + } + + public function available() + { + return TStringFuncFactory::create()->strlen($this->buf_); + } + + public function putBack($data) + { + $this->buf_ = $data . $this->buf_; + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TNullTransport.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TNullTransport.php similarity index 78% rename from vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TNullTransport.php rename to vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TNullTransport.php index feeb7a4..7e086b6 100644 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Transport/TNullTransport.php +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TNullTransport.php @@ -32,20 +32,25 @@ use Thrift\Exception\TTransportException; */ class TNullTransport extends TTransport { - public function isOpen() - { - return true; - } + public function isOpen() + { + return true; + } - public function open() {} + public function open() + { + } - public function close() {} + public function close() + { + } - public function read($len) - { - throw new TTransportException("Can't read from TNullTransport."); - } - - public function write($buf) {} + public function read($len) + { + throw new TTransportException("Can't read from TNullTransport."); + } + public function write($buf) + { + } } diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TPhpStream.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TPhpStream.php new file mode 100644 index 0000000..42823ff --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TPhpStream.php @@ -0,0 +1,124 @@ +read_ = $mode & self::MODE_R; + $this->write_ = $mode & self::MODE_W; + } + + public function open() + { + if ($this->read_) { + $this->inStream_ = @fopen(self::inStreamName(), 'r'); + if (!is_resource($this->inStream_)) { + throw new TException('TPhpStream: Could not open php://input'); + } + } + if ($this->write_) { + $this->outStream_ = @fopen('php://output', 'w'); + if (!is_resource($this->outStream_)) { + throw new TException('TPhpStream: Could not open php://output'); + } + } + } + + public function close() + { + if ($this->read_) { + @fclose($this->inStream_); + $this->inStream_ = null; + } + if ($this->write_) { + @fclose($this->outStream_); + $this->outStream_ = null; + } + } + + public function isOpen() + { + return + (!$this->read_ || is_resource($this->inStream_)) && + (!$this->write_ || is_resource($this->outStream_)); + } + + public function read($len) + { + $data = @fread($this->inStream_, $len); + if ($data === false || $data === '') { + throw new TException('TPhpStream: Could not read ' . $len . ' bytes'); + } + + return $data; + } + + public function write($buf) + { + while (TStringFuncFactory::create()->strlen($buf) > 0) { + $got = @fwrite($this->outStream_, $buf); + if ($got === 0 || $got === false) { + throw new TException( + 'TPhpStream: Could not write ' . TStringFuncFactory::create()->strlen($buf) . ' bytes' + ); + } + $buf = TStringFuncFactory::create()->substr($buf, $got); + } + } + + public function flush() + { + @fflush($this->outStream_); + } + + private static function inStreamName() + { + if (php_sapi_name() == 'cli') { + return 'php://stdin'; + } + + return 'php://input'; + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TSSLSocket.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TSSLSocket.php new file mode 100644 index 0000000..b4a0adb --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TSSLSocket.php @@ -0,0 +1,117 @@ +host_ = $this->getSSLHost($host); + $this->port_ = $port; + $this->context_ = $context; + $this->debugHandler_ = $debugHandler ? $debugHandler : 'error_log'; + } + + /** + * Creates a host name with SSL transport protocol + * if no transport protocol already specified in + * the host name. + * + * @param string $host Host to listen on + * @return string $host Host name with transport protocol + */ + private function getSSLHost($host) + { + $transport_protocol_loc = strpos($host, "://"); + if ($transport_protocol_loc === false) { + $host = 'ssl://' . $host; + } + return $host; + } + + /** + * Connects the socket. + */ + public function open() + { + if ($this->isOpen()) { + throw new TTransportException('Socket already connected', TTransportException::ALREADY_OPEN); + } + + if (empty($this->host_)) { + throw new TTransportException('Cannot open null host', TTransportException::NOT_OPEN); + } + + if ($this->port_ <= 0) { + throw new TTransportException('Cannot open without port', TTransportException::NOT_OPEN); + } + + $this->handle_ = @stream_socket_client( + $this->host_ . ':' . $this->port_, + $errno, + $errstr, + $this->sendTimeoutSec_ + ($this->sendTimeoutUsec_ / 1000000), + STREAM_CLIENT_CONNECT, + $this->context_ + ); + + // Connect failed? + if ($this->handle_ === false) { + $error = 'TSocket: Could not connect to ' . + $this->host_ . ':' . $this->port_ . ' (' . $errstr . ' [' . $errno . '])'; + if ($this->debug_) { + call_user_func($this->debugHandler_, $error); + } + throw new TException($error); + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TSocket.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TSocket.php new file mode 100644 index 0000000..5147efa --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TSocket.php @@ -0,0 +1,366 @@ +host_ = $host; + $this->port_ = $port; + $this->persist_ = $persist; + $this->debugHandler_ = $debugHandler ? $debugHandler : 'error_log'; + } + + /** + * @param resource $handle + * @return void + */ + public function setHandle($handle) + { + $this->handle_ = $handle; + stream_set_blocking($this->handle_, false); + } + + /** + * Sets the send timeout. + * + * @param int $timeout Timeout in milliseconds. + */ + public function setSendTimeout($timeout) + { + $this->sendTimeoutSec_ = floor($timeout / 1000); + $this->sendTimeoutUsec_ = + ($timeout - ($this->sendTimeoutSec_ * 1000)) * 1000; + } + + /** + * Sets the receive timeout. + * + * @param int $timeout Timeout in milliseconds. + */ + public function setRecvTimeout($timeout) + { + $this->recvTimeoutSec_ = floor($timeout / 1000); + $this->recvTimeoutUsec_ = + ($timeout - ($this->recvTimeoutSec_ * 1000)) * 1000; + } + + /** + * Sets debugging output on or off + * + * @param bool $debug + */ + public function setDebug($debug) + { + $this->debug_ = $debug; + } + + /** + * Get the host that this socket is connected to + * + * @return string host + */ + public function getHost() + { + return $this->host_; + } + + /** + * Get the remote port that this socket is connected to + * + * @return int port + */ + public function getPort() + { + return $this->port_; + } + + /** + * Tests whether this is open + * + * @return bool true if the socket is open + */ + public function isOpen() + { + return is_resource($this->handle_); + } + + /** + * Connects the socket. + */ + public function open() + { + if ($this->isOpen()) { + throw new TTransportException('Socket already connected', TTransportException::ALREADY_OPEN); + } + + if (empty($this->host_)) { + throw new TTransportException('Cannot open null host', TTransportException::NOT_OPEN); + } + + if ($this->port_ <= 0) { + throw new TTransportException('Cannot open without port', TTransportException::NOT_OPEN); + } + + if ($this->persist_) { + $this->handle_ = @pfsockopen( + $this->host_, + $this->port_, + $errno, + $errstr, + $this->sendTimeoutSec_ + ($this->sendTimeoutUsec_ / 1000000) + ); + } else { + $this->handle_ = @fsockopen( + $this->host_, + $this->port_, + $errno, + $errstr, + $this->sendTimeoutSec_ + ($this->sendTimeoutUsec_ / 1000000) + ); + } + + // Connect failed? + if ($this->handle_ === false) { + $error = 'TSocket: Could not connect to ' . + $this->host_ . ':' . $this->port_ . ' (' . $errstr . ' [' . $errno . '])'; + if ($this->debug_) { + call_user_func($this->debugHandler_, $error); + } + throw new TException($error); + } + + if (function_exists('socket_import_stream') && function_exists('socket_set_option')) { + $socket = socket_import_stream($this->handle_); + socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1); + } + } + + /** + * Closes the socket. + */ + public function close() + { + @fclose($this->handle_); + $this->handle_ = null; + } + + /** + * Read from the socket at most $len bytes. + * + * This method will not wait for all the requested data, it will return as + * soon as any data is received. + * + * @param int $len Maximum number of bytes to read. + * @return string Binary data + */ + public function read($len) + { + $null = null; + $read = array($this->handle_); + $readable = @stream_select( + $read, + $null, + $null, + $this->recvTimeoutSec_, + $this->recvTimeoutUsec_ + ); + + if ($readable > 0) { + $data = fread($this->handle_, $len); + if ($data === false) { + throw new TTransportException('TSocket: Could not read ' . $len . ' bytes from ' . + $this->host_ . ':' . $this->port_); + } elseif ($data == '' && feof($this->handle_)) { + throw new TTransportException('TSocket read 0 bytes'); + } + + return $data; + } elseif ($readable === 0) { + throw new TTransportException('TSocket: timed out reading ' . $len . ' bytes from ' . + $this->host_ . ':' . $this->port_); + } else { + throw new TTransportException('TSocket: Could not read ' . $len . ' bytes from ' . + $this->host_ . ':' . $this->port_); + } + } + + /** + * Write to the socket. + * + * @param string $buf The data to write + */ + public function write($buf) + { + $null = null; + $write = array($this->handle_); + + // keep writing until all the data has been written + while (TStringFuncFactory::create()->strlen($buf) > 0) { + // wait for stream to become available for writing + $writable = @stream_select( + $null, + $write, + $null, + $this->sendTimeoutSec_, + $this->sendTimeoutUsec_ + ); + if ($writable > 0) { + // write buffer to stream + $written = fwrite($this->handle_, $buf); + if ($written === -1 || $written === false) { + throw new TTransportException( + 'TSocket: Could not write ' . TStringFuncFactory::create()->strlen($buf) . ' bytes ' . + $this->host_ . ':' . $this->port_ + ); + } + // determine how much of the buffer is left to write + $buf = TStringFuncFactory::create()->substr($buf, $written); + } elseif ($writable === 0) { + throw new TTransportException( + 'TSocket: timed out writing ' . TStringFuncFactory::create()->strlen($buf) . ' bytes from ' . + $this->host_ . ':' . $this->port_ + ); + } else { + throw new TTransportException( + 'TSocket: Could not write ' . TStringFuncFactory::create()->strlen($buf) . ' bytes ' . + $this->host_ . ':' . $this->port_ + ); + } + } + } + + /** + * Flush output to the socket. + * + * Since read(), readAll() and write() operate on the sockets directly, + * this is a no-op + * + * If you wish to have flushable buffering behaviour, wrap this TSocket + * in a TBufferedTransport. + */ + public function flush() + { + // no-op + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TSocketPool.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TSocketPool.php new file mode 100644 index 0000000..cb9e8dd --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TSocketPool.php @@ -0,0 +1,310 @@ + $val) { + $ports[$key] = $port; + } + } + + foreach ($hosts as $key => $host) { + $this->servers_ [] = array('host' => $host, + 'port' => $ports[$key]); + } + } + + /** + * Add a server to the pool + * + * This function does not prevent you from adding a duplicate server entry. + * + * @param string $host hostname or IP + * @param int $port port + */ + public function addServer($host, $port) + { + $this->servers_[] = array('host' => $host, 'port' => $port); + } + + /** + * Sets how many time to keep retrying a host in the connect function. + * + * @param int $numRetries + */ + public function setNumRetries($numRetries) + { + $this->numRetries_ = $numRetries; + } + + /** + * Sets how long to wait until retrying a host if it was marked down + * + * @param int $numRetries + */ + public function setRetryInterval($retryInterval) + { + $this->retryInterval_ = $retryInterval; + } + + /** + * Sets how many time to keep retrying a host before marking it as down. + * + * @param int $numRetries + */ + public function setMaxConsecutiveFailures($maxConsecutiveFailures) + { + $this->maxConsecutiveFailures_ = $maxConsecutiveFailures; + } + + /** + * Turns randomization in connect order on or off. + * + * @param bool $randomize + */ + public function setRandomize($randomize) + { + $this->randomize_ = $randomize; + } + + /** + * Whether to always try the last server. + * + * @param bool $alwaysTryLast + */ + public function setAlwaysTryLast($alwaysTryLast) + { + $this->alwaysTryLast_ = $alwaysTryLast; + } + + /** + * Connects the socket by iterating through all the servers in the pool + * and trying to find one that works. + */ + public function open() + { + // Check if we want order randomization + if ($this->randomize_) { + shuffle($this->servers_); + } + + // Count servers to identify the "last" one + $numServers = count($this->servers_); + + for ($i = 0; $i < $numServers; ++$i) { + // This extracts the $host and $port variables + extract($this->servers_[$i]); + + // Check APC cache for a record of this server being down + $failtimeKey = 'thrift_failtime:' . $host . ':' . $port . '~'; + + // Cache miss? Assume it's OK + $lastFailtime = apc_fetch($failtimeKey); + if ($lastFailtime === false) { + $lastFailtime = 0; + } + + $retryIntervalPassed = false; + + // Cache hit...make sure enough the retry interval has elapsed + if ($lastFailtime > 0) { + $elapsed = time() - $lastFailtime; + if ($elapsed > $this->retryInterval_) { + $retryIntervalPassed = true; + if ($this->debug_) { + call_user_func( + $this->debugHandler_, + 'TSocketPool: retryInterval ' . + '(' . $this->retryInterval_ . ') ' . + 'has passed for host ' . $host . ':' . $port + ); + } + } + } + + // Only connect if not in the middle of a fail interval, OR if this + // is the LAST server we are trying, just hammer away on it + $isLastServer = false; + if ($this->alwaysTryLast_) { + $isLastServer = ($i == ($numServers - 1)); + } + + if (($lastFailtime === 0) || + ($isLastServer) || + ($lastFailtime > 0 && $retryIntervalPassed)) { + // Set underlying TSocket params to this one + $this->host_ = $host; + $this->port_ = $port; + + // Try up to numRetries_ connections per server + for ($attempt = 0; $attempt < $this->numRetries_; $attempt++) { + try { + // Use the underlying TSocket open function + parent::open(); + + // Only clear the failure counts if required to do so + if ($lastFailtime > 0) { + apc_store($failtimeKey, 0); + } + + // Successful connection, return now + return; + } catch (TException $tx) { + // Connection failed + } + } + + // Mark failure of this host in the cache + $consecfailsKey = 'thrift_consecfails:' . $host . ':' . $port . '~'; + + // Ignore cache misses + $consecfails = apc_fetch($consecfailsKey); + if ($consecfails === false) { + $consecfails = 0; + } + + // Increment by one + $consecfails++; + + // Log and cache this failure + if ($consecfails >= $this->maxConsecutiveFailures_) { + if ($this->debug_) { + call_user_func( + $this->debugHandler_, + 'TSocketPool: marking ' . $host . ':' . $port . + ' as down for ' . $this->retryInterval_ . ' secs ' . + 'after ' . $consecfails . ' failed attempts.' + ); + } + // Store the failure time + apc_store($failtimeKey, time()); + + // Clear the count of consecutive failures + apc_store($consecfailsKey, 0); + } else { + apc_store($consecfailsKey, $consecfails); + } + } + } + + // Oh no; we failed them all. The system is totally ill! + $error = 'TSocketPool: All hosts in pool are down. '; + $hosts = array(); + foreach ($this->servers_ as $server) { + $hosts [] = $server['host'] . ':' . $server['port']; + } + $hostlist = implode(',', $hosts); + $error .= '(' . $hostlist . ')'; + if ($this->debug_) { + call_user_func($this->debugHandler_, $error); + } + throw new TException($error); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TTransport.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TTransport.php new file mode 100644 index 0000000..35921c6 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Transport/TTransport.php @@ -0,0 +1,98 @@ +read($len); + + $data = ''; + $got = 0; + while (($got = TStringFuncFactory::create()->strlen($data)) < $len) { + $data .= $this->read($len - $got); + } + + return $data; + } + + /** + * Writes the given data out. + * + * @param string $buf The data to write + * @throws TTransportException if writing fails + */ + abstract public function write($buf); + + /** + * Flushes any pending data out of a buffer + * + * @throws TTransportException if a writing error occurs + */ + public function flush() + { + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Type/TConstant.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Type/TConstant.php similarity index 91% rename from vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Type/TConstant.php rename to vendor/git.apache.org/thrift.git/lib/php/lib/Type/TConstant.php index 7c8eceb..215da4a 100644 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Type/TConstant.php +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Type/TConstant.php @@ -30,7 +30,9 @@ abstract class TConstant /** * Don't instanciate this class */ - protected function __construct() {} + protected function __construct() + { + } /** * Get a constant value @@ -41,8 +43,8 @@ abstract class TConstant { if (is_null(static::$$constant)) { static::$$constant = call_user_func( - sprintf('static::init_%s', $constant) - ); + sprintf('static::init_%s', $constant) + ); } return static::$$constant; diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Type/TMessageType.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Type/TMessageType.php similarity index 91% rename from vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Type/TMessageType.php rename to vendor/git.apache.org/thrift.git/lib/php/lib/Type/TMessageType.php index bff224f..dc9ae62 100644 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Type/TMessageType.php +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Type/TMessageType.php @@ -27,8 +27,8 @@ namespace Thrift\Type; */ class TMessageType { - const CALL = 1; - const REPLY = 2; - const EXCEPTION = 3; - const ONEWAY = 4; + const CALL = 1; + const REPLY = 2; + const EXCEPTION = 3; + const ONEWAY = 4; } diff --git a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Type/TType.php b/vendor/git.apache.org/thrift.git/lib/php/lib/Type/TType.php similarity index 68% rename from vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Type/TType.php rename to vendor/git.apache.org/thrift.git/lib/php/lib/Type/TType.php index 71219c2..3fdb15f 100644 --- a/vendor/git.apache.org/thrift.git/lib/php/lib/Thrift/Type/TType.php +++ b/vendor/git.apache.org/thrift.git/lib/php/lib/Type/TType.php @@ -27,21 +27,21 @@ namespace Thrift\Type; */ class TType { - const STOP = 0; - const VOID = 1; - const BOOL = 2; - const BYTE = 3; - const I08 = 3; - const DOUBLE = 4; - const I16 = 6; - const I32 = 8; - const I64 = 10; - const STRING = 11; - const UTF7 = 11; - const STRUCT = 12; - const MAP = 13; - const SET = 14; - const LST = 15; // N.B. cannot use LIST keyword in PHP! - const UTF8 = 16; - const UTF16 = 17; + const STOP = 0; + const VOID = 1; + const BOOL = 2; + const BYTE = 3; + const I08 = 3; + const DOUBLE = 4; + const I16 = 6; + const I32 = 8; + const I64 = 10; + const STRING = 11; + const UTF7 = 11; + const STRUCT = 12; + const MAP = 13; + const SET = 14; + const LST = 15; // N.B. cannot use LIST keyword in PHP! + const UTF8 = 16; + const UTF16 = 17; } diff --git a/vendor/git.apache.org/thrift.git/lib/php/src/ext/thrift_protocol/php_thrift_protocol.cpp b/vendor/git.apache.org/thrift.git/lib/php/src/ext/thrift_protocol/php_thrift_protocol.cpp index a0de645..63c8905 100644 --- a/vendor/git.apache.org/thrift.git/lib/php/src/ext/thrift_protocol/php_thrift_protocol.cpp +++ b/vendor/git.apache.org/thrift.git/lib/php/src/ext/thrift_protocol/php_thrift_protocol.cpp @@ -16,7 +16,6 @@ * specific language governing permissions and limitations * under the License. */ - #ifdef HAVE_CONFIG_H #include "config.h" #endif @@ -26,23 +25,14 @@ #include "zend_exceptions.h" #include "php_thrift_protocol.h" -/* GUARD FOR PHP 5 */ -#if PHP_VERSION_ID < 70000 && PHP_VERSION_ID > 50000 +#if PHP_VERSION_ID >= 70000 #include -#if defined( WIN32 ) || defined( _WIN64 ) -typedef int int32_t; -typedef signed char int8_t; -typedef unsigned char uint8_t; -typedef unsigned short uint16_t; -typedef long long int64_t; -typedef unsigned uint32_t; -typedef short int16_t; -typedef unsigned long long uint64_t; -#else -#include -#endif +#include + +#include #include +#include #ifndef bswap_64 #define bswap_64(x) (((uint64_t)(x) << 56) | \ @@ -96,20 +86,21 @@ const int INVALID_DATA = 1; const int BAD_VERSION = 4; static zend_function_entry thrift_protocol_functions[] = { - PHP_FE(thrift_protocol_write_binary, NULL) - PHP_FE(thrift_protocol_read_binary, NULL) - {NULL, NULL, NULL} -} ; + PHP_FE(thrift_protocol_write_binary, nullptr) + PHP_FE(thrift_protocol_read_binary, nullptr) + PHP_FE(thrift_protocol_read_binary_after_message_begin, nullptr) + {nullptr, nullptr, nullptr} +}; zend_module_entry thrift_protocol_module_entry = { STANDARD_MODULE_HEADER, "thrift_protocol", thrift_protocol_functions, - NULL, - NULL, - NULL, - NULL, - NULL, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, "1.0", STANDARD_MODULE_PROPERTIES }; @@ -120,42 +111,61 @@ ZEND_GET_MODULE(thrift_protocol) class PHPExceptionWrapper : public std::exception { public: - PHPExceptionWrapper(zval* _ex) throw() : ex(_ex) { - snprintf(_what, 40, "PHP exception zval=%p", ex); + PHPExceptionWrapper(zval* _ex) throw() { + ZVAL_COPY(&ex, _ex); + snprintf(_what, 40, "PHP exception zval=%p", _ex); } - const char* what() const throw() { return _what; } - ~PHPExceptionWrapper() throw() {} - operator zval*() const throw() { return const_cast(ex); } // Zend API doesn't do 'const'... + + PHPExceptionWrapper(zend_object* _exobj) throw() { + ZVAL_OBJ(&ex, _exobj); + snprintf(_what, 40, "PHP exception zval=%p", _exobj); + } + ~PHPExceptionWrapper() throw() { + zval_dtor(&ex); + } + + const char* what() const throw() { + return _what; + } + operator zval*() const throw() { + return const_cast(&ex); + } // Zend API doesn't do 'const'... protected: - zval* ex; + zval ex; char _what[40]; } ; class PHPTransport { -public: - zval* protocol() { return p; } - zval* transport() { return t; } protected: - PHPTransport() {} + PHPTransport(zval* _p, size_t _buffer_size) { + assert(Z_TYPE_P(_p) == IS_OBJECT); + + ZVAL_UNDEF(&t); - void construct_with_zval(zval* _p, size_t _buffer_size) { buffer = reinterpret_cast(emalloc(_buffer_size)); buffer_ptr = buffer; buffer_used = 0; buffer_size = _buffer_size; - p = _p; // Get the transport for the passed protocol zval gettransport; - ZVAL_STRING(&gettransport, "getTransport", 0); - MAKE_STD_ZVAL(t); - ZVAL_NULL(t); - TSRMLS_FETCH(); - call_user_function(EG(function_table), &p, &gettransport, t, 0, NULL TSRMLS_CC); + ZVAL_STRING(&gettransport, "getTransport"); + call_user_function(nullptr, _p, &gettransport, &t, 0, nullptr); + + zval_dtor(&gettransport); + + if (EG(exception)) { + zend_object *ex = EG(exception); + EG(exception) = nullptr; + throw PHPExceptionWrapper(ex); + } + + assert(Z_TYPE(t) == IS_OBJECT); } + ~PHPTransport() { efree(buffer); - zval_ptr_dtor(&t); + zval_dtor(&t); } char* buffer; @@ -163,20 +173,14 @@ protected: size_t buffer_used; size_t buffer_size; - zval* p; - zval* t; + zval t; }; class PHPOutputTransport : public PHPTransport { public: - PHPOutputTransport(zval* _p, size_t _buffer_size = 8192) { - construct_with_zval(_p, _buffer_size); - } - - ~PHPOutputTransport() { - //flush(); - } + PHPOutputTransport(zval* _p, size_t _buffer_size = 8192) : PHPTransport(_p, _buffer_size) { } + ~PHPOutputTransport() { } void write(const char* data, size_t len) { if ((len + buffer_used) > buffer_size) { @@ -234,32 +238,35 @@ protected: } } void directFlush() { - zval ret; + zval ret, flushfn; ZVAL_NULL(&ret); - zval flushfn; - ZVAL_STRING(&flushfn, "flush", 0); - TSRMLS_FETCH(); - call_user_function(EG(function_table), &t, &flushfn, &ret, 0, NULL TSRMLS_CC); - zval_dtor(&ret); - } - void directWrite(const char* data, size_t len) { - zval writefn; - ZVAL_STRING(&writefn, "write", 0); - char* newbuf = (char*)emalloc(len + 1); - memcpy(newbuf, data, len); - newbuf[len] = '\0'; - zval *args[1]; - MAKE_STD_ZVAL(args[0]); - ZVAL_STRINGL(args[0], newbuf, len, 0); - TSRMLS_FETCH(); - zval ret; - ZVAL_NULL(&ret); - call_user_function(EG(function_table), &t, &writefn, &ret, 1, args TSRMLS_CC); - zval_ptr_dtor(args); + ZVAL_STRING(&flushfn, "flush"); + + call_user_function(EG(function_table), &(this->t), &flushfn, &ret, 0, nullptr); + zval_dtor(&flushfn); zval_dtor(&ret); if (EG(exception)) { - zval* ex = EG(exception); - EG(exception) = NULL; + zend_object *ex = EG(exception); + EG(exception) = nullptr; + throw PHPExceptionWrapper(ex); + } + } + void directWrite(const char* data, size_t len) { + zval args[1], ret, writefn; + + ZVAL_STRING(&writefn, "write"); + ZVAL_STRINGL(&args[0], data, len); + + ZVAL_NULL(&ret); + call_user_function(EG(function_table), &(this->t), &writefn, &ret, 1, args); + + zval_dtor(&writefn); + zval_dtor(&ret); + zval_dtor(&args[0]); + + if (EG(exception)) { + zend_object *ex = EG(exception); + EG(exception) = nullptr; throw PHPExceptionWrapper(ex); } } @@ -267,8 +274,7 @@ protected: class PHPInputTransport : public PHPTransport { public: - PHPInputTransport(zval* _p, size_t _buffer_size = 8192) { - construct_with_zval(_p, _buffer_size); + PHPInputTransport(zval* _p, size_t _buffer_size = 8192) : PHPTransport(_p, _buffer_size) { } ~PHPInputTransport() { @@ -277,24 +283,21 @@ public: void put_back() { if (buffer_used) { - zval putbackfn; - ZVAL_STRING(&putbackfn, "putBack", 0); - - char* newbuf = (char*)emalloc(buffer_used + 1); - memcpy(newbuf, buffer_ptr, buffer_used); - newbuf[buffer_used] = '\0'; - - zval *args[1]; - MAKE_STD_ZVAL(args[0]); - ZVAL_STRINGL(args[0], newbuf, buffer_used, 0); - - TSRMLS_FETCH(); - - zval ret; + zval args[1], ret, putbackfn; + ZVAL_STRINGL(&args[0], buffer_ptr, buffer_used); + ZVAL_STRING(&putbackfn, "putBack"); ZVAL_NULL(&ret); - call_user_function(EG(function_table), &t, &putbackfn, &ret, 1, args TSRMLS_CC); - zval_ptr_dtor(args); + + call_user_function(EG(function_table), &(this->t), &putbackfn, &ret, 1, args); + + zval_dtor(&putbackfn); zval_dtor(&ret); + zval_dtor(&args[0]); + if (EG(exception)) { + zend_object *ex = EG(exception); + EG(exception) = nullptr; + throw PHPExceptionWrapper(ex); + } } buffer_used = 0; buffer_ptr = buffer; @@ -302,7 +305,7 @@ public: void skip(size_t len) { while (len) { - size_t chunk_size = MIN(len, buffer_used); + size_t chunk_size = (std::min)(len, buffer_used); if (chunk_size) { buffer_ptr = reinterpret_cast(buffer_ptr) + chunk_size; buffer_used -= chunk_size; @@ -315,7 +318,7 @@ public: void readBytes(void* buf, size_t len) { while (len) { - size_t chunk_size = MIN(len, buffer_used); + size_t chunk_size = (std::min)(len, buffer_used); if (chunk_size) { memcpy(buf, buffer_ptr, chunk_size); buffer_ptr = reinterpret_cast(buffer_ptr) + chunk_size; @@ -356,29 +359,29 @@ protected: void refill() { assert(buffer_used == 0); zval retval; - ZVAL_NULL(&retval); - - zval *args[1]; - MAKE_STD_ZVAL(args[0]); - ZVAL_LONG(args[0], buffer_size); - - TSRMLS_FETCH(); - + zval args[1]; zval funcname; - ZVAL_STRING(&funcname, "read", 0); - call_user_function(EG(function_table), &t, &funcname, &retval, 1, args TSRMLS_CC); - zval_ptr_dtor(args); + ZVAL_NULL(&retval); + ZVAL_LONG(&args[0], buffer_size); + + ZVAL_STRING(&funcname, "read"); + + call_user_function(EG(function_table), &(this->t), &funcname, &retval, 1, args); + zval_dtor(&args[0]); + zval_dtor(&funcname); if (EG(exception)) { zval_dtor(&retval); - zval* ex = EG(exception); - EG(exception) = NULL; + + zend_object *ex = EG(exception); + EG(exception) = nullptr; throw PHPExceptionWrapper(ex); } buffer_used = Z_STRLEN(retval); memcpy(buffer, Z_STRVAL(retval), buffer_used); + zval_dtor(&retval); buffer_ptr = buffer; @@ -386,222 +389,63 @@ protected: }; +static void binary_deserialize_spec(zval* zthis, PHPInputTransport& transport, HashTable* spec); +static void binary_serialize_spec(zval* zthis, PHPOutputTransport& transport, HashTable* spec); -void binary_serialize(int8_t thrift_typeID, PHPOutputTransport& transport, zval** value, HashTable* fieldspec); -void skip_element(long thrift_typeID, PHPInputTransport& transport); -void protocol_writeMessageBegin(zval *transport, const char* method_name, int32_t msgtype, int32_t seqID); - +static +void binary_serialize(int8_t thrift_typeID, PHPOutputTransport& transport, zval* value, HashTable* fieldspec); +static inline +bool ttype_is_scalar(int8_t t); // Create a PHP object given a typename and call the ctor, optionally passing up to 2 arguments -void createObject(const char* obj_typename, zval* return_value, int nargs = 0, zval* arg1 = NULL, zval* arg2 = NULL) { - TSRMLS_FETCH(); - size_t obj_typename_len = strlen(obj_typename); - zend_class_entry* ce = zend_fetch_class(obj_typename, obj_typename_len, ZEND_FETCH_CLASS_DEFAULT TSRMLS_CC); +static +void createObject(const char* obj_typename, zval* return_value, int nargs = 0, zval* arg1 = nullptr, zval* arg2 = nullptr) { + /* is there a better way to do that on the stack ? */ + zend_string *obj_name = zend_string_init(obj_typename, strlen(obj_typename), 0); + zend_class_entry* ce = zend_fetch_class(obj_name, ZEND_FETCH_CLASS_DEFAULT); + zend_string_release(obj_name); + if (! ce) { - php_error_docref(NULL TSRMLS_CC, E_ERROR, "Class %s does not exist", obj_typename); + php_error_docref(nullptr, E_ERROR, "Class %s does not exist", obj_typename); RETURN_NULL(); } - object_and_properties_init(return_value, ce, NULL); - zend_function* constructor = zend_std_get_constructor(return_value TSRMLS_CC); - zval* ctor_rv = NULL; - zend_call_method(&return_value, ce, &constructor, NULL, 0, &ctor_rv, nargs, arg1, arg2 TSRMLS_CC); - zval_ptr_dtor(&ctor_rv); + object_and_properties_init(return_value, ce, nullptr); + zend_function* constructor = zend_std_get_constructor(Z_OBJ_P(return_value)); + zval ctor_rv; + zend_call_method(return_value, ce, &constructor, NULL, 0, &ctor_rv, nargs, arg1, arg2); + zval_dtor(&ctor_rv); + if (EG(exception)) { + zend_object *ex = EG(exception); + EG(exception) = nullptr; + throw PHPExceptionWrapper(ex); + } } +static void throw_tprotocolexception(const char* what, long errorcode) { - TSRMLS_FETCH(); + zval zwhat, zerrorcode; - zval *zwhat, *zerrorcode; - MAKE_STD_ZVAL(zwhat); - MAKE_STD_ZVAL(zerrorcode); + ZVAL_STRING(&zwhat, what); + ZVAL_LONG(&zerrorcode, errorcode); - ZVAL_STRING(zwhat, what, 1); - ZVAL_LONG(zerrorcode, errorcode); + zval ex; + createObject("\\Thrift\\Exception\\TProtocolException", &ex, 2, &zwhat, &zerrorcode); - zval* ex; - MAKE_STD_ZVAL(ex); - createObject("\\Thrift\\Exception\\TProtocolException", ex, 2, zwhat, zerrorcode); - zval_ptr_dtor(&zwhat); - zval_ptr_dtor(&zerrorcode); - throw PHPExceptionWrapper(ex); + zval_dtor(&zwhat); + zval_dtor(&zerrorcode); + + throw PHPExceptionWrapper(&ex); } // Sets EG(exception), call this and then RETURN_NULL(); -void throw_zend_exception_from_std_exception(const std::exception& ex TSRMLS_DC) { - zend_throw_exception(zend_exception_get_default(TSRMLS_C), const_cast(ex.what()), 0 TSRMLS_CC); -} - - -void binary_deserialize(int8_t thrift_typeID, PHPInputTransport& transport, zval* return_value, HashTable* fieldspec) { - zval** val_ptr; - Z_TYPE_P(return_value) = IS_NULL; // just in case - - switch (thrift_typeID) { - case T_STOP: - case T_VOID: - RETURN_NULL(); - return; - case T_STRUCT: { - if (zend_hash_find(fieldspec, "class", 6, (void**)&val_ptr) != SUCCESS) { - throw_tprotocolexception("no class type in spec", INVALID_DATA); - skip_element(T_STRUCT, transport); - RETURN_NULL(); - } - char* structType = Z_STRVAL_PP(val_ptr); - createObject(structType, return_value); - if (Z_TYPE_P(return_value) == IS_NULL) { - // unable to create class entry - skip_element(T_STRUCT, transport); - RETURN_NULL(); - } - TSRMLS_FETCH(); - zval* spec = zend_read_static_property(zend_get_class_entry(return_value TSRMLS_CC), "_TSPEC", 6, false TSRMLS_CC); - if (Z_TYPE_P(spec) != IS_ARRAY) { - char errbuf[128]; - snprintf(errbuf, 128, "spec for %s is wrong type: %d\n", structType, Z_TYPE_P(spec)); - throw_tprotocolexception(errbuf, INVALID_DATA); - RETURN_NULL(); - } - binary_deserialize_spec(return_value, transport, Z_ARRVAL_P(spec)); - return; - } break; - case T_BOOL: { - uint8_t c; - transport.readBytes(&c, 1); - RETURN_BOOL(c != 0); - } - //case T_I08: // same numeric value as T_BYTE - case T_BYTE: { - uint8_t c; - transport.readBytes(&c, 1); - RETURN_LONG((int8_t)c); - } - case T_I16: { - uint16_t c; - transport.readBytes(&c, 2); - RETURN_LONG((int16_t)ntohs(c)); - } - case T_I32: { - uint32_t c; - transport.readBytes(&c, 4); - RETURN_LONG((int32_t)ntohl(c)); - } - case T_U64: - case T_I64: { - uint64_t c; - transport.readBytes(&c, 8); - RETURN_LONG((int64_t)ntohll(c)); - } - case T_DOUBLE: { - union { - uint64_t c; - double d; - } a; - transport.readBytes(&(a.c), 8); - a.c = ntohll(a.c); - RETURN_DOUBLE(a.d); - } - //case T_UTF7: // aliases T_STRING - case T_UTF8: - case T_UTF16: - case T_STRING: { - uint32_t size = transport.readU32(); - if (size) { - char* strbuf = (char*) emalloc(size + 1); - transport.readBytes(strbuf, size); - strbuf[size] = '\0'; - ZVAL_STRINGL(return_value, strbuf, size, 0); - } else { - ZVAL_EMPTY_STRING(return_value); - } - return; - } - case T_MAP: { // array of key -> value - uint8_t types[2]; - transport.readBytes(types, 2); - uint32_t size = transport.readU32(); - array_init(return_value); - - zend_hash_find(fieldspec, "key", 4, (void**)&val_ptr); - HashTable* keyspec = Z_ARRVAL_PP(val_ptr); - zend_hash_find(fieldspec, "val", 4, (void**)&val_ptr); - HashTable* valspec = Z_ARRVAL_PP(val_ptr); - - for (uint32_t s = 0; s < size; ++s) { - zval *value; - MAKE_STD_ZVAL(value); - - zval* key; - MAKE_STD_ZVAL(key); - - binary_deserialize(types[0], transport, key, keyspec); - binary_deserialize(types[1], transport, value, valspec); - if (Z_TYPE_P(key) == IS_LONG) { - zend_hash_index_update(return_value->value.ht, Z_LVAL_P(key), &value, sizeof(zval *), NULL); - } - else { - if (Z_TYPE_P(key) != IS_STRING) convert_to_string(key); - zend_hash_update(return_value->value.ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &value, sizeof(zval *), NULL); - } - zval_ptr_dtor(&key); - } - return; // return_value already populated - } - case T_LIST: { // array with autogenerated numeric keys - int8_t type = transport.readI8(); - uint32_t size = transport.readU32(); - zend_hash_find(fieldspec, "elem", 5, (void**)&val_ptr); - HashTable* elemspec = Z_ARRVAL_PP(val_ptr); - - array_init(return_value); - for (uint32_t s = 0; s < size; ++s) { - zval *value; - MAKE_STD_ZVAL(value); - binary_deserialize(type, transport, value, elemspec); - zend_hash_next_index_insert(return_value->value.ht, &value, sizeof(zval *), NULL); - } - return; - } - case T_SET: { // array of key -> TRUE - uint8_t type; - uint32_t size; - transport.readBytes(&type, 1); - transport.readBytes(&size, 4); - size = ntohl(size); - zend_hash_find(fieldspec, "elem", 5, (void**)&val_ptr); - HashTable* elemspec = Z_ARRVAL_PP(val_ptr); - - array_init(return_value); - - for (uint32_t s = 0; s < size; ++s) { - zval* key; - zval* value; - MAKE_STD_ZVAL(key); - MAKE_STD_ZVAL(value); - ZVAL_TRUE(value); - - binary_deserialize(type, transport, key, elemspec); - - if (Z_TYPE_P(key) == IS_LONG) { - zend_hash_index_update(return_value->value.ht, Z_LVAL_P(key), &value, sizeof(zval *), NULL); - } - else { - if (Z_TYPE_P(key) != IS_STRING) convert_to_string(key); - zend_hash_update(return_value->value.ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &value, sizeof(zval *), NULL); - } - zval_ptr_dtor(&key); - } - return; - } - }; - - char errbuf[128]; - sprintf(errbuf, "Unknown thrift typeID %d", thrift_typeID); - throw_tprotocolexception(errbuf, INVALID_DATA); +static +void throw_zend_exception_from_std_exception(const std::exception& ex) { + zend_throw_exception(zend_exception_get_default(), const_cast(ex.what()), 0); } +static void skip_element(long thrift_typeID, PHPInputTransport& transport) { switch (thrift_typeID) { case T_STOP: @@ -661,101 +505,472 @@ void skip_element(long thrift_typeID, PHPInputTransport& transport) { throw_tprotocolexception(errbuf, INVALID_DATA); } -void protocol_writeMessageBegin(zval* transport, const char* method_name, int32_t msgtype, int32_t seqID) { - TSRMLS_FETCH(); - zval *args[3]; - - MAKE_STD_ZVAL(args[0]); - ZVAL_STRINGL(args[0], (char*)method_name, strlen(method_name), 1); - - MAKE_STD_ZVAL(args[1]); - ZVAL_LONG(args[1], msgtype); - - MAKE_STD_ZVAL(args[2]); - ZVAL_LONG(args[2], seqID); - - zval ret; - ZVAL_NULL(&ret); - - zval writeMessagefn; - ZVAL_STRING(&writeMessagefn, "writeMessageBegin", 0); - - call_user_function(EG(function_table), &transport, &writeMessagefn, &ret, 3, args TSRMLS_CC); - - zval_ptr_dtor(&args[0]); - zval_ptr_dtor(&args[1]); - zval_ptr_dtor(&args[2]); - zval_dtor(&ret); +static inline +bool zval_is_bool(zval* v) { + return Z_TYPE_P(v) == IS_TRUE || Z_TYPE_P(v) == IS_FALSE; } -void binary_serialize_hashtable_key(int8_t keytype, PHPOutputTransport& transport, HashTable* ht, HashPosition& ht_pos) { +static +void binary_deserialize(int8_t thrift_typeID, PHPInputTransport& transport, zval* return_value, HashTable* fieldspec) { + ZVAL_NULL(return_value); + + switch (thrift_typeID) { + case T_STOP: + case T_VOID: + RETURN_NULL(); + return; + case T_STRUCT: { + zval* val_ptr = zend_hash_str_find(fieldspec, "class", sizeof("class")-1); + if (val_ptr == nullptr) { + throw_tprotocolexception("no class type in spec", INVALID_DATA); + skip_element(T_STRUCT, transport); + RETURN_NULL(); + } + + char* structType = Z_STRVAL_P(val_ptr); + // Create an object in PHP userland based on our spec + createObject(structType, return_value); + if (Z_TYPE_P(return_value) == IS_NULL) { + // unable to create class entry + skip_element(T_STRUCT, transport); + RETURN_NULL(); + } + + zval* spec = zend_read_static_property(Z_OBJCE_P(return_value), "_TSPEC", sizeof("_TSPEC")-1, false); + ZVAL_DEREF(spec); + if (EG(exception)) { + zend_object *ex = EG(exception); + EG(exception) = nullptr; + throw PHPExceptionWrapper(ex); + } + if (Z_TYPE_P(spec) != IS_ARRAY) { + char errbuf[128]; + snprintf(errbuf, 128, "spec for %s is wrong type: %d\n", structType, Z_TYPE_P(spec)); + throw_tprotocolexception(errbuf, INVALID_DATA); + RETURN_NULL(); + } + binary_deserialize_spec(return_value, transport, Z_ARRVAL_P(spec)); + return; + } break; + case T_BOOL: { + uint8_t c; + transport.readBytes(&c, 1); + RETURN_BOOL(c != 0); + } + //case T_I08: // same numeric value as T_BYTE + case T_BYTE: { + uint8_t c; + transport.readBytes(&c, 1); + RETURN_LONG((int8_t)c); + } + case T_I16: { + uint16_t c; + transport.readBytes(&c, 2); + RETURN_LONG((int16_t)ntohs(c)); + } + case T_I32: { + uint32_t c; + transport.readBytes(&c, 4); + RETURN_LONG((int32_t)ntohl(c)); + } + case T_U64: + case T_I64: { + uint64_t c; + transport.readBytes(&c, 8); + RETURN_LONG((int64_t)ntohll(c)); + } + case T_DOUBLE: { + union { + uint64_t c; + double d; + } a; + transport.readBytes(&(a.c), 8); + a.c = ntohll(a.c); + RETURN_DOUBLE(a.d); + } + //case T_UTF7: // aliases T_STRING + case T_UTF8: + case T_UTF16: + case T_STRING: { + uint32_t size = transport.readU32(); + if (size) { + char strbuf[size+1]; + transport.readBytes(strbuf, size); + strbuf[size] = '\0'; + ZVAL_STRINGL(return_value, strbuf, size); + } else { + ZVAL_EMPTY_STRING(return_value); + } + return; + } + case T_MAP: { // array of key -> value + uint8_t types[2]; + transport.readBytes(types, 2); + uint32_t size = transport.readU32(); + array_init(return_value); + + zval *val_ptr; + val_ptr = zend_hash_str_find(fieldspec, "key", sizeof("key")-1); + HashTable* keyspec = Z_ARRVAL_P(val_ptr); + val_ptr = zend_hash_str_find(fieldspec, "val", sizeof("val")-1); + HashTable* valspec = Z_ARRVAL_P(val_ptr); + + for (uint32_t s = 0; s < size; ++s) { + zval key, value; + + binary_deserialize(types[0], transport, &key, keyspec); + binary_deserialize(types[1], transport, &value, valspec); + if (Z_TYPE(key) == IS_LONG) { + zend_hash_index_update(Z_ARR_P(return_value), Z_LVAL(key), &value); + } else { + if (Z_TYPE(key) != IS_STRING) convert_to_string(&key); + zend_symtable_update(Z_ARR_P(return_value), Z_STR(key), &value); + } + zval_dtor(&key); + } + return; // return_value already populated + } + case T_LIST: { // array with autogenerated numeric keys + int8_t type = transport.readI8(); + uint32_t size = transport.readU32(); + zval *val_ptr = zend_hash_str_find(fieldspec, "elem", sizeof("elem")-1); + HashTable* elemspec = Z_ARRVAL_P(val_ptr); + + array_init(return_value); + for (uint32_t s = 0; s < size; ++s) { + zval value; + binary_deserialize(type, transport, &value, elemspec); + zend_hash_next_index_insert(Z_ARR_P(return_value), &value); + } + return; + } + case T_SET: { // array of key -> TRUE + uint8_t type; + uint32_t size; + transport.readBytes(&type, 1); + transport.readBytes(&size, 4); + size = ntohl(size); + zval *val_ptr = zend_hash_str_find(fieldspec, "elem", sizeof("elem")-1); + HashTable* elemspec = Z_ARRVAL_P(val_ptr); + + array_init(return_value); + + for (uint32_t s = 0; s < size; ++s) { + zval key, value; + ZVAL_TRUE(&value); + + binary_deserialize(type, transport, &key, elemspec); + + if (Z_TYPE(key) == IS_LONG) { + zend_hash_index_update(Z_ARR_P(return_value), Z_LVAL(key), &value); + } else { + if (Z_TYPE(key) != IS_STRING) convert_to_string(&key); + zend_symtable_update(Z_ARR_P(return_value), Z_STR(key), &value); + } + zval_dtor(&key); + } + return; + } + }; + + char errbuf[128]; + sprintf(errbuf, "Unknown thrift typeID %d", thrift_typeID); + throw_tprotocolexception(errbuf, INVALID_DATA); +} + +static +void binary_serialize_hashtable_key(int8_t keytype, PHPOutputTransport& transport, HashTable* ht, HashPosition& ht_pos, HashTable* spec) { bool keytype_is_numeric = (!((keytype == T_STRING) || (keytype == T_UTF8) || (keytype == T_UTF16))); - char* key; + zend_string* key; uint key_len; long index = 0; - zval* z; - MAKE_STD_ZVAL(z); + zval z; - int res = zend_hash_get_current_key_ex(ht, &key, &key_len, (ulong*)&index, 0, &ht_pos); - if (keytype_is_numeric) { - if (res == HASH_KEY_IS_STRING) { - index = strtol(key, NULL, 10); - } - ZVAL_LONG(z, index); + int res = zend_hash_get_current_key_ex(ht, &key, (zend_ulong*)&index, &ht_pos); + if (res == HASH_KEY_IS_STRING) { + ZVAL_STR_COPY(&z, key); } else { - char buf[64]; - if (res == HASH_KEY_IS_STRING) { - key_len -= 1; // skip the null terminator - } else { - sprintf(buf, "%ld", index); - key = buf; key_len = strlen(buf); - } - ZVAL_STRINGL(z, key, key_len, 1); + ZVAL_LONG(&z, index); } - binary_serialize(keytype, transport, &z, NULL); - zval_ptr_dtor(&z); + binary_serialize(keytype, transport, &z, spec); + zval_dtor(&z); } -inline bool ttype_is_int(int8_t t) { +static +void binary_serialize(int8_t thrift_typeID, PHPOutputTransport& transport, zval* value, HashTable* fieldspec) { + if (value) { + ZVAL_DEREF(value); + } + // At this point the typeID (and field num, if applicable) should've already been written to the output so all we need to do is write the payload. + switch (thrift_typeID) { + case T_STOP: + case T_VOID: + return; + case T_STRUCT: { + if (Z_TYPE_P(value) != IS_OBJECT) { + throw_tprotocolexception("Attempt to send non-object type as a T_STRUCT", INVALID_DATA); + } + zval* spec = zend_read_static_property(Z_OBJCE_P(value), "_TSPEC", sizeof("_TSPEC")-1, true); + if (spec && Z_TYPE_P(spec) == IS_REFERENCE) { + ZVAL_DEREF(spec); + } + if (!spec || Z_TYPE_P(spec) != IS_ARRAY) { + throw_tprotocolexception("Attempt to send non-Thrift object as a T_STRUCT", INVALID_DATA); + } + binary_serialize_spec(value, transport, Z_ARRVAL_P(spec)); + } return; + case T_BOOL: + if (!zval_is_bool(value)) convert_to_boolean(value); + transport.writeI8(Z_TYPE_INFO_P(value) == IS_TRUE ? 1 : 0); + return; + case T_BYTE: + if (Z_TYPE_P(value) != IS_LONG) convert_to_long(value); + transport.writeI8(Z_LVAL_P(value)); + return; + case T_I16: + if (Z_TYPE_P(value) != IS_LONG) convert_to_long(value); + transport.writeI16(Z_LVAL_P(value)); + return; + case T_I32: + if (Z_TYPE_P(value) != IS_LONG) convert_to_long(value); + transport.writeI32(Z_LVAL_P(value)); + return; + case T_I64: + case T_U64: { + int64_t l_data; +#if defined(_LP64) || defined(_WIN64) + if (Z_TYPE_P(value) != IS_LONG) convert_to_long(value); + l_data = Z_LVAL_P(value); +#else + if (Z_TYPE_P(value) != IS_DOUBLE) convert_to_double(value); + l_data = (int64_t)Z_DVAL_P(value); +#endif + transport.writeI64(l_data); + } return; + case T_DOUBLE: { + union { + int64_t c; + double d; + } a; + if (Z_TYPE_P(value) != IS_DOUBLE) convert_to_double(value); + a.d = Z_DVAL_P(value); + transport.writeI64(a.c); + } return; + case T_UTF8: + case T_UTF16: + case T_STRING: + if (Z_TYPE_P(value) != IS_STRING) convert_to_string(value); + transport.writeString(Z_STRVAL_P(value), Z_STRLEN_P(value)); + return; + case T_MAP: { + if (Z_TYPE_P(value) != IS_ARRAY) convert_to_array(value); + if (Z_TYPE_P(value) != IS_ARRAY) { + throw_tprotocolexception("Attempt to send an incompatible type as an array (T_MAP)", INVALID_DATA); + } + HashTable* ht = Z_ARRVAL_P(value); + zval* val_ptr; + + val_ptr = zend_hash_str_find(fieldspec, "ktype", sizeof("ktype")-1); + if (Z_TYPE_P(val_ptr) != IS_LONG) convert_to_long(val_ptr); + uint8_t keytype = Z_LVAL_P(val_ptr); + transport.writeI8(keytype); + val_ptr = zend_hash_str_find(fieldspec, "vtype", sizeof("vtype")-1); + if (Z_TYPE_P(val_ptr) != IS_LONG) convert_to_long(val_ptr); + uint8_t valtype = Z_LVAL_P(val_ptr); + transport.writeI8(valtype); + + val_ptr = zend_hash_str_find(fieldspec, "val", sizeof("val")-1); + HashTable* valspec = Z_ARRVAL_P(val_ptr); + HashTable* keyspec = Z_ARRVAL_P(zend_hash_str_find(fieldspec, "key", sizeof("key")-1)); + + transport.writeI32(zend_hash_num_elements(ht)); + HashPosition key_ptr; + for (zend_hash_internal_pointer_reset_ex(ht, &key_ptr); + (val_ptr = zend_hash_get_current_data_ex(ht, &key_ptr)) != nullptr; + zend_hash_move_forward_ex(ht, &key_ptr)) { + binary_serialize_hashtable_key(keytype, transport, ht, key_ptr, keyspec); + binary_serialize(valtype, transport, val_ptr, valspec); + } + } return; + case T_LIST: { + if (Z_TYPE_P(value) != IS_ARRAY) convert_to_array(value); + if (Z_TYPE_P(value) != IS_ARRAY) { + throw_tprotocolexception("Attempt to send an incompatible type as an array (T_LIST)", INVALID_DATA); + } + HashTable* ht = Z_ARRVAL_P(value); + zval* val_ptr; + + val_ptr = zend_hash_str_find(fieldspec, "etype", sizeof("etype")-1); + if (Z_TYPE_P(val_ptr) != IS_LONG) convert_to_long(val_ptr); + uint8_t valtype = Z_LVAL_P(val_ptr); + transport.writeI8(valtype); + + val_ptr = zend_hash_str_find(fieldspec, "elem", sizeof("elem")-1); + HashTable* valspec = Z_ARRVAL_P(val_ptr); + + transport.writeI32(zend_hash_num_elements(ht)); + HashPosition key_ptr; + for (zend_hash_internal_pointer_reset_ex(ht, &key_ptr); + (val_ptr = zend_hash_get_current_data_ex(ht, &key_ptr)) != nullptr; + zend_hash_move_forward_ex(ht, &key_ptr)) { + binary_serialize(valtype, transport, val_ptr, valspec); + } + } return; + case T_SET: { + if (Z_TYPE_P(value) != IS_ARRAY) convert_to_array(value); + if (Z_TYPE_P(value) != IS_ARRAY) { + throw_tprotocolexception("Attempt to send an incompatible type as an array (T_SET)", INVALID_DATA); + } + HashTable* ht = Z_ARRVAL_P(value); + zval* val_ptr; + + val_ptr = zend_hash_str_find(fieldspec, "etype", sizeof("etype")-1); + HashTable* spec = Z_ARRVAL_P(zend_hash_str_find(fieldspec, "elem", sizeof("elem")-1)); + if (Z_TYPE_P(val_ptr) != IS_LONG) convert_to_long(val_ptr); + uint8_t keytype = Z_LVAL_P(val_ptr); + transport.writeI8(keytype); + + transport.writeI32(zend_hash_num_elements(ht)); + HashPosition key_ptr; + if(ttype_is_scalar(keytype)){ + for (zend_hash_internal_pointer_reset_ex(ht, &key_ptr); + (val_ptr = zend_hash_get_current_data_ex(ht, &key_ptr)) != nullptr; + zend_hash_move_forward_ex(ht, &key_ptr)) { + binary_serialize_hashtable_key(keytype, transport, ht, key_ptr, spec); + } + } else { + for (zend_hash_internal_pointer_reset_ex(ht, &key_ptr); + (val_ptr = zend_hash_get_current_data_ex(ht, &key_ptr)) != nullptr; + zend_hash_move_forward_ex(ht, &key_ptr)) { + binary_serialize(keytype, transport, val_ptr, spec); + } + } + } return; + }; + + char errbuf[128]; + snprintf(errbuf, 128, "Unknown thrift typeID %d", thrift_typeID); + throw_tprotocolexception(errbuf, INVALID_DATA); +} + +static +void protocol_writeMessageBegin(zval* transport, zend_string* method_name, int32_t msgtype, int32_t seqID) { + zval args[3]; + zval ret; + zval writeMessagefn; + + ZVAL_STR_COPY(&args[0], method_name); + ZVAL_LONG(&args[1], msgtype); + ZVAL_LONG(&args[2], seqID); + ZVAL_NULL(&ret); + ZVAL_STRING(&writeMessagefn, "writeMessageBegin"); + + call_user_function(EG(function_table), transport, &writeMessagefn, &ret, 3, args); + + zval_dtor(&writeMessagefn); + zval_dtor(&args[2]); zval_dtor(&args[1]); zval_dtor(&args[0]); + zval_dtor(&ret); + if (EG(exception)) { + zend_object *ex = EG(exception); + EG(exception) = nullptr; + throw PHPExceptionWrapper(ex); + } +} + +static inline +bool ttype_is_int(int8_t t) { return ((t == T_BYTE) || ((t >= T_I16) && (t <= T_I64))); } +static inline +bool ttype_is_scalar(int8_t t) { + return !((t == T_STRUCT) || ( t== T_MAP) || (t == T_SET) || (t == T_LIST)); +} -inline bool ttypes_are_compatible(int8_t t1, int8_t t2) { +static inline +bool ttypes_are_compatible(int8_t t1, int8_t t2) { // Integer types of different widths are considered compatible; // otherwise the typeID must match. return ((t1 == t2) || (ttype_is_int(t1) && ttype_is_int(t2))); } +//is used to validate objects before serialization and after deserialization. For now, only required fields are validated. +static +void validate_thrift_object(zval* object) { + zend_class_entry* object_class_entry = Z_OBJCE_P(object); + zval* is_validate = zend_read_static_property(object_class_entry, "isValidate", sizeof("isValidate")-1, true); + if (is_validate) { + ZVAL_DEREF(is_validate); + } + zval* spec = zend_read_static_property(object_class_entry, "_TSPEC", sizeof("_TSPEC")-1, true); + if (spec) { + ZVAL_DEREF(spec); + } + HashPosition key_ptr; + zval* val_ptr; + + if (is_validate && Z_TYPE_INFO_P(is_validate) == IS_TRUE) { + for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(spec), &key_ptr); + (val_ptr = zend_hash_get_current_data_ex(Z_ARRVAL_P(spec), &key_ptr)) != nullptr; + zend_hash_move_forward_ex(Z_ARRVAL_P(spec), &key_ptr)) { + + zend_ulong fieldno; + if (zend_hash_get_current_key_ex(Z_ARRVAL_P(spec), nullptr, &fieldno, &key_ptr) != HASH_KEY_IS_LONG) { + throw_tprotocolexception("Bad keytype in TSPEC (expected 'long')", INVALID_DATA); + return; + } + HashTable* fieldspec = Z_ARRVAL_P(val_ptr); + + // field name + zval* zvarname = zend_hash_str_find(fieldspec, "var", sizeof("var")-1); + char* varname = Z_STRVAL_P(zvarname); + + zval* is_required = zend_hash_str_find(fieldspec, "isRequired", sizeof("isRequired")-1); + zval rv; + zval* prop = zend_read_property(object_class_entry, object, varname, strlen(varname), false, &rv); + + if (Z_TYPE_INFO_P(is_required) == IS_TRUE && Z_TYPE_P(prop) == IS_NULL) { + char errbuf[128]; + snprintf(errbuf, 128, "Required field %s.%s is unset!", ZSTR_VAL(object_class_entry->name), varname); + throw_tprotocolexception(errbuf, INVALID_DATA); + } + } + } +} + +static void binary_deserialize_spec(zval* zthis, PHPInputTransport& transport, HashTable* spec) { // SET and LIST have 'elem' => array('type', [optional] 'class') // MAP has 'val' => array('type', [optiona] 'class') - TSRMLS_FETCH(); - zend_class_entry* ce = zend_get_class_entry(zthis TSRMLS_CC); + zend_class_entry* ce = Z_OBJCE_P(zthis); while (true) { - zval** val_ptr = NULL; - int8_t ttype = transport.readI8(); - if (ttype == T_STOP) return; + if (ttype == T_STOP) { + validate_thrift_object(zthis); + return; + } + int16_t fieldno = transport.readI16(); - if (zend_hash_index_find(spec, fieldno, (void**)&val_ptr) == SUCCESS) { - HashTable* fieldspec = Z_ARRVAL_PP(val_ptr); + zval* val_ptr = zend_hash_index_find(spec, fieldno); + if (val_ptr != nullptr) { + HashTable* fieldspec = Z_ARRVAL_P(val_ptr); // pull the field name - // zend hash tables use the null at the end in the length... so strlen(hash key) + 1. - zend_hash_find(fieldspec, "var", 4, (void**)&val_ptr); - char* varname = Z_STRVAL_PP(val_ptr); + val_ptr = zend_hash_str_find(fieldspec, "var", sizeof("var")-1); + char* varname = Z_STRVAL_P(val_ptr); // and the type - zend_hash_find(fieldspec, "type", 5, (void**)&val_ptr); - if (Z_TYPE_PP(val_ptr) != IS_LONG) convert_to_long(*val_ptr); - int8_t expected_ttype = Z_LVAL_PP(val_ptr); + val_ptr = zend_hash_str_find(fieldspec, "type", sizeof("type")-1); + if (Z_TYPE_P(val_ptr) != IS_LONG) convert_to_long(val_ptr); + int8_t expected_ttype = Z_LVAL_P(val_ptr); if (ttypes_are_compatible(ttype, expected_ttype)) { - zval* rv = NULL; - MAKE_STD_ZVAL(rv); - binary_deserialize(ttype, transport, rv, fieldspec); - zend_update_property(ce, zthis, varname, strlen(varname), rv TSRMLS_CC); + zval rv; + ZVAL_UNDEF(&rv); + + binary_deserialize(ttype, transport, &rv, fieldspec); + zend_update_property(ce, zthis, varname, strlen(varname), &rv); + zval_ptr_dtor(&rv); } else { skip_element(ttype, transport); @@ -766,171 +981,44 @@ void binary_deserialize_spec(zval* zthis, PHPInputTransport& transport, HashTabl } } -void binary_serialize(int8_t thrift_typeID, PHPOutputTransport& transport, zval** value, HashTable* fieldspec) { - // At this point the typeID (and field num, if applicable) should've already been written to the output so all we need to do is write the payload. - switch (thrift_typeID) { - case T_STOP: - case T_VOID: - return; - case T_STRUCT: { - TSRMLS_FETCH(); - if (Z_TYPE_PP(value) != IS_OBJECT) { - throw_tprotocolexception("Attempt to send non-object type as a T_STRUCT", INVALID_DATA); - } - zval* spec = zend_read_static_property(zend_get_class_entry(*value TSRMLS_CC), "_TSPEC", 6, false TSRMLS_CC); - if (Z_TYPE_P(spec) != IS_ARRAY) { - throw_tprotocolexception("Attempt to send non-Thrift object as a T_STRUCT", INVALID_DATA); - } - binary_serialize_spec(*value, transport, Z_ARRVAL_P(spec)); - } return; - case T_BOOL: - if (Z_TYPE_PP(value) != IS_BOOL) convert_to_boolean(*value); - transport.writeI8(Z_BVAL_PP(value) ? 1 : 0); - return; - case T_BYTE: - if (Z_TYPE_PP(value) != IS_LONG) convert_to_long(*value); - transport.writeI8(Z_LVAL_PP(value)); - return; - case T_I16: - if (Z_TYPE_PP(value) != IS_LONG) convert_to_long(*value); - transport.writeI16(Z_LVAL_PP(value)); - return; - case T_I32: - if (Z_TYPE_PP(value) != IS_LONG) convert_to_long(*value); - transport.writeI32(Z_LVAL_PP(value)); - return; - case T_I64: - case T_U64: { - int64_t l_data; -#if defined(_LP64) || defined(_WIN64) - if (Z_TYPE_PP(value) != IS_LONG) convert_to_long(*value); - l_data = Z_LVAL_PP(value); -#else - if (Z_TYPE_PP(value) != IS_DOUBLE) convert_to_double(*value); - l_data = (int64_t)Z_DVAL_PP(value); -#endif - transport.writeI64(l_data); - } return; - case T_DOUBLE: { - union { - int64_t c; - double d; - } a; - if (Z_TYPE_PP(value) != IS_DOUBLE) convert_to_double(*value); - a.d = Z_DVAL_PP(value); - transport.writeI64(a.c); - } return; - //case T_UTF7: - case T_UTF8: - case T_UTF16: - case T_STRING: - if (Z_TYPE_PP(value) != IS_STRING) convert_to_string(*value); - transport.writeString(Z_STRVAL_PP(value), Z_STRLEN_PP(value)); - return; - case T_MAP: { - if (Z_TYPE_PP(value) != IS_ARRAY) convert_to_array(*value); - if (Z_TYPE_PP(value) != IS_ARRAY) { - throw_tprotocolexception("Attempt to send an incompatible type as an array (T_MAP)", INVALID_DATA); - } - HashTable* ht = Z_ARRVAL_PP(value); - zval** val_ptr; - - zend_hash_find(fieldspec, "ktype", 6, (void**)&val_ptr); - if (Z_TYPE_PP(val_ptr) != IS_LONG) convert_to_long(*val_ptr); - uint8_t keytype = Z_LVAL_PP(val_ptr); - transport.writeI8(keytype); - zend_hash_find(fieldspec, "vtype", 6, (void**)&val_ptr); - if (Z_TYPE_PP(val_ptr) != IS_LONG) convert_to_long(*val_ptr); - uint8_t valtype = Z_LVAL_PP(val_ptr); - transport.writeI8(valtype); - - zend_hash_find(fieldspec, "val", 4, (void**)&val_ptr); - HashTable* valspec = Z_ARRVAL_PP(val_ptr); - - transport.writeI32(zend_hash_num_elements(ht)); - HashPosition key_ptr; - for (zend_hash_internal_pointer_reset_ex(ht, &key_ptr); zend_hash_get_current_data_ex(ht, (void**)&val_ptr, &key_ptr) == SUCCESS; zend_hash_move_forward_ex(ht, &key_ptr)) { - binary_serialize_hashtable_key(keytype, transport, ht, key_ptr); - binary_serialize(valtype, transport, val_ptr, valspec); - } - } return; - case T_LIST: { - if (Z_TYPE_PP(value) != IS_ARRAY) convert_to_array(*value); - if (Z_TYPE_PP(value) != IS_ARRAY) { - throw_tprotocolexception("Attempt to send an incompatible type as an array (T_LIST)", INVALID_DATA); - } - HashTable* ht = Z_ARRVAL_PP(value); - zval** val_ptr; - - zend_hash_find(fieldspec, "etype", 6, (void**)&val_ptr); - if (Z_TYPE_PP(val_ptr) != IS_LONG) convert_to_long(*val_ptr); - uint8_t valtype = Z_LVAL_PP(val_ptr); - transport.writeI8(valtype); - - zend_hash_find(fieldspec, "elem", 5, (void**)&val_ptr); - HashTable* valspec = Z_ARRVAL_PP(val_ptr); - - transport.writeI32(zend_hash_num_elements(ht)); - HashPosition key_ptr; - for (zend_hash_internal_pointer_reset_ex(ht, &key_ptr); zend_hash_get_current_data_ex(ht, (void**)&val_ptr, &key_ptr) == SUCCESS; zend_hash_move_forward_ex(ht, &key_ptr)) { - binary_serialize(valtype, transport, val_ptr, valspec); - } - } return; - case T_SET: { - if (Z_TYPE_PP(value) != IS_ARRAY) convert_to_array(*value); - if (Z_TYPE_PP(value) != IS_ARRAY) { - throw_tprotocolexception("Attempt to send an incompatible type as an array (T_SET)", INVALID_DATA); - } - HashTable* ht = Z_ARRVAL_PP(value); - zval** val_ptr; - - zend_hash_find(fieldspec, "etype", 6, (void**)&val_ptr); - if (Z_TYPE_PP(val_ptr) != IS_LONG) convert_to_long(*val_ptr); - uint8_t keytype = Z_LVAL_PP(val_ptr); - transport.writeI8(keytype); - - transport.writeI32(zend_hash_num_elements(ht)); - HashPosition key_ptr; - for (zend_hash_internal_pointer_reset_ex(ht, &key_ptr); zend_hash_get_current_data_ex(ht, (void**)&val_ptr, &key_ptr) == SUCCESS; zend_hash_move_forward_ex(ht, &key_ptr)) { - binary_serialize_hashtable_key(keytype, transport, ht, key_ptr); - } - } return; - }; - char errbuf[128]; - sprintf(errbuf, "Unknown thrift typeID %d", thrift_typeID); - throw_tprotocolexception(errbuf, INVALID_DATA); -} - - +static void binary_serialize_spec(zval* zthis, PHPOutputTransport& transport, HashTable* spec) { + + validate_thrift_object(zthis); + HashPosition key_ptr; - zval** val_ptr; + zval* val_ptr; - TSRMLS_FETCH(); - zend_class_entry* ce = zend_get_class_entry(zthis TSRMLS_CC); + for (zend_hash_internal_pointer_reset_ex(spec, &key_ptr); + (val_ptr = zend_hash_get_current_data_ex(spec, &key_ptr)) != nullptr; + zend_hash_move_forward_ex(spec, &key_ptr)) { - for (zend_hash_internal_pointer_reset_ex(spec, &key_ptr); zend_hash_get_current_data_ex(spec, (void**)&val_ptr, &key_ptr) == SUCCESS; zend_hash_move_forward_ex(spec, &key_ptr)) { - ulong fieldno; - if (zend_hash_get_current_key_ex(spec, NULL, NULL, &fieldno, 0, &key_ptr) != HASH_KEY_IS_LONG) { + zend_ulong fieldno; + if (zend_hash_get_current_key_ex(spec, nullptr, &fieldno, &key_ptr) != HASH_KEY_IS_LONG) { throw_tprotocolexception("Bad keytype in TSPEC (expected 'long')", INVALID_DATA); return; } - HashTable* fieldspec = Z_ARRVAL_PP(val_ptr); + HashTable* fieldspec = Z_ARRVAL_P(val_ptr); // field name - zend_hash_find(fieldspec, "var", 4, (void**)&val_ptr); - char* varname = Z_STRVAL_PP(val_ptr); + val_ptr = zend_hash_str_find(fieldspec, "var", sizeof("var")-1); + char* varname = Z_STRVAL_P(val_ptr); // thrift type - zend_hash_find(fieldspec, "type", 5, (void**)&val_ptr); - if (Z_TYPE_PP(val_ptr) != IS_LONG) convert_to_long(*val_ptr); - int8_t ttype = Z_LVAL_PP(val_ptr); + val_ptr = zend_hash_str_find(fieldspec, "type", sizeof("type")-1); + if (Z_TYPE_P(val_ptr) != IS_LONG) convert_to_long(val_ptr); + int8_t ttype = Z_LVAL_P(val_ptr); - zval* prop = zend_read_property(ce, zthis, varname, strlen(varname), false TSRMLS_CC); + zval rv; + zval* prop = zend_read_property(Z_OBJCE_P(zthis), zthis, varname, strlen(varname), false, &rv); + + if (Z_TYPE_P(prop) == IS_REFERENCE){ + ZVAL_UNREF(prop); + } if (Z_TYPE_P(prop) != IS_NULL) { transport.writeI8(ttype); transport.writeI16(fieldno); - binary_serialize(ttype, transport, &prop, fieldspec); + binary_serialize(ttype, transport, prop, fieldspec); } } transport.writeI8(T_STOP); // struct end @@ -938,104 +1026,59 @@ void binary_serialize_spec(zval* zthis, PHPOutputTransport& transport, HashTable // 6 params: $transport $method_name $ttype $request_struct $seqID $strict_write PHP_FUNCTION(thrift_protocol_write_binary) { - int argc = ZEND_NUM_ARGS(); - if (argc < 6) { - WRONG_PARAM_COUNT; + zval *protocol; + zval *request_struct; + zend_string *method_name; + long msgtype, seqID; + zend_bool strict_write; + + if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "oSlolb", + &protocol, &method_name, &msgtype, + &request_struct, &seqID, &strict_write) == FAILURE) { + return; } - zval ***args = (zval***) emalloc(argc * sizeof(zval**)); - zend_get_parameters_array_ex(argc, args); - - if (Z_TYPE_PP(args[0]) != IS_OBJECT) { - php_error_docref(NULL TSRMLS_CC, E_ERROR, "1st parameter is not an object (transport)"); - efree(args); - RETURN_NULL(); - } - - if (Z_TYPE_PP(args[1]) != IS_STRING) { - php_error_docref(NULL TSRMLS_CC, E_ERROR, "2nd parameter is not a string (method name)"); - efree(args); - RETURN_NULL(); - } - - if (Z_TYPE_PP(args[3]) != IS_OBJECT) { - php_error_docref(NULL TSRMLS_CC, E_ERROR, "4th parameter is not an object (request struct)"); - efree(args); - RETURN_NULL(); - } - - try { - PHPOutputTransport transport(*args[0]); - zval *protocol = *args[0]; - const char* method_name = Z_STRVAL_PP(args[1]); - convert_to_long(*args[2]); - int32_t msgtype = Z_LVAL_PP(args[2]); - zval* request_struct = *args[3]; - convert_to_long(*args[4]); - int32_t seqID = Z_LVAL_PP(args[4]); - convert_to_boolean(*args[5]); - bool strictWrite = Z_BVAL_PP(args[5]); - efree(args); - args = NULL; - protocol_writeMessageBegin(protocol, method_name, msgtype, seqID); - zval* spec = zend_read_static_property(zend_get_class_entry(request_struct TSRMLS_CC), "_TSPEC", 6, false TSRMLS_CC); - if (Z_TYPE_P(spec) != IS_ARRAY) { - throw_tprotocolexception("Attempt to send non-Thrift object", INVALID_DATA); + zval* spec = zend_read_static_property(Z_OBJCE_P(request_struct), "_TSPEC", sizeof("_TSPEC")-1, true); + if (spec) { + ZVAL_DEREF(spec); } + + if (!spec || Z_TYPE_P(spec) != IS_ARRAY) { + throw_tprotocolexception("Attempt serialize from non-Thrift object", INVALID_DATA); + } + + PHPOutputTransport transport(protocol); + protocol_writeMessageBegin(protocol, method_name, (int32_t) msgtype, (int32_t) seqID); binary_serialize_spec(request_struct, transport, Z_ARRVAL_P(spec)); transport.flush(); + } catch (const PHPExceptionWrapper& ex) { - zend_throw_exception_object(ex TSRMLS_CC); + // ex will be destructed, so copy to a zval that zend_throw_exception_object can take ownership of + zval myex; + ZVAL_COPY(&myex, ex); + zend_throw_exception_object(&myex); RETURN_NULL(); } catch (const std::exception& ex) { - throw_zend_exception_from_std_exception(ex TSRMLS_CC); + throw_zend_exception_from_std_exception(ex); RETURN_NULL(); } } + // 4 params: $transport $response_Typename $strict_read $buffer_size PHP_FUNCTION(thrift_protocol_read_binary) { - int argc = ZEND_NUM_ARGS(); + zval *protocol; + zend_string *obj_typename; + zend_bool strict_read; + size_t buffer_size = 8192; - if (argc < 3) { - WRONG_PARAM_COUNT; - } - - zval ***args = (zval***) emalloc(argc * sizeof(zval**)); - zend_get_parameters_array_ex(argc, args); - - if (Z_TYPE_PP(args[0]) != IS_OBJECT) { - php_error_docref(NULL TSRMLS_CC, E_ERROR, "1st parameter is not an object (transport)"); - efree(args); - RETURN_NULL(); - } - - if (Z_TYPE_PP(args[1]) != IS_STRING) { - php_error_docref(NULL TSRMLS_CC, E_ERROR, "2nd parameter is not a string (typename of expected response struct)"); - efree(args); - RETURN_NULL(); - } - - if (argc == 4 && Z_TYPE_PP(args[3]) != IS_LONG) { - php_error_docref(NULL TSRMLS_CC, E_ERROR, "4nd parameter is not an integer (typename of expected buffer size)"); - efree(args); - RETURN_NULL(); + if (zend_parse_parameters(ZEND_NUM_ARGS(), "oSb|l", &protocol, &obj_typename, &strict_read, &buffer_size) == FAILURE) { + return; } try { - size_t buffer_size = 8192; - if (argc == 4) { - buffer_size = Z_LVAL_PP(args[3]); - } - - PHPInputTransport transport(*args[0], buffer_size); - char* obj_typename = Z_STRVAL_PP(args[1]); - convert_to_boolean(*args[2]); - bool strict_read = Z_BVAL_PP(args[2]); - efree(args); - args = NULL; - + PHPInputTransport transport(protocol, buffer_size); int8_t messageType = 0; int32_t sz = transport.readI32(); @@ -1061,24 +1104,69 @@ PHP_FUNCTION(thrift_protocol_read_binary) { } if (messageType == T_EXCEPTION) { - zval* ex; - MAKE_STD_ZVAL(ex); - createObject("\\Thrift\\Exception\\TApplicationException", ex); - zval* spec = zend_read_static_property(zend_get_class_entry(ex TSRMLS_CC), "_TSPEC", 6, false TSRMLS_CC); - binary_deserialize_spec(ex, transport, Z_ARRVAL_P(spec)); - throw PHPExceptionWrapper(ex); + zval ex; + createObject("\\Thrift\\Exception\\TApplicationException", &ex); + zval* spec = zend_read_static_property(Z_OBJCE(ex), "_TSPEC", sizeof("_TPSEC")-1, false); + ZVAL_DEREF(spec); + if (EG(exception)) { + zend_object *ex = EG(exception); + EG(exception) = nullptr; + throw PHPExceptionWrapper(ex); + } + binary_deserialize_spec(&ex, transport, Z_ARRVAL_P(spec)); + throw PHPExceptionWrapper(&ex); } - createObject(obj_typename, return_value); - zval* spec = zend_read_static_property(zend_get_class_entry(return_value TSRMLS_CC), "_TSPEC", 6, false TSRMLS_CC); + createObject(ZSTR_VAL(obj_typename), return_value); + zval* spec = zend_read_static_property(Z_OBJCE_P(return_value), "_TSPEC", sizeof("_TSPEC")-1, true); + if (spec) { + ZVAL_DEREF(spec); + } + if (!spec || Z_TYPE_P(spec) != IS_ARRAY) { + throw_tprotocolexception("Attempt deserialize to non-Thrift object", INVALID_DATA); + } binary_deserialize_spec(return_value, transport, Z_ARRVAL_P(spec)); } catch (const PHPExceptionWrapper& ex) { - zend_throw_exception_object(ex TSRMLS_CC); + // ex will be destructed, so copy to a zval that zend_throw_exception_object can ownership of + zval myex; + ZVAL_COPY(&myex, ex); + zval_dtor(return_value); + zend_throw_exception_object(&myex); RETURN_NULL(); } catch (const std::exception& ex) { - throw_zend_exception_from_std_exception(ex TSRMLS_CC); + throw_zend_exception_from_std_exception(ex); RETURN_NULL(); } } -#endif /* PHP_VERSION_ID < 70000 && PHP_VERSION_ID > 50000 */ +// 4 params: $transport $response_Typename $strict_read $buffer_size +PHP_FUNCTION(thrift_protocol_read_binary_after_message_begin) { + zval *protocol; + zend_string *obj_typename; + zend_bool strict_read; + size_t buffer_size = 8192; + + if (zend_parse_parameters(ZEND_NUM_ARGS(), "oSb|l", &protocol, &obj_typename, &strict_read, &buffer_size) == FAILURE) { + return; + } + + try { + PHPInputTransport transport(protocol, buffer_size); + + createObject(ZSTR_VAL(obj_typename), return_value); + zval* spec = zend_read_static_property(Z_OBJCE_P(return_value), "_TSPEC", sizeof("_TSPEC")-1, false); + ZVAL_DEREF(spec); + binary_deserialize_spec(return_value, transport, Z_ARRVAL_P(spec)); + } catch (const PHPExceptionWrapper& ex) { + // ex will be destructed, so copy to a zval that zend_throw_exception_object can take ownership of + zval myex; + ZVAL_COPY(&myex, ex); + zend_throw_exception_object(&myex); + RETURN_NULL(); + } catch (const std::exception& ex) { + throw_zend_exception_from_std_exception(ex); + RETURN_NULL(); + } +} + +#endif /* PHP_VERSION_ID >= 70000 */ diff --git a/vendor/git.apache.org/thrift.git/lib/php/src/ext/thrift_protocol/php_thrift_protocol.h b/vendor/git.apache.org/thrift.git/lib/php/src/ext/thrift_protocol/php_thrift_protocol.h index 44d03cc..0420997 100644 --- a/vendor/git.apache.org/thrift.git/lib/php/src/ext/thrift_protocol/php_thrift_protocol.h +++ b/vendor/git.apache.org/thrift.git/lib/php/src/ext/thrift_protocol/php_thrift_protocol.h @@ -21,6 +21,7 @@ PHP_FUNCTION(thrift_protocol_write_binary); PHP_FUNCTION(thrift_protocol_read_binary); +PHP_FUNCTION(thrift_protocol_read_binary_after_message_begin); extern zend_module_entry thrift_protocol_module_entry; #define phpext_thrift_protocol_ptr &thrift_protocol_module_entry diff --git a/vendor/git.apache.org/thrift.git/lib/php/src/ext/thrift_protocol/php_thrift_protocol7.cpp b/vendor/git.apache.org/thrift.git/lib/php/src/ext/thrift_protocol/php_thrift_protocol7.cpp deleted file mode 100644 index 59fa30a..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/src/ext/thrift_protocol/php_thrift_protocol7.cpp +++ /dev/null @@ -1,1020 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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. - */ -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "php.h" -#include "zend_interfaces.h" -#include "zend_exceptions.h" -#include "php_thrift_protocol.h" - -#if PHP_VERSION_ID >= 70000 - -#include -#include - -#include -#include -#include - -#ifndef bswap_64 -#define bswap_64(x) (((uint64_t)(x) << 56) | \ - (((uint64_t)(x) << 40) & 0xff000000000000ULL) | \ - (((uint64_t)(x) << 24) & 0xff0000000000ULL) | \ - (((uint64_t)(x) << 8) & 0xff00000000ULL) | \ - (((uint64_t)(x) >> 8) & 0xff000000ULL) | \ - (((uint64_t)(x) >> 24) & 0xff0000ULL) | \ - (((uint64_t)(x) >> 40) & 0xff00ULL) | \ - ((uint64_t)(x) >> 56)) -#endif - -#if __BYTE_ORDER == __LITTLE_ENDIAN -#define htonll(x) bswap_64(x) -#define ntohll(x) bswap_64(x) -#elif __BYTE_ORDER == __BIG_ENDIAN -#define htonll(x) x -#define ntohll(x) x -#else -#error Unknown __BYTE_ORDER -#endif - -enum TType { - T_STOP = 0, - T_VOID = 1, - T_BOOL = 2, - T_BYTE = 3, - T_I08 = 3, - T_I16 = 6, - T_I32 = 8, - T_U64 = 9, - T_I64 = 10, - T_DOUBLE = 4, - T_STRING = 11, - T_UTF7 = 11, - T_STRUCT = 12, - T_MAP = 13, - T_SET = 14, - T_LIST = 15, - T_UTF8 = 16, - T_UTF16 = 17 -}; - -const int32_t VERSION_MASK = 0xffff0000; -const int32_t VERSION_1 = 0x80010000; -const int8_t T_CALL = 1; -const int8_t T_REPLY = 2; -const int8_t T_EXCEPTION = 3; -// tprotocolexception -const int INVALID_DATA = 1; -const int BAD_VERSION = 4; - -static zend_function_entry thrift_protocol_functions[] = { - PHP_FE(thrift_protocol_write_binary, nullptr) - PHP_FE(thrift_protocol_read_binary, nullptr) - {nullptr, nullptr, nullptr} -}; - -zend_module_entry thrift_protocol_module_entry = { - STANDARD_MODULE_HEADER, - "thrift_protocol", - thrift_protocol_functions, - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - "1.0", - STANDARD_MODULE_PROPERTIES -}; - -#ifdef COMPILE_DL_THRIFT_PROTOCOL -ZEND_GET_MODULE(thrift_protocol) -#endif - -class PHPExceptionWrapper : public std::exception { -public: - PHPExceptionWrapper(zval* _ex) throw() { - ZVAL_COPY(&ex, _ex); - snprintf(_what, 40, "PHP exception zval=%p", _ex); - } - - PHPExceptionWrapper(zend_object* _exobj) throw() { - ZVAL_OBJ(&ex, _exobj); - snprintf(_what, 40, "PHP exception zval=%p", _exobj); - } - ~PHPExceptionWrapper() throw() { - zval_dtor(&ex); - } - - const char* what() const throw() { - return _what; - } - operator zval*() const throw() { - return const_cast(&ex); - } // Zend API doesn't do 'const'... -protected: - zval ex; - char _what[40]; -} ; - -class PHPTransport { -protected: - PHPTransport(zval* _p, size_t _buffer_size) { - assert(Z_TYPE_P(_p) == IS_OBJECT); - - ZVAL_UNDEF(&t); - - buffer = reinterpret_cast(emalloc(_buffer_size)); - buffer_ptr = buffer; - buffer_used = 0; - buffer_size = _buffer_size; - - // Get the transport for the passed protocol - zval gettransport; - ZVAL_STRING(&gettransport, "getTransport"); - call_user_function(nullptr, _p, &gettransport, &t, 0, nullptr); - - zval_dtor(&gettransport); - - assert(Z_TYPE(t) == IS_OBJECT); - } - - ~PHPTransport() { - efree(buffer); - zval_dtor(&t); - } - - char* buffer; - char* buffer_ptr; - size_t buffer_used; - size_t buffer_size; - - zval t; -}; - - -class PHPOutputTransport : public PHPTransport { -public: - PHPOutputTransport(zval* _p, size_t _buffer_size = 8192) : PHPTransport(_p, _buffer_size) { } - ~PHPOutputTransport() { } - - void write(const char* data, size_t len) { - if ((len + buffer_used) > buffer_size) { - internalFlush(); - } - if (len > buffer_size) { - directWrite(data, len); - } else { - memcpy(buffer_ptr, data, len); - buffer_used += len; - buffer_ptr += len; - } - } - - void writeI64(int64_t i) { - i = htonll(i); - write((const char*)&i, 8); - } - - void writeU32(uint32_t i) { - i = htonl(i); - write((const char*)&i, 4); - } - - void writeI32(int32_t i) { - i = htonl(i); - write((const char*)&i, 4); - } - - void writeI16(int16_t i) { - i = htons(i); - write((const char*)&i, 2); - } - - void writeI8(int8_t i) { - write((const char*)&i, 1); - } - - void writeString(const char* str, size_t len) { - writeU32(len); - write(str, len); - } - - void flush() { - internalFlush(); - directFlush(); - } - -protected: - void internalFlush() { - if (buffer_used) { - directWrite(buffer, buffer_used); - buffer_ptr = buffer; - buffer_used = 0; - } - } - void directFlush() { - zval ret, flushfn; - ZVAL_NULL(&ret); - ZVAL_STRING(&flushfn, "flush"); - - call_user_function(EG(function_table), &(this->t), &flushfn, &ret, 0, nullptr); - zval_dtor(&flushfn); - zval_dtor(&ret); - } - void directWrite(const char* data, size_t len) { - zval args[1], ret, writefn; - - ZVAL_STRING(&writefn, "write"); - ZVAL_STRINGL(&args[0], data, len); - - ZVAL_NULL(&ret); - call_user_function(EG(function_table), &(this->t), &writefn, &ret, 1, args); - - zval_dtor(&writefn); - zval_dtor(&ret); - zval_dtor(&args[0]); - - if (EG(exception)) { - zend_object *ex = EG(exception); - EG(exception) = nullptr; - throw PHPExceptionWrapper(ex); - } - } -}; - -class PHPInputTransport : public PHPTransport { -public: - PHPInputTransport(zval* _p, size_t _buffer_size = 8192) : PHPTransport(_p, _buffer_size) { - } - - ~PHPInputTransport() { - put_back(); - } - - void put_back() { - if (buffer_used) { - zval args[1], ret, putbackfn; - ZVAL_STRINGL(&args[0], buffer_ptr, buffer_used); - ZVAL_STRING(&putbackfn, "putBack"); - ZVAL_NULL(&ret); - - call_user_function(EG(function_table), &(this->t), &putbackfn, &ret, 1, args); - - zval_dtor(&putbackfn); - zval_dtor(&ret); - zval_dtor(&args[0]); - } - buffer_used = 0; - buffer_ptr = buffer; - } - - void skip(size_t len) { - while (len) { - size_t chunk_size = std::min(len, buffer_used); - if (chunk_size) { - buffer_ptr = reinterpret_cast(buffer_ptr) + chunk_size; - buffer_used -= chunk_size; - len -= chunk_size; - } - if (! len) break; - refill(); - } - } - - void readBytes(void* buf, size_t len) { - while (len) { - size_t chunk_size = std::min(len, buffer_used); - if (chunk_size) { - memcpy(buf, buffer_ptr, chunk_size); - buffer_ptr = reinterpret_cast(buffer_ptr) + chunk_size; - buffer_used -= chunk_size; - buf = reinterpret_cast(buf) + chunk_size; - len -= chunk_size; - } - if (! len) break; - refill(); - } - } - - int8_t readI8() { - int8_t c; - readBytes(&c, 1); - return c; - } - - int16_t readI16() { - int16_t c; - readBytes(&c, 2); - return (int16_t)ntohs(c); - } - - uint32_t readU32() { - uint32_t c; - readBytes(&c, 4); - return (uint32_t)ntohl(c); - } - - int32_t readI32() { - int32_t c; - readBytes(&c, 4); - return (int32_t)ntohl(c); - } - -protected: - void refill() { - assert(buffer_used == 0); - zval retval; - zval args[1]; - zval funcname; - - ZVAL_NULL(&retval); - ZVAL_LONG(&args[0], buffer_size); - - ZVAL_STRING(&funcname, "read"); - - call_user_function(EG(function_table), &(this->t), &funcname, &retval, 1, args); - zval_dtor(&args[0]); - zval_dtor(&funcname); - - if (EG(exception)) { - zval_dtor(&retval); - - zend_object *ex = EG(exception); - EG(exception) = nullptr; - throw PHPExceptionWrapper(ex); - } - - buffer_used = Z_STRLEN(retval); - memcpy(buffer, Z_STRVAL(retval), buffer_used); - - zval_dtor(&retval); - - buffer_ptr = buffer; - } - -}; - -static -void binary_deserialize_spec(zval* zthis, PHPInputTransport& transport, HashTable* spec); -static -void binary_serialize_spec(zval* zthis, PHPOutputTransport& transport, HashTable* spec); -static -void binary_serialize(int8_t thrift_typeID, PHPOutputTransport& transport, zval* value, HashTable* fieldspec); - -// Create a PHP object given a typename and call the ctor, optionally passing up to 2 arguments -static -void createObject(const char* obj_typename, zval* return_value, int nargs = 0, zval* arg1 = nullptr, zval* arg2 = nullptr) { - /* is there a better way to do that on the stack ? */ - zend_string *obj_name = zend_string_init(obj_typename, strlen(obj_typename), 0); - zend_class_entry* ce = zend_fetch_class(obj_name, ZEND_FETCH_CLASS_DEFAULT); - zend_string_release(obj_name); - - if (! ce) { - php_error_docref(nullptr, E_ERROR, "Class %s does not exist", obj_typename); - RETURN_NULL(); - } - - object_and_properties_init(return_value, ce, nullptr); - zend_function* constructor = zend_std_get_constructor(Z_OBJ_P(return_value)); - zval ctor_rv; - zend_call_method(return_value, ce, &constructor, NULL, 0, &ctor_rv, nargs, arg1, arg2); - zval_dtor(&ctor_rv); -} - -static -void throw_tprotocolexception(const char* what, long errorcode) { - zval zwhat, zerrorcode; - - ZVAL_STRING(&zwhat, what); - ZVAL_LONG(&zerrorcode, errorcode); - - zval ex; - createObject("\\Thrift\\Exception\\TProtocolException", &ex, 2, &zwhat, &zerrorcode); - - zval_dtor(&zwhat); - zval_dtor(&zerrorcode); - - throw PHPExceptionWrapper(&ex); -} - -// Sets EG(exception), call this and then RETURN_NULL(); -static -void throw_zend_exception_from_std_exception(const std::exception& ex) { - zend_throw_exception(zend_exception_get_default(), const_cast(ex.what()), 0); -} - -static -void skip_element(long thrift_typeID, PHPInputTransport& transport) { - switch (thrift_typeID) { - case T_STOP: - case T_VOID: - return; - case T_STRUCT: - while (true) { - int8_t ttype = transport.readI8(); // get field type - if (ttype == T_STOP) break; - transport.skip(2); // skip field number, I16 - skip_element(ttype, transport); // skip field payload - } - return; - case T_BOOL: - case T_BYTE: - transport.skip(1); - return; - case T_I16: - transport.skip(2); - return; - case T_I32: - transport.skip(4); - return; - case T_U64: - case T_I64: - case T_DOUBLE: - transport.skip(8); - return; - //case T_UTF7: // aliases T_STRING - case T_UTF8: - case T_UTF16: - case T_STRING: { - uint32_t len = transport.readU32(); - transport.skip(len); - } return; - case T_MAP: { - int8_t keytype = transport.readI8(); - int8_t valtype = transport.readI8(); - uint32_t size = transport.readU32(); - for (uint32_t i = 0; i < size; ++i) { - skip_element(keytype, transport); - skip_element(valtype, transport); - } - } return; - case T_LIST: - case T_SET: { - int8_t valtype = transport.readI8(); - uint32_t size = transport.readU32(); - for (uint32_t i = 0; i < size; ++i) { - skip_element(valtype, transport); - } - } return; - }; - - char errbuf[128]; - sprintf(errbuf, "Unknown thrift typeID %ld", thrift_typeID); - throw_tprotocolexception(errbuf, INVALID_DATA); -} - -static inline -bool zval_is_bool(zval* v) { - return Z_TYPE_P(v) == IS_TRUE || Z_TYPE_P(v) == IS_FALSE; -} - -static -void binary_deserialize(int8_t thrift_typeID, PHPInputTransport& transport, zval* return_value, HashTable* fieldspec) { - ZVAL_NULL(return_value); - - switch (thrift_typeID) { - case T_STOP: - case T_VOID: - RETURN_NULL(); - return; - case T_STRUCT: { - zval* val_ptr = zend_hash_str_find(fieldspec, "class", sizeof("class")-1); - if (val_ptr == nullptr) { - throw_tprotocolexception("no class type in spec", INVALID_DATA); - skip_element(T_STRUCT, transport); - RETURN_NULL(); - } - - char* structType = Z_STRVAL_P(val_ptr); - // Create an object in PHP userland based on our spec - createObject(structType, return_value); - if (Z_TYPE_P(return_value) == IS_NULL) { - // unable to create class entry - skip_element(T_STRUCT, transport); - RETURN_NULL(); - } - - zval* spec = zend_read_static_property(Z_OBJCE_P(return_value), "_TSPEC", sizeof("_TSPEC")-1, false); - if (Z_TYPE_P(spec) != IS_ARRAY) { - char errbuf[128]; - snprintf(errbuf, 128, "spec for %s is wrong type: %d\n", structType, Z_TYPE_P(spec)); - throw_tprotocolexception(errbuf, INVALID_DATA); - RETURN_NULL(); - } - binary_deserialize_spec(return_value, transport, Z_ARRVAL_P(spec)); - return; - } break; - case T_BOOL: { - uint8_t c; - transport.readBytes(&c, 1); - RETURN_BOOL(c != 0); - } - //case T_I08: // same numeric value as T_BYTE - case T_BYTE: { - uint8_t c; - transport.readBytes(&c, 1); - RETURN_LONG((int8_t)c); - } - case T_I16: { - uint16_t c; - transport.readBytes(&c, 2); - RETURN_LONG((int16_t)ntohs(c)); - } - case T_I32: { - uint32_t c; - transport.readBytes(&c, 4); - RETURN_LONG((int32_t)ntohl(c)); - } - case T_U64: - case T_I64: { - uint64_t c; - transport.readBytes(&c, 8); - RETURN_LONG((int64_t)ntohll(c)); - } - case T_DOUBLE: { - union { - uint64_t c; - double d; - } a; - transport.readBytes(&(a.c), 8); - a.c = ntohll(a.c); - RETURN_DOUBLE(a.d); - } - //case T_UTF7: // aliases T_STRING - case T_UTF8: - case T_UTF16: - case T_STRING: { - uint32_t size = transport.readU32(); - if (size) { - char strbuf[size+1]; - transport.readBytes(strbuf, size); - strbuf[size] = '\0'; - ZVAL_STRINGL(return_value, strbuf, size); - } else { - ZVAL_EMPTY_STRING(return_value); - } - return; - } - case T_MAP: { // array of key -> value - uint8_t types[2]; - transport.readBytes(types, 2); - uint32_t size = transport.readU32(); - array_init(return_value); - - zval *val_ptr; - val_ptr = zend_hash_str_find(fieldspec, "key", sizeof("key")-1); - HashTable* keyspec = Z_ARRVAL_P(val_ptr); - val_ptr = zend_hash_str_find(fieldspec, "val", sizeof("val")-1); - HashTable* valspec = Z_ARRVAL_P(val_ptr); - - for (uint32_t s = 0; s < size; ++s) { - zval key, value; - - binary_deserialize(types[0], transport, &key, keyspec); - binary_deserialize(types[1], transport, &value, valspec); - if (Z_TYPE(key) == IS_LONG) { - zend_hash_index_update(Z_ARR_P(return_value), Z_LVAL(key), &value); - } else { - if (Z_TYPE(key) != IS_STRING) convert_to_string(&key); - zend_hash_update(Z_ARR_P(return_value), Z_STR(key), &value); - } - } - return; // return_value already populated - } - case T_LIST: { // array with autogenerated numeric keys - int8_t type = transport.readI8(); - uint32_t size = transport.readU32(); - zval *val_ptr = zend_hash_str_find(fieldspec, "elem", sizeof("elem")-1); - HashTable* elemspec = Z_ARRVAL_P(val_ptr); - - array_init(return_value); - for (uint32_t s = 0; s < size; ++s) { - zval value; - binary_deserialize(type, transport, &value, elemspec); - zend_hash_next_index_insert(Z_ARR_P(return_value), &value); - } - return; - } - case T_SET: { // array of key -> TRUE - uint8_t type; - uint32_t size; - transport.readBytes(&type, 1); - transport.readBytes(&size, 4); - size = ntohl(size); - zval *val_ptr = zend_hash_str_find(fieldspec, "elem", sizeof("elem")-1); - HashTable* elemspec = Z_ARRVAL_P(val_ptr); - - array_init(return_value); - - for (uint32_t s = 0; s < size; ++s) { - zval key, value; - ZVAL_TRUE(&value); - - binary_deserialize(type, transport, &key, elemspec); - - if (Z_TYPE(key) == IS_LONG) { - zend_hash_index_update(Z_ARR_P(return_value), Z_LVAL(key), &value); - } else { - if (Z_TYPE(key) != IS_STRING) convert_to_string(&key); - zend_hash_update(Z_ARR_P(return_value), Z_STR(key), &value); - } - } - return; - } - }; - - char errbuf[128]; - sprintf(errbuf, "Unknown thrift typeID %d", thrift_typeID); - throw_tprotocolexception(errbuf, INVALID_DATA); -} - -static -void binary_serialize_hashtable_key(int8_t keytype, PHPOutputTransport& transport, HashTable* ht, HashPosition& ht_pos) { - bool keytype_is_numeric = (!((keytype == T_STRING) || (keytype == T_UTF8) || (keytype == T_UTF16))); - - zend_string* key; - uint key_len; - long index = 0; - - zval z; - - int res = zend_hash_get_current_key_ex(ht, &key, (zend_ulong*)&index, &ht_pos); - if (keytype_is_numeric) { - if (res == HASH_KEY_IS_STRING) { - index = strtol(ZSTR_VAL(key), nullptr, 10); - } - ZVAL_LONG(&z, index); - } else { - char buf[64]; - if (res == HASH_KEY_IS_STRING) { - ZVAL_STR(&z, key); - } else { - snprintf(buf, 64, "%ld", index); - ZVAL_STRING(&z, buf); - } - } - binary_serialize(keytype, transport, &z, nullptr); - zval_dtor(&z); -} - -static -void binary_serialize(int8_t thrift_typeID, PHPOutputTransport& transport, zval* value, HashTable* fieldspec) { - // At this point the typeID (and field num, if applicable) should've already been written to the output so all we need to do is write the payload. - switch (thrift_typeID) { - case T_STOP: - case T_VOID: - return; - case T_STRUCT: { - if (Z_TYPE_P(value) != IS_OBJECT) { - throw_tprotocolexception("Attempt to send non-object type as a T_STRUCT", INVALID_DATA); - } - zval* spec = zend_read_static_property(Z_OBJCE_P(value), "_TSPEC", sizeof("_TSPEC")-1, false); - if (Z_TYPE_P(spec) != IS_ARRAY) { - throw_tprotocolexception("Attempt to send non-Thrift object as a T_STRUCT", INVALID_DATA); - } - binary_serialize_spec(value, transport, Z_ARRVAL_P(spec)); - } return; - case T_BOOL: - if (!zval_is_bool(value)) convert_to_boolean(value); - transport.writeI8(Z_TYPE_INFO_P(value) == IS_TRUE ? 1 : 0); - return; - case T_BYTE: - if (Z_TYPE_P(value) != IS_LONG) convert_to_long(value); - transport.writeI8(Z_LVAL_P(value)); - return; - case T_I16: - if (Z_TYPE_P(value) != IS_LONG) convert_to_long(value); - transport.writeI16(Z_LVAL_P(value)); - return; - case T_I32: - if (Z_TYPE_P(value) != IS_LONG) convert_to_long(value); - transport.writeI32(Z_LVAL_P(value)); - return; - case T_I64: - case T_U64: { - int64_t l_data; -#if defined(_LP64) || defined(_WIN64) - if (Z_TYPE_P(value) != IS_LONG) convert_to_long(value); - l_data = Z_LVAL_P(value); -#else - if (Z_TYPE_P(value) != IS_DOUBLE) convert_to_double(value); - l_data = (int64_t)Z_DVAL_P(value); -#endif - transport.writeI64(l_data); - } return; - case T_DOUBLE: { - union { - int64_t c; - double d; - } a; - if (Z_TYPE_P(value) != IS_DOUBLE) convert_to_double(value); - a.d = Z_DVAL_P(value); - transport.writeI64(a.c); - } return; - case T_UTF8: - case T_UTF16: - case T_STRING: - if (Z_TYPE_P(value) != IS_STRING) convert_to_string(value); - transport.writeString(Z_STRVAL_P(value), Z_STRLEN_P(value)); - return; - case T_MAP: { - if (Z_TYPE_P(value) != IS_ARRAY) convert_to_array(value); - if (Z_TYPE_P(value) != IS_ARRAY) { - throw_tprotocolexception("Attempt to send an incompatible type as an array (T_MAP)", INVALID_DATA); - } - HashTable* ht = Z_ARRVAL_P(value); - zval* val_ptr; - - val_ptr = zend_hash_str_find(fieldspec, "ktype", sizeof("ktype")-1); - if (Z_TYPE_P(val_ptr) != IS_LONG) convert_to_long(val_ptr); - uint8_t keytype = Z_LVAL_P(val_ptr); - transport.writeI8(keytype); - val_ptr = zend_hash_str_find(fieldspec, "vtype", sizeof("vtype")-1); - if (Z_TYPE_P(val_ptr) != IS_LONG) convert_to_long(val_ptr); - uint8_t valtype = Z_LVAL_P(val_ptr); - transport.writeI8(valtype); - - val_ptr = zend_hash_str_find(fieldspec, "val", sizeof("val")-1); - HashTable* valspec = Z_ARRVAL_P(val_ptr); - - transport.writeI32(zend_hash_num_elements(ht)); - HashPosition key_ptr; - for (zend_hash_internal_pointer_reset_ex(ht, &key_ptr); - (val_ptr = zend_hash_get_current_data_ex(ht, &key_ptr)) != nullptr; - zend_hash_move_forward_ex(ht, &key_ptr)) { - binary_serialize_hashtable_key(keytype, transport, ht, key_ptr); - binary_serialize(valtype, transport, val_ptr, valspec); - } - } return; - case T_LIST: { - if (Z_TYPE_P(value) != IS_ARRAY) convert_to_array(value); - if (Z_TYPE_P(value) != IS_ARRAY) { - throw_tprotocolexception("Attempt to send an incompatible type as an array (T_LIST)", INVALID_DATA); - } - HashTable* ht = Z_ARRVAL_P(value); - zval* val_ptr; - - val_ptr = zend_hash_str_find(fieldspec, "etype", sizeof("etype")-1); - if (Z_TYPE_P(val_ptr) != IS_LONG) convert_to_long(val_ptr); - uint8_t valtype = Z_LVAL_P(val_ptr); - transport.writeI8(valtype); - - val_ptr = zend_hash_str_find(fieldspec, "elem", sizeof("elem")-1); - HashTable* valspec = Z_ARRVAL_P(val_ptr); - - transport.writeI32(zend_hash_num_elements(ht)); - HashPosition key_ptr; - for (zend_hash_internal_pointer_reset_ex(ht, &key_ptr); - (val_ptr = zend_hash_get_current_data_ex(ht, &key_ptr)) != nullptr; - zend_hash_move_forward_ex(ht, &key_ptr)) { - binary_serialize(valtype, transport, val_ptr, valspec); - } - } return; - case T_SET: { - if (Z_TYPE_P(value) != IS_ARRAY) convert_to_array(value); - if (Z_TYPE_P(value) != IS_ARRAY) { - throw_tprotocolexception("Attempt to send an incompatible type as an array (T_SET)", INVALID_DATA); - } - HashTable* ht = Z_ARRVAL_P(value); - zval* val_ptr; - - val_ptr = zend_hash_str_find(fieldspec, "etype", sizeof("etype")-1); - if (Z_TYPE_P(val_ptr) != IS_LONG) convert_to_long(val_ptr); - uint8_t keytype = Z_LVAL_P(val_ptr); - transport.writeI8(keytype); - - transport.writeI32(zend_hash_num_elements(ht)); - HashPosition key_ptr; - for (zend_hash_internal_pointer_reset_ex(ht, &key_ptr); - (val_ptr = zend_hash_get_current_data_ex(ht, &key_ptr)) != nullptr; - zend_hash_move_forward_ex(ht, &key_ptr)) { - binary_serialize_hashtable_key(keytype, transport, ht, key_ptr); - } - } return; - }; - - char errbuf[128]; - snprintf(errbuf, 128, "Unknown thrift typeID %d", thrift_typeID); - throw_tprotocolexception(errbuf, INVALID_DATA); -} - -static -void protocol_writeMessageBegin(zval* transport, zend_string* method_name, int32_t msgtype, int32_t seqID) { - zval args[3]; - zval ret; - zval writeMessagefn; - - ZVAL_STR(&args[0], method_name); - ZVAL_LONG(&args[1], msgtype); - ZVAL_LONG(&args[2], seqID); - ZVAL_NULL(&ret); - ZVAL_STRING(&writeMessagefn, "writeMessageBegin"); - - call_user_function(EG(function_table), transport, &writeMessagefn, &ret, 3, args); - - zval_dtor(&writeMessagefn); - zval_dtor(&args[2]); zval_dtor(&args[1]); zval_dtor(&args[0]); - zval_dtor(&ret); -} - -static inline -bool ttype_is_int(int8_t t) { - return ((t == T_BYTE) || ((t >= T_I16) && (t <= T_I64))); -} - -static inline -bool ttypes_are_compatible(int8_t t1, int8_t t2) { - // Integer types of different widths are considered compatible; - // otherwise the typeID must match. - return ((t1 == t2) || (ttype_is_int(t1) && ttype_is_int(t2))); -} - -static -void binary_deserialize_spec(zval* zthis, PHPInputTransport& transport, HashTable* spec) { - // SET and LIST have 'elem' => array('type', [optional] 'class') - // MAP has 'val' => array('type', [optiona] 'class') - zend_class_entry* ce = Z_OBJCE_P(zthis); - while (true) { - int8_t ttype = transport.readI8(); - if (ttype == T_STOP) { - return; - } - - int16_t fieldno = transport.readI16(); - zval* val_ptr = zend_hash_index_find(spec, fieldno); - if (val_ptr != nullptr) { - HashTable* fieldspec = Z_ARRVAL_P(val_ptr); - // pull the field name - val_ptr = zend_hash_str_find(fieldspec, "var", sizeof("var")-1); - char* varname = Z_STRVAL_P(val_ptr); - - // and the type - val_ptr = zend_hash_str_find(fieldspec, "type", sizeof("type")-1); - if (Z_TYPE_P(val_ptr) != IS_LONG) convert_to_long(val_ptr); - int8_t expected_ttype = Z_LVAL_P(val_ptr); - - if (ttypes_are_compatible(ttype, expected_ttype)) { - zval rv; - ZVAL_UNDEF(&rv); - - binary_deserialize(ttype, transport, &rv, fieldspec); - zend_update_property(ce, zthis, varname, strlen(varname), &rv); - - zval_ptr_dtor(&rv); - } else { - skip_element(ttype, transport); - } - } else { - skip_element(ttype, transport); - } - } -} - -static -void binary_serialize_spec(zval* zthis, PHPOutputTransport& transport, HashTable* spec) { - HashPosition key_ptr; - zval* val_ptr; - - for (zend_hash_internal_pointer_reset_ex(spec, &key_ptr); - (val_ptr = zend_hash_get_current_data_ex(spec, &key_ptr)) != nullptr; - zend_hash_move_forward_ex(spec, &key_ptr)) { - - zend_ulong fieldno; - if (zend_hash_get_current_key_ex(spec, nullptr, &fieldno, &key_ptr) != HASH_KEY_IS_LONG) { - throw_tprotocolexception("Bad keytype in TSPEC (expected 'long')", INVALID_DATA); - return; - } - HashTable* fieldspec = Z_ARRVAL_P(val_ptr); - - // field name - val_ptr = zend_hash_str_find(fieldspec, "var", sizeof("var")-1); - char* varname = Z_STRVAL_P(val_ptr); - - // thrift type - val_ptr = zend_hash_str_find(fieldspec, "type", sizeof("type")-1); - if (Z_TYPE_P(val_ptr) != IS_LONG) convert_to_long(val_ptr); - int8_t ttype = Z_LVAL_P(val_ptr); - - zval rv; - zval* prop = zend_read_property(Z_OBJCE_P(zthis), zthis, varname, strlen(varname), false, &rv); - if (Z_TYPE_P(prop) != IS_NULL) { - transport.writeI8(ttype); - transport.writeI16(fieldno); - binary_serialize(ttype, transport, prop, fieldspec); - } - } - transport.writeI8(T_STOP); // struct end -} - -// 6 params: $transport $method_name $ttype $request_struct $seqID $strict_write -PHP_FUNCTION(thrift_protocol_write_binary) { - zval *protocol; - zval *request_struct; - zend_string *method_name; - long msgtype, seqID; - zend_bool strict_write; - - if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "oSlolb", - &protocol, &method_name, &msgtype, - &request_struct, &seqID, &strict_write) == FAILURE) { - return; - } - - try { - zval* spec = zend_read_static_property(Z_OBJCE_P(request_struct), "_TSPEC", sizeof("_TSPEC")-1, false); - - if (Z_TYPE_P(spec) != IS_ARRAY) { - throw_tprotocolexception("Attempt to send non-Thrift object", INVALID_DATA); - } - - PHPOutputTransport transport(protocol); - protocol_writeMessageBegin(protocol, method_name, (int32_t) msgtype, (int32_t) seqID); - binary_serialize_spec(request_struct, transport, Z_ARRVAL_P(spec)); - transport.flush(); - - } catch (const PHPExceptionWrapper& ex) { - zend_throw_exception_object(ex); - RETURN_NULL(); - } catch (const std::exception& ex) { - throw_zend_exception_from_std_exception(ex); - RETURN_NULL(); - } -} - - -// 4 params: $transport $response_Typename $strict_read $buffer_size -PHP_FUNCTION(thrift_protocol_read_binary) { - zval *protocol; - zend_string *obj_typename; - zend_bool strict_read; - size_t buffer_size = 8192; - - if (zend_parse_parameters(ZEND_NUM_ARGS(), "oSb|l", &protocol, &obj_typename, &strict_read, &buffer_size) == FAILURE) { - return; - } - - try { - PHPInputTransport transport(protocol, buffer_size); - int8_t messageType = 0; - int32_t sz = transport.readI32(); - - if (sz < 0) { - // Check for correct version number - int32_t version = sz & VERSION_MASK; - if (version != VERSION_1) { - throw_tprotocolexception("Bad version identifier", BAD_VERSION); - } - messageType = (sz & 0x000000ff); - int32_t namelen = transport.readI32(); - // skip the name string and the sequence ID, we don't care about those - transport.skip(namelen + 4); - } else { - if (strict_read) { - throw_tprotocolexception("No version identifier... old protocol client in strict mode?", BAD_VERSION); - } else { - // Handle pre-versioned input - transport.skip(sz); // skip string body - messageType = transport.readI8(); - transport.skip(4); // skip sequence number - } - } - - if (messageType == T_EXCEPTION) { - zval ex; - createObject("\\Thrift\\Exception\\TApplicationException", &ex); - zval* spec = zend_read_static_property(Z_OBJCE(ex), "_TSPEC", sizeof("_TPSEC")-1, false); - binary_deserialize_spec(&ex, transport, Z_ARRVAL_P(spec)); - throw PHPExceptionWrapper(&ex); - } - - createObject(ZSTR_VAL(obj_typename), return_value); - zval* spec = zend_read_static_property(Z_OBJCE_P(return_value), "_TSPEC", sizeof("_TSPEC")-1, false); - binary_deserialize_spec(return_value, transport, Z_ARRVAL_P(spec)); - } catch (const PHPExceptionWrapper& ex) { - zend_throw_exception_object(ex); - RETURN_NULL(); - } catch (const std::exception& ex) { - throw_zend_exception_from_std_exception(ex); - RETURN_NULL(); - } -} - -#endif /* PHP_VERSION_ID >= 70000 */ diff --git a/vendor/git.apache.org/thrift.git/lib/php/test/Fixtures.php b/vendor/git.apache.org/thrift.git/lib/php/test/Fixtures.php new file mode 100644 index 0000000..fd57d83 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/test/Fixtures.php @@ -0,0 +1,194 @@ +<><"; + + self::$testArgs['testString3'] = + "string that ends in double-backslash \\\\"; + + self::$testArgs['testUnicodeStringWithNonBMP'] = + "สวัสดี/ð’¯"; + + self::$testArgs['testDouble'] = 3.1415926535898; + + // TODO: add testBinary() call + + self::$testArgs['testByte'] = 0x01; + + self::$testArgs['testI32'] = pow(2, 30); + + if (PHP_INT_SIZE == 8) { + self::$testArgs['testI64'] = pow(2, 60); + } else { + self::$testArgs['testI64'] = "1152921504606847000"; + } + + self::$testArgs['testStruct'] = + new Xtruct( + array( + 'string_thing' => 'worked', + 'byte_thing' => 0x01, + 'i32_thing' => pow(2, 30), + 'i64_thing' => self::$testArgs['testI64'] + ) + ); + + self::$testArgs['testNestNested'] = + new Xtruct( + array( + 'string_thing' => 'worked', + 'byte_thing' => 0x01, + 'i32_thing' => pow(2, 30), + 'i64_thing' => self::$testArgs['testI64'] + ) + ); + + self::$testArgs['testNest'] = + new Xtruct2( + array( + 'byte_thing' => 0x01, + 'struct_thing' => self::$testArgs['testNestNested'], + 'i32_thing' => pow(2, 15) + ) + ); + + self::$testArgs['testMap'] = + array( + 7 => 77, + 8 => 88, + 9 => 99 + ); + + self::$testArgs['testStringMap'] = + array( + "a" => "123", + "a b" => "with spaces ", + "same" => "same", + "0" => "numeric key", + "longValue" => self::$testArgs['testString1'], + self::$testArgs['testString1'] => "long key" + ); + + self::$testArgs['testSet'] = array(1 => true, 5 => true, 6 => true); + + self::$testArgs['testList'] = array(1, 2, 3); + + self::$testArgs['testEnum'] = Numberz::ONE; + + self::$testArgs['testTypedef'] = 69; + + self::$testArgs['testMapMapExpectedResult'] = + array( + 4 => array( + 1 => 1, + 2 => 2, + 3 => 3, + 4 => 4, + ), + -4 => array( + -4 => -4, + -3 => -3, + -2 => -2, + -1 => -1 + ) + ); + + // testInsanity ... takes a few steps to set up! + + $xtruct1 = + new Xtruct( + array( + 'string_thing' => 'Goodbye4', + 'byte_thing' => 4, + 'i32_thing' => 4, + 'i64_thing' => 4 + ) + ); + + $xtruct2 = + new Xtruct( + array( + 'string_thing' => 'Hello2', + 'byte_thing' => 2, + 'i32_thing' => 2, + 'i64_thing' => 2 + ) + ); + + $userMap = + array( + Numberz::FIVE => 5, + Numberz::EIGHT => 8 + ); + + $insanity2 = + new Insanity( + array( + 'userMap' => $userMap, + 'xtructs' => array($xtruct1, $xtruct2) + ) + ); + + $insanity3 = $insanity2; + + $insanity6 = + new Insanity( + array( + 'userMap' => null, + 'xtructs' => null + ) + ); + + self::$testArgs['testInsanityExpectedResult'] = + array( + "1" => array( + Numberz::TWO => $insanity2, + Numberz::THREE => $insanity3 + ), + "2" => array( + Numberz::SIX => $insanity6 + ) + ); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/test/JsonSerialize/JsonSerializeTest.php b/vendor/git.apache.org/thrift.git/lib/php/test/JsonSerialize/JsonSerializeTest.php new file mode 100644 index 0000000..c668652 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/test/JsonSerialize/JsonSerializeTest.php @@ -0,0 +1,116 @@ +markTestSkipped('Requires PHP 5.4 or newer!'); + } + /** @var \Composer\Autoload\ClassLoader $loader */ + $loader = require __DIR__ . '/../../../../vendor/autoload.php'; + $loader->addPsr4('', __DIR__ . '/../packages/phpjs'); + } + + public function testEmptyStruct() + { + $empty = new \ThriftTest\EmptyStruct(array('non_existing_key' => 'bar')); + $this->assertEquals(new stdClass(), json_decode(json_encode($empty))); + } + + public function testStringsAndInts() + { + $input = array( + 'string_thing' => 'foo', + 'i64_thing' => 1234567890, + ); + $xtruct = new \ThriftTest\Xtruct($input); + + // Xtruct's 'i32_thing' and 'byte_thing' fields should not be present here! + $expected = new stdClass(); + $expected->string_thing = $input['string_thing']; + $expected->i64_thing = $input['i64_thing']; + $this->assertEquals($expected, json_decode(json_encode($xtruct))); + } + + public function testNestedStructs() + { + $xtruct2 = new \ThriftTest\Xtruct2(array( + 'byte_thing' => 42, + 'struct_thing' => new \ThriftTest\Xtruct(array( + 'i32_thing' => 123456, + )), + )); + + $expected = new stdClass(); + $expected->byte_thing = $xtruct2->byte_thing; + $expected->struct_thing = new stdClass(); + $expected->struct_thing->i32_thing = $xtruct2->struct_thing->i32_thing; + $this->assertEquals($expected, json_decode(json_encode($xtruct2))); + } + + public function testInsanity() + { + $xinput = array('string_thing' => 'foo'); + $xtruct = new \ThriftTest\Xtruct($xinput); + $insanity = new \ThriftTest\Insanity(array( + 'xtructs' => array($xtruct, $xtruct, $xtruct) + )); + $expected = new stdClass(); + $expected->xtructs = array((object)$xinput, (object)$xinput, (object)$xinput); + $this->assertEquals($expected, json_decode(json_encode($insanity))); + } + + public function testNestedLists() + { + $bonk = new \ThriftTest\Bonk(array('message' => 'foo')); + $nested = new \ThriftTest\NestedListsBonk(array('bonk' => array(array(array($bonk))))); + $expected = new stdClass(); + $expected->bonk = array(array(array((object)array('message' => 'foo')))); + $this->assertEquals($expected, json_decode(json_encode($nested))); + } + + public function testMaps() + { + $intmap = new \ThriftTest\ThriftTest_testMap_args(['thing' => [0 => 'zero']]); + $emptymap = new \ThriftTest\ThriftTest_testMap_args([]); + $this->assertEquals('{"thing":{"0":"zero"}}', json_encode($intmap)); + $this->assertEquals('{}', json_encode($emptymap)); + } + + public function testScalarTypes() + { + $b = new \ThriftTest\Bools(['im_true' => '1', 'im_false' => '0']); + $this->assertEquals('{"im_true":true,"im_false":false}', json_encode($b)); + $s = new \ThriftTest\StructA(['s' => 42]); + $this->assertEquals('{"s":"42"}', json_encode($s)); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/test/Makefile.am b/vendor/git.apache.org/thrift.git/lib/php/test/Makefile.am index d966246..4824688 100755 --- a/vendor/git.apache.org/thrift.git/lib/php/test/Makefile.am +++ b/vendor/git.apache.org/thrift.git/lib/php/test/Makefile.am @@ -17,11 +17,11 @@ # under the License. # -THRIFT = $(top_builddir)/compiler/cpp/thrift +PHPUNIT=php $(top_srcdir)/vendor/bin/phpunit stubs: ../../../test/ThriftTest.thrift TestValidators.thrift - mkdir -p ./packages - $(THRIFT) --gen php -r --out ./packages ../../../test/ThriftTest.thrift + mkdir -p ./packages/php + $(THRIFT) --gen php -r --out ./packages/php ../../../test/ThriftTest.thrift mkdir -p ./packages/phpv mkdir -p ./packages/phpvo mkdir -p ./packages/phpjs @@ -29,23 +29,21 @@ stubs: ../../../test/ThriftTest.thrift TestValidators.thrift $(THRIFT) --gen php:validate,oop -r --out ./packages/phpvo TestValidators.thrift $(THRIFT) --gen php:json -r --out ./packages/phpjs TestValidators.thrift -check-json-serializer: stubs -if HAVE_PHPUNIT - $(PHPUNIT) --log-junit=TEST-json-serializer.xml Test/Thrift/JsonSerialize/ -endif +deps: $(top_srcdir)/composer.json + composer install --working-dir=$(top_srcdir) -check-validator: stubs - php Test/Thrift/TestValidators.php - php Test/Thrift/TestValidators.php -oop +all-local: deps -check-protocol: stubs -if HAVE_PHPUNIT - $(PHPUNIT) --log-junit=TEST-log-json-protocol.xml Test/Thrift/Protocol/TestTJSONProtocol.php - $(PHPUNIT) --log-junit=TEST-binary-serializer.xml Test/Thrift/Protocol/TestBinarySerializer.php - $(PHPUNIT) --log-junit=TEST-log-simple-json-protocol.xml Test/Thrift/Protocol/TestTSimpleJSONProtocol.php -endif +check-json-serializer: deps stubs + $(PHPUNIT) --log-junit=TEST-log-json-serializer.xml JsonSerialize/ -check: stubs \ +check-validator: deps stubs + $(PHPUNIT) --log-junit=TEST-log-validator.xml Validator/ + +check-protocol: deps stubs + $(PHPUNIT) --log-junit=TEST-log-protocol.xml Protocol/ + +check: deps stubs \ check-protocol \ check-validator \ check-json-serializer @@ -53,9 +51,3 @@ check: stubs \ clean-local: $(RM) -r ./packages $(RM) TEST-*.xml - -EXTRA_DIST = \ - Test \ - TestValidators.thrift - - diff --git a/vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/Protocol/TestBinarySerializer.php b/vendor/git.apache.org/thrift.git/lib/php/test/Protocol/BinarySerializerTest.php similarity index 54% rename from vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/Protocol/TestBinarySerializer.php rename to vendor/git.apache.org/thrift.git/lib/php/test/Protocol/BinarySerializerTest.php index a983216..71b0bb5 100644 --- a/vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/Protocol/TestBinarySerializer.php +++ b/vendor/git.apache.org/thrift.git/lib/php/test/Protocol/BinarySerializerTest.php @@ -23,16 +23,10 @@ namespace Test\Thrift\Protocol; -use Thrift\ClassLoader\ThriftClassLoader; +use PHPUnit\Framework\TestCase; use Thrift\Serializer\TBinarySerializer; -require_once __DIR__.'/../../../../lib/Thrift/ClassLoader/ThriftClassLoader.php'; - -$loader = new ThriftClassLoader(); -$loader->registerNamespace('Thrift', __DIR__ . '/../../../../lib'); -$loader->registerNamespace('Test', __DIR__ . '/../../..'); -$loader->registerDefinition('ThriftTest', __DIR__ . '/../../../packages'); -$loader->register(); +require __DIR__ . '/../../../../vendor/autoload.php'; /*** * This test suite depends on running the compiler against the @@ -40,25 +34,27 @@ $loader->register(); * * lib/php/test$ ../../../compiler/cpp/thrift --gen php -r \ * --out ./packages ../../../test/ThriftTest.thrift + * + * @runTestsInSeparateProcesses */ - -class TestBinarySerializer extends \PHPUnit_Framework_TestCase +class BinarySerializerTest extends TestCase { + public function setUp() + { + /** @var \Composer\Autoload\ClassLoader $loader */ + $loader = require __DIR__ . '/../../../../vendor/autoload.php'; + $loader->addPsr4('', __DIR__ . '/../packages/php'); + } - public function setUp() - { - } - - /** - * We try to serialize and deserialize a random object to make sure no exceptions are thrown. - * @see THRIFT-1579 - */ - public function testBinarySerializer() - { - $struct = new \ThriftTest\Xtruct(array('string_thing' => 'abc')); - $serialized = TBinarySerializer::serialize($struct, 'ThriftTest\\Xtruct'); - $deserialized = TBinarySerializer::deserialize($serialized, 'ThriftTest\\Xtruct'); - $this->assertEquals($struct, $deserialized); - } - + /** + * We try to serialize and deserialize a random object to make sure no exceptions are thrown. + * @see THRIFT-1579 + */ + public function testBinarySerializer() + { + $struct = new \ThriftTest\Xtruct(array('string_thing' => 'abc')); + $serialized = TBinarySerializer::serialize($struct, 'ThriftTest\\Xtruct'); + $deserialized = TBinarySerializer::deserialize($serialized, 'ThriftTest\\Xtruct'); + $this->assertEquals($struct, $deserialized); + } } diff --git a/vendor/git.apache.org/thrift.git/lib/php/test/Protocol/TJSONProtocolFixtures.php b/vendor/git.apache.org/thrift.git/lib/php/test/Protocol/TJSONProtocolFixtures.php new file mode 100644 index 0000000..dd9039f --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/test/Protocol/TJSONProtocolFixtures.php @@ -0,0 +1,74 @@ +<><"}}'; + + self::$testArgsJSON['testString3'] = '{"1":{"str":"string that ends in double-backslash \\\\\\\\"}}'; + + self::$testArgsJSON['testUnicodeStringWithNonBMP'] = '{"1":{"str":"สวัสดี\/ð’¯"}}'; + + self::$testArgsJSON['testDouble'] = '{"1":{"dbl":3.1415926535898}}'; + + self::$testArgsJSON['testByte'] = '{"1":{"i8":1}}'; + + self::$testArgsJSON['testI32'] = '{"1":{"i32":1073741824}}'; + + if (PHP_INT_SIZE == 8) { + self::$testArgsJSON['testI64'] = '{"1":{"i64":' . pow(2, 60) . '}}'; + self::$testArgsJSON['testStruct'] = '{"1":{"rec":{"1":{"str":"worked"},"4":{"i8":1},"9":{"i32":1073741824},"11":{"i64":' . pow(2, 60) . '}}}}'; + self::$testArgsJSON['testNest'] = '{"1":{"rec":{"1":{"i8":1},"2":{"rec":{"1":{"str":"worked"},"4":{"i8":1},"9":{"i32":1073741824},"11":{"i64":' . pow(2, 60) . '}}},"3":{"i32":32768}}}}'; + } else { + self::$testArgsJSON['testI64'] = '{"1":{"i64":1152921504606847000}}'; + self::$testArgsJSON['testStruct'] = '{"1":{"rec":{"1":{"str":"worked"},"4":{"i8":1},"9":{"i32":1073741824},"11":{"i64":1152921504606847000}}}}'; + self::$testArgsJSON['testNest'] = '{"1":{"rec":{"1":{"i8":1},"2":{"rec":{"1":{"str":"worked"},"4":{"i8":1},"9":{"i32":1073741824},"11":{"i64":1152921504606847000}}},"3":{"i32":32768}}}}'; + } + + self::$testArgsJSON['testMap'] = '{"1":{"map":["i32","i32",3,{"7":77,"8":88,"9":99}]}}'; + + self::$testArgsJSON['testStringMap'] = '{"1":{"map":["str","str",6,{"a":"123","a b":"with spaces ","same":"same","0":"numeric key","longValue":"Afrikaans, Alemannisch, Aragon\u00e9s, \u0627\u0644\u0639\u0631\u0628\u064a\u0629, \u0645\u0635\u0631\u0649, Asturianu, Aymar aru, Az\u0259rbaycan, \u0411\u0430\u0448\u04a1\u043e\u0440\u0442, Boarisch, \u017demait\u0117\u0161ka, \u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f, \u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f (\u0442\u0430\u0440\u0430\u0448\u043a\u0435\u0432\u0456\u0446\u0430), \u0411\u044a\u043b\u0433\u0430\u0440\u0441\u043a\u0438, Bamanankan, \u09ac\u09be\u0982\u09b2\u09be, Brezhoneg, Bosanski, Catal\u00e0, M\u00ecng-d\u0115\u0324ng-ng\u1e73\u0304, \u041d\u043e\u0445\u0447\u0438\u0439\u043d, Cebuano, \u13e3\u13b3\u13a9, \u010cesky, \u0421\u043b\u043e\u0432\u0463\u0301\u043d\u044c\u0441\u043a\u044a \/ \u2c14\u2c0e\u2c11\u2c02\u2c21\u2c10\u2c20\u2c14\u2c0d\u2c1f, \u0427\u04d1\u0432\u0430\u0448\u043b\u0430, Cymraeg, Dansk, Zazaki, \u078b\u07a8\u0788\u07ac\u0780\u07a8\u0784\u07a6\u0790\u07b0, \u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac, Emili\u00e0n e rumagn\u00f2l, English, Esperanto, Espa\u00f1ol, Eesti, Euskara, \u0641\u0627\u0631\u0633\u06cc, Suomi, V\u00f5ro, F\u00f8royskt, Fran\u00e7ais, Arpetan, Furlan, Frysk, Gaeilge, \u8d1b\u8a9e, G\u00e0idhlig, Galego, Ava\u00f1e\'\u1ebd, \u0a97\u0ac1\u0a9c\u0ab0\u0abe\u0aa4\u0ac0, Gaelg, \u05e2\u05d1\u05e8\u05d9\u05ea, \u0939\u093f\u0928\u094d\u0926\u0940, Fiji Hindi, Hrvatski, Krey\u00f2l ayisyen, Magyar, \u0540\u0561\u0575\u0565\u0580\u0565\u0576, Interlingua, Bahasa Indonesia, Ilokano, Ido, \u00cdslenska, Italiano, \u65e5\u672c\u8a9e, Lojban, Basa Jawa, \u10e5\u10d0\u10e0\u10d7\u10e3\u10da\u10d8, Kongo, Kalaallisut, \u0c95\u0ca8\u0ccd\u0ca8\u0ca1, \ud55c\uad6d\uc5b4, \u041a\u044a\u0430\u0440\u0430\u0447\u0430\u0439-\u041c\u0430\u043b\u043a\u044a\u0430\u0440, Ripoarisch, Kurd\u00ee, \u041a\u043e\u043c\u0438, Kernewek, \u041a\u044b\u0440\u0433\u044b\u0437\u0447\u0430, Latina, Ladino, L\u00ebtzebuergesch, Limburgs, Ling\u00e1la, \u0ea5\u0eb2\u0ea7, Lietuvi\u0173, Latvie\u0161u, Basa Banyumasan, Malagasy, \u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a\u0438, \u0d2e\u0d32\u0d2f\u0d3e\u0d33\u0d02, \u092e\u0930\u093e\u0920\u0940, Bahasa Melayu, \u0645\u0627\u0632\u0650\u0631\u0648\u0646\u06cc, Nnapulitano, Nedersaksisch, \u0928\u0947\u092a\u093e\u0932 \u092d\u093e\u0937\u093e, Nederlands, \u202aNorsk (nynorsk)\u202c, \u202aNorsk (bokm\u00e5l)\u202c, Nouormand, Din\u00e9 bizaad, Occitan, \u0418\u0440\u043e\u043d\u0430\u0443, Papiamentu, Deitsch, Norfuk \/ Pitkern, Polski, \u067e\u0646\u062c\u0627\u0628\u06cc, \u067e\u069a\u062a\u0648, Portugu\u00eas, Runa Simi, Rumantsch, Romani, Rom\u00e2n\u0103, \u0420\u0443\u0441\u0441\u043a\u0438\u0439, \u0421\u0430\u0445\u0430 \u0442\u044b\u043b\u0430, Sardu, Sicilianu, Scots, S\u00e1megiella, Simple English, Sloven\u010dina, Sloven\u0161\u010dina, \u0421\u0440\u043f\u0441\u043a\u0438 \/ Srpski, Seeltersk, Svenska, Kiswahili, \u0ba4\u0bae\u0bbf\u0bb4\u0bcd, \u0c24\u0c46\u0c32\u0c41\u0c17\u0c41, \u0422\u043e\u04b7\u0438\u043a\u04e3, \u0e44\u0e17\u0e22, T\u00fcrkmen\u00e7e, Tagalog, T\u00fcrk\u00e7e, \u0422\u0430\u0442\u0430\u0440\u0447\u0430\/Tatar\u00e7a, \u0423\u043a\u0440\u0430\u0457\u043d\u0441\u044c\u043a\u0430, \u0627\u0631\u062f\u0648, Ti\u1ebfng Vi\u1ec7t, Volap\u00fck, Walon, Winaray, \u5434\u8bed, isiXhosa, \u05d9\u05d9\u05b4\u05d3\u05d9\u05e9, Yor\u00f9b\u00e1, Ze\u00eauws, \u4e2d\u6587, B\u00e2n-l\u00e2m-g\u00fa, \u7cb5\u8a9e","Afrikaans, Alemannisch, Aragon\u00e9s, \u0627\u0644\u0639\u0631\u0628\u064a\u0629, \u0645\u0635\u0631\u0649, Asturianu, Aymar aru, Az\u0259rbaycan, \u0411\u0430\u0448\u04a1\u043e\u0440\u0442, Boarisch, \u017demait\u0117\u0161ka, \u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f, \u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f (\u0442\u0430\u0440\u0430\u0448\u043a\u0435\u0432\u0456\u0446\u0430), \u0411\u044a\u043b\u0433\u0430\u0440\u0441\u043a\u0438, Bamanankan, \u09ac\u09be\u0982\u09b2\u09be, Brezhoneg, Bosanski, Catal\u00e0, M\u00ecng-d\u0115\u0324ng-ng\u1e73\u0304, \u041d\u043e\u0445\u0447\u0438\u0439\u043d, Cebuano, \u13e3\u13b3\u13a9, \u010cesky, \u0421\u043b\u043e\u0432\u0463\u0301\u043d\u044c\u0441\u043a\u044a \/ \u2c14\u2c0e\u2c11\u2c02\u2c21\u2c10\u2c20\u2c14\u2c0d\u2c1f, \u0427\u04d1\u0432\u0430\u0448\u043b\u0430, Cymraeg, Dansk, Zazaki, \u078b\u07a8\u0788\u07ac\u0780\u07a8\u0784\u07a6\u0790\u07b0, \u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac, Emili\u00e0n e rumagn\u00f2l, English, Esperanto, Espa\u00f1ol, Eesti, Euskara, \u0641\u0627\u0631\u0633\u06cc, Suomi, V\u00f5ro, F\u00f8royskt, Fran\u00e7ais, Arpetan, Furlan, Frysk, Gaeilge, \u8d1b\u8a9e, G\u00e0idhlig, Galego, Ava\u00f1e\'\u1ebd, \u0a97\u0ac1\u0a9c\u0ab0\u0abe\u0aa4\u0ac0, Gaelg, \u05e2\u05d1\u05e8\u05d9\u05ea, \u0939\u093f\u0928\u094d\u0926\u0940, Fiji Hindi, Hrvatski, Krey\u00f2l ayisyen, Magyar, \u0540\u0561\u0575\u0565\u0580\u0565\u0576, Interlingua, Bahasa Indonesia, Ilokano, Ido, \u00cdslenska, Italiano, \u65e5\u672c\u8a9e, Lojban, Basa Jawa, \u10e5\u10d0\u10e0\u10d7\u10e3\u10da\u10d8, Kongo, Kalaallisut, \u0c95\u0ca8\u0ccd\u0ca8\u0ca1, \ud55c\uad6d\uc5b4, \u041a\u044a\u0430\u0440\u0430\u0447\u0430\u0439-\u041c\u0430\u043b\u043a\u044a\u0430\u0440, Ripoarisch, Kurd\u00ee, \u041a\u043e\u043c\u0438, Kernewek, \u041a\u044b\u0440\u0433\u044b\u0437\u0447\u0430, Latina, Ladino, L\u00ebtzebuergesch, Limburgs, Ling\u00e1la, \u0ea5\u0eb2\u0ea7, Lietuvi\u0173, Latvie\u0161u, Basa Banyumasan, Malagasy, \u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a\u0438, \u0d2e\u0d32\u0d2f\u0d3e\u0d33\u0d02, \u092e\u0930\u093e\u0920\u0940, Bahasa Melayu, \u0645\u0627\u0632\u0650\u0631\u0648\u0646\u06cc, Nnapulitano, Nedersaksisch, \u0928\u0947\u092a\u093e\u0932 \u092d\u093e\u0937\u093e, Nederlands, \u202aNorsk (nynorsk)\u202c, \u202aNorsk (bokm\u00e5l)\u202c, Nouormand, Din\u00e9 bizaad, Occitan, \u0418\u0440\u043e\u043d\u0430\u0443, Papiamentu, Deitsch, Norfuk \/ Pitkern, Polski, \u067e\u0646\u062c\u0627\u0628\u06cc, \u067e\u069a\u062a\u0648, Portugu\u00eas, Runa Simi, Rumantsch, Romani, Rom\u00e2n\u0103, \u0420\u0443\u0441\u0441\u043a\u0438\u0439, \u0421\u0430\u0445\u0430 \u0442\u044b\u043b\u0430, Sardu, Sicilianu, Scots, S\u00e1megiella, Simple English, Sloven\u010dina, Sloven\u0161\u010dina, \u0421\u0440\u043f\u0441\u043a\u0438 \/ Srpski, Seeltersk, Svenska, Kiswahili, \u0ba4\u0bae\u0bbf\u0bb4\u0bcd, \u0c24\u0c46\u0c32\u0c41\u0c17\u0c41, \u0422\u043e\u04b7\u0438\u043a\u04e3, \u0e44\u0e17\u0e22, T\u00fcrkmen\u00e7e, Tagalog, T\u00fcrk\u00e7e, \u0422\u0430\u0442\u0430\u0440\u0447\u0430\/Tatar\u00e7a, \u0423\u043a\u0440\u0430\u0457\u043d\u0441\u044c\u043a\u0430, \u0627\u0631\u062f\u0648, Ti\u1ebfng Vi\u1ec7t, Volap\u00fck, Walon, Winaray, \u5434\u8bed, isiXhosa, \u05d9\u05d9\u05b4\u05d3\u05d9\u05e9, Yor\u00f9b\u00e1, Ze\u00eauws, \u4e2d\u6587, B\u00e2n-l\u00e2m-g\u00fa, \u7cb5\u8a9e":"long key"}]}}'; + + self::$testArgsJSON['testSet'] = '{"1":{"set":["i32",3,1,5,6]}}'; + + self::$testArgsJSON['testList'] = '{"1":{"lst":["i32",3,1,2,3]}}'; + + self::$testArgsJSON['testEnum'] = '{"1":{"i32":1}}'; + + self::$testArgsJSON['testTypedef'] = '{"1":{"i64":69}}'; + + self::$testArgsJSON['testMapMap'] = '{"0":{"map":["i32","map",2,{"4":["i32","i32",4,{"1":1,"2":2,"3":3,"4":4}],"-4":["i32","i32",4,{"-4":-4,"-3":-3,"-2":-2,"-1":-1}]}]}}'; + + self::$testArgsJSON['testInsanity'] = '{"0":{"map":["i64","map",2,{"1":["i32","rec",2,{"2":{"1":{"map":["i32","i64",2,{"5":5,"8":8}]},"2":{"lst":["rec",2,{"1":{"str":"Goodbye4"},"4":{"i8":4},"9":{"i32":4},"11":{"i64":4}},{"1":{"str":"Hello2"},"4":{"i8":2},"9":{"i32":2},"11":{"i64":2}}]}},"3":{"1":{"map":["i32","i64",2,{"5":5,"8":8}]},"2":{"lst":["rec",2,{"1":{"str":"Goodbye4"},"4":{"i8":4},"9":{"i32":4},"11":{"i64":4}},{"1":{"str":"Hello2"},"4":{"i8":2},"9":{"i32":2},"11":{"i64":2}}]}}}],"2":["i32","rec",1,{"6":{}}]}]}}'; + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/test/Protocol/TJSONProtocolTest.php b/vendor/git.apache.org/thrift.git/lib/php/test/Protocol/TJSONProtocolTest.php new file mode 100644 index 0000000..bf0ecce --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/test/Protocol/TJSONProtocolTest.php @@ -0,0 +1,518 @@ +addPsr4('', __DIR__ . '/../packages/php'); + + Fixtures::populateTestArgs(); + TJSONProtocolFixtures::populateTestArgsJSON(); + } + + public function setUp() + { + $this->transport = new TMemoryBuffer(); + $this->protocol = new TJSONProtocol($this->transport); + $this->transport->open(); + } + + /** + * WRITE TESTS + */ + public function testVoidWrite() + { + $args = new \ThriftTest\ThriftTest_testVoid_args(); + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TJSONProtocolFixtures::$testArgsJSON['testVoid']; + + $this->assertEquals($expected, $actual); + } + + public function testString1Write() + { + $args = new \ThriftTest\ThriftTest_testString_args(); + $args->thing = Fixtures::$testArgs['testString1']; + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TJSONProtocolFixtures::$testArgsJSON['testString1']; + + $this->assertEquals($expected, $actual); + } + + public function testString2Write() + { + $args = new \ThriftTest\ThriftTest_testString_args(); + $args->thing = Fixtures::$testArgs['testString2']; + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TJSONProtocolFixtures::$testArgsJSON['testString2']; + + $this->assertEquals($expected, $actual); + } + + public function testDoubleWrite() + { + $args = new \ThriftTest\ThriftTest_testDouble_args(); + $args->thing = Fixtures::$testArgs['testDouble']; + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TJSONProtocolFixtures::$testArgsJSON['testDouble']; + + $this->assertEquals($expected, $actual); + } + + public function testByteWrite() + { + $args = new \ThriftTest\ThriftTest_testByte_args(); + $args->thing = Fixtures::$testArgs['testByte']; + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TJSONProtocolFixtures::$testArgsJSON['testByte']; + + $this->assertEquals($expected, $actual); + } + + public function testI32Write() + { + $args = new \ThriftTest\ThriftTest_testI32_args(); + $args->thing = Fixtures::$testArgs['testI32']; + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TJSONProtocolFixtures::$testArgsJSON['testI32']; + + $this->assertEquals($expected, $actual); + } + + public function testI64Write() + { + $args = new \ThriftTest\ThriftTest_testI64_args(); + $args->thing = Fixtures::$testArgs['testI64']; + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TJSONProtocolFixtures::$testArgsJSON['testI64']; + + $this->assertEquals($expected, $actual); + } + + public function testStructWrite() + { + $args = new \ThriftTest\ThriftTest_testStruct_args(); + $args->thing = Fixtures::$testArgs['testStruct']; + + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TJSONProtocolFixtures::$testArgsJSON['testStruct']; + + $this->assertEquals($expected, $actual); + } + + public function testNestWrite() + { + $args = new \ThriftTest\ThriftTest_testNest_args(); + $args->thing = Fixtures::$testArgs['testNest']; + + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TJSONProtocolFixtures::$testArgsJSON['testNest']; + + $this->assertEquals($expected, $actual); + } + + public function testMapWrite() + { + $args = new \ThriftTest\ThriftTest_testMap_args(); + $args->thing = Fixtures::$testArgs['testMap']; + + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TJSONProtocolFixtures::$testArgsJSON['testMap']; + + $this->assertEquals($expected, $actual); + } + + public function testStringMapWrite() + { + $args = new \ThriftTest\ThriftTest_testStringMap_args(); + $args->thing = Fixtures::$testArgs['testStringMap']; + + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TJSONProtocolFixtures::$testArgsJSON['testStringMap']; + + /* + * The $actual returns unescaped string. + * It is required to to decode then encode it again + * to get the expected escaped unicode. + */ + $this->assertEquals($expected, json_encode(json_decode($actual))); + } + + public function testSetWrite() + { + $args = new \ThriftTest\ThriftTest_testSet_args(); + $args->thing = Fixtures::$testArgs['testSet']; + + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TJSONProtocolFixtures::$testArgsJSON['testSet']; + + $this->assertEquals($expected, $actual); + } + + public function testListWrite() + { + $args = new \ThriftTest\ThriftTest_testList_args(); + $args->thing = Fixtures::$testArgs['testList']; + + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TJSONProtocolFixtures::$testArgsJSON['testList']; + + $this->assertEquals($expected, $actual); + } + + public function testEnumWrite() + { + $args = new \ThriftTest\ThriftTest_testEnum_args(); + $args->thing = Fixtures::$testArgs['testEnum']; + + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TJSONProtocolFixtures::$testArgsJSON['testEnum']; + + $this->assertEquals($expected, $actual); + } + + public function testTypedefWrite() + { + $args = new \ThriftTest\ThriftTest_testTypedef_args(); + $args->thing = Fixtures::$testArgs['testTypedef']; + + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TJSONProtocolFixtures::$testArgsJSON['testTypedef']; + + $this->assertEquals($expected, $actual); + } + + /** + * READ TESTS + */ + public function testVoidRead() + { + $this->transport->write( + TJSONProtocolFixtures::$testArgsJSON['testVoid'] + ); + $args = new \ThriftTest\ThriftTest_testVoid_args(); + $args->read($this->protocol); + } + + public function testString1Read() + { + $this->transport->write( + TJSONProtocolFixtures::$testArgsJSON['testString1'] + ); + $args = new \ThriftTest\ThriftTest_testString_args(); + $args->read($this->protocol); + + $actual = $args->thing; + $expected = Fixtures::$testArgs['testString1']; + + $this->assertEquals($expected, $actual); + } + + public function testString2Read() + { + $this->transport->write( + TJSONProtocolFixtures::$testArgsJSON['testString2'] + ); + $args = new \ThriftTest\ThriftTest_testString_args(); + $args->read($this->protocol); + + $actual = $args->thing; + $expected = Fixtures::$testArgs['testString2']; + + $this->assertEquals($expected, $actual); + } + + public function testString3Write() + { + $args = new \ThriftTest\ThriftTest_testString_args(); + $args->thing = Fixtures::$testArgs['testString3']; + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TJSONProtocolFixtures::$testArgsJSON['testString3']; + + $this->assertEquals($expected, $actual); + } + + public function testString4Write() + { + $args = new \ThriftTest\ThriftTest_testString_args(); + $args->thing = Fixtures::$testArgs['testUnicodeStringWithNonBMP']; + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TJSONProtocolFixtures::$testArgsJSON['testUnicodeStringWithNonBMP']; + + $this->assertEquals($expected, $actual); + } + + public function testDoubleRead() + { + $this->transport->write( + TJSONProtocolFixtures::$testArgsJSON['testDouble'] + ); + $args = new \ThriftTest\ThriftTest_testDouble_args(); + $args->read($this->protocol); + + $actual = $args->thing; + $expected = Fixtures::$testArgs['testDouble']; + + $this->assertEquals($expected, $actual); + } + + public function testByteRead() + { + $this->transport->write( + TJSONProtocolFixtures::$testArgsJSON['testByte'] + ); + $args = new \ThriftTest\ThriftTest_testByte_args(); + $args->read($this->protocol); + + $actual = $args->thing; + $expected = Fixtures::$testArgs['testByte']; + + $this->assertEquals($expected, $actual); + } + + public function testI32Read() + { + $this->transport->write( + TJSONProtocolFixtures::$testArgsJSON['testI32'] + ); + $args = new \ThriftTest\ThriftTest_testI32_args(); + $args->read($this->protocol); + + $actual = $args->thing; + $expected = Fixtures::$testArgs['testI32']; + + $this->assertEquals($expected, $actual); + } + + public function testI64Read() + { + $this->transport->write( + TJSONProtocolFixtures::$testArgsJSON['testI64'] + ); + $args = new \ThriftTest\ThriftTest_testI64_args(); + $args->read($this->protocol); + + $actual = $args->thing; + $expected = Fixtures::$testArgs['testI64']; + + $this->assertEquals($expected, $actual); + } + + public function testStructRead() + { + $this->transport->write( + TJSONProtocolFixtures::$testArgsJSON['testStruct'] + ); + $args = new \ThriftTest\ThriftTest_testStruct_args(); + $args->read($this->protocol); + + $actual = $args->thing; + $expected = Fixtures::$testArgs['testStruct']; + + $this->assertEquals($expected, $actual); + } + + public function testNestRead() + { + $this->transport->write( + TJSONProtocolFixtures::$testArgsJSON['testNest'] + ); + $args = new \ThriftTest\ThriftTest_testNest_args(); + $args->read($this->protocol); + + $actual = $args->thing; + $expected = Fixtures::$testArgs['testNest']; + + $this->assertEquals($expected, $actual); + } + + public function testMapRead() + { + $this->transport->write( + TJSONProtocolFixtures::$testArgsJSON['testMap'] + ); + $args = new \ThriftTest\ThriftTest_testMap_args(); + $args->read($this->protocol); + + $actual = $args->thing; + $expected = Fixtures::$testArgs['testMap']; + + $this->assertEquals($expected, $actual); + } + + public function testStringMapRead() + { + $this->transport->write( + TJSONProtocolFixtures::$testArgsJSON['testStringMap'] + ); + $args = new \ThriftTest\ThriftTest_testStringMap_args(); + $args->read($this->protocol); + + $actual = $args->thing; + $expected = Fixtures::$testArgs['testStringMap']; + + $this->assertEquals($expected, $actual); + } + + public function testSetRead() + { + $this->transport->write( + TJSONProtocolFixtures::$testArgsJSON['testSet'] + ); + $args = new \ThriftTest\ThriftTest_testSet_args(); + $args->read($this->protocol); + + $actual = $args->thing; + $expected = Fixtures::$testArgs['testSet']; + + $this->assertEquals($expected, $actual); + } + + public function testListRead() + { + $this->transport->write( + TJSONProtocolFixtures::$testArgsJSON['testList'] + ); + $args = new \ThriftTest\ThriftTest_testList_args(); + $args->read($this->protocol); + + $actual = $args->thing; + $expected = Fixtures::$testArgs['testList']; + + $this->assertEquals($expected, $actual); + } + + public function testEnumRead() + { + $this->transport->write( + TJSONProtocolFixtures::$testArgsJSON['testEnum'] + ); + $args = new \ThriftTest\ThriftTest_testEnum_args(); + $args->read($this->protocol); + + $actual = $args->thing; + $expected = Fixtures::$testArgs['testEnum']; + + $this->assertEquals($expected, $actual); + } + + public function testTypedefRead() + { + $this->transport->write( + TJSONProtocolFixtures::$testArgsJSON['testTypedef'] + ); + $args = new \ThriftTest\ThriftTest_testTypedef_args(); + $args->read($this->protocol); + + $actual = $args->thing; + $expected = Fixtures::$testArgs['testTypedef']; + + $this->assertEquals($expected, $actual); + } + + public function testMapMapRead() + { + $this->transport->write( + TJSONProtocolFixtures::$testArgsJSON['testMapMap'] + ); + $result = new \ThriftTest\ThriftTest_testMapMap_result(); + $result->read($this->protocol); + + $actual = $result->success; + $expected = Fixtures::$testArgs['testMapMapExpectedResult']; + + $this->assertEquals($expected, $actual); + } + + public function testInsanityRead() + { + $this->transport->write( + TJSONProtocolFixtures::$testArgsJSON['testInsanity'] + ); + $result = new \ThriftTest\ThriftTest_testInsanity_result(); + $result->read($this->protocol); + + $actual = $result->success; + $expected = Fixtures::$testArgs['testInsanityExpectedResult']; + + $this->assertEquals($expected, $actual); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/test/Protocol/TSimpleJSONProtocolFixtures.php b/vendor/git.apache.org/thrift.git/lib/php/test/Protocol/TSimpleJSONProtocolFixtures.php new file mode 100644 index 0000000..547fd86 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/test/Protocol/TSimpleJSONProtocolFixtures.php @@ -0,0 +1,67 @@ +<><"}'; + + self::$testArgsJSON['testDouble'] = '{"thing":3.1415926535898}'; + + self::$testArgsJSON['testByte'] = '{"thing":1}'; + + self::$testArgsJSON['testI32'] = '{"thing":1073741824}'; + + if (PHP_INT_SIZE == 8) { + self::$testArgsJSON['testI64'] = '{"thing":' . pow(2, 60) . '}'; + self::$testArgsJSON['testStruct'] = '{"thing":{"string_thing":"worked","byte_thing":1,"i32_thing":1073741824,"i64_thing":' . pow(2, 60) . '}}'; + self::$testArgsJSON['testNest'] = '{"thing":{"byte_thing":1,"struct_thing":{"string_thing":"worked","byte_thing":1,"i32_thing":1073741824,"i64_thing":' . pow(2, 60) . '},"i32_thing":32768}}'; + } else { + self::$testArgsJSON['testI64'] = '{"thing":1152921504606847000}'; + + self::$testArgsJSON['testStruct'] = '{"thing":{"string_thing":"worked","byte_thing":1,"i32_thing":1073741824,"i64_thing":1152921504606847000}}'; + self::$testArgsJSON['testNest'] = '{"thing":{"byte_thing":1,"struct_thing":{"string_thing":"worked","byte_thing":1,"i32_thing":1073741824,"i64_thing":1152921504606847000},"i32_thing":32768}}'; + } + + self::$testArgsJSON['testMap'] = '{"thing":{"7":77,"8":88,"9":99}}'; + + self::$testArgsJSON['testStringMap'] = '{"thing":{"a":"123","a b":"with spaces ","same":"same","0":"numeric key","longValue":"Afrikaans, Alemannisch, Aragon\u00e9s, \u0627\u0644\u0639\u0631\u0628\u064a\u0629, \u0645\u0635\u0631\u0649, Asturianu, Aymar aru, Az\u0259rbaycan, \u0411\u0430\u0448\u04a1\u043e\u0440\u0442, Boarisch, \u017demait\u0117\u0161ka, \u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f, \u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f (\u0442\u0430\u0440\u0430\u0448\u043a\u0435\u0432\u0456\u0446\u0430), \u0411\u044a\u043b\u0433\u0430\u0440\u0441\u043a\u0438, Bamanankan, \u09ac\u09be\u0982\u09b2\u09be, Brezhoneg, Bosanski, Catal\u00e0, M\u00ecng-d\u0115\u0324ng-ng\u1e73\u0304, \u041d\u043e\u0445\u0447\u0438\u0439\u043d, Cebuano, \u13e3\u13b3\u13a9, \u010cesky, \u0421\u043b\u043e\u0432\u0463\u0301\u043d\u044c\u0441\u043a\u044a \/ \u2c14\u2c0e\u2c11\u2c02\u2c21\u2c10\u2c20\u2c14\u2c0d\u2c1f, \u0427\u04d1\u0432\u0430\u0448\u043b\u0430, Cymraeg, Dansk, Zazaki, \u078b\u07a8\u0788\u07ac\u0780\u07a8\u0784\u07a6\u0790\u07b0, \u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac, Emili\u00e0n e rumagn\u00f2l, English, Esperanto, Espa\u00f1ol, Eesti, Euskara, \u0641\u0627\u0631\u0633\u06cc, Suomi, V\u00f5ro, F\u00f8royskt, Fran\u00e7ais, Arpetan, Furlan, Frysk, Gaeilge, \u8d1b\u8a9e, G\u00e0idhlig, Galego, Ava\u00f1e\'\u1ebd, \u0a97\u0ac1\u0a9c\u0ab0\u0abe\u0aa4\u0ac0, Gaelg, \u05e2\u05d1\u05e8\u05d9\u05ea, \u0939\u093f\u0928\u094d\u0926\u0940, Fiji Hindi, Hrvatski, Krey\u00f2l ayisyen, Magyar, \u0540\u0561\u0575\u0565\u0580\u0565\u0576, Interlingua, Bahasa Indonesia, Ilokano, Ido, \u00cdslenska, Italiano, \u65e5\u672c\u8a9e, Lojban, Basa Jawa, \u10e5\u10d0\u10e0\u10d7\u10e3\u10da\u10d8, Kongo, Kalaallisut, \u0c95\u0ca8\u0ccd\u0ca8\u0ca1, \ud55c\uad6d\uc5b4, \u041a\u044a\u0430\u0440\u0430\u0447\u0430\u0439-\u041c\u0430\u043b\u043a\u044a\u0430\u0440, Ripoarisch, Kurd\u00ee, \u041a\u043e\u043c\u0438, Kernewek, \u041a\u044b\u0440\u0433\u044b\u0437\u0447\u0430, Latina, Ladino, L\u00ebtzebuergesch, Limburgs, Ling\u00e1la, \u0ea5\u0eb2\u0ea7, Lietuvi\u0173, Latvie\u0161u, Basa Banyumasan, Malagasy, \u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a\u0438, \u0d2e\u0d32\u0d2f\u0d3e\u0d33\u0d02, \u092e\u0930\u093e\u0920\u0940, Bahasa Melayu, \u0645\u0627\u0632\u0650\u0631\u0648\u0646\u06cc, Nnapulitano, Nedersaksisch, \u0928\u0947\u092a\u093e\u0932 \u092d\u093e\u0937\u093e, Nederlands, \u202aNorsk (nynorsk)\u202c, \u202aNorsk (bokm\u00e5l)\u202c, Nouormand, Din\u00e9 bizaad, Occitan, \u0418\u0440\u043e\u043d\u0430\u0443, Papiamentu, Deitsch, Norfuk \/ Pitkern, Polski, \u067e\u0646\u062c\u0627\u0628\u06cc, \u067e\u069a\u062a\u0648, Portugu\u00eas, Runa Simi, Rumantsch, Romani, Rom\u00e2n\u0103, \u0420\u0443\u0441\u0441\u043a\u0438\u0439, \u0421\u0430\u0445\u0430 \u0442\u044b\u043b\u0430, Sardu, Sicilianu, Scots, S\u00e1megiella, Simple English, Sloven\u010dina, Sloven\u0161\u010dina, \u0421\u0440\u043f\u0441\u043a\u0438 \/ Srpski, Seeltersk, Svenska, Kiswahili, \u0ba4\u0bae\u0bbf\u0bb4\u0bcd, \u0c24\u0c46\u0c32\u0c41\u0c17\u0c41, \u0422\u043e\u04b7\u0438\u043a\u04e3, \u0e44\u0e17\u0e22, T\u00fcrkmen\u00e7e, Tagalog, T\u00fcrk\u00e7e, \u0422\u0430\u0442\u0430\u0440\u0447\u0430\/Tatar\u00e7a, \u0423\u043a\u0440\u0430\u0457\u043d\u0441\u044c\u043a\u0430, \u0627\u0631\u062f\u0648, Ti\u1ebfng Vi\u1ec7t, Volap\u00fck, Walon, Winaray, \u5434\u8bed, isiXhosa, \u05d9\u05d9\u05b4\u05d3\u05d9\u05e9, Yor\u00f9b\u00e1, Ze\u00eauws, \u4e2d\u6587, B\u00e2n-l\u00e2m-g\u00fa, \u7cb5\u8a9e","Afrikaans, Alemannisch, Aragon\u00e9s, \u0627\u0644\u0639\u0631\u0628\u064a\u0629, \u0645\u0635\u0631\u0649, Asturianu, Aymar aru, Az\u0259rbaycan, \u0411\u0430\u0448\u04a1\u043e\u0440\u0442, Boarisch, \u017demait\u0117\u0161ka, \u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f, \u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f (\u0442\u0430\u0440\u0430\u0448\u043a\u0435\u0432\u0456\u0446\u0430), \u0411\u044a\u043b\u0433\u0430\u0440\u0441\u043a\u0438, Bamanankan, \u09ac\u09be\u0982\u09b2\u09be, Brezhoneg, Bosanski, Catal\u00e0, M\u00ecng-d\u0115\u0324ng-ng\u1e73\u0304, \u041d\u043e\u0445\u0447\u0438\u0439\u043d, Cebuano, \u13e3\u13b3\u13a9, \u010cesky, \u0421\u043b\u043e\u0432\u0463\u0301\u043d\u044c\u0441\u043a\u044a \/ \u2c14\u2c0e\u2c11\u2c02\u2c21\u2c10\u2c20\u2c14\u2c0d\u2c1f, \u0427\u04d1\u0432\u0430\u0448\u043b\u0430, Cymraeg, Dansk, Zazaki, \u078b\u07a8\u0788\u07ac\u0780\u07a8\u0784\u07a6\u0790\u07b0, \u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac, Emili\u00e0n e rumagn\u00f2l, English, Esperanto, Espa\u00f1ol, Eesti, Euskara, \u0641\u0627\u0631\u0633\u06cc, Suomi, V\u00f5ro, F\u00f8royskt, Fran\u00e7ais, Arpetan, Furlan, Frysk, Gaeilge, \u8d1b\u8a9e, G\u00e0idhlig, Galego, Ava\u00f1e\'\u1ebd, \u0a97\u0ac1\u0a9c\u0ab0\u0abe\u0aa4\u0ac0, Gaelg, \u05e2\u05d1\u05e8\u05d9\u05ea, \u0939\u093f\u0928\u094d\u0926\u0940, Fiji Hindi, Hrvatski, Krey\u00f2l ayisyen, Magyar, \u0540\u0561\u0575\u0565\u0580\u0565\u0576, Interlingua, Bahasa Indonesia, Ilokano, Ido, \u00cdslenska, Italiano, \u65e5\u672c\u8a9e, Lojban, Basa Jawa, \u10e5\u10d0\u10e0\u10d7\u10e3\u10da\u10d8, Kongo, Kalaallisut, \u0c95\u0ca8\u0ccd\u0ca8\u0ca1, \ud55c\uad6d\uc5b4, \u041a\u044a\u0430\u0440\u0430\u0447\u0430\u0439-\u041c\u0430\u043b\u043a\u044a\u0430\u0440, Ripoarisch, Kurd\u00ee, \u041a\u043e\u043c\u0438, Kernewek, \u041a\u044b\u0440\u0433\u044b\u0437\u0447\u0430, Latina, Ladino, L\u00ebtzebuergesch, Limburgs, Ling\u00e1la, \u0ea5\u0eb2\u0ea7, Lietuvi\u0173, Latvie\u0161u, Basa Banyumasan, Malagasy, \u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a\u0438, \u0d2e\u0d32\u0d2f\u0d3e\u0d33\u0d02, \u092e\u0930\u093e\u0920\u0940, Bahasa Melayu, \u0645\u0627\u0632\u0650\u0631\u0648\u0646\u06cc, Nnapulitano, Nedersaksisch, \u0928\u0947\u092a\u093e\u0932 \u092d\u093e\u0937\u093e, Nederlands, \u202aNorsk (nynorsk)\u202c, \u202aNorsk (bokm\u00e5l)\u202c, Nouormand, Din\u00e9 bizaad, Occitan, \u0418\u0440\u043e\u043d\u0430\u0443, Papiamentu, Deitsch, Norfuk \/ Pitkern, Polski, \u067e\u0646\u062c\u0627\u0628\u06cc, \u067e\u069a\u062a\u0648, Portugu\u00eas, Runa Simi, Rumantsch, Romani, Rom\u00e2n\u0103, \u0420\u0443\u0441\u0441\u043a\u0438\u0439, \u0421\u0430\u0445\u0430 \u0442\u044b\u043b\u0430, Sardu, Sicilianu, Scots, S\u00e1megiella, Simple English, Sloven\u010dina, Sloven\u0161\u010dina, \u0421\u0440\u043f\u0441\u043a\u0438 \/ Srpski, Seeltersk, Svenska, Kiswahili, \u0ba4\u0bae\u0bbf\u0bb4\u0bcd, \u0c24\u0c46\u0c32\u0c41\u0c17\u0c41, \u0422\u043e\u04b7\u0438\u043a\u04e3, \u0e44\u0e17\u0e22, T\u00fcrkmen\u00e7e, Tagalog, T\u00fcrk\u00e7e, \u0422\u0430\u0442\u0430\u0440\u0447\u0430\/Tatar\u00e7a, \u0423\u043a\u0440\u0430\u0457\u043d\u0441\u044c\u043a\u0430, \u0627\u0631\u062f\u0648, Ti\u1ebfng Vi\u1ec7t, Volap\u00fck, Walon, Winaray, \u5434\u8bed, isiXhosa, \u05d9\u05d9\u05b4\u05d3\u05d9\u05e9, Yor\u00f9b\u00e1, Ze\u00eauws, \u4e2d\u6587, B\u00e2n-l\u00e2m-g\u00fa, \u7cb5\u8a9e":"long key"}}'; + + self::$testArgsJSON['testSet'] = '{"thing":[1,5,6]}'; + + self::$testArgsJSON['testList'] = '{"thing":[1,2,3]}'; + + self::$testArgsJSON['testEnum'] = '{"thing":1}'; + + self::$testArgsJSON['testTypedef'] = '{"thing":69}'; + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/test/Protocol/TSimpleJSONProtocolTest.php b/vendor/git.apache.org/thrift.git/lib/php/test/Protocol/TSimpleJSONProtocolTest.php new file mode 100644 index 0000000..e4a1373 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/test/Protocol/TSimpleJSONProtocolTest.php @@ -0,0 +1,254 @@ +addPsr4('', __DIR__ . '/../packages/php'); + + Fixtures::populateTestArgs(); + TSimpleJSONProtocolFixtures::populateTestArgsSimpleJSON(); + } + + public function setUp() + { + $this->transport = new TMemoryBuffer(); + $this->protocol = new TSimpleJSONProtocol($this->transport); + $this->transport->open(); + } + + /** + * WRITE TESTS + */ + public function testVoidWrite() + { + $args = new \ThriftTest\ThriftTest_testVoid_args(); + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TSimpleJSONProtocolFixtures::$testArgsJSON['testVoid']; + + $this->assertEquals($expected, $actual); + } + + public function testString1Write() + { + $args = new \ThriftTest\ThriftTest_testString_args(); + $args->thing = Fixtures::$testArgs['testString1']; + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TSimpleJSONProtocolFixtures::$testArgsJSON['testString1']; + + $this->assertEquals($expected, $actual); + } + + public function testString2Write() + { + $args = new \ThriftTest\ThriftTest_testString_args(); + $args->thing = Fixtures::$testArgs['testString2']; + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TSimpleJSONProtocolFixtures::$testArgsJSON['testString2']; + + $this->assertEquals($expected, $actual); + } + + public function testDoubleWrite() + { + $args = new \ThriftTest\ThriftTest_testDouble_args(); + $args->thing = Fixtures::$testArgs['testDouble']; + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TSimpleJSONProtocolFixtures::$testArgsJSON['testDouble']; + + $this->assertEquals($expected, $actual); + } + + public function testByteWrite() + { + $args = new \ThriftTest\ThriftTest_testByte_args(); + $args->thing = Fixtures::$testArgs['testByte']; + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TSimpleJSONProtocolFixtures::$testArgsJSON['testByte']; + + $this->assertEquals($expected, $actual); + } + + public function testI32Write() + { + $args = new \ThriftTest\ThriftTest_testI32_args(); + $args->thing = Fixtures::$testArgs['testI32']; + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TSimpleJSONProtocolFixtures::$testArgsJSON['testI32']; + + $this->assertEquals($expected, $actual); + } + + public function testI64Write() + { + $args = new \ThriftTest\ThriftTest_testI64_args(); + $args->thing = Fixtures::$testArgs['testI64']; + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TSimpleJSONProtocolFixtures::$testArgsJSON['testI64']; + + $this->assertEquals($expected, $actual); + } + + public function testStructWrite() + { + $args = new \ThriftTest\ThriftTest_testStruct_args(); + $args->thing = Fixtures::$testArgs['testStruct']; + + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TSimpleJSONProtocolFixtures::$testArgsJSON['testStruct']; + + $this->assertEquals($expected, $actual); + } + + public function testNestWrite() + { + $args = new \ThriftTest\ThriftTest_testNest_args(); + $args->thing = Fixtures::$testArgs['testNest']; + + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TSimpleJSONProtocolFixtures::$testArgsJSON['testNest']; + + $this->assertEquals($expected, $actual); + } + + public function testMapWrite() + { + $args = new \ThriftTest\ThriftTest_testMap_args(); + $args->thing = Fixtures::$testArgs['testMap']; + + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TSimpleJSONProtocolFixtures::$testArgsJSON['testMap']; + + $this->assertEquals($expected, $actual); + } + + public function testStringMapWrite() + { + $args = new \ThriftTest\ThriftTest_testStringMap_args(); + $args->thing = Fixtures::$testArgs['testStringMap']; + + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TSimpleJSONProtocolFixtures::$testArgsJSON['testStringMap']; + + $this->assertEquals($expected, $actual); + } + + public function testSetWrite() + { + $args = new \ThriftTest\ThriftTest_testSet_args(); + $args->thing = Fixtures::$testArgs['testSet']; + + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TSimpleJSONProtocolFixtures::$testArgsJSON['testSet']; + + $this->assertEquals($expected, $actual); + } + + public function testListWrite() + { + $args = new \ThriftTest\ThriftTest_testList_args(); + $args->thing = Fixtures::$testArgs['testList']; + + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TSimpleJSONProtocolFixtures::$testArgsJSON['testList']; + + $this->assertEquals($expected, $actual); + } + + public function testEnumWrite() + { + $args = new \ThriftTest\ThriftTest_testEnum_args(); + $args->thing = Fixtures::$testArgs['testEnum']; + + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TSimpleJSONProtocolFixtures::$testArgsJSON['testEnum']; + + $this->assertEquals($expected, $actual); + } + + public function testTypedefWrite() + { + $args = new \ThriftTest\ThriftTest_testTypedef_args(); + $args->thing = Fixtures::$testArgs['testTypedef']; + + $args->write($this->protocol); + + $actual = $this->transport->read(Fixtures::$bufsize); + $expected = TSimpleJSONProtocolFixtures::$testArgsJSON['testTypedef']; + + $this->assertEquals($expected, $actual); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/Fixtures.php b/vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/Fixtures.php deleted file mode 100644 index 2c60a08..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/Fixtures.php +++ /dev/null @@ -1,194 +0,0 @@ -<><"; - - self::$testArgs['testString3'] = - "string that ends in double-backslash \\\\"; - - self::$testArgs['testUnicodeStringWithNonBMP'] = - "สวัสดี/ð’¯"; - - self::$testArgs['testDouble'] = 3.1415926535898; - - // TODO: add testBinary() call - - self::$testArgs['testByte'] = 0x01; - - self::$testArgs['testI32'] = pow( 2, 30 ); - - if (PHP_INT_SIZE == 8) { - self::$testArgs['testI64'] = pow( 2, 60 ); - } else { - self::$testArgs['testI64'] = "1152921504606847000"; - } - - self::$testArgs['testStruct'] = - new Xtruct( - array( - 'string_thing' => 'worked', - 'byte_thing' => 0x01, - 'i32_thing' => pow( 2, 30 ), - 'i64_thing' => self::$testArgs['testI64'] - ) - ); - - self::$testArgs['testNestNested'] = - new Xtruct( - array( - 'string_thing' => 'worked', - 'byte_thing' => 0x01, - 'i32_thing' => pow( 2, 30 ), - 'i64_thing' => self::$testArgs['testI64'] - ) - ); - - self::$testArgs['testNest'] = - new Xtruct2( - array( - 'byte_thing' => 0x01, - 'struct_thing' => self::$testArgs['testNestNested'], - 'i32_thing' => pow( 2, 15 ) - ) - ); - - self::$testArgs['testMap'] = - array( - 7 => 77, - 8 => 88, - 9 => 99 - ); - - self::$testArgs['testStringMap'] = - array( - "a" => "123", - "a b" => "with spaces ", - "same" => "same", - "0" => "numeric key", - "longValue" => self::$testArgs['testString1'], - self::$testArgs['testString1'] => "long key" - ); - - self::$testArgs['testSet'] = array( 1 => true, 5 => true, 6 => true ); - - self::$testArgs['testList'] = array( 1, 2, 3 ); - - self::$testArgs['testEnum'] = Numberz::ONE; - - self::$testArgs['testTypedef'] = 69; - - self::$testArgs['testMapMapExpectedResult'] = - array( - 4 => array( - 1 => 1, - 2 => 2, - 3 => 3, - 4 => 4, - ), - -4 => array( - -4 => -4, - -3 => -3, - -2 => -2, - -1 => -1 - ) - ); - - // testInsanity ... takes a few steps to set up! - - $xtruct1 = - new Xtruct( - array( - 'string_thing' => 'Goodbye4', - 'byte_thing' => 4, - 'i32_thing' => 4, - 'i64_thing' => 4 - ) - ); - - $xtruct2 = - new Xtruct( - array( - 'string_thing' => 'Hello2', - 'byte_thing' =>2, - 'i32_thing' => 2, - 'i64_thing' => 2 - ) - ); - - $userMap = - array( - Numberz::FIVE => 5, - Numberz::EIGHT => 8 - ); - - $insanity2 = - new Insanity( - array( - 'userMap' => $userMap, - 'xtructs' => array($xtruct1,$xtruct2) - ) - ); - - $insanity3 = $insanity2; - - $insanity6 = - new Insanity( - array( - 'userMap' => null, - 'xtructs' => null - ) - ); - - self::$testArgs['testInsanityExpectedResult'] = - array( - "1" => array( - Numberz::TWO => $insanity2, - Numberz::THREE => $insanity3 - ), - "2" => array( - Numberz::SIX => $insanity6 - ) - ); - - } -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/JsonSerialize/JsonSerializeTest.php b/vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/JsonSerialize/JsonSerializeTest.php deleted file mode 100644 index 2471b52..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/JsonSerialize/JsonSerializeTest.php +++ /dev/null @@ -1,116 +0,0 @@ -registerNamespace('Thrift', __DIR__ . '/../../../../lib'); -$loader->registerNamespace('Test', __DIR__ . '/../../..'); -$loader->registerDefinition('ThriftTest', __DIR__ . '/../../../packages/phpjs'); -$loader->register(); - -class JsonSerializeTest extends \PHPUnit_Framework_TestCase -{ - protected function setUp() { - if (version_compare(phpversion(), '5.4', '<')) { - $this->markTestSkipped('Requires PHP 5.4 or newer!'); - } - } - - public function testEmptyStruct() - { - $empty = new \ThriftTest\EmptyStruct(array('non_existing_key' => 'bar')); - $this->assertEquals(new stdClass(), json_decode(json_encode($empty))); - } - - public function testStringsAndInts() - { - $input = array( - 'string_thing' => 'foo', - 'i64_thing' => 1234567890, - ); - $xtruct = new \ThriftTest\Xtruct($input); - - // Xtruct's 'i32_thing' and 'byte_thing' fields should not be present here! - $expected = new stdClass(); - $expected->string_thing = $input['string_thing']; - $expected->i64_thing = $input['i64_thing']; - $this->assertEquals($expected, json_decode(json_encode($xtruct))); - } - - public function testNestedStructs() - { - $xtruct2 = new \ThriftTest\Xtruct2(array( - 'byte_thing' => 42, - 'struct_thing' => new \ThriftTest\Xtruct(array( - 'i32_thing' => 123456, - )), - )); - - $expected = new stdClass(); - $expected->byte_thing = $xtruct2->byte_thing; - $expected->struct_thing = new stdClass(); - $expected->struct_thing->i32_thing = $xtruct2->struct_thing->i32_thing; - $this->assertEquals($expected, json_decode(json_encode($xtruct2))); - } - - public function testInsanity() - { - $xinput = array('string_thing' => 'foo'); - $xtruct = new \ThriftTest\Xtruct($xinput); - $insanity = new \ThriftTest\Insanity(array( - 'xtructs' => array($xtruct, $xtruct, $xtruct) - )); - $expected = new stdClass(); - $expected->xtructs = array((object) $xinput, (object) $xinput, (object) $xinput); - $this->assertEquals($expected, json_decode(json_encode($insanity))); - } - - public function testNestedLists() - { - $bonk = new \ThriftTest\Bonk(array('message' => 'foo')); - $nested = new \ThriftTest\NestedListsBonk(array('bonk' => array(array(array($bonk))))); - $expected = new stdClass(); - $expected->bonk = array(array(array((object) array('message' => 'foo')))); - $this->assertEquals($expected, json_decode(json_encode($nested))); - } - - public function testMaps() - { - $intmap = new \ThriftTest\ThriftTest_testMap_args(['thing' => [0 => 'zero']]); - $emptymap = new \ThriftTest\ThriftTest_testMap_args([]); - $this->assertEquals('{"thing":{"0":"zero"}}', json_encode($intmap)); - $this->assertEquals('{}', json_encode($emptymap)); - } - - public function testScalarTypes() - { - $b = new \ThriftTest\Bools(['im_true' => '1', 'im_false' => '0']); - $this->assertEquals('{"im_true":true,"im_false":false}', json_encode($b)); - $s = new \ThriftTest\StructA(['s' => 42]); - $this->assertEquals('{"s":"42"}', json_encode($s)); - } - -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/Protocol/TestTJSONProtocol.php b/vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/Protocol/TestTJSONProtocol.php deleted file mode 100755 index a4ca9d5..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/Protocol/TestTJSONProtocol.php +++ /dev/null @@ -1,583 +0,0 @@ -registerNamespace('Thrift', __DIR__ . '/../../../../lib'); -$loader->registerNamespace('Test', __DIR__ . '/../../..'); -$loader->registerDefinition('ThriftTest', __DIR__ . '/../../../packages'); -$loader->register(); - -/*** - * This test suite depends on running the compiler against the - * standard ThriftTest.thrift file: - * - * lib/php/test$ ../../../compiler/cpp/thrift --gen php -r \ - * --out ./packages ../../../test/ThriftTest.thrift - */ - -class TestTJSONProtocol extends \PHPUnit_Framework_TestCase -{ - private $transport; - private $protocol; - - public static function setUpBeforeClass() - { - Fixtures::populateTestArgs(); - TestTJSONProtocol_Fixtures::populateTestArgsJSON(); - } - - public function setUp() - { - $this->transport = new TMemoryBuffer(); - $this->protocol = new TJSONProtocol($this->transport); - $this->transport->open(); - } - - /*** - * WRITE TESTS - */ - - public function testVoid_Write() - { - $args = new \ThriftTest\ThriftTest_testVoid_args(); - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTJSONProtocol_Fixtures::$testArgsJSON['testVoid']; - - $this->assertEquals( $expected, $actual ); - } - - public function testString1_Write() - { - $args = new \ThriftTest\ThriftTest_testString_args(); - $args->thing = Fixtures::$testArgs['testString1']; - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTJSONProtocol_Fixtures::$testArgsJSON['testString1']; - - #$this->assertEquals( $expected, $actual ); - } - - public function testString2_Write() - { - $args = new \ThriftTest\ThriftTest_testString_args(); - $args->thing = Fixtures::$testArgs['testString2']; - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTJSONProtocol_Fixtures::$testArgsJSON['testString2']; - - $this->assertEquals( $expected, $actual ); - } - - public function testDouble_Write() - { - $args = new \ThriftTest\ThriftTest_testDouble_args(); - $args->thing = Fixtures::$testArgs['testDouble']; - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTJSONProtocol_Fixtures::$testArgsJSON['testDouble']; - - $this->assertEquals( $expected, $actual ); - } - - public function testByte_Write() - { - $args = new \ThriftTest\ThriftTest_testByte_args(); - $args->thing = Fixtures::$testArgs['testByte']; - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTJSONProtocol_Fixtures::$testArgsJSON['testByte']; - - $this->assertEquals( $expected, $actual ); - } - - public function testI32_Write() - { - $args = new \ThriftTest\ThriftTest_testI32_args(); - $args->thing = Fixtures::$testArgs['testI32']; - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTJSONProtocol_Fixtures::$testArgsJSON['testI32']; - - $this->assertEquals( $expected, $actual ); - } - - public function testI64_Write() - { - $args = new \ThriftTest\ThriftTest_testI64_args(); - $args->thing = Fixtures::$testArgs['testI64']; - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTJSONProtocol_Fixtures::$testArgsJSON['testI64']; - - $this->assertEquals( $expected, $actual ); - } - - public function testStruct_Write() - { - $args = new \ThriftTest\ThriftTest_testStruct_args(); - $args->thing = Fixtures::$testArgs['testStruct']; - - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTJSONProtocol_Fixtures::$testArgsJSON['testStruct']; - - $this->assertEquals( $expected, $actual ); - } - - public function testNest_Write() - { - $args = new \ThriftTest\ThriftTest_testNest_args(); - $args->thing = Fixtures::$testArgs['testNest']; - - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTJSONProtocol_Fixtures::$testArgsJSON['testNest']; - - $this->assertEquals( $expected, $actual ); - } - - public function testMap_Write() - { - $args = new \ThriftTest\ThriftTest_testMap_args(); - $args->thing = Fixtures::$testArgs['testMap']; - - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTJSONProtocol_Fixtures::$testArgsJSON['testMap']; - - $this->assertEquals( $expected, $actual ); - } - - public function testStringMap_Write() - { - $args = new \ThriftTest\ThriftTest_testStringMap_args(); - $args->thing = Fixtures::$testArgs['testStringMap']; - - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTJSONProtocol_Fixtures::$testArgsJSON['testStringMap']; - - /* - * The $actual returns unescaped string. - * It is required to to decode then encode it again - * to get the expected escaped unicode. - */ - $this->assertEquals( $expected, json_encode(json_decode($actual)) ); - } - - public function testSet_Write() - { - $args = new \ThriftTest\ThriftTest_testSet_args(); - $args->thing = Fixtures::$testArgs['testSet']; - - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTJSONProtocol_Fixtures::$testArgsJSON['testSet']; - - $this->assertEquals( $expected, $actual ); - } - - public function testList_Write() - { - $args = new \ThriftTest\ThriftTest_testList_args(); - $args->thing = Fixtures::$testArgs['testList']; - - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTJSONProtocol_Fixtures::$testArgsJSON['testList']; - - $this->assertEquals( $expected, $actual ); - } - - public function testEnum_Write() - { - $args = new \ThriftTest\ThriftTest_testEnum_args(); - $args->thing = Fixtures::$testArgs['testEnum']; - - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTJSONProtocol_Fixtures::$testArgsJSON['testEnum']; - - $this->assertEquals( $expected, $actual ); - } - - public function testTypedef_Write() - { - $args = new \ThriftTest\ThriftTest_testTypedef_args(); - $args->thing = Fixtures::$testArgs['testTypedef']; - - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTJSONProtocol_Fixtures::$testArgsJSON['testTypedef']; - - $this->assertEquals( $expected, $actual ); - } - - /*** - * READ TESTS - */ - - public function testVoid_Read() - { - $this->transport->write( - TestTJSONProtocol_Fixtures::$testArgsJSON['testVoid'] - ); - $args = new \ThriftTest\ThriftTest_testVoid_args(); - $args->read( $this->protocol ); - } - - public function testString1_Read() - { - $this->transport->write( - TestTJSONProtocol_Fixtures::$testArgsJSON['testString1'] - ); - $args = new \ThriftTest\ThriftTest_testString_args(); - $args->read( $this->protocol ); - - $actual = $args->thing; - $expected = Fixtures::$testArgs['testString1']; - - $this->assertEquals( $expected, $actual ); - } - - public function testString2_Read() - { - $this->transport->write( - TestTJSONProtocol_Fixtures::$testArgsJSON['testString2'] - ); - $args = new \ThriftTest\ThriftTest_testString_args(); - $args->read( $this->protocol ); - - $actual = $args->thing; - $expected = Fixtures::$testArgs['testString2']; - - $this->assertEquals( $expected, $actual ); - } - - public function testString3_Write() - { - $args = new \ThriftTest\ThriftTest_testString_args(); - $args->thing = Fixtures::$testArgs['testString3']; - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTJSONProtocol_Fixtures::$testArgsJSON['testString3']; - - $this->assertEquals( $expected, $actual ); - } - - public function testString4_Write() - { - $args = new \ThriftTest\ThriftTest_testString_args(); - $args->thing = Fixtures::$testArgs['testUnicodeStringWithNonBMP']; - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTJSONProtocol_Fixtures::$testArgsJSON['testUnicodeStringWithNonBMP']; - - $this->assertEquals( $expected, $actual ); - } - - public function testDouble_Read() - { - $this->transport->write( - TestTJSONProtocol_Fixtures::$testArgsJSON['testDouble'] - ); - $args = new \ThriftTest\ThriftTest_testDouble_args(); - $args->read( $this->protocol ); - - $actual = $args->thing; - $expected = Fixtures::$testArgs['testDouble']; - - $this->assertEquals( $expected, $actual ); - } - - public function testByte_Read() - { - $this->transport->write( - TestTJSONProtocol_Fixtures::$testArgsJSON['testByte'] - ); - $args = new \ThriftTest\ThriftTest_testByte_args(); - $args->read( $this->protocol ); - - $actual = $args->thing; - $expected = Fixtures::$testArgs['testByte']; - - $this->assertEquals( $expected, $actual ); - } - - public function testI32_Read() - { - $this->transport->write( - TestTJSONProtocol_Fixtures::$testArgsJSON['testI32'] - ); - $args = new \ThriftTest\ThriftTest_testI32_args(); - $args->read( $this->protocol ); - - $actual = $args->thing; - $expected = Fixtures::$testArgs['testI32']; - - $this->assertEquals( $expected, $actual ); - } - - public function testI64_Read() - { - $this->transport->write( - TestTJSONProtocol_Fixtures::$testArgsJSON['testI64'] - ); - $args = new \ThriftTest\ThriftTest_testI64_args(); - $args->read( $this->protocol ); - - $actual = $args->thing; - $expected = Fixtures::$testArgs['testI64']; - - $this->assertEquals( $expected, $actual ); - - } - - public function testStruct_Read() - { - $this->transport->write( - TestTJSONProtocol_Fixtures::$testArgsJSON['testStruct'] - ); - $args = new \ThriftTest\ThriftTest_testStruct_args(); - $args->read( $this->protocol ); - - $actual = $args->thing; - $expected = Fixtures::$testArgs['testStruct']; - - $this->assertEquals( $expected, $actual ); - - } - - public function testNest_Read() - { - $this->transport->write( - TestTJSONProtocol_Fixtures::$testArgsJSON['testNest'] - ); - $args = new \ThriftTest\ThriftTest_testNest_args(); - $args->read( $this->protocol ); - - $actual = $args->thing; - $expected = Fixtures::$testArgs['testNest']; - - $this->assertEquals( $expected, $actual ); - - } - - public function testMap_Read() - { - $this->transport->write( - TestTJSONProtocol_Fixtures::$testArgsJSON['testMap'] - ); - $args = new \ThriftTest\ThriftTest_testMap_args(); - $args->read( $this->protocol ); - - $actual = $args->thing; - $expected = Fixtures::$testArgs['testMap']; - - $this->assertEquals( $expected, $actual ); - - } - - public function testStringMap_Read() - { - $this->transport->write( - TestTJSONProtocol_Fixtures::$testArgsJSON['testStringMap'] - ); - $args = new \ThriftTest\ThriftTest_testStringMap_args(); - $args->read( $this->protocol ); - - $actual = $args->thing; - $expected = Fixtures::$testArgs['testStringMap']; - - $this->assertEquals( $expected, $actual ); - - } - - public function testSet_Read() - { - $this->transport->write( - TestTJSONProtocol_Fixtures::$testArgsJSON['testSet'] - ); - $args = new \ThriftTest\ThriftTest_testSet_args(); - $args->read( $this->protocol ); - - $actual = $args->thing; - $expected = Fixtures::$testArgs['testSet']; - - $this->assertEquals( $expected, $actual ); - - } - - public function testList_Read() - { - $this->transport->write( - TestTJSONProtocol_Fixtures::$testArgsJSON['testList'] - ); - $args = new \ThriftTest\ThriftTest_testList_args(); - $args->read( $this->protocol ); - - $actual = $args->thing; - $expected = Fixtures::$testArgs['testList']; - - $this->assertEquals( $expected, $actual ); - - } - - public function testEnum_Read() - { - $this->transport->write( - TestTJSONProtocol_Fixtures::$testArgsJSON['testEnum'] - ); - $args = new \ThriftTest\ThriftTest_testEnum_args(); - $args->read( $this->protocol ); - - $actual = $args->thing; - $expected = Fixtures::$testArgs['testEnum']; - - $this->assertEquals( $expected, $actual ); - - } - - public function testTypedef_Read() - { - $this->transport->write( - TestTJSONProtocol_Fixtures::$testArgsJSON['testTypedef'] - ); - $args = new \ThriftTest\ThriftTest_testTypedef_args(); - $args->read( $this->protocol ); - - $actual = $args->thing; - $expected = Fixtures::$testArgs['testTypedef']; - - $this->assertEquals( $expected, $actual ); - } - - public function testMapMap_Read() - { - $this->transport->write( - TestTJSONProtocol_Fixtures::$testArgsJSON['testMapMap'] - ); - $result = new \ThriftTest\ThriftTest_testMapMap_result(); - $result->read( $this->protocol ); - - $actual = $result->success; - $expected = Fixtures::$testArgs['testMapMapExpectedResult']; - - $this->assertEquals( $expected, $actual ); - } - - public function testInsanity_Read() - { - $this->transport->write( - TestTJSONProtocol_Fixtures::$testArgsJSON['testInsanity'] - ); - $result = new \ThriftTest\ThriftTest_testInsanity_result(); - $result->read( $this->protocol ); - - $actual = $result->success; - $expected = Fixtures::$testArgs['testInsanityExpectedResult']; - - $this->assertEquals( $expected, $actual ); - } - -} - -class TestTJSONProtocol_Fixtures -{ - public static $testArgsJSON = array(); - - public static function populateTestArgsJSON() - { - self::$testArgsJSON['testVoid'] = '{}'; - - self::$testArgsJSON['testString1'] = '{"1":{"str":"Afrikaans, Alemannisch, Aragon\u00e9s, \u0627\u0644\u0639\u0631\u0628\u064a\u0629, \u0645\u0635\u0631\u0649, Asturianu, Aymar aru, Az\u0259rbaycan, \u0411\u0430\u0448\u04a1\u043e\u0440\u0442, Boarisch, \u017demait\u0117\u0161ka, \u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f, \u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f (\u0442\u0430\u0440\u0430\u0448\u043a\u0435\u0432\u0456\u0446\u0430), \u0411\u044a\u043b\u0433\u0430\u0440\u0441\u043a\u0438, Bamanankan, \u09ac\u09be\u0982\u09b2\u09be, Brezhoneg, Bosanski, Catal\u00e0, M\u00ecng-d\u0115\u0324ng-ng\u1e73\u0304, \u041d\u043e\u0445\u0447\u0438\u0439\u043d, Cebuano, \u13e3\u13b3\u13a9, \u010cesky, \u0421\u043b\u043e\u0432\u0463\u0301\u043d\u044c\u0441\u043a\u044a \/ \u2c14\u2c0e\u2c11\u2c02\u2c21\u2c10\u2c20\u2c14\u2c0d\u2c1f, \u0427\u04d1\u0432\u0430\u0448\u043b\u0430, Cymraeg, Dansk, Zazaki, \u078b\u07a8\u0788\u07ac\u0780\u07a8\u0784\u07a6\u0790\u07b0, \u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac, Emili\u00e0n e rumagn\u00f2l, English, Esperanto, Espa\u00f1ol, Eesti, Euskara, \u0641\u0627\u0631\u0633\u06cc, Suomi, V\u00f5ro, F\u00f8royskt, Fran\u00e7ais, Arpetan, Furlan, Frysk, Gaeilge, \u8d1b\u8a9e, G\u00e0idhlig, Galego, Ava\u00f1e\'\u1ebd, \u0a97\u0ac1\u0a9c\u0ab0\u0abe\u0aa4\u0ac0, Gaelg, \u05e2\u05d1\u05e8\u05d9\u05ea, \u0939\u093f\u0928\u094d\u0926\u0940, Fiji Hindi, Hrvatski, Krey\u00f2l ayisyen, Magyar, \u0540\u0561\u0575\u0565\u0580\u0565\u0576, Interlingua, Bahasa Indonesia, Ilokano, Ido, \u00cdslenska, Italiano, \u65e5\u672c\u8a9e, Lojban, Basa Jawa, \u10e5\u10d0\u10e0\u10d7\u10e3\u10da\u10d8, Kongo, Kalaallisut, \u0c95\u0ca8\u0ccd\u0ca8\u0ca1, \ud55c\uad6d\uc5b4, \u041a\u044a\u0430\u0440\u0430\u0447\u0430\u0439-\u041c\u0430\u043b\u043a\u044a\u0430\u0440, Ripoarisch, Kurd\u00ee, \u041a\u043e\u043c\u0438, Kernewek, \u041a\u044b\u0440\u0433\u044b\u0437\u0447\u0430, Latina, Ladino, L\u00ebtzebuergesch, Limburgs, Ling\u00e1la, \u0ea5\u0eb2\u0ea7, Lietuvi\u0173, Latvie\u0161u, Basa Banyumasan, Malagasy, \u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a\u0438, \u0d2e\u0d32\u0d2f\u0d3e\u0d33\u0d02, \u092e\u0930\u093e\u0920\u0940, Bahasa Melayu, \u0645\u0627\u0632\u0650\u0631\u0648\u0646\u06cc, Nnapulitano, Nedersaksisch, \u0928\u0947\u092a\u093e\u0932 \u092d\u093e\u0937\u093e, Nederlands, \u202aNorsk (nynorsk)\u202c, \u202aNorsk (bokm\u00e5l)\u202c, Nouormand, Din\u00e9 bizaad, Occitan, \u0418\u0440\u043e\u043d\u0430\u0443, Papiamentu, Deitsch, Norfuk \/ Pitkern, Polski, \u067e\u0646\u062c\u0627\u0628\u06cc, \u067e\u069a\u062a\u0648, Portugu\u00eas, Runa Simi, Rumantsch, Romani, Rom\u00e2n\u0103, \u0420\u0443\u0441\u0441\u043a\u0438\u0439, \u0421\u0430\u0445\u0430 \u0442\u044b\u043b\u0430, Sardu, Sicilianu, Scots, S\u00e1megiella, Simple English, Sloven\u010dina, Sloven\u0161\u010dina, \u0421\u0440\u043f\u0441\u043a\u0438 \/ Srpski, Seeltersk, Svenska, Kiswahili, \u0ba4\u0bae\u0bbf\u0bb4\u0bcd, \u0c24\u0c46\u0c32\u0c41\u0c17\u0c41, \u0422\u043e\u04b7\u0438\u043a\u04e3, \u0e44\u0e17\u0e22, T\u00fcrkmen\u00e7e, Tagalog, T\u00fcrk\u00e7e, \u0422\u0430\u0442\u0430\u0440\u0447\u0430\/Tatar\u00e7a, \u0423\u043a\u0440\u0430\u0457\u043d\u0441\u044c\u043a\u0430, \u0627\u0631\u062f\u0648, Ti\u1ebfng Vi\u1ec7t, Volap\u00fck, Walon, Winaray, \u5434\u8bed, isiXhosa, \u05d9\u05d9\u05b4\u05d3\u05d9\u05e9, Yor\u00f9b\u00e1, Ze\u00eauws, \u4e2d\u6587, B\u00e2n-l\u00e2m-g\u00fa, \u7cb5\u8a9e"}}'; - - self::$testArgsJSON['testString2'] = '{"1":{"str":"quote: \\\\\" backslash: forwardslash-escaped: \\\\\/ backspace: \\\\b formfeed: \f newline: \n return: \r tab: now-all-of-them-together: \"\\\\\\\\\/\\\\b\n\r\t now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><"}}'; - - self::$testArgsJSON['testString3'] = '{"1":{"str":"string that ends in double-backslash \\\\\\\\"}}'; - - self::$testArgsJSON['testUnicodeStringWithNonBMP'] = '{"1":{"str":"สวัสดี\/ð’¯"}}'; - - self::$testArgsJSON['testDouble'] = '{"1":{"dbl":3.1415926535898}}'; - - self::$testArgsJSON['testByte'] = '{"1":{"i8":1}}'; - - self::$testArgsJSON['testI32'] = '{"1":{"i32":1073741824}}'; - - if (PHP_INT_SIZE == 8) { - self::$testArgsJSON['testI64'] = '{"1":{"i64":'.pow( 2, 60 ).'}}'; - self::$testArgsJSON['testStruct'] = '{"1":{"rec":{"1":{"str":"worked"},"4":{"i8":1},"9":{"i32":1073741824},"11":{"i64":'.pow( 2, 60 ).'}}}}'; - self::$testArgsJSON['testNest'] = '{"1":{"rec":{"1":{"i8":1},"2":{"rec":{"1":{"str":"worked"},"4":{"i8":1},"9":{"i32":1073741824},"11":{"i64":'.pow( 2, 60 ).'}}},"3":{"i32":32768}}}}'; - } else { - self::$testArgsJSON['testI64'] = '{"1":{"i64":1152921504606847000}}'; - self::$testArgsJSON['testStruct'] = '{"1":{"rec":{"1":{"str":"worked"},"4":{"i8":1},"9":{"i32":1073741824},"11":{"i64":1152921504606847000}}}}'; - self::$testArgsJSON['testNest'] = '{"1":{"rec":{"1":{"i8":1},"2":{"rec":{"1":{"str":"worked"},"4":{"i8":1},"9":{"i32":1073741824},"11":{"i64":1152921504606847000}}},"3":{"i32":32768}}}}'; - } - - self::$testArgsJSON['testMap'] = '{"1":{"map":["i32","i32",3,{"7":77,"8":88,"9":99}]}}'; - - self::$testArgsJSON['testStringMap'] = '{"1":{"map":["str","str",6,{"a":"123","a b":"with spaces ","same":"same","0":"numeric key","longValue":"Afrikaans, Alemannisch, Aragon\u00e9s, \u0627\u0644\u0639\u0631\u0628\u064a\u0629, \u0645\u0635\u0631\u0649, Asturianu, Aymar aru, Az\u0259rbaycan, \u0411\u0430\u0448\u04a1\u043e\u0440\u0442, Boarisch, \u017demait\u0117\u0161ka, \u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f, \u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f (\u0442\u0430\u0440\u0430\u0448\u043a\u0435\u0432\u0456\u0446\u0430), \u0411\u044a\u043b\u0433\u0430\u0440\u0441\u043a\u0438, Bamanankan, \u09ac\u09be\u0982\u09b2\u09be, Brezhoneg, Bosanski, Catal\u00e0, M\u00ecng-d\u0115\u0324ng-ng\u1e73\u0304, \u041d\u043e\u0445\u0447\u0438\u0439\u043d, Cebuano, \u13e3\u13b3\u13a9, \u010cesky, \u0421\u043b\u043e\u0432\u0463\u0301\u043d\u044c\u0441\u043a\u044a \/ \u2c14\u2c0e\u2c11\u2c02\u2c21\u2c10\u2c20\u2c14\u2c0d\u2c1f, \u0427\u04d1\u0432\u0430\u0448\u043b\u0430, Cymraeg, Dansk, Zazaki, \u078b\u07a8\u0788\u07ac\u0780\u07a8\u0784\u07a6\u0790\u07b0, \u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac, Emili\u00e0n e rumagn\u00f2l, English, Esperanto, Espa\u00f1ol, Eesti, Euskara, \u0641\u0627\u0631\u0633\u06cc, Suomi, V\u00f5ro, F\u00f8royskt, Fran\u00e7ais, Arpetan, Furlan, Frysk, Gaeilge, \u8d1b\u8a9e, G\u00e0idhlig, Galego, Ava\u00f1e\'\u1ebd, \u0a97\u0ac1\u0a9c\u0ab0\u0abe\u0aa4\u0ac0, Gaelg, \u05e2\u05d1\u05e8\u05d9\u05ea, \u0939\u093f\u0928\u094d\u0926\u0940, Fiji Hindi, Hrvatski, Krey\u00f2l ayisyen, Magyar, \u0540\u0561\u0575\u0565\u0580\u0565\u0576, Interlingua, Bahasa Indonesia, Ilokano, Ido, \u00cdslenska, Italiano, \u65e5\u672c\u8a9e, Lojban, Basa Jawa, \u10e5\u10d0\u10e0\u10d7\u10e3\u10da\u10d8, Kongo, Kalaallisut, \u0c95\u0ca8\u0ccd\u0ca8\u0ca1, \ud55c\uad6d\uc5b4, \u041a\u044a\u0430\u0440\u0430\u0447\u0430\u0439-\u041c\u0430\u043b\u043a\u044a\u0430\u0440, Ripoarisch, Kurd\u00ee, \u041a\u043e\u043c\u0438, Kernewek, \u041a\u044b\u0440\u0433\u044b\u0437\u0447\u0430, Latina, Ladino, L\u00ebtzebuergesch, Limburgs, Ling\u00e1la, \u0ea5\u0eb2\u0ea7, Lietuvi\u0173, Latvie\u0161u, Basa Banyumasan, Malagasy, \u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a\u0438, \u0d2e\u0d32\u0d2f\u0d3e\u0d33\u0d02, \u092e\u0930\u093e\u0920\u0940, Bahasa Melayu, \u0645\u0627\u0632\u0650\u0631\u0648\u0646\u06cc, Nnapulitano, Nedersaksisch, \u0928\u0947\u092a\u093e\u0932 \u092d\u093e\u0937\u093e, Nederlands, \u202aNorsk (nynorsk)\u202c, \u202aNorsk (bokm\u00e5l)\u202c, Nouormand, Din\u00e9 bizaad, Occitan, \u0418\u0440\u043e\u043d\u0430\u0443, Papiamentu, Deitsch, Norfuk \/ Pitkern, Polski, \u067e\u0646\u062c\u0627\u0628\u06cc, \u067e\u069a\u062a\u0648, Portugu\u00eas, Runa Simi, Rumantsch, Romani, Rom\u00e2n\u0103, \u0420\u0443\u0441\u0441\u043a\u0438\u0439, \u0421\u0430\u0445\u0430 \u0442\u044b\u043b\u0430, Sardu, Sicilianu, Scots, S\u00e1megiella, Simple English, Sloven\u010dina, Sloven\u0161\u010dina, \u0421\u0440\u043f\u0441\u043a\u0438 \/ Srpski, Seeltersk, Svenska, Kiswahili, \u0ba4\u0bae\u0bbf\u0bb4\u0bcd, \u0c24\u0c46\u0c32\u0c41\u0c17\u0c41, \u0422\u043e\u04b7\u0438\u043a\u04e3, \u0e44\u0e17\u0e22, T\u00fcrkmen\u00e7e, Tagalog, T\u00fcrk\u00e7e, \u0422\u0430\u0442\u0430\u0440\u0447\u0430\/Tatar\u00e7a, \u0423\u043a\u0440\u0430\u0457\u043d\u0441\u044c\u043a\u0430, \u0627\u0631\u062f\u0648, Ti\u1ebfng Vi\u1ec7t, Volap\u00fck, Walon, Winaray, \u5434\u8bed, isiXhosa, \u05d9\u05d9\u05b4\u05d3\u05d9\u05e9, Yor\u00f9b\u00e1, Ze\u00eauws, \u4e2d\u6587, B\u00e2n-l\u00e2m-g\u00fa, \u7cb5\u8a9e","Afrikaans, Alemannisch, Aragon\u00e9s, \u0627\u0644\u0639\u0631\u0628\u064a\u0629, \u0645\u0635\u0631\u0649, Asturianu, Aymar aru, Az\u0259rbaycan, \u0411\u0430\u0448\u04a1\u043e\u0440\u0442, Boarisch, \u017demait\u0117\u0161ka, \u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f, \u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f (\u0442\u0430\u0440\u0430\u0448\u043a\u0435\u0432\u0456\u0446\u0430), \u0411\u044a\u043b\u0433\u0430\u0440\u0441\u043a\u0438, Bamanankan, \u09ac\u09be\u0982\u09b2\u09be, Brezhoneg, Bosanski, Catal\u00e0, M\u00ecng-d\u0115\u0324ng-ng\u1e73\u0304, \u041d\u043e\u0445\u0447\u0438\u0439\u043d, Cebuano, \u13e3\u13b3\u13a9, \u010cesky, \u0421\u043b\u043e\u0432\u0463\u0301\u043d\u044c\u0441\u043a\u044a \/ \u2c14\u2c0e\u2c11\u2c02\u2c21\u2c10\u2c20\u2c14\u2c0d\u2c1f, \u0427\u04d1\u0432\u0430\u0448\u043b\u0430, Cymraeg, Dansk, Zazaki, \u078b\u07a8\u0788\u07ac\u0780\u07a8\u0784\u07a6\u0790\u07b0, \u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac, Emili\u00e0n e rumagn\u00f2l, English, Esperanto, Espa\u00f1ol, Eesti, Euskara, \u0641\u0627\u0631\u0633\u06cc, Suomi, V\u00f5ro, F\u00f8royskt, Fran\u00e7ais, Arpetan, Furlan, Frysk, Gaeilge, \u8d1b\u8a9e, G\u00e0idhlig, Galego, Ava\u00f1e\'\u1ebd, \u0a97\u0ac1\u0a9c\u0ab0\u0abe\u0aa4\u0ac0, Gaelg, \u05e2\u05d1\u05e8\u05d9\u05ea, \u0939\u093f\u0928\u094d\u0926\u0940, Fiji Hindi, Hrvatski, Krey\u00f2l ayisyen, Magyar, \u0540\u0561\u0575\u0565\u0580\u0565\u0576, Interlingua, Bahasa Indonesia, Ilokano, Ido, \u00cdslenska, Italiano, \u65e5\u672c\u8a9e, Lojban, Basa Jawa, \u10e5\u10d0\u10e0\u10d7\u10e3\u10da\u10d8, Kongo, Kalaallisut, \u0c95\u0ca8\u0ccd\u0ca8\u0ca1, \ud55c\uad6d\uc5b4, \u041a\u044a\u0430\u0440\u0430\u0447\u0430\u0439-\u041c\u0430\u043b\u043a\u044a\u0430\u0440, Ripoarisch, Kurd\u00ee, \u041a\u043e\u043c\u0438, Kernewek, \u041a\u044b\u0440\u0433\u044b\u0437\u0447\u0430, Latina, Ladino, L\u00ebtzebuergesch, Limburgs, Ling\u00e1la, \u0ea5\u0eb2\u0ea7, Lietuvi\u0173, Latvie\u0161u, Basa Banyumasan, Malagasy, \u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a\u0438, \u0d2e\u0d32\u0d2f\u0d3e\u0d33\u0d02, \u092e\u0930\u093e\u0920\u0940, Bahasa Melayu, \u0645\u0627\u0632\u0650\u0631\u0648\u0646\u06cc, Nnapulitano, Nedersaksisch, \u0928\u0947\u092a\u093e\u0932 \u092d\u093e\u0937\u093e, Nederlands, \u202aNorsk (nynorsk)\u202c, \u202aNorsk (bokm\u00e5l)\u202c, Nouormand, Din\u00e9 bizaad, Occitan, \u0418\u0440\u043e\u043d\u0430\u0443, Papiamentu, Deitsch, Norfuk \/ Pitkern, Polski, \u067e\u0646\u062c\u0627\u0628\u06cc, \u067e\u069a\u062a\u0648, Portugu\u00eas, Runa Simi, Rumantsch, Romani, Rom\u00e2n\u0103, \u0420\u0443\u0441\u0441\u043a\u0438\u0439, \u0421\u0430\u0445\u0430 \u0442\u044b\u043b\u0430, Sardu, Sicilianu, Scots, S\u00e1megiella, Simple English, Sloven\u010dina, Sloven\u0161\u010dina, \u0421\u0440\u043f\u0441\u043a\u0438 \/ Srpski, Seeltersk, Svenska, Kiswahili, \u0ba4\u0bae\u0bbf\u0bb4\u0bcd, \u0c24\u0c46\u0c32\u0c41\u0c17\u0c41, \u0422\u043e\u04b7\u0438\u043a\u04e3, \u0e44\u0e17\u0e22, T\u00fcrkmen\u00e7e, Tagalog, T\u00fcrk\u00e7e, \u0422\u0430\u0442\u0430\u0440\u0447\u0430\/Tatar\u00e7a, \u0423\u043a\u0440\u0430\u0457\u043d\u0441\u044c\u043a\u0430, \u0627\u0631\u062f\u0648, Ti\u1ebfng Vi\u1ec7t, Volap\u00fck, Walon, Winaray, \u5434\u8bed, isiXhosa, \u05d9\u05d9\u05b4\u05d3\u05d9\u05e9, Yor\u00f9b\u00e1, Ze\u00eauws, \u4e2d\u6587, B\u00e2n-l\u00e2m-g\u00fa, \u7cb5\u8a9e":"long key"}]}}'; - - self::$testArgsJSON['testSet'] = '{"1":{"set":["i32",3,1,5,6]}}'; - - self::$testArgsJSON['testList'] = '{"1":{"lst":["i32",3,1,2,3]}}'; - - self::$testArgsJSON['testEnum'] = '{"1":{"i32":1}}'; - - self::$testArgsJSON['testTypedef'] = '{"1":{"i64":69}}'; - - self::$testArgsJSON['testMapMap'] = '{"0":{"map":["i32","map",2,{"4":["i32","i32",4,{"1":1,"2":2,"3":3,"4":4}],"-4":["i32","i32",4,{"-4":-4,"-3":-3,"-2":-2,"-1":-1}]}]}}'; - - self::$testArgsJSON['testInsanity'] = '{"0":{"map":["i64","map",2,{"1":["i32","rec",2,{"2":{"1":{"map":["i32","i64",2,{"5":5,"8":8}]},"2":{"lst":["rec",2,{"1":{"str":"Goodbye4"},"4":{"i8":4},"9":{"i32":4},"11":{"i64":4}},{"1":{"str":"Hello2"},"4":{"i8":2},"9":{"i32":2},"11":{"i64":2}}]}},"3":{"1":{"map":["i32","i64",2,{"5":5,"8":8}]},"2":{"lst":["rec",2,{"1":{"str":"Goodbye4"},"4":{"i8":4},"9":{"i32":4},"11":{"i64":4}},{"1":{"str":"Hello2"},"4":{"i8":2},"9":{"i32":2},"11":{"i64":2}}]}}}],"2":["i32","rec",1,{"6":{}}]}]}}'; - - } -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/Protocol/TestTSimpleJSONProtocol.php b/vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/Protocol/TestTSimpleJSONProtocol.php deleted file mode 100755 index 973f55c..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/Protocol/TestTSimpleJSONProtocol.php +++ /dev/null @@ -1,300 +0,0 @@ -registerNamespace('Thrift', __DIR__ . '/../../../../lib'); -$loader->registerNamespace('Test', __DIR__ . '/../../..'); -$loader->registerDefinition('ThriftTest', __DIR__ . '/../../../packages'); -$loader->register(); - -/*** - * This test suite depends on running the compiler against the - * standard ThriftTest.thrift file: - * - * lib/php/test$ ../../../compiler/cpp/thrift --gen php -r \ - * --out ./packages ../../../test/ThriftTest.thrift - */ - -class TestTSimpleJSONProtocol extends \PHPUnit_Framework_TestCase -{ - private $transport; - private $protocol; - - public static function setUpBeforeClass() - { - Fixtures::populateTestArgs(); - TestTSimpleJSONProtocol_Fixtures::populateTestArgsSimpleJSON(); - } - - public function setUp() - { - $this->transport = new TMemoryBuffer(); - $this->protocol = new TSimpleJSONProtocol($this->transport); - $this->transport->open(); - } - - /*** - * WRITE TESTS - */ - - public function testVoid_Write() - { - $args = new \ThriftTest\ThriftTest_testVoid_args(); - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTSimpleJSONProtocol_Fixtures::$testArgsJSON['testVoid']; - - $this->assertEquals( $expected, $actual ); - } - - public function testString1_Write() - { - $args = new \ThriftTest\ThriftTest_testString_args(); - $args->thing = Fixtures::$testArgs['testString1']; - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTSimpleJSONProtocol_Fixtures::$testArgsJSON['testString1']; - - #$this->assertEquals( $expected, $actual ); - } - - public function testString2_Write() - { - $args = new \ThriftTest\ThriftTest_testString_args(); - $args->thing = Fixtures::$testArgs['testString2']; - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTSimpleJSONProtocol_Fixtures::$testArgsJSON['testString2']; - - $this->assertEquals( $expected, $actual ); - } - - public function testDouble_Write() - { - $args = new \ThriftTest\ThriftTest_testDouble_args(); - $args->thing = Fixtures::$testArgs['testDouble']; - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTSimpleJSONProtocol_Fixtures::$testArgsJSON['testDouble']; - - $this->assertEquals( $expected, $actual ); - } - - public function testByte_Write() - { - $args = new \ThriftTest\ThriftTest_testByte_args(); - $args->thing = Fixtures::$testArgs['testByte']; - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTSimpleJSONProtocol_Fixtures::$testArgsJSON['testByte']; - - $this->assertEquals( $expected, $actual ); - } - - public function testI32_Write() - { - $args = new \ThriftTest\ThriftTest_testI32_args(); - $args->thing = Fixtures::$testArgs['testI32']; - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTSimpleJSONProtocol_Fixtures::$testArgsJSON['testI32']; - - $this->assertEquals( $expected, $actual ); - } - - public function testI64_Write() - { - $args = new \ThriftTest\ThriftTest_testI64_args(); - $args->thing = Fixtures::$testArgs['testI64']; - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTSimpleJSONProtocol_Fixtures::$testArgsJSON['testI64']; - - $this->assertEquals( $expected, $actual ); - } - - public function testStruct_Write() - { - $args = new \ThriftTest\ThriftTest_testStruct_args(); - $args->thing = Fixtures::$testArgs['testStruct']; - - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTSimpleJSONProtocol_Fixtures::$testArgsJSON['testStruct']; - - $this->assertEquals( $expected, $actual ); - } - - public function testNest_Write() - { - $args = new \ThriftTest\ThriftTest_testNest_args(); - $args->thing = Fixtures::$testArgs['testNest']; - - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTSimpleJSONProtocol_Fixtures::$testArgsJSON['testNest']; - - $this->assertEquals( $expected, $actual ); - } - - public function testMap_Write() - { - $args = new \ThriftTest\ThriftTest_testMap_args(); - $args->thing = Fixtures::$testArgs['testMap']; - - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTSimpleJSONProtocol_Fixtures::$testArgsJSON['testMap']; - - $this->assertEquals( $expected, $actual ); - } - - public function testStringMap_Write() - { - $args = new \ThriftTest\ThriftTest_testStringMap_args(); - $args->thing = Fixtures::$testArgs['testStringMap']; - - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTSimpleJSONProtocol_Fixtures::$testArgsJSON['testStringMap']; - - $this->assertEquals( $expected, $actual ); - } - - public function testSet_Write() - { - $args = new \ThriftTest\ThriftTest_testSet_args(); - $args->thing = Fixtures::$testArgs['testSet']; - - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTSimpleJSONProtocol_Fixtures::$testArgsJSON['testSet']; - - $this->assertEquals( $expected, $actual ); - } - - public function testList_Write() - { - $args = new \ThriftTest\ThriftTest_testList_args(); - $args->thing = Fixtures::$testArgs['testList']; - - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTSimpleJSONProtocol_Fixtures::$testArgsJSON['testList']; - - $this->assertEquals( $expected, $actual ); - } - - public function testEnum_Write() - { - $args = new \ThriftTest\ThriftTest_testEnum_args(); - $args->thing = Fixtures::$testArgs['testEnum']; - - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTSimpleJSONProtocol_Fixtures::$testArgsJSON['testEnum']; - - $this->assertEquals( $expected, $actual ); - } - - public function testTypedef_Write() - { - $args = new \ThriftTest\ThriftTest_testTypedef_args(); - $args->thing = Fixtures::$testArgs['testTypedef']; - - $args->write( $this->protocol ); - - $actual = $this->transport->read( BUFSIZ ); - $expected = TestTSimpleJSONProtocol_Fixtures::$testArgsJSON['testTypedef']; - - $this->assertEquals( $expected, $actual ); - } -} - -class TestTSimpleJSONProtocol_Fixtures -{ - public static $testArgsJSON = array(); - - public static function populateTestArgsSimpleJSON() - { - self::$testArgsJSON['testVoid'] = '{}'; - - self::$testArgsJSON['testString1'] = '{"1":{"str":"Afrikaans, Alemannisch, Aragon\u00e9s, \u0627\u0644\u0639\u0631\u0628\u064a\u0629, \u0645\u0635\u0631\u0649, Asturianu, Aymar aru, Az\u0259rbaycan, \u0411\u0430\u0448\u04a1\u043e\u0440\u0442, Boarisch, \u017demait\u0117\u0161ka, \u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f, \u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f (\u0442\u0430\u0440\u0430\u0448\u043a\u0435\u0432\u0456\u0446\u0430), \u0411\u044a\u043b\u0433\u0430\u0440\u0441\u043a\u0438, Bamanankan, \u09ac\u09be\u0982\u09b2\u09be, Brezhoneg, Bosanski, Catal\u00e0, M\u00ecng-d\u0115\u0324ng-ng\u1e73\u0304, \u041d\u043e\u0445\u0447\u0438\u0439\u043d, Cebuano, \u13e3\u13b3\u13a9, \u010cesky, \u0421\u043b\u043e\u0432\u0463\u0301\u043d\u044c\u0441\u043a\u044a \/ \u2c14\u2c0e\u2c11\u2c02\u2c21\u2c10\u2c20\u2c14\u2c0d\u2c1f, \u0427\u04d1\u0432\u0430\u0448\u043b\u0430, Cymraeg, Dansk, Zazaki, \u078b\u07a8\u0788\u07ac\u0780\u07a8\u0784\u07a6\u0790\u07b0, \u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac, Emili\u00e0n e rumagn\u00f2l, English, Esperanto, Espa\u00f1ol, Eesti, Euskara, \u0641\u0627\u0631\u0633\u06cc, Suomi, V\u00f5ro, F\u00f8royskt, Fran\u00e7ais, Arpetan, Furlan, Frysk, Gaeilge, \u8d1b\u8a9e, G\u00e0idhlig, Galego, Ava\u00f1e\'\u1ebd, \u0a97\u0ac1\u0a9c\u0ab0\u0abe\u0aa4\u0ac0, Gaelg, \u05e2\u05d1\u05e8\u05d9\u05ea, \u0939\u093f\u0928\u094d\u0926\u0940, Fiji Hindi, Hrvatski, Krey\u00f2l ayisyen, Magyar, \u0540\u0561\u0575\u0565\u0580\u0565\u0576, Interlingua, Bahasa Indonesia, Ilokano, Ido, \u00cdslenska, Italiano, \u65e5\u672c\u8a9e, Lojban, Basa Jawa, \u10e5\u10d0\u10e0\u10d7\u10e3\u10da\u10d8, Kongo, Kalaallisut, \u0c95\u0ca8\u0ccd\u0ca8\u0ca1, \ud55c\uad6d\uc5b4, \u041a\u044a\u0430\u0440\u0430\u0447\u0430\u0439-\u041c\u0430\u043b\u043a\u044a\u0430\u0440, Ripoarisch, Kurd\u00ee, \u041a\u043e\u043c\u0438, Kernewek, \u041a\u044b\u0440\u0433\u044b\u0437\u0447\u0430, Latina, Ladino, L\u00ebtzebuergesch, Limburgs, Ling\u00e1la, \u0ea5\u0eb2\u0ea7, Lietuvi\u0173, Latvie\u0161u, Basa Banyumasan, Malagasy, \u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a\u0438, \u0d2e\u0d32\u0d2f\u0d3e\u0d33\u0d02, \u092e\u0930\u093e\u0920\u0940, Bahasa Melayu, \u0645\u0627\u0632\u0650\u0631\u0648\u0646\u06cc, Nnapulitano, Nedersaksisch, \u0928\u0947\u092a\u093e\u0932 \u092d\u093e\u0937\u093e, Nederlands, \u202aNorsk (nynorsk)\u202c, \u202aNorsk (bokm\u00e5l)\u202c, Nouormand, Din\u00e9 bizaad, Occitan, \u0418\u0440\u043e\u043d\u0430\u0443, Papiamentu, Deitsch, Norfuk \/ Pitkern, Polski, \u067e\u0646\u062c\u0627\u0628\u06cc, \u067e\u069a\u062a\u0648, Portugu\u00eas, Runa Simi, Rumantsch, Romani, Rom\u00e2n\u0103, \u0420\u0443\u0441\u0441\u043a\u0438\u0439, \u0421\u0430\u0445\u0430 \u0442\u044b\u043b\u0430, Sardu, Sicilianu, Scots, S\u00e1megiella, Simple English, Sloven\u010dina, Sloven\u0161\u010dina, \u0421\u0440\u043f\u0441\u043a\u0438 \/ Srpski, Seeltersk, Svenska, Kiswahili, \u0ba4\u0bae\u0bbf\u0bb4\u0bcd, \u0c24\u0c46\u0c32\u0c41\u0c17\u0c41, \u0422\u043e\u04b7\u0438\u043a\u04e3, \u0e44\u0e17\u0e22, T\u00fcrkmen\u00e7e, Tagalog, T\u00fcrk\u00e7e, \u0422\u0430\u0442\u0430\u0440\u0447\u0430\/Tatar\u00e7a, \u0423\u043a\u0440\u0430\u0457\u043d\u0441\u044c\u043a\u0430, \u0627\u0631\u062f\u0648, Ti\u1ebfng Vi\u1ec7t, Volap\u00fck, Walon, Winaray, \u5434\u8bed, isiXhosa, \u05d9\u05d9\u05b4\u05d3\u05d9\u05e9, Yor\u00f9b\u00e1, Ze\u00eauws, \u4e2d\u6587, B\u00e2n-l\u00e2m-g\u00fa, \u7cb5\u8a9e"}}'; - - self::$testArgsJSON['testString2'] = '{"thing":"quote: \\\\\" backslash: forwardslash-escaped: \\\\\/ backspace: \\\\b formfeed: \f newline: \n return: \r tab: now-all-of-them-together: \"\\\\\\\\\/\\\\b\n\r\t now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><"}'; - - self::$testArgsJSON['testDouble'] = '{"thing":3.1415926535898}'; - - self::$testArgsJSON['testByte'] = '{"thing":1}'; - - self::$testArgsJSON['testI32'] = '{"thing":1073741824}'; - - if (PHP_INT_SIZE == 8) { - self::$testArgsJSON['testI64'] = '{"thing":'.pow( 2, 60 ).'}'; - self::$testArgsJSON['testStruct'] = '{"thing":{"string_thing":"worked","byte_thing":1,"i32_thing":1073741824,"i64_thing":'.pow( 2, 60 ).'}}'; - self::$testArgsJSON['testNest'] = '{"thing":{"byte_thing":1,"struct_thing":{"string_thing":"worked","byte_thing":1,"i32_thing":1073741824,"i64_thing":'.pow( 2, 60 ).'},"i32_thing":32768}}'; - } else { - self::$testArgsJSON['testI64'] = '{"thing":1152921504606847000}'; - - self::$testArgsJSON['testStruct'] = '{"thing":{"string_thing":"worked","byte_thing":1,"i32_thing":1073741824,"i64_thing":1152921504606847000}}'; - self::$testArgsJSON['testNest'] = '{"thing":{"byte_thing":1,"struct_thing":{"string_thing":"worked","byte_thing":1,"i32_thing":1073741824,"i64_thing":1152921504606847000},"i32_thing":32768}}'; - } - - self::$testArgsJSON['testMap'] = '{"thing":{"7":77,"8":88,"9":99}}'; - - self::$testArgsJSON['testStringMap'] = '{"thing":{"a":"123","a b":"with spaces ","same":"same","0":"numeric key","longValue":"Afrikaans, Alemannisch, Aragon\u00e9s, \u0627\u0644\u0639\u0631\u0628\u064a\u0629, \u0645\u0635\u0631\u0649, Asturianu, Aymar aru, Az\u0259rbaycan, \u0411\u0430\u0448\u04a1\u043e\u0440\u0442, Boarisch, \u017demait\u0117\u0161ka, \u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f, \u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f (\u0442\u0430\u0440\u0430\u0448\u043a\u0435\u0432\u0456\u0446\u0430), \u0411\u044a\u043b\u0433\u0430\u0440\u0441\u043a\u0438, Bamanankan, \u09ac\u09be\u0982\u09b2\u09be, Brezhoneg, Bosanski, Catal\u00e0, M\u00ecng-d\u0115\u0324ng-ng\u1e73\u0304, \u041d\u043e\u0445\u0447\u0438\u0439\u043d, Cebuano, \u13e3\u13b3\u13a9, \u010cesky, \u0421\u043b\u043e\u0432\u0463\u0301\u043d\u044c\u0441\u043a\u044a \/ \u2c14\u2c0e\u2c11\u2c02\u2c21\u2c10\u2c20\u2c14\u2c0d\u2c1f, \u0427\u04d1\u0432\u0430\u0448\u043b\u0430, Cymraeg, Dansk, Zazaki, \u078b\u07a8\u0788\u07ac\u0780\u07a8\u0784\u07a6\u0790\u07b0, \u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac, Emili\u00e0n e rumagn\u00f2l, English, Esperanto, Espa\u00f1ol, Eesti, Euskara, \u0641\u0627\u0631\u0633\u06cc, Suomi, V\u00f5ro, F\u00f8royskt, Fran\u00e7ais, Arpetan, Furlan, Frysk, Gaeilge, \u8d1b\u8a9e, G\u00e0idhlig, Galego, Ava\u00f1e\'\u1ebd, \u0a97\u0ac1\u0a9c\u0ab0\u0abe\u0aa4\u0ac0, Gaelg, \u05e2\u05d1\u05e8\u05d9\u05ea, \u0939\u093f\u0928\u094d\u0926\u0940, Fiji Hindi, Hrvatski, Krey\u00f2l ayisyen, Magyar, \u0540\u0561\u0575\u0565\u0580\u0565\u0576, Interlingua, Bahasa Indonesia, Ilokano, Ido, \u00cdslenska, Italiano, \u65e5\u672c\u8a9e, Lojban, Basa Jawa, \u10e5\u10d0\u10e0\u10d7\u10e3\u10da\u10d8, Kongo, Kalaallisut, \u0c95\u0ca8\u0ccd\u0ca8\u0ca1, \ud55c\uad6d\uc5b4, \u041a\u044a\u0430\u0440\u0430\u0447\u0430\u0439-\u041c\u0430\u043b\u043a\u044a\u0430\u0440, Ripoarisch, Kurd\u00ee, \u041a\u043e\u043c\u0438, Kernewek, \u041a\u044b\u0440\u0433\u044b\u0437\u0447\u0430, Latina, Ladino, L\u00ebtzebuergesch, Limburgs, Ling\u00e1la, \u0ea5\u0eb2\u0ea7, Lietuvi\u0173, Latvie\u0161u, Basa Banyumasan, Malagasy, \u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a\u0438, \u0d2e\u0d32\u0d2f\u0d3e\u0d33\u0d02, \u092e\u0930\u093e\u0920\u0940, Bahasa Melayu, \u0645\u0627\u0632\u0650\u0631\u0648\u0646\u06cc, Nnapulitano, Nedersaksisch, \u0928\u0947\u092a\u093e\u0932 \u092d\u093e\u0937\u093e, Nederlands, \u202aNorsk (nynorsk)\u202c, \u202aNorsk (bokm\u00e5l)\u202c, Nouormand, Din\u00e9 bizaad, Occitan, \u0418\u0440\u043e\u043d\u0430\u0443, Papiamentu, Deitsch, Norfuk \/ Pitkern, Polski, \u067e\u0646\u062c\u0627\u0628\u06cc, \u067e\u069a\u062a\u0648, Portugu\u00eas, Runa Simi, Rumantsch, Romani, Rom\u00e2n\u0103, \u0420\u0443\u0441\u0441\u043a\u0438\u0439, \u0421\u0430\u0445\u0430 \u0442\u044b\u043b\u0430, Sardu, Sicilianu, Scots, S\u00e1megiella, Simple English, Sloven\u010dina, Sloven\u0161\u010dina, \u0421\u0440\u043f\u0441\u043a\u0438 \/ Srpski, Seeltersk, Svenska, Kiswahili, \u0ba4\u0bae\u0bbf\u0bb4\u0bcd, \u0c24\u0c46\u0c32\u0c41\u0c17\u0c41, \u0422\u043e\u04b7\u0438\u043a\u04e3, \u0e44\u0e17\u0e22, T\u00fcrkmen\u00e7e, Tagalog, T\u00fcrk\u00e7e, \u0422\u0430\u0442\u0430\u0440\u0447\u0430\/Tatar\u00e7a, \u0423\u043a\u0440\u0430\u0457\u043d\u0441\u044c\u043a\u0430, \u0627\u0631\u062f\u0648, Ti\u1ebfng Vi\u1ec7t, Volap\u00fck, Walon, Winaray, \u5434\u8bed, isiXhosa, \u05d9\u05d9\u05b4\u05d3\u05d9\u05e9, Yor\u00f9b\u00e1, Ze\u00eauws, \u4e2d\u6587, B\u00e2n-l\u00e2m-g\u00fa, \u7cb5\u8a9e","Afrikaans, Alemannisch, Aragon\u00e9s, \u0627\u0644\u0639\u0631\u0628\u064a\u0629, \u0645\u0635\u0631\u0649, Asturianu, Aymar aru, Az\u0259rbaycan, \u0411\u0430\u0448\u04a1\u043e\u0440\u0442, Boarisch, \u017demait\u0117\u0161ka, \u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f, \u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f (\u0442\u0430\u0440\u0430\u0448\u043a\u0435\u0432\u0456\u0446\u0430), \u0411\u044a\u043b\u0433\u0430\u0440\u0441\u043a\u0438, Bamanankan, \u09ac\u09be\u0982\u09b2\u09be, Brezhoneg, Bosanski, Catal\u00e0, M\u00ecng-d\u0115\u0324ng-ng\u1e73\u0304, \u041d\u043e\u0445\u0447\u0438\u0439\u043d, Cebuano, \u13e3\u13b3\u13a9, \u010cesky, \u0421\u043b\u043e\u0432\u0463\u0301\u043d\u044c\u0441\u043a\u044a \/ \u2c14\u2c0e\u2c11\u2c02\u2c21\u2c10\u2c20\u2c14\u2c0d\u2c1f, \u0427\u04d1\u0432\u0430\u0448\u043b\u0430, Cymraeg, Dansk, Zazaki, \u078b\u07a8\u0788\u07ac\u0780\u07a8\u0784\u07a6\u0790\u07b0, \u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac, Emili\u00e0n e rumagn\u00f2l, English, Esperanto, Espa\u00f1ol, Eesti, Euskara, \u0641\u0627\u0631\u0633\u06cc, Suomi, V\u00f5ro, F\u00f8royskt, Fran\u00e7ais, Arpetan, Furlan, Frysk, Gaeilge, \u8d1b\u8a9e, G\u00e0idhlig, Galego, Ava\u00f1e\'\u1ebd, \u0a97\u0ac1\u0a9c\u0ab0\u0abe\u0aa4\u0ac0, Gaelg, \u05e2\u05d1\u05e8\u05d9\u05ea, \u0939\u093f\u0928\u094d\u0926\u0940, Fiji Hindi, Hrvatski, Krey\u00f2l ayisyen, Magyar, \u0540\u0561\u0575\u0565\u0580\u0565\u0576, Interlingua, Bahasa Indonesia, Ilokano, Ido, \u00cdslenska, Italiano, \u65e5\u672c\u8a9e, Lojban, Basa Jawa, \u10e5\u10d0\u10e0\u10d7\u10e3\u10da\u10d8, Kongo, Kalaallisut, \u0c95\u0ca8\u0ccd\u0ca8\u0ca1, \ud55c\uad6d\uc5b4, \u041a\u044a\u0430\u0440\u0430\u0447\u0430\u0439-\u041c\u0430\u043b\u043a\u044a\u0430\u0440, Ripoarisch, Kurd\u00ee, \u041a\u043e\u043c\u0438, Kernewek, \u041a\u044b\u0440\u0433\u044b\u0437\u0447\u0430, Latina, Ladino, L\u00ebtzebuergesch, Limburgs, Ling\u00e1la, \u0ea5\u0eb2\u0ea7, Lietuvi\u0173, Latvie\u0161u, Basa Banyumasan, Malagasy, \u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a\u0438, \u0d2e\u0d32\u0d2f\u0d3e\u0d33\u0d02, \u092e\u0930\u093e\u0920\u0940, Bahasa Melayu, \u0645\u0627\u0632\u0650\u0631\u0648\u0646\u06cc, Nnapulitano, Nedersaksisch, \u0928\u0947\u092a\u093e\u0932 \u092d\u093e\u0937\u093e, Nederlands, \u202aNorsk (nynorsk)\u202c, \u202aNorsk (bokm\u00e5l)\u202c, Nouormand, Din\u00e9 bizaad, Occitan, \u0418\u0440\u043e\u043d\u0430\u0443, Papiamentu, Deitsch, Norfuk \/ Pitkern, Polski, \u067e\u0646\u062c\u0627\u0628\u06cc, \u067e\u069a\u062a\u0648, Portugu\u00eas, Runa Simi, Rumantsch, Romani, Rom\u00e2n\u0103, \u0420\u0443\u0441\u0441\u043a\u0438\u0439, \u0421\u0430\u0445\u0430 \u0442\u044b\u043b\u0430, Sardu, Sicilianu, Scots, S\u00e1megiella, Simple English, Sloven\u010dina, Sloven\u0161\u010dina, \u0421\u0440\u043f\u0441\u043a\u0438 \/ Srpski, Seeltersk, Svenska, Kiswahili, \u0ba4\u0bae\u0bbf\u0bb4\u0bcd, \u0c24\u0c46\u0c32\u0c41\u0c17\u0c41, \u0422\u043e\u04b7\u0438\u043a\u04e3, \u0e44\u0e17\u0e22, T\u00fcrkmen\u00e7e, Tagalog, T\u00fcrk\u00e7e, \u0422\u0430\u0442\u0430\u0440\u0447\u0430\/Tatar\u00e7a, \u0423\u043a\u0440\u0430\u0457\u043d\u0441\u044c\u043a\u0430, \u0627\u0631\u062f\u0648, Ti\u1ebfng Vi\u1ec7t, Volap\u00fck, Walon, Winaray, \u5434\u8bed, isiXhosa, \u05d9\u05d9\u05b4\u05d3\u05d9\u05e9, Yor\u00f9b\u00e1, Ze\u00eauws, \u4e2d\u6587, B\u00e2n-l\u00e2m-g\u00fa, \u7cb5\u8a9e":"long key"}}'; - - self::$testArgsJSON['testSet'] = '{"thing":[1,5,6]}'; - - self::$testArgsJSON['testList'] = '{"thing":[1,2,3]}'; - - self::$testArgsJSON['testEnum'] = '{"thing":1}'; - - self::$testArgsJSON['testTypedef'] = '{"thing":69}'; - } -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/TestValidators.php b/vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/TestValidators.php deleted file mode 100644 index 36cf000..0000000 --- a/vendor/git.apache.org/thrift.git/lib/php/test/Test/Thrift/TestValidators.php +++ /dev/null @@ -1,156 +0,0 @@ -registerNamespace('Thrift', __DIR__ . '/../../../lib'); -$loader->registerDefinition('ThriftTest', __DIR__ . '/../../packages/' . $GEN_DIR); -$loader->registerDefinition('TestValidators', __DIR__ . '/../../packages/' . $GEN_DIR); -$loader->register(); - -// Would be nice to have PHPUnit here, but for now just hack it. - -set_exception_handler(function ($e) { - my_assert(false, "Unexpected exception caught: " . $e->getMessage()); -}); - -set_error_handler(function ($errno, $errmsg) { - my_assert(false, "Unexpected PHP error: " . $errmsg); -}); - -// Empty structs should not have validators -assert_has_no_read_validator('ThriftTest\EmptyStruct'); -assert_has_no_write_validator('ThriftTest\EmptyStruct'); - -// Bonk has only opt_in_req_out fields -{ - assert_has_no_read_validator('ThriftTest\Bonk'); - assert_has_a_write_validator('ThriftTest\Bonk'); - { - // Check that we can read an empty object - $bonk = new \ThriftTest\Bonk(); - $transport = new TMemoryBuffer("\000"); - $protocol = new TBinaryProtocol($transport); - $bonk->read($protocol); - } - { - // ...but not write an empty object - $bonk = new \ThriftTest\Bonk(); - $transport = new TMemoryBuffer(); - $protocol = new TBinaryProtocol($transport); - assert_protocol_exception_thrown(function () use ($bonk, $protocol) { $bonk->write($protocol); }, - 'Bonk was able to write an empty object'); - } -} - -// StructA has a single required field -{ - assert_has_a_read_validator('ThriftTest\StructA'); - assert_has_a_write_validator('ThriftTest\StructA'); - { - // Check that we are not able to write StructA with a missing required field - $structa = new \ThriftTest\StructA(); - $transport = new TMemoryBuffer(); - $protocol = new TBinaryProtocol($transport); - assert_protocol_exception_thrown(function () use ($structa, $protocol) { $structa->write($protocol); }, - 'StructA was able to write an empty object'); - } - { - // Check that we are able to read and write a message with a good StructA - $transport = new TMemoryBuffer(base64_decode('CwABAAAAA2FiYwA=')); - $protocol = new TBinaryProtocol($transport); - $structa = new \ThriftTest\StructA(); - $structa->read($protocol); - $structa->write($protocol); - } -} - -// Unions should not get write validators -assert_has_no_write_validator('TestValidators\UnionOfStrings'); - -// Service _result classes should not get any validators -assert_has_no_read_validator('TestValidators\TestService_test_result'); -assert_has_no_write_validator('TestValidators\TestService_test_result'); - -function assert_has_a_read_validator($class) -{ - my_assert(has_read_validator_method($class), - $class . ' class should have a read validator'); -} - -function assert_has_no_read_validator($class) -{ - my_assert(!has_read_validator_method($class), - $class . ' class should not have a read validator'); -} - -function assert_has_a_write_validator($class) -{ - my_assert(has_write_validator_method($class), - $class . ' class should have a write validator'); -} - -function assert_has_no_write_validator($class) -{ - my_assert(!has_write_validator_method($class), - $class . ' class should not have a write validator'); -} - -function assert_protocol_exception_thrown($callable, $message) -{ - try { - call_user_func($callable); - my_assert(false, $message); - } catch (TProtocolException $e) { - } -} - -function has_write_validator_method($class) -{ - $rc = new \ReflectionClass($class); - - return $rc->hasMethod('_validateForWrite'); -} - -function has_read_validator_method($class) -{ - $rc = new \ReflectionClass($class); - - return $rc->hasMethod('_validateForRead'); -} - -function my_assert($something, $message) -{ - if (!$something) { - fwrite(STDERR, basename(__FILE__) . " FAILED: $message\n"); - exit(1); - } -} diff --git a/vendor/git.apache.org/thrift.git/lib/php/test/Validator/BaseValidatorTest.php b/vendor/git.apache.org/thrift.git/lib/php/test/Validator/BaseValidatorTest.php new file mode 100644 index 0000000..6029083 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/test/Validator/BaseValidatorTest.php @@ -0,0 +1,154 @@ +assertNoReadValidator('ThriftTest\EmptyStruct'); + $this->assertNoWriteValidator('ThriftTest\EmptyStruct'); + } + + public function testBonkValidator() + { + $this->assertNoReadValidator('ThriftTest\Bonk'); + $this->assertHasWriteValidator('ThriftTest\Bonk'); + } + + public function testStructAValidator() + { + $this->assertHasReadValidator('ThriftTest\StructA'); + $this->assertHasWriteValidator('ThriftTest\StructA'); + } + + public function testUnionOfStringsValidator() + { + $this->assertNoWriteValidator('TestValidators\UnionOfStrings'); + } + + public function testServiceResultValidator() + { + $this->assertNoReadValidator('TestValidators\TestService_test_result'); + $this->assertNoWriteValidator('TestValidators\TestService_test_result'); + } + + public function testReadEmpty() + { + $bonk = new \ThriftTest\Bonk(); + $transport = new TMemoryBuffer("\000"); + $protocol = new TBinaryProtocol($transport); + $bonk->read($protocol); + } + + public function testWriteEmpty() + { + $bonk = new \ThriftTest\Bonk(); + $transport = new TMemoryBuffer(); + $protocol = new TBinaryProtocol($transport); + try { + $bonk->write($protocol); + $this->fail('Bonk was able to write an empty object'); + } catch (TProtocolException $e) { + } + } + + public function testWriteWithMissingRequired() + { + // Check that we are not able to write StructA with a missing required field + $structa = new \ThriftTest\StructA(); + $transport = new TMemoryBuffer(); + $protocol = new TBinaryProtocol($transport); + + try { + $structa->write($protocol); + $this->fail('StructA was able to write an empty object'); + } catch (TProtocolException $e) { + } + } + + public function testReadStructA() + { + $transport = new TMemoryBuffer(base64_decode('CwABAAAAA2FiYwA=')); + $protocol = new TBinaryProtocol($transport); + $structa = new \ThriftTest\StructA(); + $structa->read($protocol); + $this->assertEquals("abc", $structa->s); + } + + public function testWriteStructA() + { + $transport = new TMemoryBuffer(); + $protocol = new TBinaryProtocol($transport); + $structa = new \ThriftTest\StructA(); + $structa->s = "abc"; + $structa->write($protocol); + $writeResult = base64_encode($transport->getBuffer()); + $this->assertEquals('CwABAAAAA2FiYwA=', $writeResult); + } + + protected static function assertHasReadValidator($class) + { + if (!static::hasReadValidator($class)) { + static::fail($class . ' class should have a read validator'); + } + } + + protected static function assertNoReadValidator($class) + { + if (static::hasReadValidator($class)) { + static::fail($class . ' class should not have a write validator'); + } + } + + protected static function assertHasWriteValidator($class) + { + if (!static::hasWriteValidator($class)) { + static::fail($class . ' class should have a write validator'); + } + } + + protected static function assertNoWriteValidator($class) + { + if (static::hasWriteValidator($class)) { + static::fail($class . ' class should not have a write validator'); + } + } + + private static function hasReadValidator($class) + { + $rc = new \ReflectionClass($class); + + return $rc->hasMethod('_validateForRead'); + } + + private static function hasWriteValidator($class) + { + $rc = new \ReflectionClass($class); + + return $rc->hasMethod('_validateForWrite'); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/test/Validator/ValidatorTest.php b/vendor/git.apache.org/thrift.git/lib/php/test/Validator/ValidatorTest.php new file mode 100644 index 0000000..fa6c7a9 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/test/Validator/ValidatorTest.php @@ -0,0 +1,41 @@ +addPsr4('', __DIR__ . '/../packages/phpv'); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/php/test/Validator/ValidatorTestOop.php b/vendor/git.apache.org/thrift.git/lib/php/test/Validator/ValidatorTestOop.php new file mode 100644 index 0000000..93bca4d --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/php/test/Validator/ValidatorTestOop.php @@ -0,0 +1,41 @@ +addPsr4('', __DIR__ . '/../packages/phpvo'); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/py/MANIFEST.in b/vendor/git.apache.org/thrift.git/lib/py/MANIFEST.in new file mode 100644 index 0000000..af54e29 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/py/MANIFEST.in @@ -0,0 +1 @@ +include src/ext/* diff --git a/vendor/git.apache.org/thrift.git/lib/py/Makefile.am b/vendor/git.apache.org/thrift.git/lib/py/Makefile.am index fd9ce25..5861858 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/Makefile.am +++ b/vendor/git.apache.org/thrift.git/lib/py/Makefile.am @@ -49,6 +49,7 @@ check-local: all py3-test EXTRA_DIST = \ CMakeLists.txt \ + MANIFEST.in \ coding_standards.md \ compat \ setup.py \ diff --git a/vendor/git.apache.org/thrift.git/lib/py/setup.py b/vendor/git.apache.org/thrift.git/lib/py/setup.py index 1fdfe72..6ee28df 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/setup.py +++ b/vendor/git.apache.org/thrift.git/lib/py/setup.py @@ -22,7 +22,7 @@ import sys try: from setuptools import setup, Extension -except: +except Exception: from distutils.core import setup, Extension from distutils.command.build_ext import build_ext @@ -31,7 +31,10 @@ from distutils.errors import CCompilerError, DistutilsExecError, DistutilsPlatfo # Fix to build sdist under vagrant import os if 'vagrant' in str(os.environ): - del os.link + try: + del os.link + except AttributeError: + pass include_dirs = ['src'] if sys.platform == 'win32': @@ -87,7 +90,7 @@ def run_setup(with_binary): twisted_deps = ['twisted'] setup(name='thrift', - version='0.10.0', + version='0.12.0', description='Python bindings for the Apache Thrift RPC system', author='Thrift Developers', author_email='dev@thrift.apache.org', @@ -117,9 +120,11 @@ def run_setup(with_binary): 'Topic :: Software Development :: Libraries', 'Topic :: System :: Networking' ], + zip_safe=False, **extensions ) + try: with_binary = True run_setup(with_binary) diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/TMultiplexedProcessor.py b/vendor/git.apache.org/thrift.git/lib/py/src/TMultiplexedProcessor.py index 605aa1f..3ac5af0 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/TMultiplexedProcessor.py +++ b/vendor/git.apache.org/thrift.git/lib/py/src/TMultiplexedProcessor.py @@ -31,11 +31,11 @@ class TMultiplexedProcessor(TProcessor): def process(self, iprot, oprot): (name, type, seqid) = iprot.readMessageBegin() if type != TMessageType.CALL and type != TMessageType.ONEWAY: - raise TException("TMultiplex protocol only supports CALL & ONEWAY") + raise TException("TMultiplexed protocol only supports CALL & ONEWAY") index = name.find(TMultiplexedProtocol.SEPARATOR) if index < 0: - raise TException("Service name not found in message name: " + name + ". Did you forget to use TMultiplexProtocol in your client?") + raise TException("Service name not found in message name: " + name + ". Did you forget to use TMultiplexedProtocol in your client?") serviceName = name[0:index] call = name[index + len(TMultiplexedProtocol.SEPARATOR):] @@ -48,7 +48,6 @@ class TMultiplexedProcessor(TProcessor): class StoredMessageProtocol(TProtocolDecorator.TProtocolDecorator): def __init__(self, protocol, messageBegin): - TProtocolDecorator.TProtocolDecorator.__init__(self, protocol) self.messageBegin = messageBegin def readMessageBegin(self): diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/TRecursive.py b/vendor/git.apache.org/thrift.git/lib/py/src/TRecursive.py new file mode 100644 index 0000000..abf202c --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/py/src/TRecursive.py @@ -0,0 +1,83 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +from thrift.Thrift import TType + +TYPE_IDX = 1 +SPEC_ARGS_IDX = 3 +SPEC_ARGS_CLASS_REF_IDX = 0 +SPEC_ARGS_THRIFT_SPEC_IDX = 1 + + +def fix_spec(all_structs): + """Wire up recursive references for all TStruct definitions inside of each thrift_spec.""" + for struc in all_structs: + spec = struc.thrift_spec + for thrift_spec in spec: + if thrift_spec is None: + continue + elif thrift_spec[TYPE_IDX] == TType.STRUCT: + other = thrift_spec[SPEC_ARGS_IDX][SPEC_ARGS_CLASS_REF_IDX].thrift_spec + thrift_spec[SPEC_ARGS_IDX][SPEC_ARGS_THRIFT_SPEC_IDX] = other + elif thrift_spec[TYPE_IDX] in (TType.LIST, TType.SET): + _fix_list_or_set(thrift_spec[SPEC_ARGS_IDX]) + elif thrift_spec[TYPE_IDX] == TType.MAP: + _fix_map(thrift_spec[SPEC_ARGS_IDX]) + + +def _fix_list_or_set(element_type): + # For a list or set, the thrift_spec entry looks like, + # (1, TType.LIST, 'lister', (TType.STRUCT, [RecList, None], False), None, ), # 1 + # so ``element_type`` will be, + # (TType.STRUCT, [RecList, None], False) + if element_type[0] == TType.STRUCT: + element_type[1][1] = element_type[1][0].thrift_spec + elif element_type[0] in (TType.LIST, TType.SET): + _fix_list_or_set(element_type[1]) + elif element_type[0] == TType.MAP: + _fix_map(element_type[1]) + + +def _fix_map(element_type): + # For a map of key -> value type, ``element_type`` will be, + # (TType.I16, None, TType.STRUCT, [RecMapBasic, None], False), None, ) + # which is just a normal struct definition. + # + # For a map of key -> list / set, ``element_type`` will be, + # (TType.I16, None, TType.LIST, (TType.STRUCT, [RecMapList, None], False), False) + # and we need to process the 3rd element as a list. + # + # For a map of key -> map, ``element_type`` will be, + # (TType.I16, None, TType.MAP, (TType.I16, None, TType.STRUCT, + # [RecMapMap, None], False), False) + # and need to process 3rd element as a map. + + # Is the map key a struct? + if element_type[0] == TType.STRUCT: + element_type[1][1] = element_type[1][0].thrift_spec + elif element_type[0] in (TType.LIST, TType.SET): + _fix_list_or_set(element_type[1]) + elif element_type[0] == TType.MAP: + _fix_map(element_type[1]) + + # Is the map value a struct? + if element_type[2] == TType.STRUCT: + element_type[3][1] = element_type[3][0].thrift_spec + elif element_type[2] in (TType.LIST, TType.SET): + _fix_list_or_set(element_type[3]) + elif element_type[2] == TType.MAP: + _fix_map(element_type[3]) diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/Thrift.py b/vendor/git.apache.org/thrift.git/lib/py/src/Thrift.py index c4dabdc..00941d8 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/Thrift.py +++ b/vendor/git.apache.org/thrift.git/lib/py/src/Thrift.py @@ -69,9 +69,9 @@ class TMessageType(object): class TProcessor(object): - """Base class for procsessor, which works on two streams.""" + """Base class for processor, which works on two streams.""" - def process(iprot, oprot): + def process(self, iprot, oprot): pass diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/compat.py b/vendor/git.apache.org/thrift.git/lib/py/src/compat.py index 41bcf35..0e8271d 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/compat.py +++ b/vendor/git.apache.org/thrift.git/lib/py/src/compat.py @@ -29,6 +29,9 @@ if sys.version_info[0] == 2: def str_to_binary(str_val): return str_val + def byte_index(bytes_val, i): + return ord(bytes_val[i]) + else: from io import BytesIO as BufferIO # noqa @@ -38,3 +41,6 @@ else: def str_to_binary(str_val): return bytes(str_val, 'utf8') + + def byte_index(bytes_val, i): + return bytes_val[i] diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/ext/binary.h b/vendor/git.apache.org/thrift.git/lib/py/src/ext/binary.h index dedeec3..960b0d0 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/ext/binary.h +++ b/vendor/git.apache.org/thrift.git/lib/py/src/ext/binary.h @@ -113,7 +113,8 @@ public: if (!readBytes(&buf, sizeof(int16_t))) { return false; } - val = static_cast(ntohs(*reinterpret_cast(buf))); + memcpy(&val, buf, sizeof(int16_t)); + val = ntohs(val); return true; } @@ -122,7 +123,8 @@ public: if (!readBytes(&buf, sizeof(int32_t))) { return false; } - val = static_cast(ntohl(*reinterpret_cast(buf))); + memcpy(&val, buf, sizeof(int32_t)); + val = ntohl(val); return true; } @@ -131,7 +133,8 @@ public: if (!readBytes(&buf, sizeof(int64_t))) { return false; } - val = static_cast(ntohll(*reinterpret_cast(buf))); + memcpy(&val, buf, sizeof(int64_t)); + val = ntohll(val); return true; } diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/ext/compact.h b/vendor/git.apache.org/thrift.git/lib/py/src/ext/compact.h index 5bba237..a78d7a7 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/ext/compact.h +++ b/vendor/git.apache.org/thrift.git/lib/py/src/ext/compact.h @@ -162,7 +162,8 @@ public: if (!readBytes(&buf, 8)) { return false; } - transfer.f = letohll(*reinterpret_cast(buf)); + memcpy(&transfer.f, buf, sizeof(int64_t)); + transfer.f = letohll(transfer.f); val = transfer.t; return true; } diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/ext/module.cpp b/vendor/git.apache.org/thrift.git/lib/py/src/ext/module.cpp index 34ec7f6..7158b8f 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/ext/module.cpp +++ b/vendor/git.apache.org/thrift.git/lib/py/src/ext/module.cpp @@ -87,12 +87,7 @@ static PyObject* decode_impl(PyObject* args) { } T protocol; -#ifdef _MSC_VER - // workaround strange VC++ 2015 bug where #else path does not compile - int32_t default_limit = INT32_MAX; -#else - int32_t default_limit = std::numeric_limits::max(); -#endif + int32_t default_limit = (std::numeric_limits::max)(); protocol.setStringLengthLimit( as_long_then_delete(PyObject_GetAttr(oprot, INTERN_STRING(string_length_limit)), default_limit)); diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/ext/protocol.h b/vendor/git.apache.org/thrift.git/lib/py/src/ext/protocol.h index 126dbc3..521b7ee 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/ext/protocol.h +++ b/vendor/git.apache.org/thrift.git/lib/py/src/ext/protocol.h @@ -33,8 +33,8 @@ class ProtocolBase { public: ProtocolBase() - : stringLimit_(std::numeric_limits::max()), - containerLimit_(std::numeric_limits::max()), + : stringLimit_((std::numeric_limits::max)()), + containerLimit_((std::numeric_limits::max)()), output_(NULL) {} inline virtual ~ProtocolBase(); diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/ext/protocol.tcc b/vendor/git.apache.org/thrift.git/lib/py/src/ext/protocol.tcc index 6e978d7..e15df7e 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/ext/protocol.tcc +++ b/vendor/git.apache.org/thrift.git/lib/py/src/ext/protocol.tcc @@ -102,7 +102,7 @@ inline bool ProtocolBase::writeBuffer(char* data, size_t size) { PyErr_SetString(PyExc_IOError, "failed to write to cStringIO object"); return false; } - if (len != size) { + if (static_cast(len) != size) { PyErr_Format(PyExc_EOFError, "write length mismatch: expected %lu got %d", size, len); return false; } @@ -144,7 +144,7 @@ inline int read_buffer(PyObject* buf, char** output, int len) { *output = PyBytes_AS_STRING(buf2->buf) + buf2->pos; #endif Py_ssize_t pos0 = buf2->pos; - buf2->pos = std::min(buf2->pos + static_cast(len), buf2->string_size); + buf2->pos = (std::min)(buf2->pos + static_cast(len), buf2->string_size); return static_cast(buf2->pos - pos0); } } @@ -212,7 +212,7 @@ inline bool check_ssize_t_32(Py_ssize_t len) { if (INT_CONV_ERROR_OCCURRED(len)) { return false; } - if (!CHECK_RANGE(len, 0, std::numeric_limits::max())) { + if (!CHECK_RANGE(len, 0, (std::numeric_limits::max)())) { PyErr_SetString(PyExc_OverflowError, "size out of range: exceeded INT32_MAX"); return false; } @@ -360,8 +360,8 @@ bool ProtocolBase::encodeValue(PyObject* value, TType type, PyObject* type case T_I08: { int8_t val; - if (!parse_pyint(value, &val, std::numeric_limits::min(), - std::numeric_limits::max())) { + if (!parse_pyint(value, &val, (std::numeric_limits::min)(), + (std::numeric_limits::max)())) { return false; } @@ -371,8 +371,8 @@ bool ProtocolBase::encodeValue(PyObject* value, TType type, PyObject* type case T_I16: { int16_t val; - if (!parse_pyint(value, &val, std::numeric_limits::min(), - std::numeric_limits::max())) { + if (!parse_pyint(value, &val, (std::numeric_limits::min)(), + (std::numeric_limits::max)())) { return false; } @@ -382,8 +382,8 @@ bool ProtocolBase::encodeValue(PyObject* value, TType type, PyObject* type case T_I32: { int32_t val; - if (!parse_pyint(value, &val, std::numeric_limits::min(), - std::numeric_limits::max())) { + if (!parse_pyint(value, &val, (std::numeric_limits::min)(), + (std::numeric_limits::max)())) { return false; } @@ -397,8 +397,8 @@ bool ProtocolBase::encodeValue(PyObject* value, TType type, PyObject* type return false; } - if (!CHECK_RANGE(nval, std::numeric_limits::min(), - std::numeric_limits::max())) { + if (!CHECK_RANGE(nval, (std::numeric_limits::min)(), + (std::numeric_limits::max)())) { PyErr_SetString(PyExc_OverflowError, "int out of range"); return false; } diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/ext/types.cpp b/vendor/git.apache.org/thrift.git/lib/py/src/ext/types.cpp index 849ab2f..68443fb 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/ext/types.cpp +++ b/vendor/git.apache.org/thrift.git/lib/py/src/ext/types.cpp @@ -98,13 +98,13 @@ bool parse_map_args(MapTypeArgs* dest, PyObject* typeargs) { } bool parse_struct_args(StructTypeArgs* dest, PyObject* typeargs) { - if (PyTuple_Size(typeargs) != 2) { - PyErr_SetString(PyExc_TypeError, "expecting tuple of size 2 for struct args"); + if (PyList_Size(typeargs) != 2) { + PyErr_SetString(PyExc_TypeError, "expecting list of size 2 for struct args"); return false; } - dest->klass = PyTuple_GET_ITEM(typeargs, 0); - dest->spec = PyTuple_GET_ITEM(typeargs, 1); + dest->klass = PyList_GET_ITEM(typeargs, 0); + dest->spec = PyList_GET_ITEM(typeargs, 1); return true; } diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/ext/types.h b/vendor/git.apache.org/thrift.git/lib/py/src/ext/types.h index 2fc9d9c..5cd8dda 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/ext/types.h +++ b/vendor/git.apache.org/thrift.git/lib/py/src/ext/types.h @@ -23,6 +23,7 @@ #include #ifdef _MSC_VER +#define __STDC_FORMAT_MACROS #define __STDC_LIMIT_MACROS #endif #include diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/protocol/TBase.py b/vendor/git.apache.org/thrift.git/lib/py/src/protocol/TBase.py index 55da19e..9ae1b11 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/protocol/TBase.py +++ b/vendor/git.apache.org/thrift.git/lib/py/src/protocol/TBase.py @@ -44,14 +44,14 @@ class TBase(object): if (iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None): - iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec)) + iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) else: iprot.readStruct(self, self.thrift_spec) def write(self, oprot): if (oprot._fast_encode is not None and self.thrift_spec is not None): oprot.trans.write( - oprot._fast_encode(self, (self.__class__, self.thrift_spec))) + oprot._fast_encode(self, [self.__class__, self.thrift_spec])) else: oprot.writeStruct(self, self.thrift_spec) @@ -77,6 +77,6 @@ class TFrozenBase(TBase): cls.thrift_spec is not None): self = cls() return iprot._fast_decode(None, iprot, - (self.__class__, self.thrift_spec)) + [self.__class__, self.thrift_spec]) else: return iprot.readStruct(cls, cls.thrift_spec, True) diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/protocol/TCompactProtocol.py b/vendor/git.apache.org/thrift.git/lib/py/src/protocol/TCompactProtocol.py index 16fd9be..e485cff 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/protocol/TCompactProtocol.py +++ b/vendor/git.apache.org/thrift.git/lib/py/src/protocol/TCompactProtocol.py @@ -42,6 +42,8 @@ def make_helper(v_from, container): return func(self, *args, **kwargs) return nested return helper + + writer = make_helper(VALUE_WRITE, CONTAINER_WRITE) reader = make_helper(VALUE_READ, CONTAINER_READ) @@ -94,6 +96,7 @@ class CompactType(object): MAP = 0x0B STRUCT = 0x0C + CTYPES = { TType.STOP: CompactType.STOP, TType.BOOL: CompactType.TRUE, # used for collection diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/protocol/THeaderProtocol.py b/vendor/git.apache.org/thrift.git/lib/py/src/protocol/THeaderProtocol.py new file mode 100644 index 0000000..b27a749 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/py/src/protocol/THeaderProtocol.py @@ -0,0 +1,225 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +from thrift.protocol.TBinaryProtocol import TBinaryProtocolAccelerated +from thrift.protocol.TCompactProtocol import TCompactProtocolAccelerated +from thrift.protocol.TProtocol import TProtocolBase, TProtocolException +from thrift.Thrift import TApplicationException, TMessageType +from thrift.transport.THeaderTransport import THeaderTransport, THeaderSubprotocolID, THeaderClientType + + +PROTOCOLS_BY_ID = { + THeaderSubprotocolID.BINARY: TBinaryProtocolAccelerated, + THeaderSubprotocolID.COMPACT: TCompactProtocolAccelerated, +} + + +class THeaderProtocol(TProtocolBase): + """A framed protocol with headers and payload transforms. + + THeaderProtocol frames other Thrift protocols and adds support for optional + out-of-band headers. The currently supported subprotocols are + TBinaryProtocol and TCompactProtocol. + + It's also possible to apply transforms to the encoded message payload. The + only transform currently supported is to gzip. + + When used in a server, THeaderProtocol can accept messages from + non-THeaderProtocol clients if allowed (see `allowed_client_types`). This + includes framed and unframed transports and both TBinaryProtocol and + TCompactProtocol. The server will respond in the appropriate dialect for + the connected client. HTTP clients are not currently supported. + + THeaderProtocol does not currently support THTTPServer, TNonblockingServer, + or TProcessPoolServer. + + See doc/specs/HeaderFormat.md for details of the wire format. + + """ + + def __init__(self, transport, allowed_client_types): + # much of the actual work for THeaderProtocol happens down in + # THeaderTransport since we need to do low-level shenanigans to detect + # if the client is sending us headers or one of the headerless formats + # we support. this wraps the real transport with the one that does all + # the magic. + if not isinstance(transport, THeaderTransport): + transport = THeaderTransport(transport, allowed_client_types) + super(THeaderProtocol, self).__init__(transport) + self._set_protocol() + + def get_headers(self): + return self.trans.get_headers() + + def set_header(self, key, value): + self.trans.set_header(key, value) + + def clear_headers(self): + self.trans.clear_headers() + + def add_transform(self, transform_id): + self.trans.add_transform(transform_id) + + def writeMessageBegin(self, name, ttype, seqid): + self.trans.sequence_id = seqid + return self._protocol.writeMessageBegin(name, ttype, seqid) + + def writeMessageEnd(self): + return self._protocol.writeMessageEnd() + + def writeStructBegin(self, name): + return self._protocol.writeStructBegin(name) + + def writeStructEnd(self): + return self._protocol.writeStructEnd() + + def writeFieldBegin(self, name, ttype, fid): + return self._protocol.writeFieldBegin(name, ttype, fid) + + def writeFieldEnd(self): + return self._protocol.writeFieldEnd() + + def writeFieldStop(self): + return self._protocol.writeFieldStop() + + def writeMapBegin(self, ktype, vtype, size): + return self._protocol.writeMapBegin(ktype, vtype, size) + + def writeMapEnd(self): + return self._protocol.writeMapEnd() + + def writeListBegin(self, etype, size): + return self._protocol.writeListBegin(etype, size) + + def writeListEnd(self): + return self._protocol.writeListEnd() + + def writeSetBegin(self, etype, size): + return self._protocol.writeSetBegin(etype, size) + + def writeSetEnd(self): + return self._protocol.writeSetEnd() + + def writeBool(self, bool_val): + return self._protocol.writeBool(bool_val) + + def writeByte(self, byte): + return self._protocol.writeByte(byte) + + def writeI16(self, i16): + return self._protocol.writeI16(i16) + + def writeI32(self, i32): + return self._protocol.writeI32(i32) + + def writeI64(self, i64): + return self._protocol.writeI64(i64) + + def writeDouble(self, dub): + return self._protocol.writeDouble(dub) + + def writeBinary(self, str_val): + return self._protocol.writeBinary(str_val) + + def _set_protocol(self): + try: + protocol_cls = PROTOCOLS_BY_ID[self.trans.protocol_id] + except KeyError: + raise TApplicationException( + TProtocolException.INVALID_PROTOCOL, + "Unknown protocol requested.", + ) + + self._protocol = protocol_cls(self.trans) + self._fast_encode = self._protocol._fast_encode + self._fast_decode = self._protocol._fast_decode + + def readMessageBegin(self): + try: + self.trans.readFrame(0) + self._set_protocol() + except TApplicationException as exc: + self._protocol.writeMessageBegin(b"", TMessageType.EXCEPTION, 0) + exc.write(self._protocol) + self._protocol.writeMessageEnd() + self.trans.flush() + + return self._protocol.readMessageBegin() + + def readMessageEnd(self): + return self._protocol.readMessageEnd() + + def readStructBegin(self): + return self._protocol.readStructBegin() + + def readStructEnd(self): + return self._protocol.readStructEnd() + + def readFieldBegin(self): + return self._protocol.readFieldBegin() + + def readFieldEnd(self): + return self._protocol.readFieldEnd() + + def readMapBegin(self): + return self._protocol.readMapBegin() + + def readMapEnd(self): + return self._protocol.readMapEnd() + + def readListBegin(self): + return self._protocol.readListBegin() + + def readListEnd(self): + return self._protocol.readListEnd() + + def readSetBegin(self): + return self._protocol.readSetBegin() + + def readSetEnd(self): + return self._protocol.readSetEnd() + + def readBool(self): + return self._protocol.readBool() + + def readByte(self): + return self._protocol.readByte() + + def readI16(self): + return self._protocol.readI16() + + def readI32(self): + return self._protocol.readI32() + + def readI64(self): + return self._protocol.readI64() + + def readDouble(self): + return self._protocol.readDouble() + + def readBinary(self): + return self._protocol.readBinary() + + +class THeaderProtocolFactory(object): + def __init__(self, allowed_client_types=(THeaderClientType.HEADERS,)): + self.allowed_client_types = allowed_client_types + + def getProtocol(self, trans): + return THeaderProtocol(trans, self.allowed_client_types) diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/protocol/TMultiplexedProtocol.py b/vendor/git.apache.org/thrift.git/lib/py/src/protocol/TMultiplexedProtocol.py index 309f896..0f8390f 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/protocol/TMultiplexedProtocol.py +++ b/vendor/git.apache.org/thrift.git/lib/py/src/protocol/TMultiplexedProtocol.py @@ -25,16 +25,15 @@ SEPARATOR = ":" class TMultiplexedProtocol(TProtocolDecorator.TProtocolDecorator): def __init__(self, protocol, serviceName): - TProtocolDecorator.TProtocolDecorator.__init__(self, protocol) self.serviceName = serviceName def writeMessageBegin(self, name, type, seqid): if (type == TMessageType.CALL or type == TMessageType.ONEWAY): - self.protocol.writeMessageBegin( + super(TMultiplexedProtocol, self).writeMessageBegin( self.serviceName + SEPARATOR + name, type, seqid ) else: - self.protocol.writeMessageBegin(name, type, seqid) + super(TMultiplexedProtocol, self).writeMessageBegin(name, type, seqid) diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/protocol/TProtocol.py b/vendor/git.apache.org/thrift.git/lib/py/src/protocol/TProtocol.py index f29c58d..8314cf6 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/protocol/TProtocol.py +++ b/vendor/git.apache.org/thrift.git/lib/py/src/protocol/TProtocol.py @@ -37,6 +37,7 @@ class TProtocolException(TException): BAD_VERSION = 4 NOT_IMPLEMENTED = 5 DEPTH_LIMIT = 6 + INVALID_PROTOCOL = 7 def __init__(self, type=UNKNOWN, message=None): TException.__init__(self, message) @@ -268,7 +269,7 @@ class TProtocolBase(object): return self._TTYPE_HANDLERS[ttype] if ttype < len(self._TTYPE_HANDLERS) else (None, None, False) def _read_by_ttype(self, ttype, spec, espec): - reader_name, _, is_container = self._ttype_handlers(ttype, spec) + reader_name, _, is_container = self._ttype_handlers(ttype, espec) if reader_name is None: raise TProtocolException(type=TProtocolException.INVALID_DATA, message='Invalid type %d' % (ttype)) @@ -389,7 +390,7 @@ class TProtocolBase(object): self.writeStructEnd() def _write_by_ttype(self, ttype, vals, spec, espec): - _, writer_name, is_container = self._ttype_handlers(ttype, spec) + _, writer_name, is_container = self._ttype_handlers(ttype, espec) writer_func = getattr(self, writer_name) write = (lambda v: writer_func(v, espec)) if is_container else writer_func for v in vals: diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/protocol/TProtocolDecorator.py b/vendor/git.apache.org/thrift.git/lib/py/src/protocol/TProtocolDecorator.py index 8b270a4..f5546c7 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/protocol/TProtocolDecorator.py +++ b/vendor/git.apache.org/thrift.git/lib/py/src/protocol/TProtocolDecorator.py @@ -17,34 +17,10 @@ # under the License. # -import types -from thrift.protocol.TProtocol import TProtocolBase - - -class TProtocolDecorator(): - def __init__(self, protocol): - TProtocolBase(protocol) - self.protocol = protocol - - def __getattr__(self, name): - if hasattr(self.protocol, name): - member = getattr(self.protocol, name) - if type(member) in [ - types.MethodType, - types.FunctionType, - types.LambdaType, - types.BuiltinFunctionType, - types.BuiltinMethodType, - ]: - return lambda *args, **kwargs: self._wrap(member, args, kwargs) - else: - return member - raise AttributeError(name) - - def _wrap(self, func, args, kwargs): - if isinstance(func, types.MethodType): - result = func(*args, **kwargs) - else: - result = func(self.protocol, *args, **kwargs) - return result +class TProtocolDecorator(object): + def __new__(cls, protocol, *args, **kwargs): + decorated_cls = type(''.join(['Decorated', protocol.__class__.__name__]), + (cls, protocol.__class__), + protocol.__dict__) + return object.__new__(decorated_cls) diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/server/THttpServer.py b/vendor/git.apache.org/thrift.git/lib/py/src/server/THttpServer.py index 1b501a7..85cf400 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/server/THttpServer.py +++ b/vendor/git.apache.org/thrift.git/lib/py/src/server/THttpServer.py @@ -17,6 +17,8 @@ # under the License. # +import ssl + from six.moves import BaseHTTPServer from thrift.server import TServer @@ -47,11 +49,17 @@ class THttpServer(TServer.TServer): server_address, inputProtocolFactory, outputProtocolFactory=None, - server_class=BaseHTTPServer.HTTPServer): - """Set up protocol factories and HTTP server. + server_class=BaseHTTPServer.HTTPServer, + **kwargs): + """Set up protocol factories and HTTP (or HTTPS) server. See BaseHTTPServer for server_address. See TServer for protocol factories. + + To make a secure server, provide the named arguments: + * cafile - to validate clients [optional] + * cert_file - the server cert + * key_file - the server's key """ if outputProtocolFactory is None: outputProtocolFactory = inputProtocolFactory @@ -83,5 +91,16 @@ class THttpServer(TServer.TServer): self.httpd = server_class(server_address, RequestHander) + if (kwargs.get('cafile') or kwargs.get('cert_file') or kwargs.get('key_file')): + context = ssl.create_default_context(cafile=kwargs.get('cafile')) + context.check_hostname = False + context.load_cert_chain(kwargs.get('cert_file'), kwargs.get('key_file')) + context.verify_mode = ssl.CERT_REQUIRED if kwargs.get('cafile') else ssl.CERT_NONE + self.httpd.socket = context.wrap_socket(self.httpd.socket, server_side=True) + def serve(self): self.httpd.serve_forever() + + def shutdown(self): + self.httpd.socket.close() + # self.httpd.shutdown() # hangs forever, python doesn't handle POLLNVAL properly! diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/server/TNonblockingServer.py b/vendor/git.apache.org/thrift.git/lib/py/src/server/TNonblockingServer.py index 87031c1..f62d486 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/server/TNonblockingServer.py +++ b/vendor/git.apache.org/thrift.git/lib/py/src/server/TNonblockingServer.py @@ -31,6 +31,7 @@ import socket import struct import threading +from collections import deque from six.moves import queue from thrift.transport import TTransport @@ -58,9 +59,10 @@ class Worker(threading.Thread): processor.process(iprot, oprot) callback(True, otrans.getvalue()) except Exception: - logger.exception("Exception while processing request") + logger.exception("Exception while processing request", exc_info=True) callback(False, b'') + WAIT_LEN = 0 WAIT_MESSAGE = 1 WAIT_PROCESS = 2 @@ -85,10 +87,23 @@ def socket_exception(func): try: return func(self, *args, **kwargs) except socket.error: + logger.debug('ignoring socket exception', exc_info=True) self.close() return read +class Message(object): + def __init__(self, offset, len_, header): + self.offset = offset + self.len = len_ + self.buffer = None + self.is_header = header + + @property + def end(self): + return self.offset + self.len + + class Connection(object): """Basic class is represented connection. @@ -106,68 +121,60 @@ class Connection(object): self.socket.setblocking(False) self.status = WAIT_LEN self.len = 0 - self.message = b'' + self.received = deque() + self._reading = Message(0, 4, True) + self._rbuf = b'' + self._wbuf = b'' self.lock = threading.Lock() self.wake_up = wake_up - - def _read_len(self): - """Reads length of request. - - It's a safer alternative to self.socket.recv(4) - """ - read = self.socket.recv(4 - len(self.message)) - if len(read) == 0: - # if we read 0 bytes and self.message is empty, then - # the client closed the connection - if len(self.message) != 0: - logger.error("can't read frame size from socket") - self.close() - return - self.message += read - if len(self.message) == 4: - self.len, = struct.unpack('!i', self.message) - if self.len < 0: - logger.error("negative frame size, it seems client " - "doesn't use FramedTransport") - self.close() - elif self.len == 0: - logger.error("empty frame, it's really strange") - self.close() - else: - self.message = b'' - self.status = WAIT_MESSAGE + self.remaining = False @socket_exception def read(self): """Reads data from stream and switch state.""" assert self.status in (WAIT_LEN, WAIT_MESSAGE) - if self.status == WAIT_LEN: - self._read_len() - # go back to the main loop here for simplicity instead of - # falling through, even though there is a good chance that - # the message is already available - elif self.status == WAIT_MESSAGE: - read = self.socket.recv(self.len - len(self.message)) - if len(read) == 0: - logger.error("can't read frame from socket (get %d of " - "%d bytes)" % (len(self.message), self.len)) + assert not self.received + buf_size = 8192 + first = True + done = False + while not done: + read = self.socket.recv(buf_size) + rlen = len(read) + done = rlen < buf_size + self._rbuf += read + if first and rlen == 0: + if self.status != WAIT_LEN or self._rbuf: + logger.error('could not read frame from socket') + else: + logger.debug('read zero length. client might have disconnected') self.close() - return - self.message += read - if len(self.message) == self.len: + while len(self._rbuf) >= self._reading.end: + if self._reading.is_header: + mlen, = struct.unpack('!i', self._rbuf[:4]) + self._reading = Message(self._reading.end, mlen, False) + self.status = WAIT_MESSAGE + else: + self._reading.buffer = self._rbuf + self.received.append(self._reading) + self._rbuf = self._rbuf[self._reading.end:] + self._reading = Message(0, 4, True) + first = False + if self.received: self.status = WAIT_PROCESS + break + self.remaining = not done @socket_exception def write(self): """Writes data from socket and switch state.""" assert self.status == SEND_ANSWER - sent = self.socket.send(self.message) - if sent == len(self.message): + sent = self.socket.send(self._wbuf) + if sent == len(self._wbuf): self.status = WAIT_LEN - self.message = b'' + self._wbuf = b'' self.len = 0 else: - self.message = self.message[sent:] + self._wbuf = self._wbuf[sent:] @locked def ready(self, all_ok, message): @@ -190,10 +197,10 @@ class Connection(object): self.len = 0 if len(message) == 0: # it was a oneway request, do not write answer - self.message = b'' + self._wbuf = b'' self.status = WAIT_LEN else: - self.message = struct.pack('!i', len(message)) + message + self._wbuf = struct.pack('!i', len(message)) + message self.status = SEND_ANSWER self.wake_up() @@ -292,14 +299,20 @@ class TNonblockingServer(object): """Does select on open connections.""" readable = [self.socket.handle.fileno(), self._read.fileno()] writable = [] + remaining = [] for i, connection in list(self.clients.items()): if connection.is_readable(): readable.append(connection.fileno()) + if connection.remaining or connection.received: + remaining.append(connection.fileno()) if connection.is_writeable(): writable.append(connection.fileno()) if connection.is_closed(): del self.clients[i] - return select.select(readable, writable, readable) + if remaining: + return remaining, [], [], False + else: + return select.select(readable, writable, readable) + (True,) def handle(self): """Handle requests. @@ -307,20 +320,27 @@ class TNonblockingServer(object): WARNING! You must call prepare() BEFORE calling handle() """ assert self.prepared, "You have to call prepare before handle" - rset, wset, xset = self._select() + rset, wset, xset, selected = self._select() for readable in rset: if readable == self._read.fileno(): # don't care i just need to clean readable flag self._read.recv(1024) elif readable == self.socket.handle.fileno(): - client = self.socket.accept().handle - self.clients[client.fileno()] = Connection(client, - self.wake_up) + try: + client = self.socket.accept() + if client: + self.clients[client.handle.fileno()] = Connection(client.handle, + self.wake_up) + except socket.error: + logger.debug('error while accepting', exc_info=True) else: connection = self.clients[readable] - connection.read() - if connection.status == WAIT_PROCESS: - itransport = TTransport.TMemoryBuffer(connection.message) + if selected: + connection.read() + if connection.received: + connection.status = WAIT_PROCESS + msg = connection.received.popleft() + itransport = TTransport.TMemoryBuffer(msg.buffer, msg.offset) otransport = TTransport.TMemoryBuffer() iprot = self.in_protocol.getProtocol(itransport) oprot = self.out_protocol.getProtocol(otransport) diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/server/TServer.py b/vendor/git.apache.org/thrift.git/lib/py/src/server/TServer.py index d5d9c98..df2a7bb 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/server/TServer.py +++ b/vendor/git.apache.org/thrift.git/lib/py/src/server/TServer.py @@ -23,6 +23,7 @@ import os import threading from thrift.protocol import TBinaryProtocol +from thrift.protocol.THeaderProtocol import THeaderProtocolFactory from thrift.transport import TTransport logger = logging.getLogger(__name__) @@ -60,6 +61,12 @@ class TServer(object): self.inputProtocolFactory = inputProtocolFactory self.outputProtocolFactory = outputProtocolFactory + input_is_header = isinstance(self.inputProtocolFactory, THeaderProtocolFactory) + output_is_header = isinstance(self.outputProtocolFactory, THeaderProtocolFactory) + if any((input_is_header, output_is_header)) and input_is_header != output_is_header: + raise ValueError("THeaderProtocol servers require that both the input and " + "output protocols are THeaderProtocol.") + def serve(self): pass @@ -76,10 +83,20 @@ class TSimpleServer(TServer): client = self.serverTransport.accept() if not client: continue + itrans = self.inputTransportFactory.getTransport(client) - otrans = self.outputTransportFactory.getTransport(client) iprot = self.inputProtocolFactory.getProtocol(itrans) - oprot = self.outputProtocolFactory.getProtocol(otrans) + + # for THeaderProtocol, we must use the same protocol instance for + # input and output so that the response is in the same dialect that + # the server detected the request was in. + if isinstance(self.inputProtocolFactory, THeaderProtocolFactory): + otrans = None + oprot = iprot + else: + otrans = self.outputTransportFactory.getTransport(client) + oprot = self.outputProtocolFactory.getProtocol(otrans) + try: while True: self.processor.process(iprot, oprot) @@ -89,7 +106,8 @@ class TSimpleServer(TServer): logger.exception(x) itrans.close() - otrans.close() + if otrans: + otrans.close() class TThreadedServer(TServer): @@ -116,9 +134,18 @@ class TThreadedServer(TServer): def handle(self, client): itrans = self.inputTransportFactory.getTransport(client) - otrans = self.outputTransportFactory.getTransport(client) iprot = self.inputProtocolFactory.getProtocol(itrans) - oprot = self.outputProtocolFactory.getProtocol(otrans) + + # for THeaderProtocol, we must use the same protocol instance for input + # and output so that the response is in the same dialect that the + # server detected the request was in. + if isinstance(self.inputProtocolFactory, THeaderProtocolFactory): + otrans = None + oprot = iprot + else: + otrans = self.outputTransportFactory.getTransport(client) + oprot = self.outputProtocolFactory.getProtocol(otrans) + try: while True: self.processor.process(iprot, oprot) @@ -128,7 +155,8 @@ class TThreadedServer(TServer): logger.exception(x) itrans.close() - otrans.close() + if otrans: + otrans.close() class TThreadPoolServer(TServer): @@ -156,9 +184,18 @@ class TThreadPoolServer(TServer): def serveClient(self, client): """Process input/output from a client for as long as possible""" itrans = self.inputTransportFactory.getTransport(client) - otrans = self.outputTransportFactory.getTransport(client) iprot = self.inputProtocolFactory.getProtocol(itrans) - oprot = self.outputProtocolFactory.getProtocol(otrans) + + # for THeaderProtocol, we must use the same protocol instance for input + # and output so that the response is in the same dialect that the + # server detected the request was in. + if isinstance(self.inputProtocolFactory, THeaderProtocolFactory): + otrans = None + oprot = iprot + else: + otrans = self.outputTransportFactory.getTransport(client) + oprot = self.outputProtocolFactory.getProtocol(otrans) + try: while True: self.processor.process(iprot, oprot) @@ -168,7 +205,8 @@ class TThreadPoolServer(TServer): logger.exception(x) itrans.close() - otrans.close() + if otrans: + otrans.close() def serve(self): """Start a fixed number of worker threads and put client into a queue""" @@ -237,10 +275,18 @@ class TForkingServer(TServer): try_close(otrans) else: itrans = self.inputTransportFactory.getTransport(client) - otrans = self.outputTransportFactory.getTransport(client) - iprot = self.inputProtocolFactory.getProtocol(itrans) - oprot = self.outputProtocolFactory.getProtocol(otrans) + + # for THeaderProtocol, we must use the same protocol + # instance for input and output so that the response is in + # the same dialect that the server detected the request was + # in. + if isinstance(self.inputProtocolFactory, THeaderProtocolFactory): + otrans = None + oprot = iprot + else: + otrans = self.outputTransportFactory.getTransport(client) + oprot = self.outputProtocolFactory.getProtocol(otrans) ecode = 0 try: @@ -254,7 +300,8 @@ class TForkingServer(TServer): ecode = 1 finally: try_close(itrans) - try_close(otrans) + if otrans: + try_close(otrans) os._exit(ecode) diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/transport/THeaderTransport.py b/vendor/git.apache.org/thrift.git/lib/py/src/transport/THeaderTransport.py new file mode 100644 index 0000000..c0d5640 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/py/src/transport/THeaderTransport.py @@ -0,0 +1,352 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +import struct +import zlib + +from thrift.compat import BufferIO, byte_index +from thrift.protocol.TBinaryProtocol import TBinaryProtocol +from thrift.protocol.TCompactProtocol import TCompactProtocol, readVarint, writeVarint +from thrift.Thrift import TApplicationException +from thrift.transport.TTransport import ( + CReadableTransport, + TMemoryBuffer, + TTransportBase, + TTransportException, +) + + +U16 = struct.Struct("!H") +I32 = struct.Struct("!i") +HEADER_MAGIC = 0x0FFF +HARD_MAX_FRAME_SIZE = 0x3FFFFFFF + + +class THeaderClientType(object): + HEADERS = 0x00 + + FRAMED_BINARY = 0x01 + UNFRAMED_BINARY = 0x02 + + FRAMED_COMPACT = 0x03 + UNFRAMED_COMPACT = 0x04 + + +class THeaderSubprotocolID(object): + BINARY = 0x00 + COMPACT = 0x02 + + +class TInfoHeaderType(object): + KEY_VALUE = 0x01 + + +class THeaderTransformID(object): + ZLIB = 0x01 + + +READ_TRANSFORMS_BY_ID = { + THeaderTransformID.ZLIB: zlib.decompress, +} + + +WRITE_TRANSFORMS_BY_ID = { + THeaderTransformID.ZLIB: zlib.compress, +} + + +def _readString(trans): + size = readVarint(trans) + if size < 0: + raise TTransportException( + TTransportException.NEGATIVE_SIZE, + "Negative length" + ) + return trans.read(size) + + +def _writeString(trans, value): + writeVarint(trans, len(value)) + trans.write(value) + + +class THeaderTransport(TTransportBase, CReadableTransport): + def __init__(self, transport, allowed_client_types): + self._transport = transport + self._client_type = THeaderClientType.HEADERS + self._allowed_client_types = allowed_client_types + + self._read_buffer = BufferIO(b"") + self._read_headers = {} + + self._write_buffer = BufferIO() + self._write_headers = {} + self._write_transforms = [] + + self.flags = 0 + self.sequence_id = 0 + self._protocol_id = THeaderSubprotocolID.BINARY + self._max_frame_size = HARD_MAX_FRAME_SIZE + + def isOpen(self): + return self._transport.isOpen() + + def open(self): + return self._transport.open() + + def close(self): + return self._transport.close() + + def get_headers(self): + return self._read_headers + + def set_header(self, key, value): + if not isinstance(key, bytes): + raise ValueError("header names must be bytes") + if not isinstance(value, bytes): + raise ValueError("header values must be bytes") + self._write_headers[key] = value + + def clear_headers(self): + self._write_headers.clear() + + def add_transform(self, transform_id): + if transform_id not in WRITE_TRANSFORMS_BY_ID: + raise ValueError("unknown transform") + self._write_transforms.append(transform_id) + + def set_max_frame_size(self, size): + if not 0 < size < HARD_MAX_FRAME_SIZE: + raise ValueError("maximum frame size should be < %d and > 0" % HARD_MAX_FRAME_SIZE) + self._max_frame_size = size + + @property + def protocol_id(self): + if self._client_type == THeaderClientType.HEADERS: + return self._protocol_id + elif self._client_type in (THeaderClientType.FRAMED_BINARY, THeaderClientType.UNFRAMED_BINARY): + return THeaderSubprotocolID.BINARY + elif self._client_type in (THeaderClientType.FRAMED_COMPACT, THeaderClientType.UNFRAMED_COMPACT): + return THeaderSubprotocolID.COMPACT + else: + raise TTransportException( + TTransportException.INVALID_CLIENT_TYPE, + "Protocol ID not know for client type %d" % self._client_type, + ) + + def read(self, sz): + # if there are bytes left in the buffer, produce those first. + bytes_read = self._read_buffer.read(sz) + bytes_left_to_read = sz - len(bytes_read) + if bytes_left_to_read == 0: + return bytes_read + + # if we've determined this is an unframed client, just pass the read + # through to the underlying transport until we're reset again at the + # beginning of the next message. + if self._client_type in (THeaderClientType.UNFRAMED_BINARY, THeaderClientType.UNFRAMED_COMPACT): + return bytes_read + self._transport.read(bytes_left_to_read) + + # we're empty and (maybe) framed. fill the buffers with the next frame. + self.readFrame(bytes_left_to_read) + return bytes_read + self._read_buffer.read(bytes_left_to_read) + + def _set_client_type(self, client_type): + if client_type not in self._allowed_client_types: + raise TTransportException( + TTransportException.INVALID_CLIENT_TYPE, + "Client type %d not allowed by server." % client_type, + ) + self._client_type = client_type + + def readFrame(self, req_sz): + # the first word could either be the length field of a framed message + # or the first bytes of an unframed message. + first_word = self._transport.readAll(I32.size) + frame_size, = I32.unpack(first_word) + is_unframed = False + if frame_size & TBinaryProtocol.VERSION_MASK == TBinaryProtocol.VERSION_1: + self._set_client_type(THeaderClientType.UNFRAMED_BINARY) + is_unframed = True + elif (byte_index(first_word, 0) == TCompactProtocol.PROTOCOL_ID and + byte_index(first_word, 1) & TCompactProtocol.VERSION_MASK == TCompactProtocol.VERSION): + self._set_client_type(THeaderClientType.UNFRAMED_COMPACT) + is_unframed = True + + if is_unframed: + bytes_left_to_read = req_sz - I32.size + if bytes_left_to_read > 0: + rest = self._transport.read(bytes_left_to_read) + else: + rest = b"" + self._read_buffer = BufferIO(first_word + rest) + return + + # ok, we're still here so we're framed. + if frame_size > self._max_frame_size: + raise TTransportException( + TTransportException.SIZE_LIMIT, + "Frame was too large.", + ) + read_buffer = BufferIO(self._transport.readAll(frame_size)) + + # the next word is either going to be the version field of a + # binary/compact protocol message or the magic value + flags of a + # header protocol message. + second_word = read_buffer.read(I32.size) + version, = I32.unpack(second_word) + read_buffer.seek(0) + if version >> 16 == HEADER_MAGIC: + self._set_client_type(THeaderClientType.HEADERS) + self._read_buffer = self._parse_header_format(read_buffer) + elif version & TBinaryProtocol.VERSION_MASK == TBinaryProtocol.VERSION_1: + self._set_client_type(THeaderClientType.FRAMED_BINARY) + self._read_buffer = read_buffer + elif (byte_index(second_word, 0) == TCompactProtocol.PROTOCOL_ID and + byte_index(second_word, 1) & TCompactProtocol.VERSION_MASK == TCompactProtocol.VERSION): + self._set_client_type(THeaderClientType.FRAMED_COMPACT) + self._read_buffer = read_buffer + else: + raise TTransportException( + TTransportException.INVALID_CLIENT_TYPE, + "Could not detect client transport type.", + ) + + def _parse_header_format(self, buffer): + # make BufferIO look like TTransport for varint helpers + buffer_transport = TMemoryBuffer() + buffer_transport._buffer = buffer + + buffer.read(2) # discard the magic bytes + self.flags, = U16.unpack(buffer.read(U16.size)) + self.sequence_id, = I32.unpack(buffer.read(I32.size)) + + header_length = U16.unpack(buffer.read(U16.size))[0] * 4 + end_of_headers = buffer.tell() + header_length + if end_of_headers > len(buffer.getvalue()): + raise TTransportException( + TTransportException.SIZE_LIMIT, + "Header size is larger than whole frame.", + ) + + self._protocol_id = readVarint(buffer_transport) + + transforms = [] + transform_count = readVarint(buffer_transport) + for _ in range(transform_count): + transform_id = readVarint(buffer_transport) + if transform_id not in READ_TRANSFORMS_BY_ID: + raise TApplicationException( + TApplicationException.INVALID_TRANSFORM, + "Unknown transform: %d" % transform_id, + ) + transforms.append(transform_id) + transforms.reverse() + + headers = {} + while buffer.tell() < end_of_headers: + header_type = readVarint(buffer_transport) + if header_type == TInfoHeaderType.KEY_VALUE: + count = readVarint(buffer_transport) + for _ in range(count): + key = _readString(buffer_transport) + value = _readString(buffer_transport) + headers[key] = value + else: + break # ignore unknown headers + self._read_headers = headers + + # skip padding / anything we didn't understand + buffer.seek(end_of_headers) + + payload = buffer.read() + for transform_id in transforms: + transform_fn = READ_TRANSFORMS_BY_ID[transform_id] + payload = transform_fn(payload) + return BufferIO(payload) + + def write(self, buf): + self._write_buffer.write(buf) + + def flush(self): + payload = self._write_buffer.getvalue() + self._write_buffer = BufferIO() + + buffer = BufferIO() + if self._client_type == THeaderClientType.HEADERS: + for transform_id in self._write_transforms: + transform_fn = WRITE_TRANSFORMS_BY_ID[transform_id] + payload = transform_fn(payload) + + headers = BufferIO() + writeVarint(headers, self._protocol_id) + writeVarint(headers, len(self._write_transforms)) + for transform_id in self._write_transforms: + writeVarint(headers, transform_id) + if self._write_headers: + writeVarint(headers, TInfoHeaderType.KEY_VALUE) + writeVarint(headers, len(self._write_headers)) + for key, value in self._write_headers.items(): + _writeString(headers, key) + _writeString(headers, value) + self._write_headers = {} + padding_needed = (4 - (len(headers.getvalue()) % 4)) % 4 + headers.write(b"\x00" * padding_needed) + header_bytes = headers.getvalue() + + buffer.write(I32.pack(10 + len(header_bytes) + len(payload))) + buffer.write(U16.pack(HEADER_MAGIC)) + buffer.write(U16.pack(self.flags)) + buffer.write(I32.pack(self.sequence_id)) + buffer.write(U16.pack(len(header_bytes) // 4)) + buffer.write(header_bytes) + buffer.write(payload) + elif self._client_type in (THeaderClientType.FRAMED_BINARY, THeaderClientType.FRAMED_COMPACT): + buffer.write(I32.pack(len(payload))) + buffer.write(payload) + elif self._client_type in (THeaderClientType.UNFRAMED_BINARY, THeaderClientType.UNFRAMED_COMPACT): + buffer.write(payload) + else: + raise TTransportException( + TTransportException.INVALID_CLIENT_TYPE, + "Unknown client type.", + ) + + # the frame length field doesn't count towards the frame payload size + frame_bytes = buffer.getvalue() + frame_payload_size = len(frame_bytes) - 4 + if frame_payload_size > self._max_frame_size: + raise TTransportException( + TTransportException.SIZE_LIMIT, + "Attempting to send frame that is too large.", + ) + + self._transport.write(frame_bytes) + self._transport.flush() + + @property + def cstringio_buf(self): + return self._read_buffer + + def cstringio_refill(self, partialread, reqlen): + result = bytearray(partialread) + while len(result) < reqlen: + result += self.read(reqlen - len(result)) + self._read_buffer = BufferIO(result) + return self._read_buffer diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/transport/THttpClient.py b/vendor/git.apache.org/thrift.git/lib/py/src/transport/THttpClient.py index fb33421..37b0a4d 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/transport/THttpClient.py +++ b/vendor/git.apache.org/thrift.git/lib/py/src/transport/THttpClient.py @@ -19,7 +19,7 @@ from io import BytesIO import os -import socket +import ssl import sys import warnings import base64 @@ -34,17 +34,20 @@ import six class THttpClient(TTransportBase): """Http implementation of TTransport base.""" - def __init__(self, uri_or_host, port=None, path=None): - """THttpClient supports two different types constructor parameters. + def __init__(self, uri_or_host, port=None, path=None, cafile=None, cert_file=None, key_file=None, ssl_context=None): + """THttpClient supports two different types of construction: THttpClient(host, port, path) - deprecated - THttpClient(uri) + THttpClient(uri, [port=, path=, cafile=, cert_file=, key_file=, ssl_context=]) - Only the second supports https. + Only the second supports https. To properly authenticate against the server, + provide the client's identity by specifying cert_file and key_file. To properly + authenticate the server, specify either cafile or ssl_context with a CA defined. + NOTE: if both cafile and ssl_context are defined, ssl_context will override cafile. """ if port is not None: warnings.warn( - "Please use the THttpClient('http://host:port/path') syntax", + "Please use the THttpClient('http{s}://host:port/path') constructor", DeprecationWarning, stacklevel=2) self.host = uri_or_host @@ -60,6 +63,9 @@ class THttpClient(TTransportBase): self.port = parsed.port or http_client.HTTP_PORT elif self.scheme == 'https': self.port = parsed.port or http_client.HTTPS_PORT + self.certfile = cert_file + self.keyfile = key_file + self.context = ssl.create_default_context(cafile=cafile) if (cafile and not ssl_context) else ssl_context self.host = parsed.hostname self.path = parsed.path if parsed.query: @@ -100,12 +106,17 @@ class THttpClient(TTransportBase): def open(self): if self.scheme == 'http': - self.__http = http_client.HTTPConnection(self.host, self.port) + self.__http = http_client.HTTPConnection(self.host, self.port, + timeout=self.__timeout) elif self.scheme == 'https': - self.__http = http_client.HTTPSConnection(self.host, self.port) - if self.using_proxy(): - self.__http.set_tunnel(self.realhost, self.realport, - {"Proxy-Authorization": self.proxy_auth}) + self.__http = http_client.HTTPSConnection(self.host, self.port, + key_file=self.keyfile, + cert_file=self.certfile, + timeout=self.__timeout, + context=self.context) + if self.using_proxy(): + self.__http.set_tunnel(self.realhost, self.realport, + {"Proxy-Authorization": self.proxy_auth}) def close(self): self.__http.close() @@ -116,9 +127,6 @@ class THttpClient(TTransportBase): return self.__http is not None def setTimeout(self, ms): - if not hasattr(socket, 'getdefaulttimeout'): - raise NotImplementedError - if ms is None: self.__timeout = None else: @@ -133,17 +141,6 @@ class THttpClient(TTransportBase): def write(self, buf): self.__wbuf.write(buf) - def __withTimeout(f): - def _f(*args, **kwargs): - orig_timeout = socket.getdefaulttimeout() - socket.setdefaulttimeout(args[0].__timeout) - try: - result = f(*args, **kwargs) - finally: - socket.setdefaulttimeout(orig_timeout) - return result - return _f - def flush(self): if self.isOpen(): self.close() @@ -188,7 +185,3 @@ class THttpClient(TTransportBase): self.code = self.__http_response.status self.message = self.__http_response.reason self.headers = self.__http_response.msg - - # Decorate if we know how to timeout - if hasattr(socket, 'getdefaulttimeout'): - flush = __withTimeout(flush) diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/transport/TSSLSocket.py b/vendor/git.apache.org/thrift.git/lib/py/src/transport/TSSLSocket.py index 0f7d45e..b54ca5d 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/transport/TSSLSocket.py +++ b/vendor/git.apache.org/thrift.git/lib/py/src/transport/TSSLSocket.py @@ -40,10 +40,10 @@ class TSSLBase(object): # ciphers argument is not available for Python < 2.7.0 _has_ciphers = sys.hexversion >= 0x020700F0 - # For pythoon >= 2.7.9, use latest TLS that both client and server + # For python >= 2.7.9, use latest TLS that both client and server # supports. # SSL 2.0 and 3.0 are disabled via ssl.OP_NO_SSLv2 and ssl.OP_NO_SSLv3. - # For pythoon < 2.7.9, use TLS 1.0 since TLSv1_X nor OP_NO_SSLvX is + # For python < 2.7.9, use TLS 1.0 since TLSv1_X nor OP_NO_SSLvX is # unavailable. _default_protocol = ssl.PROTOCOL_SSLv23 if _has_ssl_context else \ ssl.PROTOCOL_TLSv1 @@ -368,7 +368,7 @@ class TSSLServerSocket(TSocket.TServerSocket, TSSLBase): plain_client, addr = self.handle.accept() try: client = self._wrap_socket(plain_client) - except ssl.SSLError: + except (ssl.SSLError, socket.error, OSError): logger.exception('Error while accepting from %s', addr) # failed handshake/ssl wrap, close socket to client plain_client.close() diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/transport/TSocket.py b/vendor/git.apache.org/thrift.git/lib/py/src/transport/TSocket.py index c91de9d..a7d6617 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/transport/TSocket.py +++ b/vendor/git.apache.org/thrift.git/lib/py/src/transport/TSocket.py @@ -159,6 +159,15 @@ class TServerSocket(TSocketBase, TServerTransportBase): self._unix_socket = unix_socket self._socket_family = socket_family self.handle = None + self._backlog = 128 + + def setBacklog(self, backlog=None): + if not self.handle: + self._backlog = backlog + else: + # We cann't update backlog when it is already listening, since the + # handle has been created. + logger.warn('You have to set backlog before listen.') def listen(self): res0 = self._resolveAddr() @@ -183,7 +192,7 @@ class TServerSocket(TSocketBase, TServerTransportBase): if hasattr(self.handle, 'settimeout'): self.handle.settimeout(None) self.handle.bind(res[4]) - self.handle.listen(128) + self.handle.listen(self._backlog) def accept(self): client, addr = self.handle.accept() diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/transport/TTransport.py b/vendor/git.apache.org/thrift.git/lib/py/src/transport/TTransport.py index 5283fce..d13060f 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/transport/TTransport.py +++ b/vendor/git.apache.org/thrift.git/lib/py/src/transport/TTransport.py @@ -32,6 +32,7 @@ class TTransportException(TException): END_OF_FILE = 4 NEGATIVE_SIZE = 5 SIZE_LIMIT = 6 + INVALID_CLIENT_TYPE = 7 def __init__(self, type=UNKNOWN, message=None): TException.__init__(self, message) @@ -58,10 +59,11 @@ class TTransportBase(object): have = 0 while (have < sz): chunk = self.read(sz - have) - have += len(chunk) + chunkLen = len(chunk) + have += chunkLen buff += chunk - if len(chunk) == 0: + if chunkLen == 0: raise EOFError() return buff @@ -168,7 +170,6 @@ class TBufferedTransport(TTransportBase, CReadableTransport): # on exception reset wbuf so it doesn't contain a partial function call self.__wbuf = BufferIO() raise e - self.__wbuf.getvalue() def flush(self): out = self.__wbuf.getvalue() @@ -205,7 +206,7 @@ class TMemoryBuffer(TTransportBase, CReadableTransport): TODO(dreiss): Make this work like the C++ version. """ - def __init__(self, value=None): + def __init__(self, value=None, offset=0): """value -- a value to read from for stringio If value is set, this will be a transport for reading, @@ -214,6 +215,8 @@ class TMemoryBuffer(TTransportBase, CReadableTransport): self._buffer = BufferIO(value) else: self._buffer = BufferIO() + if offset: + self._buffer.seek(offset) def isOpen(self): return not self._buffer.closed diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/transport/TTwisted.py b/vendor/git.apache.org/thrift.git/lib/py/src/transport/TTwisted.py index 5710b57..a27f0ad 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/transport/TTwisted.py +++ b/vendor/git.apache.org/thrift.git/lib/py/src/transport/TTwisted.py @@ -20,7 +20,7 @@ from io import BytesIO import struct -from zope.interface import implements, Interface, Attribute +from zope.interface import implementer, Interface, Attribute from twisted.internet.protocol import ServerFactory, ClientFactory, \ connectionDone from twisted.internet import defer @@ -257,10 +257,9 @@ class IThriftClientFactory(Interface): oprot_factory = Attribute("Output protocol factory") +@implementer(IThriftServerFactory) class ThriftServerFactory(ServerFactory): - implements(IThriftServerFactory) - protocol = ThriftServerProtocol def __init__(self, processor, iprot_factory, oprot_factory=None): @@ -272,10 +271,9 @@ class ThriftServerFactory(ServerFactory): self.oprot_factory = oprot_factory +@implementer(IThriftClientFactory) class ThriftClientFactory(ClientFactory): - implements(IThriftClientFactory) - protocol = ThriftClientProtocol def __init__(self, client_class, iprot_factory, oprot_factory=None): diff --git a/vendor/git.apache.org/thrift.git/lib/py/src/transport/sslcompat.py b/vendor/git.apache.org/thrift.git/lib/py/src/transport/sslcompat.py index 7bf5e06..ab00cb2 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/src/transport/sslcompat.py +++ b/vendor/git.apache.org/thrift.git/lib/py/src/transport/sslcompat.py @@ -25,7 +25,7 @@ from thrift.transport.TTransport import TTransportException logger = logging.getLogger(__name__) -def legacy_validate_callback(self, cert, hostname): +def legacy_validate_callback(cert, hostname): """legacy method to validate the peer's SSL certificate, and to check the commonName of the certificate to ensure it matches the hostname we used to make this connection. Does not support subjectAltName records @@ -36,7 +36,7 @@ def legacy_validate_callback(self, cert, hostname): if 'subject' not in cert: raise TTransportException( TTransportException.NOT_OPEN, - 'No SSL certificate found from %s:%s' % (self.host, self.port)) + 'No SSL certificate found from %s' % hostname) fields = cert['subject'] for field in fields: # ensure structure we get back is what we expect @@ -57,7 +57,7 @@ def legacy_validate_callback(self, cert, hostname): raise TTransportException( TTransportException.UNKNOWN, 'Hostname we connected to "%s" doesn\'t match certificate ' - 'provided commonName "%s"' % (self.host, certhost)) + 'provided commonName "%s"' % (hostname, certhost)) raise TTransportException( TTransportException.UNKNOWN, 'Could not validate SSL certificate from host "%s". Cert=%s' @@ -96,4 +96,5 @@ def _optional_dependencies(): match = legacy_validate_callback return ipaddr, match + _match_has_ipaddress, _match_hostname = _optional_dependencies() diff --git a/vendor/git.apache.org/thrift.git/lib/py/test/test_sslsocket.py b/vendor/git.apache.org/thrift.git/lib/py/test/test_sslsocket.py index 3e4b266..f1344e5 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/test/test_sslsocket.py +++ b/vendor/git.apache.org/thrift.git/lib/py/test/test_sslsocket.py @@ -42,7 +42,7 @@ CLIENT_CERT = os.path.join(ROOT_DIR, 'test', 'keys', 'client_v3.crt') CLIENT_KEY = os.path.join(ROOT_DIR, 'test', 'keys', 'client_v3.key') CLIENT_CA = os.path.join(ROOT_DIR, 'test', 'keys', 'CA.pem') -TEST_CIPHERS = 'DES-CBC3-SHA' +TEST_CIPHERS = 'DES-CBC3-SHA:ECDHE-RSA-AES128-GCM-SHA256' class ServerAcceptor(threading.Thread): @@ -95,6 +95,11 @@ class ServerAcceptor(threading.Thread): self._client_accepted.wait() return self._client + def close(self): + if self._client: + self._client.close() + self._server.close() + # Python 2.6 compat class AssertRaises(object): @@ -125,9 +130,7 @@ class TSSLSocketTest(unittest.TestCase): client = TSSLSocket(host, port, unix_socket=path, **client_kwargs) yield acc, client finally: - if acc.client: - acc.client.close() - server.close() + acc.close() def _assert_connection_failure(self, server, path=None, **client_args): logging.disable(logging.CRITICAL) @@ -237,6 +240,9 @@ class TSSLSocketTest(unittest.TestCase): self._assert_connection_success(server, cert_reqs=ssl.CERT_REQUIRED, ca_certs=SERVER_CERT) def test_client_cert(self): + if not _match_has_ipaddress: + print('skipping test_client_cert') + return server = self._server_socket( cert_reqs=ssl.CERT_REQUIRED, keyfile=SERVER_KEY, certfile=SERVER_CERT, ca_certs=CLIENT_CERT) @@ -331,9 +337,10 @@ class TSSLSocketTest(unittest.TestCase): self._assert_connection_success(server, ssl_context=client_context) + if __name__ == '__main__': logging.basicConfig(level=logging.WARN) - from thrift.transport.TSSLSocket import TSSLSocket, TSSLServerSocket + from thrift.transport.TSSLSocket import TSSLSocket, TSSLServerSocket, _match_has_ipaddress from thrift.transport.TTransport import TTransportException unittest.main() diff --git a/vendor/git.apache.org/thrift.git/lib/py/test/thrift_json.py b/vendor/git.apache.org/thrift.git/lib/py/test/thrift_json.py index fc1e79c..40e7a47 100644 --- a/vendor/git.apache.org/thrift.git/lib/py/test/thrift_json.py +++ b/vendor/git.apache.org/thrift.git/lib/py/test/thrift_json.py @@ -46,5 +46,6 @@ class TestJSONString(unittest.TestCase): unicode_text = unicode_text.encode('utf8') self.assertEqual(protocol.readString(), unicode_text) + if __name__ == '__main__': unittest.main() diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/processor.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/processor.rb index fd312ee..ce21e12 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/processor.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/processor.rb @@ -17,10 +17,18 @@ # under the License. # +require 'logger' + module Thrift module Processor - def initialize(handler) + def initialize(handler, logger=nil) @handler = handler + if logger.nil? + @logger = Logger.new(STDERR) + @logger.level = Logger::WARN + else + @logger = logger + end end def process(iprot, oprot) @@ -30,6 +38,7 @@ module Thrift send("process_#{name}", seqid, iprot, oprot) rescue => e x = ApplicationException.new(ApplicationException::INTERNAL_ERROR, 'Internal error') + @logger.debug "Internal error : #{e.message}\n#{e.backtrace.join("\n")}" write_error(x, oprot, name, seqid) end true diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/base_protocol.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/base_protocol.rb index 88f44d4..5c693e9 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/base_protocol.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/base_protocol.rb @@ -369,11 +369,19 @@ module Thrift read_list_end end end + + def to_s + "#{trans.to_s}" + end end class BaseProtocolFactory def get_protocol(trans) raise NotImplementedError end + + def to_s + "base" + end end -end \ No newline at end of file +end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/binary_protocol.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/binary_protocol.rb index e70b1e3..d8279db 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/binary_protocol.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/binary_protocol.rb @@ -226,12 +226,19 @@ module Thrift size = read_i32 trans.read_all(size) end - + + def to_s + "binary(#{super.to_s})" + end end class BinaryProtocolFactory < BaseProtocolFactory def get_protocol(trans) return Thrift::BinaryProtocol.new(trans) end + + def to_s + "binary" + end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/binary_protocol_accelerated.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/binary_protocol_accelerated.rb index 70ea652..09b0264 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/binary_protocol_accelerated.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/binary_protocol_accelerated.rb @@ -35,5 +35,13 @@ module Thrift BinaryProtocol.new(trans) end end + + def to_s + if (defined? BinaryProtocolAccelerated) + "binary-accel" + else + "binary" + end + end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/compact_protocol.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/compact_protocol.rb index 605eea6..1f9bd30 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/compact_protocol.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/compact_protocol.rb @@ -345,6 +345,10 @@ module Thrift size = read_varint32() trans.read_all(size) end + + def to_s + "compact(#{super.to_s})" + end private @@ -431,5 +435,9 @@ module Thrift def get_protocol(trans) CompactProtocol.new(trans) end + + def to_s + "compact" + end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/json_protocol.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/json_protocol.rb index 2b8ac15..91e74e4 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/json_protocol.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/json_protocol.rb @@ -333,7 +333,7 @@ module Thrift # "NaN" or "Infinity" or "-Infinity". def write_json_double(num) @context.write(trans) - # Normalize output of boost::lexical_cast for NaNs and Infinities + # Normalize output of thrift::to_string for NaNs and Infinities special = false; if (num.nan?) special = true; @@ -768,11 +768,19 @@ module Thrift def read_binary read_json_base64 end + + def to_s + "json(#{super.to_s})" + end end class JsonProtocolFactory < BaseProtocolFactory def get_protocol(trans) return Thrift::JsonProtocol.new(trans) end + + def to_s + "json" + end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/multiplexed_protocol.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/multiplexed_protocol.rb index 13c9d93..b4428a7 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/multiplexed_protocol.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/protocol/multiplexed_protocol.rb @@ -36,5 +36,9 @@ module Thrift @protocol.write_message_begin(name, type, seqid) end end + + def to_s + "multiplexed(#{@service_name=@protocol.to_s})" + end end -end \ No newline at end of file +end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/server/base_server.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/server/base_server.rb index 1ee1213..aa4d09c 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/server/base_server.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/server/base_server.rb @@ -26,6 +26,12 @@ module Thrift @protocol_factory = protocol_factory ? protocol_factory : Thrift::BinaryProtocolFactory.new end - def serve; nil; end + def serve + raise NotImplementedError + end + + def to_s + "server(#{@protocol_factory.to_s}(#{@transport_factory.to_s}(#{@server_transport.to_s})))" + end end -end \ No newline at end of file +end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/server/simple_server.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/server/simple_server.rb index 21e8659..905fe9b 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/server/simple_server.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/server/simple_server.rb @@ -39,5 +39,9 @@ module Thrift @server_transport.close end end + + def to_s + "simple(#{super.to_s})" + end end -end \ No newline at end of file +end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/server/thread_pool_server.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/server/thread_pool_server.rb index 8cec805..bb754ad 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/server/thread_pool_server.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/server/thread_pool_server.rb @@ -71,5 +71,9 @@ module Thrift @server_transport.close end end + + def to_s + "threadpool(#{super.to_s})" + end end -end \ No newline at end of file +end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/server/threaded_server.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/server/threaded_server.rb index a2c917c..88ee183 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/server/threaded_server.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/server/threaded_server.rb @@ -43,5 +43,9 @@ module Thrift @server_transport.close end end + + def to_s + "threaded(#{super.to_s})" + end end -end \ No newline at end of file +end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/base_server_transport.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/base_server_transport.rb index 68c5af0..0105463 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/base_server_transport.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/base_server_transport.rb @@ -34,4 +34,4 @@ module Thrift raise NotImplementedError end end -end \ No newline at end of file +end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/base_transport.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/base_transport.rb index 8790326..97e5935 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/base_transport.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/base_transport.rb @@ -99,11 +99,19 @@ module Thrift alias_method :<<, :write def flush; end + + def to_s + "base" + end end class BaseTransportFactory def get_transport(trans) return trans end + + def to_s + "base" + end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/buffered_transport.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/buffered_transport.rb index 781d3c6..4fe9c41 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/buffered_transport.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/buffered_transport.rb @@ -104,11 +104,19 @@ module Thrift @transport.flush end + + def to_s + "buffered(#{@transport.to_s})" + end end class BufferedTransportFactory < BaseTransportFactory def get_transport(transport) return BufferedTransport.new(transport) end + + def to_s + "buffered" + end end -end \ No newline at end of file +end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/framed_transport.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/framed_transport.rb index d806ce0..9531778 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/framed_transport.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/framed_transport.rb @@ -99,6 +99,10 @@ module Thrift @wbuf = Bytes.empty_byte_buffer end + def to_s + "framed(#{@transport.to_s})" + end + private def read_frame @@ -113,5 +117,9 @@ module Thrift def get_transport(transport) return FramedTransport.new(transport) end + + def to_s + "framed" + end end -end \ No newline at end of file +end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/http_client_transport.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/http_client_transport.rb index c9c4fec..5c1dd5c 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/http_client_transport.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/http_client_transport.rb @@ -53,5 +53,9 @@ module Thrift ensure @outbuf = Bytes.empty_byte_buffer end + + def to_s + "@{self.url}" + end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/io_stream_transport.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/io_stream_transport.rb index e3c8379..ccec68f 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/io_stream_transport.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/io_stream_transport.rb @@ -35,5 +35,8 @@ module Thrift def write(buf); @output.write(Bytes.force_binary_encoding(buf)) end def close; @input.close; @output.close end def to_io; @input end # we're assuming this is used in a IO.select for reading + def to_s + "iostream(input=#{@input.to_s},output=#{@output.to_s})" + end end -end \ No newline at end of file +end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/memory_buffer_transport.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/memory_buffer_transport.rb index ad5ad85..469ea73 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/memory_buffer_transport.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/memory_buffer_transport.rb @@ -121,5 +121,9 @@ module Thrift end out.join(" ") end + + def to_s + "memory" + end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/server_socket.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/server_socket.rb index 7feb9ab..5000232 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/server_socket.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/server_socket.rb @@ -59,5 +59,10 @@ module Thrift end alias to_io handle + + def to_s + "socket(#{@host}:#{@port})" + end + end -end \ No newline at end of file +end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/socket.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/socket.rb index 517d112..f5e6f3b 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/socket.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/socket.rb @@ -134,8 +134,10 @@ module Thrift @handle = nil end - def to_io - @handle + alias to_io handle + + def to_s + "socket(#{@host}:#{@port})" end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/ssl_server_socket.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/ssl_server_socket.rb index abc1343..3abd5ec 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/ssl_server_socket.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/ssl_server_socket.rb @@ -33,5 +33,9 @@ module Thrift socket = TCPServer.new(@host, @port) @handle = OpenSSL::SSL::SSLServer.new(socket, @ssl_context) end + + def to_s + "ssl(#{super.to_s})" + end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/ssl_socket.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/ssl_socket.rb index dbbcc94..7ab96ab 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/ssl_socket.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/ssl_socket.rb @@ -43,5 +43,9 @@ module Thrift raise TransportException.new(TransportException::NOT_OPEN, "Could not connect to #{@desc}: #{e}") end end + + def to_s + "ssl(#{super.to_s})" + end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/unix_server_socket.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/unix_server_socket.rb index a135d25..057d122 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/unix_server_socket.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/unix_server_socket.rb @@ -56,5 +56,9 @@ module Thrift end alias to_io handle + + def to_s + "domain(#{@path})" + end end -end \ No newline at end of file +end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/unix_socket.rb b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/unix_socket.rb index 8f692e4..5dffd59 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/unix_socket.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/lib/thrift/transport/unix_socket.rb @@ -36,5 +36,9 @@ module Thrift raise TransportException.new(TransportException::NOT_OPEN, "Could not open UNIX socket at #{@path}") end end + + def to_s + "domain(#{@path})" + end end -end \ No newline at end of file +end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/base_protocol_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/base_protocol_spec.rb index ec50c48..eca936b 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/base_protocol_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/base_protocol_spec.rb @@ -22,41 +22,46 @@ require 'spec_helper' describe 'BaseProtocol' do before(:each) do - @trans = mock("MockTransport") + @trans = double("MockTransport") @prot = Thrift::BaseProtocol.new(@trans) end describe Thrift::BaseProtocol do # most of the methods are stubs, so we can ignore them + it "should provide a reasonable to_s" do + expect(@trans).to receive(:to_s).once.and_return("trans") + expect(@prot.to_s).to eq("trans") + end + it "should make trans accessible" do - @prot.trans.should eql(@trans) + expect(@prot.trans).to eql(@trans) end it 'should write out a field nicely (deprecated write_field signature)' do - @prot.should_receive(:write_field_begin).with('field', 'type', 'fid').ordered - @prot.should_receive(:write_type).with({:name => 'field', :type => 'type'}, 'value').ordered - @prot.should_receive(:write_field_end).ordered + expect(@prot).to receive(:write_field_begin).with('field', 'type', 'fid').ordered + expect(@prot).to receive(:write_type).with({:name => 'field', :type => 'type'}, 'value').ordered + expect(@prot).to receive(:write_field_end).ordered @prot.write_field('field', 'type', 'fid', 'value') end it 'should write out a field nicely' do - @prot.should_receive(:write_field_begin).with('field', 'type', 'fid').ordered - @prot.should_receive(:write_type).with({:name => 'field', :type => 'type', :binary => false}, 'value').ordered - @prot.should_receive(:write_field_end).ordered + expect(@prot).to receive(:write_field_begin).with('field', 'type', 'fid').ordered + expect(@prot).to receive(:write_type).with({:name => 'field', :type => 'type', :binary => false}, 'value').ordered + expect(@prot).to receive(:write_field_end).ordered @prot.write_field({:name => 'field', :type => 'type', :binary => false}, 'fid', 'value') end it 'should write out the different types (deprecated write_type signature)' do - @prot.should_receive(:write_bool).with('bool').ordered - @prot.should_receive(:write_byte).with('byte').ordered - @prot.should_receive(:write_double).with('double').ordered - @prot.should_receive(:write_i16).with('i16').ordered - @prot.should_receive(:write_i32).with('i32').ordered - @prot.should_receive(:write_i64).with('i64').ordered - @prot.should_receive(:write_string).with('string').ordered - struct = mock('Struct') - struct.should_receive(:write).with(@prot).ordered + expect(@prot).to receive(:write_bool).with('bool').ordered + expect(@prot).to receive(:write_byte).with('byte').ordered + expect(@prot).to receive(:write_double).with('double').ordered + expect(@prot).to receive(:write_i16).with('i16').ordered + expect(@prot).to receive(:write_i32).with('i32').ordered + expect(@prot).to receive(:write_i64).with('i64').ordered + expect(@prot).to receive(:write_string).with('string').ordered + struct = double('Struct') + expect(struct).to receive(:write).with(@prot).ordered @prot.write_type(Thrift::Types::BOOL, 'bool') @prot.write_type(Thrift::Types::BYTE, 'byte') @prot.write_type(Thrift::Types::DOUBLE, 'double') @@ -72,16 +77,16 @@ describe 'BaseProtocol' do end it 'should write out the different types' do - @prot.should_receive(:write_bool).with('bool').ordered - @prot.should_receive(:write_byte).with('byte').ordered - @prot.should_receive(:write_double).with('double').ordered - @prot.should_receive(:write_i16).with('i16').ordered - @prot.should_receive(:write_i32).with('i32').ordered - @prot.should_receive(:write_i64).with('i64').ordered - @prot.should_receive(:write_string).with('string').ordered - @prot.should_receive(:write_binary).with('binary').ordered - struct = mock('Struct') - struct.should_receive(:write).with(@prot).ordered + expect(@prot).to receive(:write_bool).with('bool').ordered + expect(@prot).to receive(:write_byte).with('byte').ordered + expect(@prot).to receive(:write_double).with('double').ordered + expect(@prot).to receive(:write_i16).with('i16').ordered + expect(@prot).to receive(:write_i32).with('i32').ordered + expect(@prot).to receive(:write_i64).with('i64').ordered + expect(@prot).to receive(:write_string).with('string').ordered + expect(@prot).to receive(:write_binary).with('binary').ordered + struct = double('Struct') + expect(struct).to receive(:write).with(@prot).ordered @prot.write_type({:type => Thrift::Types::BOOL}, 'bool') @prot.write_type({:type => Thrift::Types::BYTE}, 'byte') @prot.write_type({:type => Thrift::Types::DOUBLE}, 'double') @@ -98,13 +103,13 @@ describe 'BaseProtocol' do end it 'should read the different types (deprecated read_type signature)' do - @prot.should_receive(:read_bool).ordered - @prot.should_receive(:read_byte).ordered - @prot.should_receive(:read_i16).ordered - @prot.should_receive(:read_i32).ordered - @prot.should_receive(:read_i64).ordered - @prot.should_receive(:read_double).ordered - @prot.should_receive(:read_string).ordered + expect(@prot).to receive(:read_bool).ordered + expect(@prot).to receive(:read_byte).ordered + expect(@prot).to receive(:read_i16).ordered + expect(@prot).to receive(:read_i32).ordered + expect(@prot).to receive(:read_i64).ordered + expect(@prot).to receive(:read_double).ordered + expect(@prot).to receive(:read_string).ordered @prot.read_type(Thrift::Types::BOOL) @prot.read_type(Thrift::Types::BYTE) @prot.read_type(Thrift::Types::I16) @@ -120,14 +125,14 @@ describe 'BaseProtocol' do end it 'should read the different types' do - @prot.should_receive(:read_bool).ordered - @prot.should_receive(:read_byte).ordered - @prot.should_receive(:read_i16).ordered - @prot.should_receive(:read_i32).ordered - @prot.should_receive(:read_i64).ordered - @prot.should_receive(:read_double).ordered - @prot.should_receive(:read_string).ordered - @prot.should_receive(:read_binary).ordered + expect(@prot).to receive(:read_bool).ordered + expect(@prot).to receive(:read_byte).ordered + expect(@prot).to receive(:read_i16).ordered + expect(@prot).to receive(:read_i32).ordered + expect(@prot).to receive(:read_i64).ordered + expect(@prot).to receive(:read_double).ordered + expect(@prot).to receive(:read_string).ordered + expect(@prot).to receive(:read_binary).ordered @prot.read_type({:type => Thrift::Types::BOOL}) @prot.read_type({:type => Thrift::Types::BYTE}) @prot.read_type({:type => Thrift::Types::I16}) @@ -144,13 +149,13 @@ describe 'BaseProtocol' do end it "should skip the basic types" do - @prot.should_receive(:read_bool).ordered - @prot.should_receive(:read_byte).ordered - @prot.should_receive(:read_i16).ordered - @prot.should_receive(:read_i32).ordered - @prot.should_receive(:read_i64).ordered - @prot.should_receive(:read_double).ordered - @prot.should_receive(:read_string).ordered + expect(@prot).to receive(:read_bool).ordered + expect(@prot).to receive(:read_byte).ordered + expect(@prot).to receive(:read_i16).ordered + expect(@prot).to receive(:read_i32).ordered + expect(@prot).to receive(:read_i64).ordered + expect(@prot).to receive(:read_double).ordered + expect(@prot).to receive(:read_string).ordered @prot.skip(Thrift::Types::BOOL) @prot.skip(Thrift::Types::BYTE) @prot.skip(Thrift::Types::I16) @@ -163,47 +168,47 @@ describe 'BaseProtocol' do it "should skip structs" do real_skip = @prot.method(:skip) - @prot.should_receive(:read_struct_begin).ordered - @prot.should_receive(:read_field_begin).exactly(4).times.and_return( + expect(@prot).to receive(:read_struct_begin).ordered + expect(@prot).to receive(:read_field_begin).exactly(4).times.and_return( ['field 1', Thrift::Types::STRING, 1], ['field 2', Thrift::Types::I32, 2], ['field 3', Thrift::Types::MAP, 3], [nil, Thrift::Types::STOP, 0] ) - @prot.should_receive(:read_field_end).exactly(3).times - @prot.should_receive(:read_string).exactly(3).times - @prot.should_receive(:read_i32).ordered - @prot.should_receive(:read_map_begin).ordered.and_return([Thrift::Types::STRING, Thrift::Types::STRING, 1]) + expect(@prot).to receive(:read_field_end).exactly(3).times + expect(@prot).to receive(:read_string).exactly(3).times + expect(@prot).to receive(:read_i32).ordered + expect(@prot).to receive(:read_map_begin).ordered.and_return([Thrift::Types::STRING, Thrift::Types::STRING, 1]) # @prot.should_receive(:read_string).exactly(2).times - @prot.should_receive(:read_map_end).ordered - @prot.should_receive(:read_struct_end).ordered + expect(@prot).to receive(:read_map_end).ordered + expect(@prot).to receive(:read_struct_end).ordered real_skip.call(Thrift::Types::STRUCT) end it "should skip maps" do real_skip = @prot.method(:skip) - @prot.should_receive(:read_map_begin).ordered.and_return([Thrift::Types::STRING, Thrift::Types::STRUCT, 1]) - @prot.should_receive(:read_string).ordered - @prot.should_receive(:read_struct_begin).ordered.and_return(["some_struct"]) - @prot.should_receive(:read_field_begin).ordered.and_return([nil, Thrift::Types::STOP, nil]); - @prot.should_receive(:read_struct_end).ordered - @prot.should_receive(:read_map_end).ordered + expect(@prot).to receive(:read_map_begin).ordered.and_return([Thrift::Types::STRING, Thrift::Types::STRUCT, 1]) + expect(@prot).to receive(:read_string).ordered + expect(@prot).to receive(:read_struct_begin).ordered.and_return(["some_struct"]) + expect(@prot).to receive(:read_field_begin).ordered.and_return([nil, Thrift::Types::STOP, nil]); + expect(@prot).to receive(:read_struct_end).ordered + expect(@prot).to receive(:read_map_end).ordered real_skip.call(Thrift::Types::MAP) end it "should skip sets" do real_skip = @prot.method(:skip) - @prot.should_receive(:read_set_begin).ordered.and_return([Thrift::Types::I64, 9]) - @prot.should_receive(:read_i64).ordered.exactly(9).times - @prot.should_receive(:read_set_end) + expect(@prot).to receive(:read_set_begin).ordered.and_return([Thrift::Types::I64, 9]) + expect(@prot).to receive(:read_i64).ordered.exactly(9).times + expect(@prot).to receive(:read_set_end) real_skip.call(Thrift::Types::SET) end it "should skip lists" do real_skip = @prot.method(:skip) - @prot.should_receive(:read_list_begin).ordered.and_return([Thrift::Types::DOUBLE, 11]) - @prot.should_receive(:read_double).ordered.exactly(11).times - @prot.should_receive(:read_list_end) + expect(@prot).to receive(:read_list_begin).ordered.and_return([Thrift::Types::DOUBLE, 11]) + expect(@prot).to receive(:read_double).ordered.exactly(11).times + expect(@prot).to receive(:read_list_end) real_skip.call(Thrift::Types::LIST) end end @@ -211,7 +216,11 @@ describe 'BaseProtocol' do describe Thrift::BaseProtocolFactory do it "should raise NotImplementedError" do # returning nil since Protocol is just an abstract class - lambda {Thrift::BaseProtocolFactory.new.get_protocol(mock("MockTransport"))}.should raise_error(NotImplementedError) + expect {Thrift::BaseProtocolFactory.new.get_protocol(double("MockTransport"))}.to raise_error(NotImplementedError) + end + + it "should provide a reasonable to_s" do + expect(Thrift::BaseProtocolFactory.new.to_s).to eq("base") end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/base_transport_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/base_transport_spec.rb index 4196572..d2f60aa 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/base_transport_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/base_transport_spec.rb @@ -24,105 +24,119 @@ describe 'BaseTransport' do describe Thrift::TransportException do it "should make type accessible" do exc = Thrift::TransportException.new(Thrift::TransportException::ALREADY_OPEN, "msg") - exc.type.should == Thrift::TransportException::ALREADY_OPEN - exc.message.should == "msg" + expect(exc.type).to eq(Thrift::TransportException::ALREADY_OPEN) + expect(exc.message).to eq("msg") end end describe Thrift::BaseTransport do it "should read the specified size" do transport = Thrift::BaseTransport.new - transport.should_receive(:read).with(40).ordered.and_return("10 letters") - transport.should_receive(:read).with(30).ordered.and_return("fifteen letters") - transport.should_receive(:read).with(15).ordered.and_return("more characters") - transport.read_all(40).should == "10 lettersfifteen lettersmore characters" + expect(transport).to receive(:read).with(40).ordered.and_return("10 letters") + expect(transport).to receive(:read).with(30).ordered.and_return("fifteen letters") + expect(transport).to receive(:read).with(15).ordered.and_return("more characters") + expect(transport.read_all(40)).to eq("10 lettersfifteen lettersmore characters") end it "should stub out the rest of the methods" do # can't test for stubbiness, so just make sure they're defined [:open?, :open, :close, :read, :write, :flush].each do |sym| - Thrift::BaseTransport.method_defined?(sym).should be_true + expect(Thrift::BaseTransport.method_defined?(sym)).to be_truthy end end it "should alias << to write" do - Thrift::BaseTransport.instance_method(:<<).should == Thrift::BaseTransport.instance_method(:write) + expect(Thrift::BaseTransport.instance_method(:<<)).to eq(Thrift::BaseTransport.instance_method(:write)) + end + + it "should provide a reasonable to_s" do + expect(Thrift::BaseTransport.new.to_s).to eq("base") end end describe Thrift::BaseServerTransport do it "should stub out its methods" do [:listen, :accept, :close].each do |sym| - Thrift::BaseServerTransport.method_defined?(sym).should be_true + expect(Thrift::BaseServerTransport.method_defined?(sym)).to be_truthy end end end describe Thrift::BaseTransportFactory do it "should return the transport it's given" do - transport = mock("Transport") - Thrift::BaseTransportFactory.new.get_transport(transport).should eql(transport) + transport = double("Transport") + expect(Thrift::BaseTransportFactory.new.get_transport(transport)).to eql(transport) + end + + it "should provide a reasonable to_s" do + expect(Thrift::BaseTransportFactory.new.to_s).to eq("base") end end describe Thrift::BufferedTransport do + it "should provide a to_s that describes the encapsulation" do + trans = double("Transport") + expect(trans).to receive(:to_s).and_return("mock") + expect(Thrift::BufferedTransport.new(trans).to_s).to eq("buffered(mock)") + end + it "should pass through everything but write/flush/read" do - trans = mock("Transport") - trans.should_receive(:open?).ordered.and_return("+ open?") - trans.should_receive(:open).ordered.and_return("+ open") - trans.should_receive(:flush).ordered # from the close - trans.should_receive(:close).ordered.and_return("+ close") + trans = double("Transport") + expect(trans).to receive(:open?).ordered.and_return("+ open?") + expect(trans).to receive(:open).ordered.and_return("+ open") + expect(trans).to receive(:flush).ordered # from the close + expect(trans).to receive(:close).ordered.and_return("+ close") btrans = Thrift::BufferedTransport.new(trans) - btrans.open?.should == "+ open?" - btrans.open.should == "+ open" - btrans.close.should == "+ close" + expect(btrans.open?).to eq("+ open?") + expect(btrans.open).to eq("+ open") + expect(btrans.close).to eq("+ close") end it "should buffer reads in chunks of #{Thrift::BufferedTransport::DEFAULT_BUFFER}" do - trans = mock("Transport") - trans.should_receive(:read).with(Thrift::BufferedTransport::DEFAULT_BUFFER).and_return("lorum ipsum dolor emet") + trans = double("Transport") + expect(trans).to receive(:read).with(Thrift::BufferedTransport::DEFAULT_BUFFER).and_return("lorum ipsum dolor emet") btrans = Thrift::BufferedTransport.new(trans) - btrans.read(6).should == "lorum " - btrans.read(6).should == "ipsum " - btrans.read(6).should == "dolor " - btrans.read(6).should == "emet" + expect(btrans.read(6)).to eq("lorum ") + expect(btrans.read(6)).to eq("ipsum ") + expect(btrans.read(6)).to eq("dolor ") + expect(btrans.read(6)).to eq("emet") end it "should buffer writes and send them on flush" do - trans = mock("Transport") + trans = double("Transport") btrans = Thrift::BufferedTransport.new(trans) btrans.write("one/") btrans.write("two/") btrans.write("three/") - trans.should_receive(:write).with("one/two/three/").ordered - trans.should_receive(:flush).ordered + expect(trans).to receive(:write).with("one/two/three/").ordered + expect(trans).to receive(:flush).ordered btrans.flush end it "should only send buffered data once" do - trans = mock("Transport") + trans = double("Transport") btrans = Thrift::BufferedTransport.new(trans) btrans.write("one/") btrans.write("two/") btrans.write("three/") - trans.should_receive(:write).with("one/two/three/") - trans.stub!(:flush) + expect(trans).to receive(:write).with("one/two/three/") + allow(trans).to receive(:flush) btrans.flush # Nothing to flush with no data btrans.flush end it "should flush on close" do - trans = mock("Transport") - trans.should_receive(:close) + trans = double("Transport") + expect(trans).to receive(:close) btrans = Thrift::BufferedTransport.new(trans) - btrans.should_receive(:flush) + expect(btrans).to receive(:flush) btrans.close end it "should not write to socket if there's no data" do - trans = mock("Transport") - trans.should_receive(:flush) + trans = double("Transport") + expect(trans).to receive(:flush) btrans = Thrift::BufferedTransport.new(trans) btrans.flush end @@ -130,80 +144,90 @@ describe 'BaseTransport' do describe Thrift::BufferedTransportFactory do it "should wrap the given transport in a BufferedTransport" do - trans = mock("Transport") - btrans = mock("BufferedTransport") - Thrift::BufferedTransport.should_receive(:new).with(trans).and_return(btrans) - Thrift::BufferedTransportFactory.new.get_transport(trans).should == btrans + trans = double("Transport") + btrans = double("BufferedTransport") + expect(Thrift::BufferedTransport).to receive(:new).with(trans).and_return(btrans) + expect(Thrift::BufferedTransportFactory.new.get_transport(trans)).to eq(btrans) + end + + it "should provide a reasonable to_s" do + expect(Thrift::BufferedTransportFactory.new.to_s).to eq("buffered") end end describe Thrift::FramedTransport do before(:each) do - @trans = mock("Transport") + @trans = double("Transport") + end + + it "should provide a to_s that describes the encapsulation" do + trans = double("Transport") + expect(trans).to receive(:to_s).and_return("mock") + expect(Thrift::FramedTransport.new(trans).to_s).to eq("framed(mock)") end it "should pass through open?/open/close" do ftrans = Thrift::FramedTransport.new(@trans) - @trans.should_receive(:open?).ordered.and_return("+ open?") - @trans.should_receive(:open).ordered.and_return("+ open") - @trans.should_receive(:close).ordered.and_return("+ close") - ftrans.open?.should == "+ open?" - ftrans.open.should == "+ open" - ftrans.close.should == "+ close" + expect(@trans).to receive(:open?).ordered.and_return("+ open?") + expect(@trans).to receive(:open).ordered.and_return("+ open") + expect(@trans).to receive(:close).ordered.and_return("+ close") + expect(ftrans.open?).to eq("+ open?") + expect(ftrans.open).to eq("+ open") + expect(ftrans.close).to eq("+ close") end it "should pass through read when read is turned off" do ftrans = Thrift::FramedTransport.new(@trans, false, true) - @trans.should_receive(:read).with(17).ordered.and_return("+ read") - ftrans.read(17).should == "+ read" + expect(@trans).to receive(:read).with(17).ordered.and_return("+ read") + expect(ftrans.read(17)).to eq("+ read") end it "should pass through write/flush when write is turned off" do ftrans = Thrift::FramedTransport.new(@trans, true, false) - @trans.should_receive(:write).with("foo").ordered.and_return("+ write") - @trans.should_receive(:flush).ordered.and_return("+ flush") - ftrans.write("foo").should == "+ write" - ftrans.flush.should == "+ flush" + expect(@trans).to receive(:write).with("foo").ordered.and_return("+ write") + expect(@trans).to receive(:flush).ordered.and_return("+ flush") + expect(ftrans.write("foo")).to eq("+ write") + expect(ftrans.flush).to eq("+ flush") end it "should return a full frame if asked for >= the frame's length" do frame = "this is a frame" - @trans.should_receive(:read_all).with(4).and_return("\000\000\000\017") - @trans.should_receive(:read_all).with(frame.length).and_return(frame) - Thrift::FramedTransport.new(@trans).read(frame.length + 10).should == frame + expect(@trans).to receive(:read_all).with(4).and_return("\000\000\000\017") + expect(@trans).to receive(:read_all).with(frame.length).and_return(frame) + expect(Thrift::FramedTransport.new(@trans).read(frame.length + 10)).to eq(frame) end it "should return slices of the frame when asked for < the frame's length" do frame = "this is a frame" - @trans.should_receive(:read_all).with(4).and_return("\000\000\000\017") - @trans.should_receive(:read_all).with(frame.length).and_return(frame) + expect(@trans).to receive(:read_all).with(4).and_return("\000\000\000\017") + expect(@trans).to receive(:read_all).with(frame.length).and_return(frame) ftrans = Thrift::FramedTransport.new(@trans) - ftrans.read(4).should == "this" - ftrans.read(4).should == " is " - ftrans.read(16).should == "a frame" + expect(ftrans.read(4)).to eq("this") + expect(ftrans.read(4)).to eq(" is ") + expect(ftrans.read(16)).to eq("a frame") end it "should return nothing if asked for <= 0" do - Thrift::FramedTransport.new(@trans).read(-2).should == "" + expect(Thrift::FramedTransport.new(@trans).read(-2)).to eq("") end it "should pull a new frame when the first is exhausted" do frame = "this is a frame" frame2 = "yet another frame" - @trans.should_receive(:read_all).with(4).and_return("\000\000\000\017", "\000\000\000\021") - @trans.should_receive(:read_all).with(frame.length).and_return(frame) - @trans.should_receive(:read_all).with(frame2.length).and_return(frame2) + expect(@trans).to receive(:read_all).with(4).and_return("\000\000\000\017", "\000\000\000\021") + expect(@trans).to receive(:read_all).with(frame.length).and_return(frame) + expect(@trans).to receive(:read_all).with(frame2.length).and_return(frame2) ftrans = Thrift::FramedTransport.new(@trans) - ftrans.read(4).should == "this" - ftrans.read(8).should == " is a fr" - ftrans.read(6).should == "ame" - ftrans.read(4).should == "yet " - ftrans.read(16).should == "another frame" + expect(ftrans.read(4)).to eq("this") + expect(ftrans.read(8)).to eq(" is a fr") + expect(ftrans.read(6)).to eq("ame") + expect(ftrans.read(4)).to eq("yet ") + expect(ftrans.read(16)).to eq("another frame") end it "should buffer writes" do ftrans = Thrift::FramedTransport.new(@trans) - @trans.should_not_receive(:write) + expect(@trans).not_to receive(:write) ftrans.write("foo") ftrans.write("bar") ftrans.write("this is a frame") @@ -213,15 +237,15 @@ describe 'BaseTransport' do ftrans = Thrift::FramedTransport.new(@trans) ftrans.write("foobar", 3) ftrans.write("barfoo", 1) - @trans.stub!(:flush) - @trans.should_receive(:write).with("\000\000\000\004foob") + allow(@trans).to receive(:flush) + expect(@trans).to receive(:write).with("\000\000\000\004foob") ftrans.flush end it "should flush frames with a 4-byte header" do ftrans = Thrift::FramedTransport.new(@trans) - @trans.should_receive(:write).with("\000\000\000\035one/two/three/this is a frame").ordered - @trans.should_receive(:flush).ordered + expect(@trans).to receive(:write).with("\000\000\000\035one/two/three/this is a frame").ordered + expect(@trans).to receive(:flush).ordered ftrans.write("one/") ftrans.write("two/") ftrans.write("three/") @@ -231,22 +255,26 @@ describe 'BaseTransport' do it "should not flush the same buffered data twice" do ftrans = Thrift::FramedTransport.new(@trans) - @trans.should_receive(:write).with("\000\000\000\007foo/bar") - @trans.stub!(:flush) + expect(@trans).to receive(:write).with("\000\000\000\007foo/bar") + allow(@trans).to receive(:flush) ftrans.write("foo") ftrans.write("/bar") ftrans.flush - @trans.should_receive(:write).with("\000\000\000\000") + expect(@trans).to receive(:write).with("\000\000\000\000") ftrans.flush end end describe Thrift::FramedTransportFactory do it "should wrap the given transport in a FramedTransport" do - trans = mock("Transport") - Thrift::FramedTransport.should_receive(:new).with(trans) + trans = double("Transport") + expect(Thrift::FramedTransport).to receive(:new).with(trans) Thrift::FramedTransportFactory.new.get_transport(trans) end + + it "should provide a reasonable to_s" do + expect(Thrift::FramedTransportFactory.new.to_s).to eq("framed") + end end describe Thrift::MemoryBufferTransport do @@ -254,96 +282,106 @@ describe 'BaseTransport' do @buffer = Thrift::MemoryBufferTransport.new end + it "should provide a reasonable to_s" do + expect(@buffer.to_s).to eq("memory") + end + it "should accept a buffer on input and use it directly" do s = "this is a test" @buffer = Thrift::MemoryBufferTransport.new(s) - @buffer.read(4).should == "this" + expect(@buffer.read(4)).to eq("this") s.slice!(-4..-1) - @buffer.read(@buffer.available).should == " is a " + expect(@buffer.read(@buffer.available)).to eq(" is a ") end it "should always remain open" do - @buffer.should be_open + expect(@buffer).to be_open @buffer.close - @buffer.should be_open + expect(@buffer).to be_open end it "should respond to peek and available" do @buffer.write "some data" - @buffer.peek.should be_true - @buffer.available.should == 9 + expect(@buffer.peek).to be_truthy + expect(@buffer.available).to eq(9) @buffer.read(4) - @buffer.peek.should be_true - @buffer.available.should == 5 + expect(@buffer.peek).to be_truthy + expect(@buffer.available).to eq(5) @buffer.read(5) - @buffer.peek.should be_false - @buffer.available.should == 0 + expect(@buffer.peek).to be_falsey + expect(@buffer.available).to eq(0) end it "should be able to reset the buffer" do @buffer.write "test data" @buffer.reset_buffer("foobar") - @buffer.available.should == 6 - @buffer.read(@buffer.available).should == "foobar" + expect(@buffer.available).to eq(6) + expect(@buffer.read(@buffer.available)).to eq("foobar") @buffer.reset_buffer - @buffer.available.should == 0 + expect(@buffer.available).to eq(0) end it "should copy the given string when resetting the buffer" do s = "this is a test" @buffer.reset_buffer(s) - @buffer.available.should == 14 + expect(@buffer.available).to eq(14) @buffer.read(10) - @buffer.available.should == 4 - s.should == "this is a test" + expect(@buffer.available).to eq(4) + expect(s).to eq("this is a test") end it "should return from read what was given in write" do @buffer.write "test data" - @buffer.read(4).should == "test" - @buffer.read(@buffer.available).should == " data" + expect(@buffer.read(4)).to eq("test") + expect(@buffer.read(@buffer.available)).to eq(" data") @buffer.write "foo" @buffer.write " bar" - @buffer.read(@buffer.available).should == "foo bar" + expect(@buffer.read(@buffer.available)).to eq("foo bar") end it "should throw an EOFError when there isn't enough data in the buffer" do @buffer.reset_buffer("") - lambda{@buffer.read(1)}.should raise_error(EOFError) + expect{@buffer.read(1)}.to raise_error(EOFError) @buffer.reset_buffer("1234") - lambda{@buffer.read(5)}.should raise_error(EOFError) + expect{@buffer.read(5)}.to raise_error(EOFError) end end describe Thrift::IOStreamTransport do before(:each) do - @input = mock("Input", :closed? => false) - @output = mock("Output", :closed? => false) + @input = double("Input", :closed? => false) + @output = double("Output", :closed? => false) @trans = Thrift::IOStreamTransport.new(@input, @output) end + it "should provide a reasonable to_s" do + expect(@input).to receive(:to_s).and_return("mock_input") + expect(@output).to receive(:to_s).and_return("mock_output") + expect(@trans.to_s).to eq("iostream(input=mock_input,output=mock_output)") + end + it "should be open as long as both input or output are open" do - @trans.should be_open - @input.stub!(:closed?).and_return(true) - @trans.should be_open - @input.stub!(:closed?).and_return(false) - @output.stub!(:closed?).and_return(true) - @trans.should be_open - @input.stub!(:closed?).and_return(true) - @trans.should_not be_open + expect(@trans).to be_open + allow(@input).to receive(:closed?).and_return(true) + expect(@trans).to be_open + allow(@input).to receive(:closed?).and_return(false) + allow(@output).to receive(:closed?).and_return(true) + expect(@trans).to be_open + allow(@input).to receive(:closed?).and_return(true) + expect(@trans).not_to be_open end it "should pass through read/write to input/output" do - @input.should_receive(:read).with(17).and_return("+ read") - @output.should_receive(:write).with("foobar").and_return("+ write") - @trans.read(17).should == "+ read" - @trans.write("foobar").should == "+ write" + expect(@input).to receive(:read).with(17).and_return("+ read") + expect(@output).to receive(:write).with("foobar").and_return("+ write") + expect(@trans.read(17)).to eq("+ read") + expect(@trans.write("foobar")).to eq("+ write") end it "should close both input and output when closed" do - @input.should_receive(:close) - @output.should_receive(:close) + expect(@input).to receive(:close) + expect(@output).to receive(:close) @trans.close end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/binary_protocol_accelerated_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/binary_protocol_accelerated_spec.rb index bac9ea7..b2cd04b 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/binary_protocol_accelerated_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/binary_protocol_accelerated_spec.rb @@ -33,10 +33,14 @@ if defined? Thrift::BinaryProtocolAccelerated describe Thrift::BinaryProtocolAcceleratedFactory do it "should create a BinaryProtocolAccelerated" do - Thrift::BinaryProtocolAcceleratedFactory.new.get_protocol(mock("MockTransport")).should be_instance_of(Thrift::BinaryProtocolAccelerated) + expect(Thrift::BinaryProtocolAcceleratedFactory.new.get_protocol(double("MockTransport"))).to be_instance_of(Thrift::BinaryProtocolAccelerated) + end + + it "should provide a reasonable to_s" do + expect(Thrift::BinaryProtocolAcceleratedFactory.new.to_s).to eq("binary-accel") end end end else puts "skipping BinaryProtocolAccelerated spec because it is not defined." -end \ No newline at end of file +end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/binary_protocol_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/binary_protocol_spec.rb index 32772d3..065f5ce 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/binary_protocol_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/binary_protocol_spec.rb @@ -38,29 +38,37 @@ describe 'BinaryProtocol' do it "should read a message header" do @trans.write([protocol_class.const_get(:VERSION_1) | Thrift::MessageTypes::REPLY].pack('N')) @trans.write([42].pack('N')) - @prot.should_receive(:read_string).and_return('testMessage') - @prot.read_message_begin.should == ['testMessage', Thrift::MessageTypes::REPLY, 42] + expect(@prot).to receive(:read_string).and_return('testMessage') + expect(@prot.read_message_begin).to eq(['testMessage', Thrift::MessageTypes::REPLY, 42]) end it "should raise an exception if the message header has the wrong version" do - @prot.should_receive(:read_i32).and_return(-1) - lambda { @prot.read_message_begin }.should raise_error(Thrift::ProtocolException, 'Missing version identifier') do |e| + expect(@prot).to receive(:read_i32).and_return(-1) + expect { @prot.read_message_begin }.to raise_error(Thrift::ProtocolException, 'Missing version identifier') do |e| e.type == Thrift::ProtocolException::BAD_VERSION end end it "should raise an exception if the message header does not exist and strict_read is enabled" do - @prot.should_receive(:read_i32).and_return(42) - @prot.should_receive(:strict_read).and_return(true) - lambda { @prot.read_message_begin }.should raise_error(Thrift::ProtocolException, 'No version identifier, old protocol client?') do |e| + expect(@prot).to receive(:read_i32).and_return(42) + expect(@prot).to receive(:strict_read).and_return(true) + expect { @prot.read_message_begin }.to raise_error(Thrift::ProtocolException, 'No version identifier, old protocol client?') do |e| e.type == Thrift::ProtocolException::BAD_VERSION end end + + it "should provide a reasonable to_s" do + expect(@prot.to_s).to eq("binary(memory)") + end end describe Thrift::BinaryProtocolFactory do it "should create a BinaryProtocol" do - Thrift::BinaryProtocolFactory.new.get_protocol(mock("MockTransport")).should be_instance_of(Thrift::BinaryProtocol) + expect(Thrift::BinaryProtocolFactory.new.get_protocol(double("MockTransport"))).to be_instance_of(Thrift::BinaryProtocol) + end + + it "should provide a reasonable to_s" do + expect(Thrift::BinaryProtocolFactory.new.to_s).to eq("binary") end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/binary_protocol_spec_shared.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/binary_protocol_spec_shared.rb index 7a9d028..58d65f0 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/binary_protocol_spec_shared.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/binary_protocol_spec_shared.rb @@ -27,34 +27,34 @@ shared_examples_for 'a binary protocol' do end it "should define the proper VERSION_1, VERSION_MASK AND TYPE_MASK" do - protocol_class.const_get(:VERSION_MASK).should == 0xffff0000 - protocol_class.const_get(:VERSION_1).should == 0x80010000 - protocol_class.const_get(:TYPE_MASK).should == 0x000000ff + expect(protocol_class.const_get(:VERSION_MASK)).to eq(0xffff0000) + expect(protocol_class.const_get(:VERSION_1)).to eq(0x80010000) + expect(protocol_class.const_get(:TYPE_MASK)).to eq(0x000000ff) end it "should make strict_read readable" do - @prot.strict_read.should eql(true) + expect(@prot.strict_read).to eql(true) end it "should make strict_write readable" do - @prot.strict_write.should eql(true) + expect(@prot.strict_write).to eql(true) end it "should write the message header" do @prot.write_message_begin('testMessage', Thrift::MessageTypes::CALL, 17) - @trans.read(@trans.available).should == [protocol_class.const_get(:VERSION_1) | Thrift::MessageTypes::CALL, "testMessage".size, "testMessage", 17].pack("NNa11N") + expect(@trans.read(@trans.available)).to eq([protocol_class.const_get(:VERSION_1) | Thrift::MessageTypes::CALL, "testMessage".size, "testMessage", 17].pack("NNa11N")) end it "should write the message header without version when writes are not strict" do @prot = protocol_class.new(@trans, true, false) # no strict write @prot.write_message_begin('testMessage', Thrift::MessageTypes::CALL, 17) - @trans.read(@trans.available).should == "\000\000\000\vtestMessage\001\000\000\000\021" + expect(@trans.read(@trans.available)).to eq("\000\000\000\vtestMessage\001\000\000\000\021") end it "should write the message header with a version when writes are strict" do @prot = protocol_class.new(@trans) # strict write @prot.write_message_begin('testMessage', Thrift::MessageTypes::CALL, 17) - @trans.read(@trans.available).should == "\200\001\000\001\000\000\000\vtestMessage\000\000\000\021" + expect(@trans.read(@trans.available)).to eq("\200\001\000\001\000\000\000\vtestMessage\000\000\000\021") end @@ -62,64 +62,67 @@ shared_examples_for 'a binary protocol' do it "should write the field header" do @prot.write_field_begin('foo', Thrift::Types::DOUBLE, 3) - @trans.read(@trans.available).should == [Thrift::Types::DOUBLE, 3].pack("cn") + expect(@trans.read(@trans.available)).to eq([Thrift::Types::DOUBLE, 3].pack("cn")) end # field footer is a noop it "should write the STOP field" do @prot.write_field_stop - @trans.read(1).should == "\000" + expect(@trans.read(1)).to eq("\000") end it "should write the map header" do @prot.write_map_begin(Thrift::Types::STRING, Thrift::Types::LIST, 17) - @trans.read(@trans.available).should == [Thrift::Types::STRING, Thrift::Types::LIST, 17].pack("ccN"); + expect(@trans.read(@trans.available)).to eq([Thrift::Types::STRING, Thrift::Types::LIST, 17].pack("ccN")); end # map footer is a noop it "should write the list header" do @prot.write_list_begin(Thrift::Types::I16, 42) - @trans.read(@trans.available).should == [Thrift::Types::I16, 42].pack("cN") + expect(@trans.read(@trans.available)).to eq([Thrift::Types::I16, 42].pack("cN")) end # list footer is a noop it "should write the set header" do @prot.write_set_begin(Thrift::Types::I16, 42) - @trans.read(@trans.available).should == [Thrift::Types::I16, 42].pack("cN") + expect(@trans.read(@trans.available)).to eq([Thrift::Types::I16, 42].pack("cN")) end it "should write a bool" do @prot.write_bool(true) @prot.write_bool(false) - @trans.read(@trans.available).should == "\001\000" + expect(@trans.read(@trans.available)).to eq("\001\000") end it "should treat a nil bool as false" do @prot.write_bool(nil) - @trans.read(1).should == "\000" + expect(@trans.read(1)).to eq("\000") end it "should write a byte" do # byte is small enough, let's check -128..127 (-128..127).each do |i| @prot.write_byte(i) - @trans.read(1).should == [i].pack('c') + expect(@trans.read(1)).to eq([i].pack('c')) end - # handing it numbers out of signed range should clip - @trans.rspec_verify + end + + it "should clip numbers out of signed range" do (128..255).each do |i| @prot.write_byte(i) - @trans.read(1).should == [i].pack('c') + expect(@trans.read(1)).to eq([i].pack('c')) end - # and lastly, a Bignum is going to error out - lambda { @prot.write_byte(2**65) }.should raise_error(RangeError) + end + + it "errors out with a Bignum" do + expect { @prot.write_byte(2**65) }.to raise_error(RangeError) end it "should error gracefully when trying to write a nil byte" do - lambda { @prot.write_byte(nil) }.should raise_error + expect { @prot.write_byte(nil) }.to raise_error end it "should write an i16" do @@ -131,14 +134,14 @@ shared_examples_for 'a binary protocol' do # and try something out of signed range, it should clip @prot.write_i16(2**15 + 5) - @trans.read(@trans.available).should == "\200\000\374\000\000\021\000\000\330\360\006\273\177\377\200\005" + expect(@trans.read(@trans.available)).to eq("\200\000\374\000\000\021\000\000\330\360\006\273\177\377\200\005") # a Bignum should error # lambda { @prot.write_i16(2**65) }.should raise_error(RangeError) end it "should error gracefully when trying to write a nil i16" do - lambda { @prot.write_i16(nil) }.should raise_error + expect { @prot.write_i16(nil) }.to raise_error end it "should write an i32" do @@ -148,14 +151,14 @@ shared_examples_for 'a binary protocol' do @prot.write_i32(i) end # try something out of signed range, it should clip - @trans.read(@trans.available).should == "\200\000\000\000" + "\377\376\037\r" + "\377\377\366\034" + "\377\377\377\375" + "\000\000\000\000" + "\000#\340\203" + "\000\0000+" + "\177\377\377\377" + expect(@trans.read(@trans.available)).to eq("\200\000\000\000" + "\377\376\037\r" + "\377\377\366\034" + "\377\377\377\375" + "\000\000\000\000" + "\000#\340\203" + "\000\0000+" + "\177\377\377\377") [2 ** 31 + 5, 2 ** 65 + 5].each do |i| - lambda { @prot.write_i32(i) }.should raise_error(RangeError) + expect { @prot.write_i32(i) }.to raise_error(RangeError) end end it "should error gracefully when trying to write a nil i32" do - lambda { @prot.write_i32(nil) }.should raise_error + expect { @prot.write_i32(nil) }.to raise_error end it "should write an i64" do @@ -165,7 +168,7 @@ shared_examples_for 'a binary protocol' do @prot.write_i64(i) end # try something out of signed range, it should clip - @trans.read(@trans.available).should == ["\200\000\000\000\000\000\000\000", + expect(@trans.read(@trans.available)).to eq(["\200\000\000\000\000\000\000\000", "\377\377\364\303\035\244+]", "\377\377\377\377\376\231:\341", "\377\377\377\377\377\377\377\026", @@ -173,12 +176,12 @@ shared_examples_for 'a binary protocol' do "\000\000\000\000\000\000\004\317", "\000\000\000\000\000#\340\204", "\000\000\000\002\340\311~\365", - "\177\377\377\377\377\377\377\377"].join("") - lambda { @prot.write_i64(2 ** 65 + 5) }.should raise_error(RangeError) + "\177\377\377\377\377\377\377\377"].join("")) + expect { @prot.write_i64(2 ** 65 + 5) }.to raise_error(RangeError) end it "should error gracefully when trying to write a nil i64" do - lambda { @prot.write_i64(nil) }.should raise_error + expect { @prot.write_i64(nil) }.to raise_error end it "should write a double" do @@ -186,12 +189,12 @@ shared_examples_for 'a binary protocol' do values = [Float::MIN,-1231.15325, -123123.23, -23.23515123, 0, 12351.1325, 523.23, Float::MAX] values.each do |f| @prot.write_double(f) - @trans.read(@trans.available).should == [f].pack("G") + expect(@trans.read(@trans.available)).to eq([f].pack("G")) end end it "should error gracefully when trying to write a nil double" do - lambda { @prot.write_double(nil) }.should raise_error + expect { @prot.write_double(nil) }.to raise_error end if RUBY_VERSION >= '1.9' @@ -199,111 +202,111 @@ shared_examples_for 'a binary protocol' do str = 'abc' @prot.write_string(str) a = @trans.read(@trans.available) - a.encoding.should == Encoding::BINARY - a.unpack('C*').should == [0x00, 0x00, 0x00, 0x03, 0x61, 0x62, 0x63] + expect(a.encoding).to eq(Encoding::BINARY) + expect(a.unpack('C*')).to eq([0x00, 0x00, 0x00, 0x03, 0x61, 0x62, 0x63]) end it 'should write a string with unicode characters' do str = "abc \u20AC \u20AD".encode('UTF-8') @prot.write_string(str) a = @trans.read(@trans.available) - a.encoding.should == Encoding::BINARY - a.unpack('C*').should == [0x00, 0x00, 0x00, 0x0B, 0x61, 0x62, 0x63, 0x20, - 0xE2, 0x82, 0xAC, 0x20, 0xE2, 0x82, 0xAD] + expect(a.encoding).to eq(Encoding::BINARY) + expect(a.unpack('C*')).to eq([0x00, 0x00, 0x00, 0x0B, 0x61, 0x62, 0x63, 0x20, + 0xE2, 0x82, 0xAC, 0x20, 0xE2, 0x82, 0xAD]) end it 'should write should write a string with unicode characters and transcoding' do str = "abc \u20AC".encode('ISO-8859-15') @prot.write_string(str) a = @trans.read(@trans.available) - a.encoding.should == Encoding::BINARY - a.unpack('C*').should == [0x00, 0x00, 0x00, 0x07, 0x61, 0x62, 0x63, 0x20, 0xE2, 0x82, 0xAC] + expect(a.encoding).to eq(Encoding::BINARY) + expect(a.unpack('C*')).to eq([0x00, 0x00, 0x00, 0x07, 0x61, 0x62, 0x63, 0x20, 0xE2, 0x82, 0xAC]) end it 'should write a binary string' do buffer = [0, 1, 2, 3].pack('C*') @prot.write_binary(buffer) a = @trans.read(@trans.available) - a.encoding.should == Encoding::BINARY - a.unpack('C*').should == [0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x02, 0x03] + expect(a.encoding).to eq(Encoding::BINARY) + expect(a.unpack('C*')).to eq([0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x02, 0x03]) end else it 'should write a string' do str = 'abc' @prot.write_string(str) a = @trans.read(@trans.available) - a.unpack('C*').should == [0x00, 0x00, 0x00, 0x03, 0x61, 0x62, 0x63] + expect(a.unpack('C*')).to eq([0x00, 0x00, 0x00, 0x03, 0x61, 0x62, 0x63]) end it 'should write a binary string' do buffer = [0, 1, 2, 3].pack('C*') @prot.write_binary(buffer) a = @trans.read(@trans.available) - a.unpack('C*').should == [0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x02, 0x03] + expect(a.unpack('C*')).to eq([0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x02, 0x03]) end end it "should error gracefully when trying to write a nil string" do - lambda { @prot.write_string(nil) }.should raise_error + expect { @prot.write_string(nil) }.to raise_error end it "should write the message header without version when writes are not strict" do @prot = protocol_class.new(@trans, true, false) # no strict write @prot.write_message_begin('testMessage', Thrift::MessageTypes::CALL, 17) - @trans.read(@trans.available).should == "\000\000\000\vtestMessage\001\000\000\000\021" + expect(@trans.read(@trans.available)).to eq("\000\000\000\vtestMessage\001\000\000\000\021") end it "should write the message header with a version when writes are strict" do @prot = protocol_class.new(@trans) # strict write @prot.write_message_begin('testMessage', Thrift::MessageTypes::CALL, 17) - @trans.read(@trans.available).should == "\200\001\000\001\000\000\000\vtestMessage\000\000\000\021" + expect(@trans.read(@trans.available)).to eq("\200\001\000\001\000\000\000\vtestMessage\000\000\000\021") end # message footer is a noop it "should read a field header" do @trans.write([Thrift::Types::STRING, 3].pack("cn")) - @prot.read_field_begin.should == [nil, Thrift::Types::STRING, 3] + expect(@prot.read_field_begin).to eq([nil, Thrift::Types::STRING, 3]) end # field footer is a noop it "should read a stop field" do @trans.write([Thrift::Types::STOP].pack("c")); - @prot.read_field_begin.should == [nil, Thrift::Types::STOP, 0] + expect(@prot.read_field_begin).to eq([nil, Thrift::Types::STOP, 0]) end it "should read a map header" do @trans.write([Thrift::Types::DOUBLE, Thrift::Types::I64, 42].pack("ccN")) - @prot.read_map_begin.should == [Thrift::Types::DOUBLE, Thrift::Types::I64, 42] + expect(@prot.read_map_begin).to eq([Thrift::Types::DOUBLE, Thrift::Types::I64, 42]) end # map footer is a noop it "should read a list header" do @trans.write([Thrift::Types::STRING, 17].pack("cN")) - @prot.read_list_begin.should == [Thrift::Types::STRING, 17] + expect(@prot.read_list_begin).to eq([Thrift::Types::STRING, 17]) end # list footer is a noop it "should read a set header" do @trans.write([Thrift::Types::STRING, 17].pack("cN")) - @prot.read_set_begin.should == [Thrift::Types::STRING, 17] + expect(@prot.read_set_begin).to eq([Thrift::Types::STRING, 17]) end # set footer is a noop it "should read a bool" do @trans.write("\001\000"); - @prot.read_bool.should == true - @prot.read_bool.should == false + expect(@prot.read_bool).to eq(true) + expect(@prot.read_bool).to eq(false) end it "should read a byte" do [-128, -57, -3, 0, 17, 24, 127].each do |i| @trans.write([i].pack("c")) - @prot.read_byte.should == i + expect(@prot.read_byte).to eq(i) end end @@ -311,7 +314,7 @@ shared_examples_for 'a binary protocol' do # try a scattering of values, including min/max [-2**15, -5237, -353, 0, 1527, 2234, 2**15-1].each do |i| @trans.write([i].pack("n")); - @prot.read_i16.should == i + expect(@prot.read_i16).to eq(i) end end @@ -319,7 +322,7 @@ shared_examples_for 'a binary protocol' do # try a scattering of values, including min/max [-2**31, -235125, -6236, 0, 2351, 123123, 2**31-1].each do |i| @trans.write([i].pack("N")) - @prot.read_i32.should == i + expect(@prot.read_i32).to eq(i) end end @@ -327,7 +330,7 @@ shared_examples_for 'a binary protocol' do # try a scattering of values, including min/max [-2**63, -123512312, -6346, 0, 32, 2346322323, 2**63-1].each do |i| @trans.write([i >> 32, i & 0xFFFFFFFF].pack("NN")) - @prot.read_i64.should == i + expect(@prot.read_i64).to eq(i) end end @@ -335,7 +338,7 @@ shared_examples_for 'a binary protocol' do # try a random scattering of values, including min/max [Float::MIN, -231231.12351, -323.233513, 0, 123.2351235, 2351235.12351235, Float::MAX].each do |f| @trans.write([f].pack("G")); - @prot.read_double.should == f + expect(@prot.read_double).to eq(f) end end @@ -345,8 +348,8 @@ shared_examples_for 'a binary protocol' do buffer = [0x00, 0x00, 0x00, 0x03, 0x61, 0x62, 0x63].pack('C*') @trans.write(buffer) a = @prot.read_string - a.should == 'abc'.encode('UTF-8') - a.encoding.should == Encoding::UTF_8 + expect(a).to eq('abc'.encode('UTF-8')) + expect(a.encoding).to eq(Encoding::UTF_8) end it 'should read a string containing unicode characters from UTF-8 encoded buffer' do @@ -354,44 +357,44 @@ shared_examples_for 'a binary protocol' do buffer = [0x00, 0x00, 0x00, 0x03, 0xE2, 0x82, 0xAC].pack('C*') @trans.write(buffer) a = @prot.read_string - a.should == "\u20AC".encode('UTF-8') - a.encoding.should == Encoding::UTF_8 + expect(a).to eq("\u20AC".encode('UTF-8')) + expect(a.encoding).to eq(Encoding::UTF_8) end it 'should read a binary string' do buffer = [0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x02, 0x03].pack('C*') @trans.write(buffer) a = @prot.read_binary - a.should == [0x00, 0x01, 0x02, 0x03].pack('C*') - a.encoding.should == Encoding::BINARY + expect(a).to eq([0x00, 0x01, 0x02, 0x03].pack('C*')) + expect(a.encoding).to eq(Encoding::BINARY) end else it 'should read a string' do # i32 of value 3, followed by three characters/UTF-8 bytes 'a', 'b', 'c' buffer = [0x00, 0x00, 0x00, 0x03, 0x61, 0x62, 0x63].pack('C*') @trans.write(buffer) - @prot.read_string.should == 'abc' + expect(@prot.read_string).to eq('abc') end it 'should read a binary string' do buffer = [0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x02, 0x03].pack('C*') @trans.write(buffer) a = @prot.read_binary - a.should == [0x00, 0x01, 0x02, 0x03].pack('C*') + expect(a).to eq([0x00, 0x01, 0x02, 0x03].pack('C*')) end end it "should perform a complete rpc with no args or return" do srv_test( proc {|client| client.send_voidMethod()}, - proc {|client| client.recv_voidMethod.should == nil} + proc {|client| expect(client.recv_voidMethod).to eq(nil)} ) end it "should perform a complete rpc with a primitive return type" do srv_test( proc {|client| client.send_primitiveMethod()}, - proc {|client| client.recv_primitiveMethod.should == 1} + proc {|client| expect(client.recv_primitiveMethod).to eq(1)} ) end @@ -402,7 +405,7 @@ shared_examples_for 'a binary protocol' do result = client.recv_structMethod result.set_byte_map = nil result.map_byte_map = nil - result.should == Fixtures::COMPACT_PROTOCOL_TEST_STRUCT + expect(result).to eq(Fixtures::COMPACT_PROTOCOL_TEST_STRUCT) } ) end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/bytes_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/bytes_spec.rb index b82e304..2e8653c 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/bytes_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/bytes_spec.rb @@ -25,33 +25,33 @@ describe Thrift::Bytes do describe '.empty_byte_buffer' do it 'should create an empty buffer' do b = Thrift::Bytes.empty_byte_buffer - b.length.should == 0 - b.encoding.should == Encoding::BINARY + expect(b.length).to eq(0) + expect(b.encoding).to eq(Encoding::BINARY) end it 'should create an empty buffer of given size' do b = Thrift::Bytes.empty_byte_buffer 2 - b.length.should == 2 - b.getbyte(0).should == 0 - b.getbyte(1).should == 0 - b.encoding.should == Encoding::BINARY + expect(b.length).to eq(2) + expect(b.getbyte(0)).to eq(0) + expect(b.getbyte(1)).to eq(0) + expect(b.encoding).to eq(Encoding::BINARY) end end describe '.force_binary_encoding' do it 'should change encoding' do e = 'STRING'.encode('UTF-8') - e.encoding.should_not == Encoding::BINARY + expect(e.encoding).not_to eq(Encoding::BINARY) a = Thrift::Bytes.force_binary_encoding e - a.encoding.should == Encoding::BINARY + expect(a.encoding).to eq(Encoding::BINARY) end end describe '.get_string_byte' do it 'should get the byte at index' do s = "\x41\x42" - Thrift::Bytes.get_string_byte(s, 0).should == 0x41 - Thrift::Bytes.get_string_byte(s, 1).should == 0x42 + expect(Thrift::Bytes.get_string_byte(s, 0)).to eq(0x41) + expect(Thrift::Bytes.get_string_byte(s, 1)).to eq(0x42) end end @@ -59,42 +59,42 @@ describe Thrift::Bytes do it 'should set byte value at index' do s = "\x41\x42" Thrift::Bytes.set_string_byte(s, 0, 0x43) - s.getbyte(0).should == 0x43 - s.should == 'CB' + expect(s.getbyte(0)).to eq(0x43) + expect(s).to eq('CB') end end describe '.convert_to_utf8_byte_buffer' do it 'should convert UTF-8 String to byte buffer' do e = "\u20AC".encode('UTF-8') # a string with euro sign character U+20AC - e.length.should == 1 + expect(e.length).to eq(1) a = Thrift::Bytes.convert_to_utf8_byte_buffer e - a.encoding.should == Encoding::BINARY - a.length.should == 3 - a.unpack('C*').should == [0xE2, 0x82, 0xAC] + expect(a.encoding).to eq(Encoding::BINARY) + expect(a.length).to eq(3) + expect(a.unpack('C*')).to eq([0xE2, 0x82, 0xAC]) end it 'should convert ISO-8859-15 String to UTF-8 byte buffer' do # Assumptions e = "\u20AC".encode('ISO-8859-15') # a string with euro sign character U+20AC, then converted to ISO-8859-15 - e.length.should == 1 - e.unpack('C*').should == [0xA4] # euro sign is a different code point in ISO-8859-15 + expect(e.length).to eq(1) + expect(e.unpack('C*')).to eq([0xA4]) # euro sign is a different code point in ISO-8859-15 a = Thrift::Bytes.convert_to_utf8_byte_buffer e - a.encoding.should == Encoding::BINARY - a.length.should == 3 - a.unpack('C*').should == [0xE2, 0x82, 0xAC] + expect(a.encoding).to eq(Encoding::BINARY) + expect(a.length).to eq(3) + expect(a.unpack('C*')).to eq([0xE2, 0x82, 0xAC]) end end describe '.convert_to_string' do it 'should convert UTF-8 byte buffer to a UTF-8 String' do e = [0xE2, 0x82, 0xAC].pack("C*") - e.encoding.should == Encoding::BINARY + expect(e.encoding).to eq(Encoding::BINARY) a = Thrift::Bytes.convert_to_string e - a.encoding.should == Encoding::UTF_8 - a.should == "\u20AC" + expect(a.encoding).to eq(Encoding::UTF_8) + expect(a).to eq("\u20AC") end end @@ -102,14 +102,14 @@ describe Thrift::Bytes do describe '.empty_byte_buffer' do it 'should create an empty buffer' do b = Thrift::Bytes.empty_byte_buffer - b.length.should == 0 + expect(b.length).to eq(0) end it 'should create an empty buffer of given size' do b = Thrift::Bytes.empty_byte_buffer 2 - b.length.should == 2 - b[0].should == 0 - b[1].should == 0 + expect(b.length).to eq(2) + expect(b[0]).to eq(0) + expect(b[1]).to eq(0) end end @@ -117,16 +117,16 @@ describe Thrift::Bytes do it 'should be a no-op' do e = 'STRING' a = Thrift::Bytes.force_binary_encoding e - a.should == e - a.should be(e) + expect(a).to eq(e) + expect(a).to be(e) end end describe '.get_string_byte' do it 'should get the byte at index' do s = "\x41\x42" - Thrift::Bytes.get_string_byte(s, 0).should == 0x41 - Thrift::Bytes.get_string_byte(s, 1).should == 0x42 + expect(Thrift::Bytes.get_string_byte(s, 0)).to eq(0x41) + expect(Thrift::Bytes.get_string_byte(s, 1)).to eq(0x42) end end @@ -134,8 +134,8 @@ describe Thrift::Bytes do it 'should set byte value at index' do s = "\x41\x42" Thrift::Bytes.set_string_byte(s, 0, 0x43) - s[0].should == 0x43 - s.should == 'CB' + expect(s[0]).to eq(0x43) + expect(s).to eq('CB') end end @@ -143,8 +143,8 @@ describe Thrift::Bytes do it 'should be a no-op' do e = 'STRING' a = Thrift::Bytes.convert_to_utf8_byte_buffer e - a.should == e - a.should be(e) + expect(a).to eq(e) + expect(a).to be(e) end end @@ -152,8 +152,8 @@ describe Thrift::Bytes do it 'should be a no-op' do e = 'STRING' a = Thrift::Bytes.convert_to_string e - a.should == e - a.should be(e) + expect(a).to eq(e) + expect(a).to be(e) end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/client_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/client_spec.rb index f8ffe8a..d5d4cee 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/client_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/client_spec.rb @@ -26,74 +26,73 @@ describe 'Client' do end before(:each) do - @prot = mock("MockProtocol") + @prot = double("MockProtocol") @client = ClientSpec.new(@prot) end describe Thrift::Client do it "should re-use iprot for oprot if not otherwise specified" do - @client.instance_variable_get(:'@iprot').should eql(@prot) - @client.instance_variable_get(:'@oprot').should eql(@prot) + expect(@client.instance_variable_get(:'@iprot')).to eql(@prot) + expect(@client.instance_variable_get(:'@oprot')).to eql(@prot) end it "should send a test message" do - @prot.should_receive(:write_message_begin).with('testMessage', Thrift::MessageTypes::CALL, 0) - mock_args = mock('#') - mock_args.should_receive(:foo=).with('foo') - mock_args.should_receive(:bar=).with(42) - mock_args.should_receive(:write).with(@prot) - @prot.should_receive(:write_message_end) - @prot.should_receive(:trans) do - mock('trans').tap do |trans| - trans.should_receive(:flush) + expect(@prot).to receive(:write_message_begin).with('testMessage', Thrift::MessageTypes::CALL, 0) + mock_args = double('#') + expect(mock_args).to receive(:foo=).with('foo') + expect(mock_args).to receive(:bar=).with(42) + expect(mock_args).to receive(:write).with(@prot) + expect(@prot).to receive(:write_message_end) + expect(@prot).to receive(:trans) do + double('trans').tap do |trans| + expect(trans).to receive(:flush) end end - klass = stub("TestMessage_args", :new => mock_args) + klass = double("TestMessage_args", :new => mock_args) @client.send_message('testMessage', klass, :foo => 'foo', :bar => 42) end it "should increment the sequence id when sending messages" do - pending "it seems sequence ids are completely ignored right now" do - @prot.should_receive(:write_message_begin).with('testMessage', Thrift::MessageTypes::CALL, 0).ordered - @prot.should_receive(:write_message_begin).with('testMessage2', Thrift::MessageTypes::CALL, 1).ordered - @prot.should_receive(:write_message_begin).with('testMessage3', Thrift::MessageTypes::CALL, 2).ordered - @prot.stub!(:write_message_end) - @prot.stub!(:trans).and_return mock("trans").as_null_object - @client.send_message('testMessage', mock("args class").as_null_object) - @client.send_message('testMessage2', mock("args class").as_null_object) - @client.send_message('testMessage3', mock("args class").as_null_object) - end + pending "it seems sequence ids are completely ignored right now" + @prot.expect(:write_message_begin).with('testMessage', Thrift::MessageTypes::CALL, 0).ordered + @prot.expect(:write_message_begin).with('testMessage2', Thrift::MessageTypes::CALL, 1).ordered + @prot.expect(:write_message_begin).with('testMessage3', Thrift::MessageTypes::CALL, 2).ordered + @prot.stub!(:write_message_end) + @prot.stub!(:trans).and_return double("trans").as_null_object + @client.send_message('testMessage', double("args class").as_null_object) + @client.send_message('testMessage2', double("args class").as_null_object) + @client.send_message('testMessage3', double("args class").as_null_object) end it "should receive a test message" do - @prot.should_receive(:read_message_begin).and_return [nil, Thrift::MessageTypes::CALL, 0] - @prot.should_receive(:read_message_end) - mock_klass = mock("#") - mock_klass.should_receive(:read).with(@prot) - @client.receive_message(stub("MockClass", :new => mock_klass)) + expect(@prot).to receive(:read_message_begin).and_return [nil, Thrift::MessageTypes::CALL, 0] + expect(@prot).to receive(:read_message_end) + mock_klass = double("#") + expect(mock_klass).to receive(:read).with(@prot) + @client.receive_message(double("MockClass", :new => mock_klass)) end it "should handle received exceptions" do - @prot.should_receive(:read_message_begin).and_return [nil, Thrift::MessageTypes::EXCEPTION, 0] - @prot.should_receive(:read_message_end) - Thrift::ApplicationException.should_receive(:new).and_return do + expect(@prot).to receive(:read_message_begin).and_return [nil, Thrift::MessageTypes::EXCEPTION, 0] + expect(@prot).to receive(:read_message_end) + expect(Thrift::ApplicationException).to receive(:new) do StandardError.new.tap do |mock_exc| - mock_exc.should_receive(:read).with(@prot) + expect(mock_exc).to receive(:read).with(@prot) end end - lambda { @client.receive_message(nil) }.should raise_error(StandardError) + expect { @client.receive_message(nil) }.to raise_error(StandardError) end it "should close the transport if an error occurs while sending a message" do - @prot.stub!(:write_message_begin) - @prot.should_not_receive(:write_message_end) - mock_args = mock("#") - mock_args.should_receive(:write).with(@prot).and_raise(StandardError) - trans = mock("MockTransport") - @prot.stub!(:trans).and_return(trans) - trans.should_receive(:close) - klass = mock("TestMessage_args", :new => mock_args) - lambda { @client.send_message("testMessage", klass) }.should raise_error(StandardError) + allow(@prot).to receive(:write_message_begin) + expect(@prot).not_to receive(:write_message_end) + mock_args = double("#") + expect(mock_args).to receive(:write).with(@prot).and_raise(StandardError) + trans = double("MockTransport") + allow(@prot).to receive(:trans).and_return(trans) + expect(trans).to receive(:close) + klass = double("TestMessage_args", :new => mock_args) + expect { @client.send_message("testMessage", klass) }.to raise_error(StandardError) end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/compact_protocol_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/compact_protocol_spec.rb index 8a1a228..513dd69 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/compact_protocol_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/compact_protocol_spec.rb @@ -42,7 +42,7 @@ describe Thrift::CompactProtocol do proto.send(writer(primitive_type), value) # puts "buf: #{trans.inspect_buffer}" if primitive_type == :i64 read_back = proto.send(reader(primitive_type)) - read_back.should == value + expect(read_back).to eq(value) end end end @@ -62,10 +62,10 @@ describe Thrift::CompactProtocol do proto = Thrift::CompactProtocol.new(trans) name, type, id = proto.read_field_begin - type.should == thrift_type - id.should == 15 + expect(type).to eq(thrift_type) + expect(id).to eq(15) read_back = proto.send(reader(primitive_type)) - read_back.should == value + expect(read_back).to eq(value) proto.read_field_end end end @@ -81,7 +81,7 @@ describe Thrift::CompactProtocol do struct2 = Thrift::Test::CompactProtoTestStruct.new struct2.read(proto) - struct2.should == struct + expect(struct2).to eq(struct) end it "should make method calls correctly" do @@ -97,7 +97,7 @@ describe Thrift::CompactProtocol do client.send_Janky(1) # puts client_out_trans.inspect_buffer processor.process(client_out_proto, client_in_proto) - client.recv_Janky.should == 2 + expect(client.recv_Janky).to eq(2) end it "should deal with fields following fields that have non-delta ids" do @@ -113,7 +113,7 @@ describe Thrift::CompactProtocol do deser = Thrift::Deserializer.new(Thrift::CompactProtocolFactory.new) brcp2 = Thrift::Test::BreaksRubyCompactProtocol.new deser.deserialize(brcp2, bytes) - brcp2.should == brcp + expect(brcp2).to eq(brcp) end it "should deserialize an empty map to an empty hash" do @@ -124,7 +124,12 @@ describe Thrift::CompactProtocol do deser = Thrift::Deserializer.new(Thrift::CompactProtocolFactory.new) struct2 = Thrift::Test::SingleMapTestStruct.new deser.deserialize(struct2, bytes) - struct.should == struct2 + expect(struct).to eq(struct2) + end + + it "should provide a reasonable to_s" do + trans = Thrift::MemoryBufferTransport.new + expect(Thrift::CompactProtocol.new(trans).to_s).to eq("compact(memory)") end class JankyHandler @@ -141,3 +146,13 @@ describe Thrift::CompactProtocol do "read_#{sym.to_s}" end end + +describe Thrift::CompactProtocolFactory do + it "should create a CompactProtocol" do + expect(Thrift::CompactProtocolFactory.new.get_protocol(double("MockTransport"))).to be_instance_of(Thrift::CompactProtocol) + end + + it "should provide a reasonable to_s" do + expect(Thrift::CompactProtocolFactory.new.to_s).to eq("compact") + end +end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/exception_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/exception_spec.rb index d1da621..379ae69 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/exception_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/exception_spec.rb @@ -24,107 +24,107 @@ describe 'Exception' do describe Thrift::Exception do it "should have an accessible message" do e = Thrift::Exception.new("test message") - e.message.should == "test message" + expect(e.message).to eq("test message") end end describe Thrift::ApplicationException do it "should inherit from Thrift::Exception" do - Thrift::ApplicationException.superclass.should == Thrift::Exception + expect(Thrift::ApplicationException.superclass).to eq(Thrift::Exception) end it "should have an accessible type and message" do e = Thrift::ApplicationException.new - e.type.should == Thrift::ApplicationException::UNKNOWN - e.message.should be_nil + expect(e.type).to eq(Thrift::ApplicationException::UNKNOWN) + expect(e.message).to be_nil e = Thrift::ApplicationException.new(Thrift::ApplicationException::UNKNOWN_METHOD, "test message") - e.type.should == Thrift::ApplicationException::UNKNOWN_METHOD - e.message.should == "test message" + expect(e.type).to eq(Thrift::ApplicationException::UNKNOWN_METHOD) + expect(e.message).to eq("test message") end it "should read a struct off of a protocol" do - prot = mock("MockProtocol") - prot.should_receive(:read_struct_begin).ordered - prot.should_receive(:read_field_begin).exactly(3).times.and_return( + prot = double("MockProtocol") + expect(prot).to receive(:read_struct_begin).ordered + expect(prot).to receive(:read_field_begin).exactly(3).times.and_return( ["message", Thrift::Types::STRING, 1], ["type", Thrift::Types::I32, 2], [nil, Thrift::Types::STOP, 0] ) - prot.should_receive(:read_string).ordered.and_return "test message" - prot.should_receive(:read_i32).ordered.and_return Thrift::ApplicationException::BAD_SEQUENCE_ID - prot.should_receive(:read_field_end).exactly(2).times - prot.should_receive(:read_struct_end).ordered + expect(prot).to receive(:read_string).ordered.and_return "test message" + expect(prot).to receive(:read_i32).ordered.and_return Thrift::ApplicationException::BAD_SEQUENCE_ID + expect(prot).to receive(:read_field_end).exactly(2).times + expect(prot).to receive(:read_struct_end).ordered e = Thrift::ApplicationException.new e.read(prot) - e.message.should == "test message" - e.type.should == Thrift::ApplicationException::BAD_SEQUENCE_ID + expect(e.message).to eq("test message") + expect(e.type).to eq(Thrift::ApplicationException::BAD_SEQUENCE_ID) end it "should skip bad fields when reading a struct" do - prot = mock("MockProtocol") - prot.should_receive(:read_struct_begin).ordered - prot.should_receive(:read_field_begin).exactly(5).times.and_return( + prot = double("MockProtocol") + expect(prot).to receive(:read_struct_begin).ordered + expect(prot).to receive(:read_field_begin).exactly(5).times.and_return( ["type", Thrift::Types::I32, 2], ["type", Thrift::Types::STRING, 2], ["message", Thrift::Types::MAP, 1], ["message", Thrift::Types::STRING, 3], [nil, Thrift::Types::STOP, 0] ) - prot.should_receive(:read_i32).and_return Thrift::ApplicationException::INVALID_MESSAGE_TYPE - prot.should_receive(:skip).with(Thrift::Types::STRING).twice - prot.should_receive(:skip).with(Thrift::Types::MAP) - prot.should_receive(:read_field_end).exactly(4).times - prot.should_receive(:read_struct_end).ordered + expect(prot).to receive(:read_i32).and_return Thrift::ApplicationException::INVALID_MESSAGE_TYPE + expect(prot).to receive(:skip).with(Thrift::Types::STRING).twice + expect(prot).to receive(:skip).with(Thrift::Types::MAP) + expect(prot).to receive(:read_field_end).exactly(4).times + expect(prot).to receive(:read_struct_end).ordered e = Thrift::ApplicationException.new e.read(prot) - e.message.should be_nil - e.type.should == Thrift::ApplicationException::INVALID_MESSAGE_TYPE + expect(e.message).to be_nil + expect(e.type).to eq(Thrift::ApplicationException::INVALID_MESSAGE_TYPE) end it "should write a Thrift::ApplicationException struct to the oprot" do - prot = mock("MockProtocol") - prot.should_receive(:write_struct_begin).with("Thrift::ApplicationException").ordered - prot.should_receive(:write_field_begin).with("message", Thrift::Types::STRING, 1).ordered - prot.should_receive(:write_string).with("test message").ordered - prot.should_receive(:write_field_begin).with("type", Thrift::Types::I32, 2).ordered - prot.should_receive(:write_i32).with(Thrift::ApplicationException::UNKNOWN_METHOD).ordered - prot.should_receive(:write_field_end).twice - prot.should_receive(:write_field_stop).ordered - prot.should_receive(:write_struct_end).ordered + prot = double("MockProtocol") + expect(prot).to receive(:write_struct_begin).with("Thrift::ApplicationException").ordered + expect(prot).to receive(:write_field_begin).with("message", Thrift::Types::STRING, 1).ordered + expect(prot).to receive(:write_string).with("test message").ordered + expect(prot).to receive(:write_field_begin).with("type", Thrift::Types::I32, 2).ordered + expect(prot).to receive(:write_i32).with(Thrift::ApplicationException::UNKNOWN_METHOD).ordered + expect(prot).to receive(:write_field_end).twice + expect(prot).to receive(:write_field_stop).ordered + expect(prot).to receive(:write_struct_end).ordered e = Thrift::ApplicationException.new(Thrift::ApplicationException::UNKNOWN_METHOD, "test message") e.write(prot) end it "should skip nil fields when writing to the oprot" do - prot = mock("MockProtocol") - prot.should_receive(:write_struct_begin).with("Thrift::ApplicationException").ordered - prot.should_receive(:write_field_begin).with("message", Thrift::Types::STRING, 1).ordered - prot.should_receive(:write_string).with("test message").ordered - prot.should_receive(:write_field_end).ordered - prot.should_receive(:write_field_stop).ordered - prot.should_receive(:write_struct_end).ordered + prot = double("MockProtocol") + expect(prot).to receive(:write_struct_begin).with("Thrift::ApplicationException").ordered + expect(prot).to receive(:write_field_begin).with("message", Thrift::Types::STRING, 1).ordered + expect(prot).to receive(:write_string).with("test message").ordered + expect(prot).to receive(:write_field_end).ordered + expect(prot).to receive(:write_field_stop).ordered + expect(prot).to receive(:write_struct_end).ordered e = Thrift::ApplicationException.new(nil, "test message") e.write(prot) - prot = mock("MockProtocol") - prot.should_receive(:write_struct_begin).with("Thrift::ApplicationException").ordered - prot.should_receive(:write_field_begin).with("type", Thrift::Types::I32, 2).ordered - prot.should_receive(:write_i32).with(Thrift::ApplicationException::BAD_SEQUENCE_ID).ordered - prot.should_receive(:write_field_end).ordered - prot.should_receive(:write_field_stop).ordered - prot.should_receive(:write_struct_end).ordered + prot = double("MockProtocol") + expect(prot).to receive(:write_struct_begin).with("Thrift::ApplicationException").ordered + expect(prot).to receive(:write_field_begin).with("type", Thrift::Types::I32, 2).ordered + expect(prot).to receive(:write_i32).with(Thrift::ApplicationException::BAD_SEQUENCE_ID).ordered + expect(prot).to receive(:write_field_end).ordered + expect(prot).to receive(:write_field_stop).ordered + expect(prot).to receive(:write_struct_end).ordered e = Thrift::ApplicationException.new(Thrift::ApplicationException::BAD_SEQUENCE_ID) e.write(prot) - prot = mock("MockProtocol") - prot.should_receive(:write_struct_begin).with("Thrift::ApplicationException").ordered - prot.should_receive(:write_field_stop).ordered - prot.should_receive(:write_struct_end).ordered + prot = double("MockProtocol") + expect(prot).to receive(:write_struct_begin).with("Thrift::ApplicationException").ordered + expect(prot).to receive(:write_field_stop).ordered + expect(prot).to receive(:write_struct_end).ordered e = Thrift::ApplicationException.new(nil) e.write(prot) @@ -134,8 +134,8 @@ describe 'Exception' do describe Thrift::ProtocolException do it "should have an accessible type" do prot = Thrift::ProtocolException.new(Thrift::ProtocolException::SIZE_LIMIT, "message") - prot.type.should == Thrift::ProtocolException::SIZE_LIMIT - prot.message.should == "message" + expect(prot.type).to eq(Thrift::ProtocolException::SIZE_LIMIT) + expect(prot.message).to eq("message") end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/flat_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/flat_spec.rb index f378782..893056c 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/flat_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/flat_spec.rb @@ -32,7 +32,7 @@ describe 'generation' do "other_namespace/referenced_constants.rb", "other_namespace/referenced_types.rb" ].each do |name| - File.exist?(File.join(prefix, name)).should_not be_true + expect(File.exist?(File.join(prefix, name))).not_to be_truthy end end @@ -44,19 +44,19 @@ describe 'generation' do "referenced_constants.rb", "referenced_types.rb" ].each do |name| - File.exist?(File.join(prefix, name)).should be_true + expect(File.exist?(File.join(prefix, name))).to be_truthy end end it "has a service class in the right place" do - defined?(NamespacedSpecNamespace::NamespacedNonblockingService).should be_true + expect(defined?(NamespacedSpecNamespace::NamespacedNonblockingService)).to be_truthy end it "has a struct in the right place" do - defined?(NamespacedSpecNamespace::Hello).should be_true + expect(defined?(NamespacedSpecNamespace::Hello)).to be_truthy end it "required an included file" do - defined?(OtherNamespace::SomeEnum).should be_true + expect(defined?(OtherNamespace::SomeEnum)).to be_truthy end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/http_client_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/http_client_spec.rb index 5e8da24..df472ab 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/http_client_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/http_client_spec.rb @@ -25,28 +25,32 @@ describe 'Thrift::HTTPClientTransport' do before(:each) do @client = Thrift::HTTPClientTransport.new("http://my.domain.com/path/to/service?param=value") end + + it "should provide a reasonable to_s" do + @client.to_s == "http://my.domain.com/path/to/service?param=value" + end it "should always be open" do - @client.should be_open + expect(@client).to be_open @client.close - @client.should be_open + expect(@client).to be_open end it "should post via HTTP and return the results" do @client.write "a test" @client.write " frame" - Net::HTTP.should_receive(:new).with("my.domain.com", 80).and_return do - mock("Net::HTTP").tap do |http| - http.should_receive(:use_ssl=).with(false) - http.should_receive(:post).with("/path/to/service?param=value", "a test frame", {"Content-Type"=>"application/x-thrift"}).and_return do - mock("Net::HTTPOK").tap do |response| - response.should_receive(:body).and_return "data" + expect(Net::HTTP).to receive(:new).with("my.domain.com", 80) do + double("Net::HTTP").tap do |http| + expect(http).to receive(:use_ssl=).with(false) + expect(http).to receive(:post).with("/path/to/service?param=value", "a test frame", {"Content-Type"=>"application/x-thrift"}) do + double("Net::HTTPOK").tap do |response| + expect(response).to receive(:body).and_return "data" end end end end @client.flush - @client.read(10).should == "data" + expect(@client.read(10)).to eq("data") end it "should send custom headers if defined" do @@ -55,12 +59,12 @@ describe 'Thrift::HTTPClientTransport' do headers = {"Content-Type"=>"application/x-thrift"}.merge(custom_headers) @client.add_headers(custom_headers) - Net::HTTP.should_receive(:new).with("my.domain.com", 80).and_return do - mock("Net::HTTP").tap do |http| - http.should_receive(:use_ssl=).with(false) - http.should_receive(:post).with("/path/to/service?param=value", "test", headers).and_return do - mock("Net::HTTPOK").tap do |response| - response.should_receive(:body).and_return "data" + expect(Net::HTTP).to receive(:new).with("my.domain.com", 80) do + double("Net::HTTP").tap do |http| + expect(http).to receive(:use_ssl=).with(false) + expect(http).to receive(:post).with("/path/to/service?param=value", "test", headers) do + double("Net::HTTPOK").tap do |response| + expect(response).to receive(:body).and_return "data" end end end @@ -71,15 +75,15 @@ describe 'Thrift::HTTPClientTransport' do it 'should reset the outbuf on HTTP failures' do @client.write "test" - Net::HTTP.should_receive(:new).with("my.domain.com", 80).and_return do - mock("Net::HTTP").tap do |http| - http.should_receive(:use_ssl=).with(false) - http.should_receive(:post).with("/path/to/service?param=value", "test", {"Content-Type"=>"application/x-thrift"}) { raise Net::ReadTimeout } + expect(Net::HTTP).to receive(:new).with("my.domain.com", 80) do + double("Net::HTTP").tap do |http| + expect(http).to receive(:use_ssl=).with(false) + expect(http).to receive(:post).with("/path/to/service?param=value", "test", {"Content-Type"=>"application/x-thrift"}) { raise Net::ReadTimeout } end end @client.flush rescue - @client.instance_variable_get(:@outbuf).should eq(Thrift::Bytes.empty_byte_buffer) + expect(@client.instance_variable_get(:@outbuf)).to eq(Thrift::Bytes.empty_byte_buffer) end end @@ -95,20 +99,20 @@ describe 'Thrift::HTTPClientTransport' do client.write "test" - Net::HTTP.should_receive(:new).with("my.domain.com", 443).and_return do - mock("Net::HTTP").tap do |http| - http.should_receive(:use_ssl=).with(true) - http.should_receive(:verify_mode=).with(OpenSSL::SSL::VERIFY_PEER) - http.should_receive(:post).with(@service_path, "test", - "Content-Type" => "application/x-thrift").and_return do - mock("Net::HTTPOK").tap do |response| - response.should_receive(:body).and_return "data" + expect(Net::HTTP).to receive(:new).with("my.domain.com", 443) do + double("Net::HTTP").tap do |http| + expect(http).to receive(:use_ssl=).with(true) + expect(http).to receive(:verify_mode=).with(OpenSSL::SSL::VERIFY_PEER) + expect(http).to receive(:post).with(@service_path, "test", + "Content-Type" => "application/x-thrift") do + double("Net::HTTPOK").tap do |response| + expect(response).to receive(:body).and_return "data" end end end end client.flush - client.read(4).should == "data" + expect(client.read(4)).to eq("data") end it "should set SSL verify mode when specified" do @@ -116,20 +120,20 @@ describe 'Thrift::HTTPClientTransport' do :ssl_verify_mode => OpenSSL::SSL::VERIFY_NONE) client.write "test" - Net::HTTP.should_receive(:new).with("my.domain.com", 443).and_return do - mock("Net::HTTP").tap do |http| - http.should_receive(:use_ssl=).with(true) - http.should_receive(:verify_mode=).with(OpenSSL::SSL::VERIFY_NONE) - http.should_receive(:post).with(@service_path, "test", - "Content-Type" => "application/x-thrift").and_return do - mock("Net::HTTPOK").tap do |response| - response.should_receive(:body).and_return "data" + expect(Net::HTTP).to receive(:new).with("my.domain.com", 443) do + double("Net::HTTP").tap do |http| + expect(http).to receive(:use_ssl=).with(true) + expect(http).to receive(:verify_mode=).with(OpenSSL::SSL::VERIFY_NONE) + expect(http).to receive(:post).with(@service_path, "test", + "Content-Type" => "application/x-thrift") do + double("Net::HTTPOK").tap do |response| + expect(response).to receive(:body).and_return "data" end end end end client.flush - client.read(4).should == "data" + expect(client.read(4)).to eq("data") end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/json_protocol_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/json_protocol_spec.rb index b6b46bf..fe1af7b 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/json_protocol_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/json_protocol_spec.rb @@ -30,257 +30,257 @@ describe 'JsonProtocol' do it "should write json escaped char" do @prot.write_json_escape_char("\n") - @trans.read(@trans.available).should == '\u000a' + expect(@trans.read(@trans.available)).to eq('\u000a') @prot.write_json_escape_char(" ") - @trans.read(@trans.available).should == '\u0020' + expect(@trans.read(@trans.available)).to eq('\u0020') end it "should write json char" do @prot.write_json_char("\n") - @trans.read(@trans.available).should == '\\n' + expect(@trans.read(@trans.available)).to eq('\\n') @prot.write_json_char(" ") - @trans.read(@trans.available).should == ' ' + expect(@trans.read(@trans.available)).to eq(' ') @prot.write_json_char("\\") - @trans.read(@trans.available).should == "\\\\" + expect(@trans.read(@trans.available)).to eq("\\\\") @prot.write_json_char("@") - @trans.read(@trans.available).should == '@' + expect(@trans.read(@trans.available)).to eq('@') end it "should write json string" do @prot.write_json_string("this is a \\ json\nstring") - @trans.read(@trans.available).should == "\"this is a \\\\ json\\nstring\"" + expect(@trans.read(@trans.available)).to eq("\"this is a \\\\ json\\nstring\"") end it "should write json base64" do @prot.write_json_base64("this is a base64 string") - @trans.read(@trans.available).should == "\"dGhpcyBpcyBhIGJhc2U2NCBzdHJpbmc=\"" + expect(@trans.read(@trans.available)).to eq("\"dGhpcyBpcyBhIGJhc2U2NCBzdHJpbmc=\"") end it "should write json integer" do @prot.write_json_integer(45) - @trans.read(@trans.available).should == "45" + expect(@trans.read(@trans.available)).to eq("45") @prot.write_json_integer(33000) - @trans.read(@trans.available).should == "33000" + expect(@trans.read(@trans.available)).to eq("33000") @prot.write_json_integer(3000000000) - @trans.read(@trans.available).should == "3000000000" + expect(@trans.read(@trans.available)).to eq("3000000000") @prot.write_json_integer(6000000000) - @trans.read(@trans.available).should == "6000000000" + expect(@trans.read(@trans.available)).to eq("6000000000") end it "should write json double" do @prot.write_json_double(12.3) - @trans.read(@trans.available).should == "12.3" + expect(@trans.read(@trans.available)).to eq("12.3") @prot.write_json_double(-3.21) - @trans.read(@trans.available).should == "-3.21" + expect(@trans.read(@trans.available)).to eq("-3.21") @prot.write_json_double(((+1.0/0.0)/(+1.0/0.0))) - @trans.read(@trans.available).should == "\"NaN\"" + expect(@trans.read(@trans.available)).to eq("\"NaN\"") @prot.write_json_double((+1.0/0.0)) - @trans.read(@trans.available).should == "\"Infinity\"" + expect(@trans.read(@trans.available)).to eq("\"Infinity\"") @prot.write_json_double((-1.0/0.0)) - @trans.read(@trans.available).should == "\"-Infinity\"" + expect(@trans.read(@trans.available)).to eq("\"-Infinity\"") end it "should write json object start" do @prot.write_json_object_start - @trans.read(@trans.available).should == "{" + expect(@trans.read(@trans.available)).to eq("{") end it "should write json object end" do @prot.write_json_object_end - @trans.read(@trans.available).should == "}" + expect(@trans.read(@trans.available)).to eq("}") end it "should write json array start" do @prot.write_json_array_start - @trans.read(@trans.available).should == "[" + expect(@trans.read(@trans.available)).to eq("[") end it "should write json array end" do @prot.write_json_array_end - @trans.read(@trans.available).should == "]" + expect(@trans.read(@trans.available)).to eq("]") end it "should write message begin" do @prot.write_message_begin("name", 12, 32) - @trans.read(@trans.available).should == "[1,\"name\",12,32" + expect(@trans.read(@trans.available)).to eq("[1,\"name\",12,32") end it "should write message end" do @prot.write_message_end - @trans.read(@trans.available).should == "]" + expect(@trans.read(@trans.available)).to eq("]") end it "should write struct begin" do @prot.write_struct_begin("name") - @trans.read(@trans.available).should == "{" + expect(@trans.read(@trans.available)).to eq("{") end it "should write struct end" do @prot.write_struct_end - @trans.read(@trans.available).should == "}" + expect(@trans.read(@trans.available)).to eq("}") end it "should write field begin" do @prot.write_field_begin("name", Thrift::Types::STRUCT, 32) - @trans.read(@trans.available).should == "32{\"rec\"" + expect(@trans.read(@trans.available)).to eq("32{\"rec\"") end it "should write field end" do @prot.write_field_end - @trans.read(@trans.available).should == "}" + expect(@trans.read(@trans.available)).to eq("}") end it "should write field stop" do @prot.write_field_stop - @trans.read(@trans.available).should == "" + expect(@trans.read(@trans.available)).to eq("") end it "should write map begin" do @prot.write_map_begin(Thrift::Types::STRUCT, Thrift::Types::LIST, 32) - @trans.read(@trans.available).should == "[\"rec\",\"lst\",32,{" + expect(@trans.read(@trans.available)).to eq("[\"rec\",\"lst\",32,{") end it "should write map end" do @prot.write_map_end - @trans.read(@trans.available).should == "}]" + expect(@trans.read(@trans.available)).to eq("}]") end it "should write list begin" do @prot.write_list_begin(Thrift::Types::STRUCT, 32) - @trans.read(@trans.available).should == "[\"rec\",32" + expect(@trans.read(@trans.available)).to eq("[\"rec\",32") end it "should write list end" do @prot.write_list_end - @trans.read(@trans.available).should == "]" + expect(@trans.read(@trans.available)).to eq("]") end it "should write set begin" do @prot.write_set_begin(Thrift::Types::STRUCT, 32) - @trans.read(@trans.available).should == "[\"rec\",32" + expect(@trans.read(@trans.available)).to eq("[\"rec\",32") end it "should write set end" do @prot.write_set_end - @trans.read(@trans.available).should == "]" + expect(@trans.read(@trans.available)).to eq("]") end it "should write bool" do @prot.write_bool(true) - @trans.read(@trans.available).should == "1" + expect(@trans.read(@trans.available)).to eq("1") @prot.write_bool(false) - @trans.read(@trans.available).should == "0" + expect(@trans.read(@trans.available)).to eq("0") end it "should write byte" do @prot.write_byte(100) - @trans.read(@trans.available).should == "100" + expect(@trans.read(@trans.available)).to eq("100") end it "should write i16" do @prot.write_i16(1000) - @trans.read(@trans.available).should == "1000" + expect(@trans.read(@trans.available)).to eq("1000") end it "should write i32" do @prot.write_i32(3000000000) - @trans.read(@trans.available).should == "3000000000" + expect(@trans.read(@trans.available)).to eq("3000000000") end it "should write i64" do @prot.write_i64(6000000000) - @trans.read(@trans.available).should == "6000000000" + expect(@trans.read(@trans.available)).to eq("6000000000") end it "should write double" do @prot.write_double(1.23) - @trans.read(@trans.available).should == "1.23" + expect(@trans.read(@trans.available)).to eq("1.23") @prot.write_double(-32.1) - @trans.read(@trans.available).should == "-32.1" + expect(@trans.read(@trans.available)).to eq("-32.1") @prot.write_double(((+1.0/0.0)/(+1.0/0.0))) - @trans.read(@trans.available).should == "\"NaN\"" + expect(@trans.read(@trans.available)).to eq("\"NaN\"") @prot.write_double((+1.0/0.0)) - @trans.read(@trans.available).should == "\"Infinity\"" + expect(@trans.read(@trans.available)).to eq("\"Infinity\"") @prot.write_double((-1.0/0.0)) - @trans.read(@trans.available).should == "\"-Infinity\"" + expect(@trans.read(@trans.available)).to eq("\"-Infinity\"") end if RUBY_VERSION >= '1.9' it 'should write string' do @prot.write_string('this is a test string') a = @trans.read(@trans.available) - a.should == '"this is a test string"'.force_encoding(Encoding::BINARY) - a.encoding.should == Encoding::BINARY + expect(a).to eq('"this is a test string"'.force_encoding(Encoding::BINARY)) + expect(a.encoding).to eq(Encoding::BINARY) end it 'should write string with unicode characters' do @prot.write_string("this is a test string with unicode characters: \u20AC \u20AD") a = @trans.read(@trans.available) - a.should == "\"this is a test string with unicode characters: \u20AC \u20AD\"".force_encoding(Encoding::BINARY) - a.encoding.should == Encoding::BINARY + expect(a).to eq("\"this is a test string with unicode characters: \u20AC \u20AD\"".force_encoding(Encoding::BINARY)) + expect(a.encoding).to eq(Encoding::BINARY) end else it 'should write string' do @prot.write_string('this is a test string') - @trans.read(@trans.available).should == '"this is a test string"' + expect(@trans.read(@trans.available)).to eq('"this is a test string"') end end it "should write binary" do @prot.write_binary("this is a base64 string") - @trans.read(@trans.available).should == "\"dGhpcyBpcyBhIGJhc2U2NCBzdHJpbmc=\"" + expect(@trans.read(@trans.available)).to eq("\"dGhpcyBpcyBhIGJhc2U2NCBzdHJpbmc=\"") end it "should write long binary" do @prot.write_binary((0...256).to_a.pack('C*')) - @trans.read(@trans.available).should == "\"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==\"" + expect(@trans.read(@trans.available)).to eq("\"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==\"") end it "should get type name for type id" do expect {@prot.get_type_name_for_type_id(Thrift::Types::STOP)}.to raise_error(NotImplementedError) expect {@prot.get_type_name_for_type_id(Thrift::Types::VOID)}.to raise_error(NotImplementedError) - @prot.get_type_name_for_type_id(Thrift::Types::BOOL).should == "tf" - @prot.get_type_name_for_type_id(Thrift::Types::BYTE).should == "i8" - @prot.get_type_name_for_type_id(Thrift::Types::DOUBLE).should == "dbl" - @prot.get_type_name_for_type_id(Thrift::Types::I16).should == "i16" - @prot.get_type_name_for_type_id(Thrift::Types::I32).should == "i32" - @prot.get_type_name_for_type_id(Thrift::Types::I64).should == "i64" - @prot.get_type_name_for_type_id(Thrift::Types::STRING).should == "str" - @prot.get_type_name_for_type_id(Thrift::Types::STRUCT).should == "rec" - @prot.get_type_name_for_type_id(Thrift::Types::MAP).should == "map" - @prot.get_type_name_for_type_id(Thrift::Types::SET).should == "set" - @prot.get_type_name_for_type_id(Thrift::Types::LIST).should == "lst" + expect(@prot.get_type_name_for_type_id(Thrift::Types::BOOL)).to eq("tf") + expect(@prot.get_type_name_for_type_id(Thrift::Types::BYTE)).to eq("i8") + expect(@prot.get_type_name_for_type_id(Thrift::Types::DOUBLE)).to eq("dbl") + expect(@prot.get_type_name_for_type_id(Thrift::Types::I16)).to eq("i16") + expect(@prot.get_type_name_for_type_id(Thrift::Types::I32)).to eq("i32") + expect(@prot.get_type_name_for_type_id(Thrift::Types::I64)).to eq("i64") + expect(@prot.get_type_name_for_type_id(Thrift::Types::STRING)).to eq("str") + expect(@prot.get_type_name_for_type_id(Thrift::Types::STRUCT)).to eq("rec") + expect(@prot.get_type_name_for_type_id(Thrift::Types::MAP)).to eq("map") + expect(@prot.get_type_name_for_type_id(Thrift::Types::SET)).to eq("set") + expect(@prot.get_type_name_for_type_id(Thrift::Types::LIST)).to eq("lst") end it "should get type id for type name" do expect {@prot.get_type_id_for_type_name("pp")}.to raise_error(NotImplementedError) - @prot.get_type_id_for_type_name("tf").should == Thrift::Types::BOOL - @prot.get_type_id_for_type_name("i8").should == Thrift::Types::BYTE - @prot.get_type_id_for_type_name("dbl").should == Thrift::Types::DOUBLE - @prot.get_type_id_for_type_name("i16").should == Thrift::Types::I16 - @prot.get_type_id_for_type_name("i32").should == Thrift::Types::I32 - @prot.get_type_id_for_type_name("i64").should == Thrift::Types::I64 - @prot.get_type_id_for_type_name("str").should == Thrift::Types::STRING - @prot.get_type_id_for_type_name("rec").should == Thrift::Types::STRUCT - @prot.get_type_id_for_type_name("map").should == Thrift::Types::MAP - @prot.get_type_id_for_type_name("set").should == Thrift::Types::SET - @prot.get_type_id_for_type_name("lst").should == Thrift::Types::LIST + expect(@prot.get_type_id_for_type_name("tf")).to eq(Thrift::Types::BOOL) + expect(@prot.get_type_id_for_type_name("i8")).to eq(Thrift::Types::BYTE) + expect(@prot.get_type_id_for_type_name("dbl")).to eq(Thrift::Types::DOUBLE) + expect(@prot.get_type_id_for_type_name("i16")).to eq(Thrift::Types::I16) + expect(@prot.get_type_id_for_type_name("i32")).to eq(Thrift::Types::I32) + expect(@prot.get_type_id_for_type_name("i64")).to eq(Thrift::Types::I64) + expect(@prot.get_type_id_for_type_name("str")).to eq(Thrift::Types::STRING) + expect(@prot.get_type_id_for_type_name("rec")).to eq(Thrift::Types::STRUCT) + expect(@prot.get_type_id_for_type_name("map")).to eq(Thrift::Types::MAP) + expect(@prot.get_type_id_for_type_name("set")).to eq(Thrift::Types::SET) + expect(@prot.get_type_id_for_type_name("lst")).to eq(Thrift::Types::LIST) end it "should read json syntax char" do @@ -292,31 +292,31 @@ describe 'JsonProtocol' do it "should read json escape char" do @trans.write('0054') - @prot.read_json_escape_char.should == 'T' + expect(@prot.read_json_escape_char).to eq('T') @trans.write("\"\\\"\"") - @prot.read_json_string(false).should == "\"" + expect(@prot.read_json_string(false)).to eq("\"") @trans.write("\"\\\\\"") - @prot.read_json_string(false).should == "\\" + expect(@prot.read_json_string(false)).to eq("\\") @trans.write("\"\\/\"") - @prot.read_json_string(false).should == "\/" + expect(@prot.read_json_string(false)).to eq("\/") @trans.write("\"\\b\"") - @prot.read_json_string(false).should == "\b" + expect(@prot.read_json_string(false)).to eq("\b") @trans.write("\"\\f\"") - @prot.read_json_string(false).should == "\f" + expect(@prot.read_json_string(false)).to eq("\f") @trans.write("\"\\n\"") - @prot.read_json_string(false).should == "\n" + expect(@prot.read_json_string(false)).to eq("\n") @trans.write("\"\\r\"") - @prot.read_json_string(false).should == "\r" + expect(@prot.read_json_string(false)).to eq("\r") @trans.write("\"\\t\"") - @prot.read_json_string(false).should == "\t" + expect(@prot.read_json_string(false)).to eq("\t") end it "should read json string" do @@ -324,36 +324,36 @@ describe 'JsonProtocol' do expect {@prot.read_json_string(false)}.to raise_error(Thrift::ProtocolException) @trans.write("\"this is a test string\"") - @prot.read_json_string.should == "this is a test string" + expect(@prot.read_json_string).to eq("this is a test string") end it "should read json base64" do @trans.write("\"dGhpcyBpcyBhIHRlc3Qgc3RyaW5n\"") - @prot.read_json_base64.should == "this is a test string" + expect(@prot.read_json_base64).to eq("this is a test string") end it "should is json numeric" do - @prot.is_json_numeric("A").should == false - @prot.is_json_numeric("+").should == true - @prot.is_json_numeric("-").should == true - @prot.is_json_numeric(".").should == true - @prot.is_json_numeric("0").should == true - @prot.is_json_numeric("1").should == true - @prot.is_json_numeric("2").should == true - @prot.is_json_numeric("3").should == true - @prot.is_json_numeric("4").should == true - @prot.is_json_numeric("5").should == true - @prot.is_json_numeric("6").should == true - @prot.is_json_numeric("7").should == true - @prot.is_json_numeric("8").should == true - @prot.is_json_numeric("9").should == true - @prot.is_json_numeric("E").should == true - @prot.is_json_numeric("e").should == true + expect(@prot.is_json_numeric("A")).to eq(false) + expect(@prot.is_json_numeric("+")).to eq(true) + expect(@prot.is_json_numeric("-")).to eq(true) + expect(@prot.is_json_numeric(".")).to eq(true) + expect(@prot.is_json_numeric("0")).to eq(true) + expect(@prot.is_json_numeric("1")).to eq(true) + expect(@prot.is_json_numeric("2")).to eq(true) + expect(@prot.is_json_numeric("3")).to eq(true) + expect(@prot.is_json_numeric("4")).to eq(true) + expect(@prot.is_json_numeric("5")).to eq(true) + expect(@prot.is_json_numeric("6")).to eq(true) + expect(@prot.is_json_numeric("7")).to eq(true) + expect(@prot.is_json_numeric("8")).to eq(true) + expect(@prot.is_json_numeric("9")).to eq(true) + expect(@prot.is_json_numeric("E")).to eq(true) + expect(@prot.is_json_numeric("e")).to eq(true) end it "should read json numeric chars" do @trans.write("1.453E45T") - @prot.read_json_numeric_chars.should == "1.453E45" + expect(@prot.read_json_numeric_chars).to eq("1.453E45") end it "should read json integer" do @@ -362,7 +362,7 @@ describe 'JsonProtocol' do @prot.read_string @trans.write("1453T") - @prot.read_json_integer.should == 1453 + expect(@prot.read_json_integer).to eq(1453) end it "should read json double" do @@ -374,37 +374,37 @@ describe 'JsonProtocol' do expect {@prot.read_json_double}.to raise_error(Thrift::ProtocolException) @trans.write("1.453e01\"\"") - @prot.read_json_double.should == 14.53 + expect(@prot.read_json_double).to eq(14.53) @prot.read_string @trans.write("\"NaN\"") - @prot.read_json_double.nan?.should == true + expect(@prot.read_json_double.nan?).to eq(true) @trans.write("\"Infinity\"") - @prot.read_json_double.should == +1.0/0.0 + expect(@prot.read_json_double).to eq(+1.0/0.0) @trans.write("\"-Infinity\"") - @prot.read_json_double.should == -1.0/0.0 + expect(@prot.read_json_double).to eq(-1.0/0.0) end it "should read json object start" do @trans.write("{") - @prot.read_json_object_start.should == nil + expect(@prot.read_json_object_start).to eq(nil) end it "should read json object end" do @trans.write("}") - @prot.read_json_object_end.should == nil + expect(@prot.read_json_object_end).to eq(nil) end it "should read json array start" do @trans.write("[") - @prot.read_json_array_start.should == nil + expect(@prot.read_json_array_start).to eq(nil) end it "should read json array end" do @trans.write("]") - @prot.read_json_array_end.should == nil + expect(@prot.read_json_array_end).to eq(nil) end it "should read_message_begin" do @@ -412,133 +412,141 @@ describe 'JsonProtocol' do expect {@prot.read_message_begin}.to raise_error(Thrift::ProtocolException) @trans.write("[1,\"name\",12,32\"\"") - @prot.read_message_begin.should == ["name", 12, 32] + expect(@prot.read_message_begin).to eq(["name", 12, 32]) end it "should read message end" do @trans.write("]") - @prot.read_message_end.should == nil + expect(@prot.read_message_end).to eq(nil) end it "should read struct begin" do @trans.write("{") - @prot.read_struct_begin.should == nil + expect(@prot.read_struct_begin).to eq(nil) end it "should read struct end" do @trans.write("}") - @prot.read_struct_end.should == nil + expect(@prot.read_struct_end).to eq(nil) end it "should read field begin" do @trans.write("1{\"rec\"") - @prot.read_field_begin.should == [nil, 12, 1] + expect(@prot.read_field_begin).to eq([nil, 12, 1]) end it "should read field end" do @trans.write("}") - @prot.read_field_end.should == nil + expect(@prot.read_field_end).to eq(nil) end it "should read map begin" do @trans.write("[\"rec\",\"lst\",2,{") - @prot.read_map_begin.should == [12, 15, 2] + expect(@prot.read_map_begin).to eq([12, 15, 2]) end it "should read map end" do @trans.write("}]") - @prot.read_map_end.should == nil + expect(@prot.read_map_end).to eq(nil) end it "should read list begin" do @trans.write("[\"rec\",2\"\"") - @prot.read_list_begin.should == [12, 2] + expect(@prot.read_list_begin).to eq([12, 2]) end it "should read list end" do @trans.write("]") - @prot.read_list_end.should == nil + expect(@prot.read_list_end).to eq(nil) end it "should read set begin" do @trans.write("[\"rec\",2\"\"") - @prot.read_set_begin.should == [12, 2] + expect(@prot.read_set_begin).to eq([12, 2]) end it "should read set end" do @trans.write("]") - @prot.read_set_end.should == nil + expect(@prot.read_set_end).to eq(nil) end it "should read bool" do @trans.write("0\"\"") - @prot.read_bool.should == false + expect(@prot.read_bool).to eq(false) @prot.read_string @trans.write("1\"\"") - @prot.read_bool.should == true + expect(@prot.read_bool).to eq(true) end it "should read byte" do @trans.write("60\"\"") - @prot.read_byte.should == 60 + expect(@prot.read_byte).to eq(60) end it "should read i16" do @trans.write("1000\"\"") - @prot.read_i16.should == 1000 + expect(@prot.read_i16).to eq(1000) end it "should read i32" do @trans.write("3000000000\"\"") - @prot.read_i32.should == 3000000000 + expect(@prot.read_i32).to eq(3000000000) end it "should read i64" do @trans.write("6000000000\"\"") - @prot.read_i64.should == 6000000000 + expect(@prot.read_i64).to eq(6000000000) end it "should read double" do @trans.write("12.23\"\"") - @prot.read_double.should == 12.23 + expect(@prot.read_double).to eq(12.23) end if RUBY_VERSION >= '1.9' it 'should read string' do @trans.write('"this is a test string"'.force_encoding(Encoding::BINARY)) a = @prot.read_string - a.should == 'this is a test string' - a.encoding.should == Encoding::UTF_8 + expect(a).to eq('this is a test string') + expect(a.encoding).to eq(Encoding::UTF_8) end it 'should read string with unicode characters' do @trans.write('"this is a test string with unicode characters: \u20AC \u20AD"'.force_encoding(Encoding::BINARY)) a = @prot.read_string - a.should == "this is a test string with unicode characters: \u20AC \u20AD" - a.encoding.should == Encoding::UTF_8 + expect(a).to eq("this is a test string with unicode characters: \u20AC \u20AD") + expect(a.encoding).to eq(Encoding::UTF_8) end else it 'should read string' do @trans.write('"this is a test string"') - @prot.read_string.should == 'this is a test string' + expect(@prot.read_string).to eq('this is a test string') end end it "should read binary" do @trans.write("\"dGhpcyBpcyBhIHRlc3Qgc3RyaW5n\"") - @prot.read_binary.should == "this is a test string" + expect(@prot.read_binary).to eq("this is a test string") end it "should read long binary" do @trans.write("\"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==\"") - @prot.read_binary.bytes.to_a.should == (0...256).to_a + expect(@prot.read_binary.bytes.to_a).to eq((0...256).to_a) + end + + it "should provide a reasonable to_s" do + expect(@prot.to_s).to eq("json(memory)") end end describe Thrift::JsonProtocolFactory do it "should create a JsonProtocol" do - Thrift::JsonProtocolFactory.new.get_protocol(mock("MockTransport")).should be_instance_of(Thrift::JsonProtocol) + expect(Thrift::JsonProtocolFactory.new.get_protocol(double("MockTransport"))).to be_instance_of(Thrift::JsonProtocol) + end + + it "should provide a reasonable to_s" do + expect(Thrift::JsonProtocolFactory.new.to_s).to eq("json") end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/namespaced_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/namespaced_spec.rb index 31379d9..4d6d369 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/namespaced_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/namespaced_spec.rb @@ -32,7 +32,7 @@ describe 'namespaced generation' do "other_namespace/referenced_constants.rb", "other_namespace/referenced_types.rb" ].each do |name| - File.exist?(File.join(prefix, name)).should be_true + expect(File.exist?(File.join(prefix, name))).to be_truthy end end @@ -44,20 +44,20 @@ describe 'namespaced generation' do "referenced_constants.rb", "referenced_types.rb" ].each do |name| - File.exist?(File.join(prefix, name)).should_not be_true + expect(File.exist?(File.join(prefix, name))).not_to be_truthy end end it "has a service class in the right place" do - defined?(NamespacedSpecNamespace::NamespacedNonblockingService).should be_true + expect(defined?(NamespacedSpecNamespace::NamespacedNonblockingService)).to be_truthy end it "has a struct in the right place" do - defined?(NamespacedSpecNamespace::Hello).should be_true + expect(defined?(NamespacedSpecNamespace::Hello)).to be_truthy end it "required an included file" do - defined?(OtherNamespace::SomeEnum).should be_true + expect(defined?(OtherNamespace::SomeEnum)).to be_truthy end it "extended a service" do diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/nonblocking_server_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/nonblocking_server_spec.rb index 712cf45..613d883 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/nonblocking_server_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/nonblocking_server_spec.rb @@ -176,8 +176,8 @@ describe 'NonblockingServer' do it "should handle basic message passing" do client = setup_client - client.greeting(true).should == SpecNamespace::Hello.new - client.greeting(false).should == SpecNamespace::Hello.new(:greeting => 'Aloha!') + expect(client.greeting(true)).to eq(SpecNamespace::Hello.new) + expect(client.greeting(false)).to eq(SpecNamespace::Hello.new(:greeting => 'Aloha!')) @server.shutdown end @@ -195,7 +195,7 @@ describe 'NonblockingServer' do end 4.times { trans_queue.pop } setup_client.unblock(4) - 4.times { queue.pop.should be_true } + 4.times { expect(queue.pop).to be_truthy } @server.shutdown end @@ -212,15 +212,15 @@ describe 'NonblockingServer' do queues[4] << :hello queues[5] << :hello queues[6] << :hello - 3.times { result.pop.should == SpecNamespace::Hello.new } - client.greeting(true).should == SpecNamespace::Hello.new + 3.times { expect(result.pop).to eq(SpecNamespace::Hello.new) } + expect(client.greeting(true)).to eq(SpecNamespace::Hello.new) queues[5] << [:unblock, 4] - 4.times { result.pop.should be_true } + 4.times { expect(result.pop).to be_truthy } queues[2] << :hello - result.pop.should == SpecNamespace::Hello.new - client.greeting(false).should == SpecNamespace::Hello.new(:greeting => 'Aloha!') + expect(result.pop).to eq(SpecNamespace::Hello.new) + expect(client.greeting(false)).to eq(SpecNamespace::Hello.new(:greeting => 'Aloha!')) 7.times { queues.shift << :exit } - client.greeting(true).should == SpecNamespace::Hello.new + expect(client.greeting(true)).to eq(SpecNamespace::Hello.new) @server.shutdown end @@ -229,7 +229,7 @@ describe 'NonblockingServer' do client = setup_client client.greeting(false) # force a message pass @server.shutdown - @server_thread.join(2).should be_an_instance_of(Thread) + expect(@server_thread.join(2)).to be_an_instance_of(Thread) end it "should continue processing active messages when shutting down" do @@ -238,8 +238,8 @@ describe 'NonblockingServer' do client << :sleep sleep 0.1 # give the server time to start processing the client's message @server.shutdown - @server_thread.join(2).should be_an_instance_of(Thread) - result.pop.should == :slept + expect(@server_thread.join(2)).to be_an_instance_of(Thread) + expect(result.pop).to eq(:slept) end it "should kill active messages when they don't expire while shutting down" do @@ -249,15 +249,15 @@ describe 'NonblockingServer' do sleep 0.1 # start processing the client's message @server.shutdown(1) @catch_exceptions = true - @server_thread.join(3).should_not be_nil - result.should be_empty + expect(@server_thread.join(3)).not_to be_nil + expect(result).to be_empty end it "should allow shutting down in response to a message" do client = setup_client - client.greeting(true).should == SpecNamespace::Hello.new + expect(client.greeting(true)).to eq(SpecNamespace::Hello.new) client.shutdown - @server_thread.join(2).should_not be_nil + expect(@server_thread.join(2)).not_to be_nil end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/processor_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/processor_spec.rb index 989f5cc..d30553f 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/processor_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/processor_spec.rb @@ -27,52 +27,52 @@ describe 'Processor' do describe Thrift::Processor do before(:each) do - @processor = ProcessorSpec.new(mock("MockHandler")) - @prot = mock("MockProtocol") + @processor = ProcessorSpec.new(double("MockHandler")) + @prot = double("MockProtocol") end def mock_trans(obj) - obj.should_receive(:trans).ordered.and_return do - mock("trans").tap do |trans| - trans.should_receive(:flush).ordered + expect(obj).to receive(:trans).ordered do + double("trans").tap do |trans| + expect(trans).to receive(:flush).ordered end end end it "should call process_ when it receives that message" do - @prot.should_receive(:read_message_begin).ordered.and_return ['testMessage', Thrift::MessageTypes::CALL, 17] - @processor.should_receive(:process_testMessage).with(17, @prot, @prot).ordered - @processor.process(@prot, @prot).should == true + expect(@prot).to receive(:read_message_begin).ordered.and_return ['testMessage', Thrift::MessageTypes::CALL, 17] + expect(@processor).to receive(:process_testMessage).with(17, @prot, @prot).ordered + expect(@processor.process(@prot, @prot)).to eq(true) end it "should raise an ApplicationException when the received message cannot be processed" do - @prot.should_receive(:read_message_begin).ordered.and_return ['testMessage', Thrift::MessageTypes::CALL, 4] - @prot.should_receive(:skip).with(Thrift::Types::STRUCT).ordered - @prot.should_receive(:read_message_end).ordered - @prot.should_receive(:write_message_begin).with('testMessage', Thrift::MessageTypes::EXCEPTION, 4).ordered - e = mock(Thrift::ApplicationException) - e.should_receive(:write).with(@prot).ordered - Thrift::ApplicationException.should_receive(:new).with(Thrift::ApplicationException::UNKNOWN_METHOD, "Unknown function testMessage").and_return(e) - @prot.should_receive(:write_message_end).ordered + expect(@prot).to receive(:read_message_begin).ordered.and_return ['testMessage', Thrift::MessageTypes::CALL, 4] + expect(@prot).to receive(:skip).with(Thrift::Types::STRUCT).ordered + expect(@prot).to receive(:read_message_end).ordered + expect(@prot).to receive(:write_message_begin).with('testMessage', Thrift::MessageTypes::EXCEPTION, 4).ordered + e = double(Thrift::ApplicationException) + expect(e).to receive(:write).with(@prot).ordered + expect(Thrift::ApplicationException).to receive(:new).with(Thrift::ApplicationException::UNKNOWN_METHOD, "Unknown function testMessage").and_return(e) + expect(@prot).to receive(:write_message_end).ordered mock_trans(@prot) @processor.process(@prot, @prot) end it "should pass args off to the args class" do - args_class = mock("MockArgsClass") - args = mock("#").tap do |args| - args.should_receive(:read).with(@prot).ordered + args_class = double("MockArgsClass") + args = double("#").tap do |args| + expect(args).to receive(:read).with(@prot).ordered end - args_class.should_receive(:new).and_return args - @prot.should_receive(:read_message_end).ordered - @processor.read_args(@prot, args_class).should eql(args) + expect(args_class).to receive(:new).and_return args + expect(@prot).to receive(:read_message_end).ordered + expect(@processor.read_args(@prot, args_class)).to eql(args) end it "should write out a reply when asked" do - @prot.should_receive(:write_message_begin).with('testMessage', Thrift::MessageTypes::REPLY, 23).ordered - result = mock("MockResult") - result.should_receive(:write).with(@prot).ordered - @prot.should_receive(:write_message_end).ordered + expect(@prot).to receive(:write_message_begin).with('testMessage', Thrift::MessageTypes::REPLY, 23).ordered + result = double("MockResult") + expect(result).to receive(:write).with(@prot).ordered + expect(@prot).to receive(:write_message_end).ordered mock_trans(@prot) @processor.write_result(result, @prot, 'testMessage', 23) end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/serializer_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/serializer_spec.rb index 599b454..2a7dc6d 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/serializer_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/serializer_spec.rb @@ -25,19 +25,19 @@ describe 'Serializer' do it "should serialize structs to binary by default" do serializer = Thrift::Serializer.new(Thrift::BinaryProtocolAcceleratedFactory.new) data = serializer.serialize(SpecNamespace::Hello.new(:greeting => "'Ello guv'nor!")) - data.should == "\x0B\x00\x01\x00\x00\x00\x0E'Ello guv'nor!\x00" + expect(data).to eq("\x0B\x00\x01\x00\x00\x00\x0E'Ello guv'nor!\x00") end it "should serialize structs to the given protocol" do - protocol = Thrift::BaseProtocol.new(mock("transport")) - protocol.should_receive(:write_struct_begin).with("SpecNamespace::Hello") - protocol.should_receive(:write_field_begin).with("greeting", Thrift::Types::STRING, 1) - protocol.should_receive(:write_string).with("Good day") - protocol.should_receive(:write_field_end) - protocol.should_receive(:write_field_stop) - protocol.should_receive(:write_struct_end) - protocol_factory = mock("ProtocolFactory") - protocol_factory.stub!(:get_protocol).and_return(protocol) + protocol = Thrift::BaseProtocol.new(double("transport")) + expect(protocol).to receive(:write_struct_begin).with("SpecNamespace::Hello") + expect(protocol).to receive(:write_field_begin).with("greeting", Thrift::Types::STRING, 1) + expect(protocol).to receive(:write_string).with("Good day") + expect(protocol).to receive(:write_field_end) + expect(protocol).to receive(:write_field_stop) + expect(protocol).to receive(:write_struct_end) + protocol_factory = double("ProtocolFactory") + allow(protocol_factory).to receive(:get_protocol).and_return(protocol) serializer = Thrift::Serializer.new(protocol_factory) serializer.serialize(SpecNamespace::Hello.new(:greeting => "Good day")) end @@ -47,21 +47,21 @@ describe 'Serializer' do it "should deserialize structs from binary by default" do deserializer = Thrift::Deserializer.new data = "\x0B\x00\x01\x00\x00\x00\x0E'Ello guv'nor!\x00" - deserializer.deserialize(SpecNamespace::Hello.new, data).should == SpecNamespace::Hello.new(:greeting => "'Ello guv'nor!") + expect(deserializer.deserialize(SpecNamespace::Hello.new, data)).to eq(SpecNamespace::Hello.new(:greeting => "'Ello guv'nor!")) end it "should deserialize structs from the given protocol" do - protocol = Thrift::BaseProtocol.new(mock("transport")) - protocol.should_receive(:read_struct_begin).and_return("SpecNamespace::Hello") - protocol.should_receive(:read_field_begin).and_return(["greeting", Thrift::Types::STRING, 1], + protocol = Thrift::BaseProtocol.new(double("transport")) + expect(protocol).to receive(:read_struct_begin).and_return("SpecNamespace::Hello") + expect(protocol).to receive(:read_field_begin).and_return(["greeting", Thrift::Types::STRING, 1], [nil, Thrift::Types::STOP, 0]) - protocol.should_receive(:read_string).and_return("Good day") - protocol.should_receive(:read_field_end) - protocol.should_receive(:read_struct_end) - protocol_factory = mock("ProtocolFactory") - protocol_factory.stub!(:get_protocol).and_return(protocol) + expect(protocol).to receive(:read_string).and_return("Good day") + expect(protocol).to receive(:read_field_end) + expect(protocol).to receive(:read_struct_end) + protocol_factory = double("ProtocolFactory") + allow(protocol_factory).to receive(:get_protocol).and_return(protocol) deserializer = Thrift::Deserializer.new(protocol_factory) - deserializer.deserialize(SpecNamespace::Hello.new, "").should == SpecNamespace::Hello.new(:greeting => "Good day") + expect(deserializer.deserialize(SpecNamespace::Hello.new, "")).to eq(SpecNamespace::Hello.new(:greeting => "Good day")) end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/server_socket_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/server_socket_spec.rb index 1301d54..ec9e550 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/server_socket_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/server_socket_spec.rb @@ -28,52 +28,57 @@ describe 'Thrift::ServerSocket' do end it "should create a handle when calling listen" do - TCPServer.should_receive(:new).with(nil, 1234) + expect(TCPServer).to receive(:new).with(nil, 1234) @socket.listen end it "should accept an optional host argument" do @socket = Thrift::ServerSocket.new('localhost', 1234) - TCPServer.should_receive(:new).with('localhost', 1234) + expect(TCPServer).to receive(:new).with('localhost', 1234) + @socket.to_s == "server(localhost:1234)" @socket.listen end it "should create a Thrift::Socket to wrap accepted sockets" do - handle = mock("TCPServer") - TCPServer.should_receive(:new).with(nil, 1234).and_return(handle) + handle = double("TCPServer") + expect(TCPServer).to receive(:new).with(nil, 1234).and_return(handle) @socket.listen - sock = mock("sock") - handle.should_receive(:accept).and_return(sock) - trans = mock("Socket") - Thrift::Socket.should_receive(:new).and_return(trans) - trans.should_receive(:handle=).with(sock) - @socket.accept.should == trans + sock = double("sock") + expect(handle).to receive(:accept).and_return(sock) + trans = double("Socket") + expect(Thrift::Socket).to receive(:new).and_return(trans) + expect(trans).to receive(:handle=).with(sock) + expect(@socket.accept).to eq(trans) end it "should close the handle when closed" do - handle = mock("TCPServer", :closed? => false) - TCPServer.should_receive(:new).with(nil, 1234).and_return(handle) + handle = double("TCPServer", :closed? => false) + expect(TCPServer).to receive(:new).with(nil, 1234).and_return(handle) @socket.listen - handle.should_receive(:close) + expect(handle).to receive(:close) @socket.close end it "should return nil when accepting if there is no handle" do - @socket.accept.should be_nil + expect(@socket.accept).to be_nil end it "should return true for closed? when appropriate" do - handle = mock("TCPServer", :closed? => false) - TCPServer.stub!(:new).and_return(handle) + handle = double("TCPServer", :closed? => false) + allow(TCPServer).to receive(:new).and_return(handle) @socket.listen - @socket.should_not be_closed - handle.stub!(:close) + expect(@socket).not_to be_closed + allow(handle).to receive(:close) @socket.close - @socket.should be_closed + expect(@socket).to be_closed @socket.listen - @socket.should_not be_closed - handle.stub!(:closed?).and_return(true) - @socket.should be_closed + expect(@socket).not_to be_closed + allow(handle).to receive(:closed?).and_return(true) + expect(@socket).to be_closed + end + + it "should provide a reasonable to_s" do + expect(@socket.to_s).to eq("socket(:1234)") end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/server_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/server_spec.rb index eaecbda..57f5237 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/server_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/server_spec.rb @@ -21,95 +21,135 @@ require 'spec_helper' describe 'Server' do describe Thrift::BaseServer do - it "should default to BaseTransportFactory and BinaryProtocolFactory when not specified" do - server = Thrift::BaseServer.new(mock("Processor"), mock("BaseServerTransport")) - server.instance_variable_get(:'@transport_factory').should be_an_instance_of(Thrift::BaseTransportFactory) - server.instance_variable_get(:'@protocol_factory').should be_an_instance_of(Thrift::BinaryProtocolFactory) + before(:each) do + @processor = double("Processor") + @serverTrans = double("ServerTransport") + @trans = double("BaseTransport") + @prot = double("BaseProtocol") + @server = described_class.new(@processor, @serverTrans, @trans, @prot) end - # serve is a noop, so can't test that + it "should default to BaseTransportFactory and BinaryProtocolFactory when not specified" do + @server = Thrift::BaseServer.new(double("Processor"), double("BaseServerTransport")) + expect(@server.instance_variable_get(:'@transport_factory')).to be_an_instance_of(Thrift::BaseTransportFactory) + expect(@server.instance_variable_get(:'@protocol_factory')).to be_an_instance_of(Thrift::BinaryProtocolFactory) + end + + it "should not serve" do + expect { @server.serve()}.to raise_error(NotImplementedError) + end + + it "should provide a reasonable to_s" do + expect(@serverTrans).to receive(:to_s).once.and_return("serverTrans") + expect(@trans).to receive(:to_s).once.and_return("trans") + expect(@prot).to receive(:to_s).once.and_return("prot") + expect(@server.to_s).to eq("server(prot(trans(serverTrans)))") + end end describe Thrift::SimpleServer do before(:each) do - @processor = mock("Processor") - @serverTrans = mock("ServerTransport") - @trans = mock("BaseTransport") - @prot = mock("BaseProtocol") - @client = mock("Client") + @processor = double("Processor") + @serverTrans = double("ServerTransport") + @trans = double("BaseTransport") + @prot = double("BaseProtocol") + @client = double("Client") @server = described_class.new(@processor, @serverTrans, @trans, @prot) end + it "should provide a reasonable to_s" do + expect(@serverTrans).to receive(:to_s).once.and_return("serverTrans") + expect(@trans).to receive(:to_s).once.and_return("trans") + expect(@prot).to receive(:to_s).once.and_return("prot") + expect(@server.to_s).to eq("simple(server(prot(trans(serverTrans))))") + end + it "should serve in the main thread" do - @serverTrans.should_receive(:listen).ordered - @serverTrans.should_receive(:accept).exactly(3).times.and_return(@client) - @trans.should_receive(:get_transport).exactly(3).times.with(@client).and_return(@trans) - @prot.should_receive(:get_protocol).exactly(3).times.with(@trans).and_return(@prot) + expect(@serverTrans).to receive(:listen).ordered + expect(@serverTrans).to receive(:accept).exactly(3).times.and_return(@client) + expect(@trans).to receive(:get_transport).exactly(3).times.with(@client).and_return(@trans) + expect(@prot).to receive(:get_protocol).exactly(3).times.with(@trans).and_return(@prot) x = 0 - @processor.should_receive(:process).exactly(3).times.with(@prot, @prot).and_return do + expect(@processor).to receive(:process).exactly(3).times.with(@prot, @prot) do case (x += 1) when 1 then raise Thrift::TransportException when 2 then raise Thrift::ProtocolException when 3 then throw :stop end end - @trans.should_receive(:close).exactly(3).times - @serverTrans.should_receive(:close).ordered - lambda { @server.serve }.should throw_symbol(:stop) + expect(@trans).to receive(:close).exactly(3).times + expect(@serverTrans).to receive(:close).ordered + expect { @server.serve }.to throw_symbol(:stop) end end describe Thrift::ThreadedServer do before(:each) do - @processor = mock("Processor") - @serverTrans = mock("ServerTransport") - @trans = mock("BaseTransport") - @prot = mock("BaseProtocol") - @client = mock("Client") + @processor = double("Processor") + @serverTrans = double("ServerTransport") + @trans = double("BaseTransport") + @prot = double("BaseProtocol") + @client = double("Client") @server = described_class.new(@processor, @serverTrans, @trans, @prot) end + it "should provide a reasonable to_s" do + expect(@serverTrans).to receive(:to_s).once.and_return("serverTrans") + expect(@trans).to receive(:to_s).once.and_return("trans") + expect(@prot).to receive(:to_s).once.and_return("prot") + expect(@server.to_s).to eq("threaded(server(prot(trans(serverTrans))))") + end + it "should serve using threads" do - @serverTrans.should_receive(:listen).ordered - @serverTrans.should_receive(:accept).exactly(3).times.and_return(@client) - @trans.should_receive(:get_transport).exactly(3).times.with(@client).and_return(@trans) - @prot.should_receive(:get_protocol).exactly(3).times.with(@trans).and_return(@prot) - Thread.should_receive(:new).with(@prot, @trans).exactly(3).times.and_yield(@prot, @trans) + expect(@serverTrans).to receive(:listen).ordered + expect(@serverTrans).to receive(:accept).exactly(3).times.and_return(@client) + expect(@trans).to receive(:get_transport).exactly(3).times.with(@client).and_return(@trans) + expect(@prot).to receive(:get_protocol).exactly(3).times.with(@trans).and_return(@prot) + expect(Thread).to receive(:new).with(@prot, @trans).exactly(3).times.and_yield(@prot, @trans) x = 0 - @processor.should_receive(:process).exactly(3).times.with(@prot, @prot).and_return do + expect(@processor).to receive(:process).exactly(3).times.with(@prot, @prot) do case (x += 1) when 1 then raise Thrift::TransportException when 2 then raise Thrift::ProtocolException when 3 then throw :stop end end - @trans.should_receive(:close).exactly(3).times - @serverTrans.should_receive(:close).ordered - lambda { @server.serve }.should throw_symbol(:stop) + expect(@trans).to receive(:close).exactly(3).times + expect(@serverTrans).to receive(:close).ordered + expect { @server.serve }.to throw_symbol(:stop) end end describe Thrift::ThreadPoolServer do before(:each) do - @processor = mock("Processor") - @server_trans = mock("ServerTransport") - @trans = mock("BaseTransport") - @prot = mock("BaseProtocol") - @client = mock("Client") + @processor = double("Processor") + @server_trans = double("ServerTransport") + @trans = double("BaseTransport") + @prot = double("BaseProtocol") + @client = double("Client") @server = described_class.new(@processor, @server_trans, @trans, @prot) + sleep(0.15) end + it "should provide a reasonable to_s" do + expect(@server_trans).to receive(:to_s).once.and_return("server_trans") + expect(@trans).to receive(:to_s).once.and_return("trans") + expect(@prot).to receive(:to_s).once.and_return("prot") + expect(@server.to_s).to eq("threadpool(server(prot(trans(server_trans))))") + end + it "should serve inside a thread" do exception_q = @server.instance_variable_get(:@exception_q) - described_class.any_instance.should_receive(:serve) do + expect_any_instance_of(described_class).to receive(:serve) do exception_q.push(StandardError.new('ERROR')) end expect { @server.rescuable_serve }.to(raise_error('ERROR')) + sleep(0.15) end it "should avoid running the server twice when retrying rescuable_serve" do exception_q = @server.instance_variable_get(:@exception_q) - described_class.any_instance.should_receive(:serve) do + expect_any_instance_of(described_class).to receive(:serve) do exception_q.push(StandardError.new('ERROR1')) exception_q.push(StandardError.new('ERROR2')) end @@ -118,29 +158,29 @@ describe 'Server' do end it "should serve using a thread pool" do - thread_q = mock("SizedQueue") - exception_q = mock("Queue") + thread_q = double("SizedQueue") + exception_q = double("Queue") @server.instance_variable_set(:@thread_q, thread_q) @server.instance_variable_set(:@exception_q, exception_q) - @server_trans.should_receive(:listen).ordered - thread_q.should_receive(:push).with(:token) - thread_q.should_receive(:pop) - Thread.should_receive(:new).and_yield - @server_trans.should_receive(:accept).exactly(3).times.and_return(@client) - @trans.should_receive(:get_transport).exactly(3).times.and_return(@trans) - @prot.should_receive(:get_protocol).exactly(3).times.and_return(@prot) + expect(@server_trans).to receive(:listen).ordered + expect(thread_q).to receive(:push).with(:token) + expect(thread_q).to receive(:pop) + expect(Thread).to receive(:new).and_yield + expect(@server_trans).to receive(:accept).exactly(3).times.and_return(@client) + expect(@trans).to receive(:get_transport).exactly(3).times.and_return(@trans) + expect(@prot).to receive(:get_protocol).exactly(3).times.and_return(@prot) x = 0 error = RuntimeError.new("Stopped") - @processor.should_receive(:process).exactly(3).times.with(@prot, @prot).and_return do + expect(@processor).to receive(:process).exactly(3).times.with(@prot, @prot) do case (x += 1) when 1 then raise Thrift::TransportException when 2 then raise Thrift::ProtocolException when 3 then raise error end end - @trans.should_receive(:close).exactly(3).times - exception_q.should_receive(:push).with(error).and_throw(:stop) - @server_trans.should_receive(:close) + expect(@trans).to receive(:close).exactly(3).times + expect(exception_q).to receive(:push).with(error).and_throw(:stop) + expect(@server_trans).to receive(:close) expect { @server.serve }.to(throw_symbol(:stop)) end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/socket_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/socket_spec.rb index 8e1ef50..202c745 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/socket_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/socket_spec.rb @@ -25,37 +25,44 @@ describe 'Socket' do describe Thrift::Socket do before(:each) do @socket = Thrift::Socket.new - @handle = mock("Handle", :closed? => false) - @handle.stub!(:close) - @handle.stub!(:connect_nonblock) - @handle.stub!(:setsockopt) - ::Socket.stub!(:new).and_return(@handle) + @handle = double("Handle", :closed? => false) + allow(@handle).to receive(:close) + allow(@handle).to receive(:connect_nonblock) + allow(@handle).to receive(:setsockopt) + allow(::Socket).to receive(:new).and_return(@handle) end it_should_behave_like "a socket" it "should raise a TransportException when it cannot open a socket" do - ::Socket.should_receive(:getaddrinfo).with("localhost", 9090, nil, ::Socket::SOCK_STREAM).and_return([[]]) - lambda { @socket.open }.should raise_error(Thrift::TransportException) { |e| e.type.should == Thrift::TransportException::NOT_OPEN } + expect(::Socket).to receive(:getaddrinfo).with("localhost", 9090, nil, ::Socket::SOCK_STREAM).and_return([[]]) + expect { @socket.open }.to raise_error(Thrift::TransportException) { |e| expect(e.type).to eq(Thrift::TransportException::NOT_OPEN) } end it "should open a ::Socket with default args" do - ::Socket.should_receive(:new).and_return(mock("Handle", :connect_nonblock => true, :setsockopt => nil)) - ::Socket.should_receive(:getaddrinfo).with("localhost", 9090, nil, ::Socket::SOCK_STREAM).and_return([[]]) - ::Socket.should_receive(:sockaddr_in) + expect(::Socket).to receive(:new).and_return(double("Handle", :connect_nonblock => true, :setsockopt => nil)) + expect(::Socket).to receive(:getaddrinfo).with("localhost", 9090, nil, ::Socket::SOCK_STREAM).and_return([[]]) + expect(::Socket).to receive(:sockaddr_in) + @socket.to_s == "socket(localhost:9090)" @socket.open end it "should accept host/port options" do - ::Socket.should_receive(:new).and_return(mock("Handle", :connect_nonblock => true, :setsockopt => nil)) - ::Socket.should_receive(:getaddrinfo).with("my.domain", 1234, nil, ::Socket::SOCK_STREAM).and_return([[]]) - ::Socket.should_receive(:sockaddr_in) - Thrift::Socket.new('my.domain', 1234).open + expect(::Socket).to receive(:new).and_return(double("Handle", :connect_nonblock => true, :setsockopt => nil)) + expect(::Socket).to receive(:getaddrinfo).with("my.domain", 1234, nil, ::Socket::SOCK_STREAM).and_return([[]]) + expect(::Socket).to receive(:sockaddr_in) + @socket = Thrift::Socket.new('my.domain', 1234).open + @socket.to_s == "socket(my.domain:1234)" end it "should accept an optional timeout" do - ::Socket.stub!(:new) - Thrift::Socket.new('localhost', 8080, 5).timeout.should == 5 + allow(::Socket).to receive(:new) + expect(Thrift::Socket.new('localhost', 8080, 5).timeout).to eq(5) + end + + it "should provide a reasonable to_s" do + allow(::Socket).to receive(:new) + expect(Thrift::Socket.new('myhost', 8090).to_s).to eq("socket(myhost:8090)") end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/socket_spec_shared.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/socket_spec_shared.rb index 5fddc16..32bdb71 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/socket_spec_shared.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/socket_spec_shared.rb @@ -21,84 +21,84 @@ require 'spec_helper' shared_examples_for "a socket" do it "should open a socket" do - @socket.open.should == @handle + expect(@socket.open).to eq(@handle) end it "should be open whenever it has a handle" do - @socket.should_not be_open + expect(@socket).not_to be_open @socket.open - @socket.should be_open + expect(@socket).to be_open @socket.handle = nil - @socket.should_not be_open + expect(@socket).not_to be_open @socket.handle = @handle @socket.close - @socket.should_not be_open + expect(@socket).not_to be_open end it "should write data to the handle" do @socket.open - @handle.should_receive(:write).with("foobar") + expect(@handle).to receive(:write).with("foobar") @socket.write("foobar") - @handle.should_receive(:write).with("fail").and_raise(StandardError) - lambda { @socket.write("fail") }.should raise_error(Thrift::TransportException) { |e| e.type.should == Thrift::TransportException::NOT_OPEN } + expect(@handle).to receive(:write).with("fail").and_raise(StandardError) + expect { @socket.write("fail") }.to raise_error(Thrift::TransportException) { |e| expect(e.type).to eq(Thrift::TransportException::NOT_OPEN) } end it "should raise an error when it cannot read from the handle" do @socket.open - @handle.should_receive(:readpartial).with(17).and_raise(StandardError) - lambda { @socket.read(17) }.should raise_error(Thrift::TransportException) { |e| e.type.should == Thrift::TransportException::NOT_OPEN } + expect(@handle).to receive(:readpartial).with(17).and_raise(StandardError) + expect { @socket.read(17) }.to raise_error(Thrift::TransportException) { |e| expect(e.type).to eq(Thrift::TransportException::NOT_OPEN) } end it "should return the data read when reading from the handle works" do @socket.open - @handle.should_receive(:readpartial).with(17).and_return("test data") - @socket.read(17).should == "test data" + expect(@handle).to receive(:readpartial).with(17).and_return("test data") + expect(@socket.read(17)).to eq("test data") end it "should declare itself as closed when it has an error" do @socket.open - @handle.should_receive(:write).with("fail").and_raise(StandardError) - @socket.should be_open - lambda { @socket.write("fail") }.should raise_error - @socket.should_not be_open + expect(@handle).to receive(:write).with("fail").and_raise(StandardError) + expect(@socket).to be_open + expect { @socket.write("fail") }.to raise_error(Thrift::TransportException) { |e| expect(e.type).to eq(Thrift::TransportException::NOT_OPEN) } + expect(@socket).not_to be_open end it "should raise an error when the stream is closed" do @socket.open - @handle.stub!(:closed?).and_return(true) - @socket.should_not be_open - lambda { @socket.write("fail") }.should raise_error(IOError, "closed stream") - lambda { @socket.read(10) }.should raise_error(IOError, "closed stream") + allow(@handle).to receive(:closed?).and_return(true) + expect(@socket).not_to be_open + expect { @socket.write("fail") }.to raise_error(IOError, "closed stream") + expect { @socket.read(10) }.to raise_error(IOError, "closed stream") end it "should support the timeout accessor for read" do @socket.timeout = 3 @socket.open - IO.should_receive(:select).with([@handle], nil, nil, 3).and_return([[@handle], [], []]) - @handle.should_receive(:readpartial).with(17).and_return("test data") - @socket.read(17).should == "test data" + expect(IO).to receive(:select).with([@handle], nil, nil, 3).and_return([[@handle], [], []]) + expect(@handle).to receive(:readpartial).with(17).and_return("test data") + expect(@socket.read(17)).to eq("test data") end it "should support the timeout accessor for write" do @socket.timeout = 3 @socket.open - IO.should_receive(:select).with(nil, [@handle], nil, 3).twice.and_return([[], [@handle], []]) - @handle.should_receive(:write_nonblock).with("test data").and_return(4) - @handle.should_receive(:write_nonblock).with(" data").and_return(5) - @socket.write("test data").should == 9 + expect(IO).to receive(:select).with(nil, [@handle], nil, 3).twice.and_return([[], [@handle], []]) + expect(@handle).to receive(:write_nonblock).with("test data").and_return(4) + expect(@handle).to receive(:write_nonblock).with(" data").and_return(5) + expect(@socket.write("test data")).to eq(9) end it "should raise an error when read times out" do @socket.timeout = 0.5 @socket.open - IO.should_receive(:select).once {sleep(0.5); nil} - lambda { @socket.read(17) }.should raise_error(Thrift::TransportException) { |e| e.type.should == Thrift::TransportException::TIMED_OUT } + expect(IO).to receive(:select).once {sleep(0.5); nil} + expect { @socket.read(17) }.to raise_error(Thrift::TransportException) { |e| expect(e.type).to eq(Thrift::TransportException::TIMED_OUT) } end it "should raise an error when write times out" do @socket.timeout = 0.5 @socket.open - IO.should_receive(:select).with(nil, [@handle], nil, 0.5).any_number_of_times.and_return(nil) - lambda { @socket.write("test data") }.should raise_error(Thrift::TransportException) { |e| e.type.should == Thrift::TransportException::TIMED_OUT } + allow(IO).to receive(:select).with(nil, [@handle], nil, 0.5).and_return(nil) + expect { @socket.write("test data") }.to raise_error(Thrift::TransportException) { |e| expect(e.type).to eq(Thrift::TransportException::TIMED_OUT) } end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/ssl_server_socket_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/ssl_server_socket_spec.rb new file mode 100644 index 0000000..82e6518 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/ssl_server_socket_spec.rb @@ -0,0 +1,34 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +require 'spec_helper' +require File.expand_path("#{File.dirname(__FILE__)}/socket_spec_shared") + +describe 'SSLServerSocket' do + + describe Thrift::SSLServerSocket do + before(:each) do + @socket = Thrift::SSLServerSocket.new(1234) + end + + it "should provide a reasonable to_s" do + expect(@socket.to_s).to eq("ssl(socket(:1234))") + end + end +end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/ssl_socket_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/ssl_socket_spec.rb index a8bc785..808d8d5 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/ssl_socket_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/ssl_socket_spec.rb @@ -26,49 +26,53 @@ describe 'SSLSocket' do before(:each) do @context = OpenSSL::SSL::SSLContext.new @socket = Thrift::SSLSocket.new - @simple_socket_handle = mock("Handle", :closed? => false) - @simple_socket_handle.stub!(:close) - @simple_socket_handle.stub!(:connect_nonblock) - @simple_socket_handle.stub!(:setsockopt) + @simple_socket_handle = double("Handle", :closed? => false) + allow(@simple_socket_handle).to receive(:close) + allow(@simple_socket_handle).to receive(:connect_nonblock) + allow(@simple_socket_handle).to receive(:setsockopt) - @handle = mock(mock("SSLHandle", :connect_nonblock => true, :post_connection_check => true), :closed? => false) - @handle.stub!(:connect_nonblock) - @handle.stub!(:close) - @handle.stub!(:post_connection_check) + @handle = double(double("SSLHandle", :connect_nonblock => true, :post_connection_check => true), :closed? => false) + allow(@handle).to receive(:connect_nonblock) + allow(@handle).to receive(:close) + allow(@handle).to receive(:post_connection_check) - ::Socket.stub!(:new).and_return(@simple_socket_handle) - OpenSSL::SSL::SSLSocket.stub!(:new).and_return(@handle) + allow(::Socket).to receive(:new).and_return(@simple_socket_handle) + allow(OpenSSL::SSL::SSLSocket).to receive(:new).and_return(@handle) end it_should_behave_like "a socket" it "should raise a TransportException when it cannot open a ssl socket" do - ::Socket.should_receive(:getaddrinfo).with("localhost", 9090, nil, ::Socket::SOCK_STREAM).and_return([[]]) - lambda { @socket.open }.should raise_error(Thrift::TransportException) { |e| e.type.should == Thrift::TransportException::NOT_OPEN } + expect(::Socket).to receive(:getaddrinfo).with("localhost", 9090, nil, ::Socket::SOCK_STREAM).and_return([[]]) + expect { @socket.open }.to raise_error(Thrift::TransportException) { |e| expect(e.type).to eq(Thrift::TransportException::NOT_OPEN) } end it "should open a ::Socket with default args" do - OpenSSL::SSL::SSLSocket.should_receive(:new).with(@simple_socket_handle, nil).and_return(@handle) - @handle.should_receive(:post_connection_check).with('localhost') + expect(OpenSSL::SSL::SSLSocket).to receive(:new).with(@simple_socket_handle, nil).and_return(@handle) + expect(@handle).to receive(:post_connection_check).with('localhost') @socket.open end it "should accept host/port options" do - handle = mock("Handle", :connect_nonblock => true, :setsockopt => nil) - ::Socket.stub!(:new).and_return(handle) - ::Socket.should_receive(:getaddrinfo).with("my.domain", 1234, nil, ::Socket::SOCK_STREAM).and_return([[]]) - ::Socket.should_receive(:sockaddr_in) - OpenSSL::SSL::SSLSocket.should_receive(:new).with(handle, nil).and_return(@handle) - @handle.should_receive(:post_connection_check).with('my.domain') + handle = double("Handle", :connect_nonblock => true, :setsockopt => nil) + allow(::Socket).to receive(:new).and_return(handle) + expect(::Socket).to receive(:getaddrinfo).with("my.domain", 1234, nil, ::Socket::SOCK_STREAM).and_return([[]]) + expect(::Socket).to receive(:sockaddr_in) + expect(OpenSSL::SSL::SSLSocket).to receive(:new).with(handle, nil).and_return(@handle) + expect(@handle).to receive(:post_connection_check).with('my.domain') Thrift::SSLSocket.new('my.domain', 1234, 6000, nil).open end it "should accept an optional timeout" do - Thrift::SSLSocket.new('localhost', 8080, 5).timeout.should == 5 + expect(Thrift::SSLSocket.new('localhost', 8080, 5).timeout).to eq(5) end it "should accept an optional context" do - Thrift::SSLSocket.new('localhost', 8080, 5, @context).ssl_context.should == @context + expect(Thrift::SSLSocket.new('localhost', 8080, 5, @context).ssl_context).to eq(@context) + end + + it "should provide a reasonable to_s" do + expect(Thrift::SSLSocket.new('myhost', 8090).to_s).to eq("ssl(socket(myhost:8090))") end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/struct_nested_containers_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/struct_nested_containers_spec.rb index dc8ce5f..d063569 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/struct_nested_containers_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/struct_nested_containers_spec.rb @@ -39,9 +39,9 @@ describe 'StructNestedContainers' do thrift_struct.value = [ [1, 2, 3], [2, 3, 4] ] thrift_struct.validate end - a.should == b + expect(a).to eq(b) b.value.push [3, 4, 5] - a.should_not == b + expect(a).not_to eq(b) end end @@ -52,9 +52,9 @@ describe 'StructNestedContainers' do thrift_struct.value = [ [1, 2, 3], [2, 3, 4] ].to_set thrift_struct.validate end - a.should == b + expect(a).to eq(b) b.value.add [3, 4, 5] - a.should_not == b + expect(a).not_to eq(b) end end @@ -65,9 +65,9 @@ describe 'StructNestedContainers' do thrift_struct.value = { [1, 2, 3] => 1, [2, 3, 4] => 2 } thrift_struct.validate end - a.should == b + expect(a).to eq(b) b.value[[3, 4, 5]] = 3 - a.should_not == b + expect(a).not_to eq(b) end end @@ -78,9 +78,9 @@ describe 'StructNestedContainers' do thrift_struct.value = { 1 => [1, 2, 3], 2 => [2, 3, 4] } thrift_struct.validate end - a.should == b + expect(a).to eq(b) b.value[3] = [3, 4, 5] - a.should_not == b + expect(a).not_to eq(b) end end @@ -91,9 +91,9 @@ describe 'StructNestedContainers' do thrift_struct.value = [ [1, 2, 3].to_set, [2, 3, 4].to_set ] thrift_struct.validate end - a.should == b + expect(a).to eq(b) b.value.push([3, 4, 5].to_set) - a.should_not == b + expect(a).not_to eq(b) end end @@ -104,9 +104,9 @@ describe 'StructNestedContainers' do thrift_struct.value = [ [1, 2, 3].to_set, [2, 3, 4].to_set ].to_set thrift_struct.validate end - a.should == b + expect(a).to eq(b) b.value.add([3, 4, 5].to_set) - a.should_not == b + expect(a).not_to eq(b) end end @@ -117,9 +117,9 @@ describe 'StructNestedContainers' do thrift_struct.value = { [1, 2, 3].to_set => 1, [2, 3, 4].to_set => 2 } thrift_struct.validate end - a.should == b + expect(a).to eq(b) b.value[[3, 4, 5].to_set] = 3 - a.should_not == b + expect(a).not_to eq(b) end end @@ -130,9 +130,9 @@ describe 'StructNestedContainers' do thrift_struct.value = { 1 => [1, 2, 3].to_set, 2 => [2, 3, 4].to_set } thrift_struct.validate end - a.should == b + expect(a).to eq(b) b.value[3] = [3, 4, 5].to_set - a.should_not == b + expect(a).not_to eq(b) end end @@ -143,9 +143,9 @@ describe 'StructNestedContainers' do thrift_struct.value = [ {1 => 2, 3 => 4}, {2 => 3, 4 => 5} ] thrift_struct.validate end - a.should == b + expect(a).to eq(b) b.value.push({ 3 => 4, 5 => 6 }) - a.should_not == b + expect(a).not_to eq(b) end end @@ -156,9 +156,9 @@ describe 'StructNestedContainers' do thrift_struct.value = [ {1 => 2, 3 => 4}, {2 => 3, 4 => 5} ].to_set thrift_struct.validate end - a.should == b + expect(a).to eq(b) b.value.add({ 3 => 4, 5 => 6 }) - a.should_not == b + expect(a).not_to eq(b) end end @@ -169,9 +169,9 @@ describe 'StructNestedContainers' do thrift_struct.value = { { 1 => 2, 3 => 4} => 1, {2 => 3, 4 => 5} => 2 } thrift_struct.validate end - a.should == b + expect(a).to eq(b) b.value[{3 => 4, 5 => 6}] = 3 - a.should_not == b + expect(a).not_to eq(b) end end @@ -182,9 +182,9 @@ describe 'StructNestedContainers' do thrift_struct.value = { 1 => { 1 => 2, 3 => 4}, 2 => {2 => 3, 4 => 5} } thrift_struct.validate end - a.should == b + expect(a).to eq(b) b.value[3] = { 3 => 4, 5 => 6 } - a.should_not == b + expect(a).not_to eq(b) end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/struct_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/struct_spec.rb index 6534d61..bbd502b 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/struct_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/struct_spec.rb @@ -25,7 +25,7 @@ describe 'Struct' do it "should iterate over all fields properly" do fields = {} SpecNamespace::Foo.new.each_field { |fid,field_info| fields[fid] = field_info } - fields.should == SpecNamespace::Foo::FIELDS + expect(fields).to eq(SpecNamespace::Foo::FIELDS) end it "should initialize all fields to defaults" do @@ -39,19 +39,19 @@ describe 'Struct' do end def validate_default_arguments(object) - object.simple.should == 53 - object.words.should == "words" - object.hello.should == SpecNamespace::Hello.new(:greeting => 'hello, world!') - object.ints.should == [1, 2, 2, 3] - object.complex.should be_nil - object.shorts.should == Set.new([5, 17, 239]) + expect(object.simple).to eq(53) + expect(object.words).to eq("words") + expect(object.hello).to eq(SpecNamespace::Hello.new(:greeting => 'hello, world!')) + expect(object.ints).to eq([1, 2, 2, 3]) + expect(object.complex).to be_nil + expect(object.shorts).to eq(Set.new([5, 17, 239])) end it "should not share default values between instances" do begin struct = SpecNamespace::Foo.new struct.ints << 17 - SpecNamespace::Foo.new.ints.should == [1,2,2,3] + expect(SpecNamespace::Foo.new.ints).to eq([1,2,2,3]) ensure # ensure no leakage to other tests SpecNamespace::Foo::FIELDS[4][:default] = [1,2,2,3] @@ -60,48 +60,48 @@ describe 'Struct' do it "should properly initialize boolean values" do struct = SpecNamespace::BoolStruct.new(:yesno => false) - struct.yesno.should be_false + expect(struct.yesno).to be_falsey end it "should have proper == semantics" do - SpecNamespace::Foo.new.should_not == SpecNamespace::Hello.new - SpecNamespace::Foo.new.should == SpecNamespace::Foo.new - SpecNamespace::Foo.new(:simple => 52).should_not == SpecNamespace::Foo.new + expect(SpecNamespace::Foo.new).not_to eq(SpecNamespace::Hello.new) + expect(SpecNamespace::Foo.new).to eq(SpecNamespace::Foo.new) + expect(SpecNamespace::Foo.new(:simple => 52)).not_to eq(SpecNamespace::Foo.new) end it "should print enum value names in inspect" do - SpecNamespace::StructWithSomeEnum.new(:some_enum => SpecNamespace::SomeEnum::ONE).inspect.should == "" + expect(SpecNamespace::StructWithSomeEnum.new(:some_enum => SpecNamespace::SomeEnum::ONE).inspect).to eq("") - SpecNamespace::StructWithEnumMap.new(:my_map => {SpecNamespace::SomeEnum::ONE => [SpecNamespace::SomeEnum::TWO]}).inspect.should == "" + expect(SpecNamespace::StructWithEnumMap.new(:my_map => {SpecNamespace::SomeEnum::ONE => [SpecNamespace::SomeEnum::TWO]}).inspect).to eq("") end it "should pretty print binary fields" do - SpecNamespace::Foo2.new(:my_binary => "\001\002\003").inspect.should == "" + expect(SpecNamespace::Foo2.new(:my_binary => "\001\002\003").inspect).to eq("") end it "should offer field? methods" do - SpecNamespace::Foo.new.opt_string?.should be_false - SpecNamespace::Foo.new(:simple => 52).simple?.should be_true - SpecNamespace::Foo.new(:my_bool => false).my_bool?.should be_true - SpecNamespace::Foo.new(:my_bool => true).my_bool?.should be_true + expect(SpecNamespace::Foo.new.opt_string?).to be_falsey + expect(SpecNamespace::Foo.new(:simple => 52).simple?).to be_truthy + expect(SpecNamespace::Foo.new(:my_bool => false).my_bool?).to be_truthy + expect(SpecNamespace::Foo.new(:my_bool => true).my_bool?).to be_truthy end it "should be comparable" do s1 = SpecNamespace::StructWithSomeEnum.new(:some_enum => SpecNamespace::SomeEnum::ONE) s2 = SpecNamespace::StructWithSomeEnum.new(:some_enum => SpecNamespace::SomeEnum::TWO) - (s1 <=> s2).should == -1 - (s2 <=> s1).should == 1 - (s1 <=> s1).should == 0 - (s1 <=> SpecNamespace::StructWithSomeEnum.new()).should == -1 + expect(s1 <=> s2).to eq(-1) + expect(s2 <=> s1).to eq(1) + expect(s1 <=> s1).to eq(0) + expect(s1 <=> SpecNamespace::StructWithSomeEnum.new()).to eq(-1) end it "should read itself off the wire" do struct = SpecNamespace::Foo.new - prot = Thrift::BaseProtocol.new(mock("transport")) - prot.should_receive(:read_struct_begin).twice - prot.should_receive(:read_struct_end).twice - prot.should_receive(:read_field_begin).and_return( + prot = Thrift::BaseProtocol.new(double("transport")) + expect(prot).to receive(:read_struct_begin).twice + expect(prot).to receive(:read_struct_end).twice + expect(prot).to receive(:read_field_begin).and_return( ['complex', Thrift::Types::MAP, 5], # Foo ['words', Thrift::Types::STRING, 2], # Foo ['hello', Thrift::Types::STRUCT, 3], # Foo @@ -112,49 +112,49 @@ describe 'Struct' do ['shorts', Thrift::Types::SET, 6], # Foo [nil, Thrift::Types::STOP, 0] # Hello ) - prot.should_receive(:read_field_end).exactly(7).times - prot.should_receive(:read_map_begin).and_return( + expect(prot).to receive(:read_field_end).exactly(7).times + expect(prot).to receive(:read_map_begin).and_return( [Thrift::Types::I32, Thrift::Types::MAP, 2], # complex [Thrift::Types::STRING, Thrift::Types::DOUBLE, 2], # complex/1/value [Thrift::Types::STRING, Thrift::Types::DOUBLE, 1] # complex/2/value ) - prot.should_receive(:read_map_end).exactly(3).times - prot.should_receive(:read_list_begin).and_return([Thrift::Types::I32, 4]) - prot.should_receive(:read_list_end) - prot.should_receive(:read_set_begin).and_return([Thrift::Types::I16, 2]) - prot.should_receive(:read_set_end) - prot.should_receive(:read_i32).and_return( + expect(prot).to receive(:read_map_end).exactly(3).times + expect(prot).to receive(:read_list_begin).and_return([Thrift::Types::I32, 4]) + expect(prot).to receive(:read_list_end) + expect(prot).to receive(:read_set_begin).and_return([Thrift::Types::I16, 2]) + expect(prot).to receive(:read_set_end) + expect(prot).to receive(:read_i32).and_return( 1, 14, # complex keys 42, # simple 4, 23, 4, 29 # ints ) - prot.should_receive(:read_string).and_return("pi", "e", "feigenbaum", "apple banana", "what's up?") - prot.should_receive(:read_double).and_return(Math::PI, Math::E, 4.669201609) - prot.should_receive(:read_i16).and_return(2, 3) - prot.should_not_receive(:skip) + expect(prot).to receive(:read_string).and_return("pi", "e", "feigenbaum", "apple banana", "what's up?") + expect(prot).to receive(:read_double).and_return(Math::PI, Math::E, 4.669201609) + expect(prot).to receive(:read_i16).and_return(2, 3) + expect(prot).not_to receive(:skip) struct.read(prot) - struct.simple.should == 42 - struct.complex.should == {1 => {"pi" => Math::PI, "e" => Math::E}, 14 => {"feigenbaum" => 4.669201609}} - struct.hello.should == SpecNamespace::Hello.new(:greeting => "what's up?") - struct.words.should == "apple banana" - struct.ints.should == [4, 23, 4, 29] - struct.shorts.should == Set.new([3, 2]) + expect(struct.simple).to eq(42) + expect(struct.complex).to eq({1 => {"pi" => Math::PI, "e" => Math::E}, 14 => {"feigenbaum" => 4.669201609}}) + expect(struct.hello).to eq(SpecNamespace::Hello.new(:greeting => "what's up?")) + expect(struct.words).to eq("apple banana") + expect(struct.ints).to eq([4, 23, 4, 29]) + expect(struct.shorts).to eq(Set.new([3, 2])) end it "should serialize false boolean fields correctly" do b = SpecNamespace::BoolStruct.new(:yesno => false) prot = Thrift::BinaryProtocol.new(Thrift::MemoryBufferTransport.new) - prot.should_receive(:write_bool).with(false) + expect(prot).to receive(:write_bool).with(false) b.write(prot) end it "should skip unexpected fields in structs and use default values" do struct = SpecNamespace::Foo.new - prot = Thrift::BaseProtocol.new(mock("transport")) - prot.should_receive(:read_struct_begin) - prot.should_receive(:read_struct_end) - prot.should_receive(:read_field_begin).and_return( + prot = Thrift::BaseProtocol.new(double("transport")) + expect(prot).to receive(:read_struct_begin) + expect(prot).to receive(:read_struct_end) + expect(prot).to receive(:read_field_begin).and_return( ['simple', Thrift::Types::I32, 1], ['complex', Thrift::Types::STRUCT, 5], ['thinz', Thrift::Types::MAP, 7], @@ -162,55 +162,55 @@ describe 'Struct' do ['words', Thrift::Types::STRING, 2], [nil, Thrift::Types::STOP, 0] ) - prot.should_receive(:read_field_end).exactly(5).times - prot.should_receive(:read_i32).and_return(42) - prot.should_receive(:read_string).and_return("foobar") - prot.should_receive(:skip).with(Thrift::Types::STRUCT) - prot.should_receive(:skip).with(Thrift::Types::MAP) + expect(prot).to receive(:read_field_end).exactly(5).times + expect(prot).to receive(:read_i32).and_return(42) + expect(prot).to receive(:read_string).and_return("foobar") + expect(prot).to receive(:skip).with(Thrift::Types::STRUCT) + expect(prot).to receive(:skip).with(Thrift::Types::MAP) # prot.should_receive(:read_map_begin).and_return([Thrift::Types::I32, Thrift::Types::I32, 0]) # prot.should_receive(:read_map_end) - prot.should_receive(:skip).with(Thrift::Types::I32) + expect(prot).to receive(:skip).with(Thrift::Types::I32) struct.read(prot) - struct.simple.should == 42 - struct.complex.should be_nil - struct.words.should == "foobar" - struct.hello.should == SpecNamespace::Hello.new(:greeting => 'hello, world!') - struct.ints.should == [1, 2, 2, 3] - struct.shorts.should == Set.new([5, 17, 239]) + expect(struct.simple).to eq(42) + expect(struct.complex).to be_nil + expect(struct.words).to eq("foobar") + expect(struct.hello).to eq(SpecNamespace::Hello.new(:greeting => 'hello, world!')) + expect(struct.ints).to eq([1, 2, 2, 3]) + expect(struct.shorts).to eq(Set.new([5, 17, 239])) end it "should write itself to the wire" do - prot = Thrift::BaseProtocol.new(mock("transport")) #mock("Protocol") - prot.should_receive(:write_struct_begin).with("SpecNamespace::Foo") - prot.should_receive(:write_struct_begin).with("SpecNamespace::Hello") - prot.should_receive(:write_struct_end).twice - prot.should_receive(:write_field_begin).with('ints', Thrift::Types::LIST, 4) - prot.should_receive(:write_i32).with(1) - prot.should_receive(:write_i32).with(2).twice - prot.should_receive(:write_i32).with(3) - prot.should_receive(:write_field_begin).with('complex', Thrift::Types::MAP, 5) - prot.should_receive(:write_i32).with(5) - prot.should_receive(:write_string).with('foo') - prot.should_receive(:write_double).with(1.23) - prot.should_receive(:write_field_begin).with('shorts', Thrift::Types::SET, 6) - prot.should_receive(:write_i16).with(5) - prot.should_receive(:write_i16).with(17) - prot.should_receive(:write_i16).with(239) - prot.should_receive(:write_field_stop).twice - prot.should_receive(:write_field_end).exactly(6).times - prot.should_receive(:write_field_begin).with('simple', Thrift::Types::I32, 1) - prot.should_receive(:write_i32).with(53) - prot.should_receive(:write_field_begin).with('hello', Thrift::Types::STRUCT, 3) - prot.should_receive(:write_field_begin).with('greeting', Thrift::Types::STRING, 1) - prot.should_receive(:write_string).with('hello, world!') - prot.should_receive(:write_map_begin).with(Thrift::Types::I32, Thrift::Types::MAP, 1) - prot.should_receive(:write_map_begin).with(Thrift::Types::STRING, Thrift::Types::DOUBLE, 1) - prot.should_receive(:write_map_end).twice - prot.should_receive(:write_list_begin).with(Thrift::Types::I32, 4) - prot.should_receive(:write_list_end) - prot.should_receive(:write_set_begin).with(Thrift::Types::I16, 3) - prot.should_receive(:write_set_end) + prot = Thrift::BaseProtocol.new(double("transport")) #mock("Protocol") + expect(prot).to receive(:write_struct_begin).with("SpecNamespace::Foo") + expect(prot).to receive(:write_struct_begin).with("SpecNamespace::Hello") + expect(prot).to receive(:write_struct_end).twice + expect(prot).to receive(:write_field_begin).with('ints', Thrift::Types::LIST, 4) + expect(prot).to receive(:write_i32).with(1) + expect(prot).to receive(:write_i32).with(2).twice + expect(prot).to receive(:write_i32).with(3) + expect(prot).to receive(:write_field_begin).with('complex', Thrift::Types::MAP, 5) + expect(prot).to receive(:write_i32).with(5) + expect(prot).to receive(:write_string).with('foo') + expect(prot).to receive(:write_double).with(1.23) + expect(prot).to receive(:write_field_begin).with('shorts', Thrift::Types::SET, 6) + expect(prot).to receive(:write_i16).with(5) + expect(prot).to receive(:write_i16).with(17) + expect(prot).to receive(:write_i16).with(239) + expect(prot).to receive(:write_field_stop).twice + expect(prot).to receive(:write_field_end).exactly(6).times + expect(prot).to receive(:write_field_begin).with('simple', Thrift::Types::I32, 1) + expect(prot).to receive(:write_i32).with(53) + expect(prot).to receive(:write_field_begin).with('hello', Thrift::Types::STRUCT, 3) + expect(prot).to receive(:write_field_begin).with('greeting', Thrift::Types::STRING, 1) + expect(prot).to receive(:write_string).with('hello, world!') + expect(prot).to receive(:write_map_begin).with(Thrift::Types::I32, Thrift::Types::MAP, 1) + expect(prot).to receive(:write_map_begin).with(Thrift::Types::STRING, Thrift::Types::DOUBLE, 1) + expect(prot).to receive(:write_map_end).twice + expect(prot).to receive(:write_list_begin).with(Thrift::Types::I32, 4) + expect(prot).to receive(:write_list_end) + expect(prot).to receive(:write_set_begin).with(Thrift::Types::I16, 3) + expect(prot).to receive(:write_set_end) struct = SpecNamespace::Foo.new struct.words = nil @@ -221,50 +221,50 @@ describe 'Struct' do it "should raise an exception if presented with an unknown container" do # yeah this is silly, but I'm going for code coverage here struct = SpecNamespace::Foo.new - lambda { struct.send :write_container, nil, nil, {:type => "foo"} }.should raise_error(StandardError, "Not a container type: foo") + expect { struct.send :write_container, nil, nil, {:type => "foo"} }.to raise_error(StandardError, "Not a container type: foo") end it "should support optional type-checking in Thrift::Struct.new" do Thrift.type_checking = true begin - lambda { SpecNamespace::Hello.new(:greeting => 3) }.should raise_error(Thrift::TypeError, "Expected Types::STRING, received Fixnum for field greeting") + expect { SpecNamespace::Hello.new(:greeting => 3) }.to raise_error(Thrift::TypeError, /Expected Types::STRING, received (Integer|Fixnum) for field greeting/) ensure Thrift.type_checking = false end - lambda { SpecNamespace::Hello.new(:greeting => 3) }.should_not raise_error(Thrift::TypeError) + expect { SpecNamespace::Hello.new(:greeting => 3) }.not_to raise_error end it "should support optional type-checking in field accessors" do Thrift.type_checking = true begin hello = SpecNamespace::Hello.new - lambda { hello.greeting = 3 }.should raise_error(Thrift::TypeError, "Expected Types::STRING, received Fixnum for field greeting") + expect { hello.greeting = 3 }.to raise_error(Thrift::TypeError, /Expected Types::STRING, received (Integer|Fixnum) for field greeting/) ensure Thrift.type_checking = false end - lambda { hello.greeting = 3 }.should_not raise_error(Thrift::TypeError) + expect { hello.greeting = 3 }.not_to raise_error end it "should raise an exception when unknown types are given to Thrift::Struct.new" do - lambda { SpecNamespace::Hello.new(:fish => 'salmon') }.should raise_error(Exception, "Unknown key given to SpecNamespace::Hello.new: fish") + expect { SpecNamespace::Hello.new(:fish => 'salmon') }.to raise_error(Exception, "Unknown key given to SpecNamespace::Hello.new: fish") end it "should support `raise Xception, 'message'` for Exception structs" do begin raise SpecNamespace::Xception, "something happened" rescue Thrift::Exception => e - e.message.should == "something happened" - e.code.should == 1 + expect(e.message).to eq("something happened") + expect(e.code).to eq(1) # ensure it gets serialized properly, this is the really important part - prot = Thrift::BaseProtocol.new(mock("trans")) - prot.should_receive(:write_struct_begin).with("SpecNamespace::Xception") - prot.should_receive(:write_struct_end) - prot.should_receive(:write_field_begin).with('message', Thrift::Types::STRING, 1)#, "something happened") - prot.should_receive(:write_string).with("something happened") - prot.should_receive(:write_field_begin).with('code', Thrift::Types::I32, 2)#, 1) - prot.should_receive(:write_i32).with(1) - prot.should_receive(:write_field_stop) - prot.should_receive(:write_field_end).twice + prot = Thrift::BaseProtocol.new(double("trans")) + expect(prot).to receive(:write_struct_begin).with("SpecNamespace::Xception") + expect(prot).to receive(:write_struct_end) + expect(prot).to receive(:write_field_begin).with('message', Thrift::Types::STRING, 1)#, "something happened") + expect(prot).to receive(:write_string).with("something happened") + expect(prot).to receive(:write_field_begin).with('code', Thrift::Types::I32, 2)#, 1) + expect(prot).to receive(:write_i32).with(1) + expect(prot).to receive(:write_field_stop) + expect(prot).to receive(:write_field_end).twice e.write(prot) end @@ -274,17 +274,17 @@ describe 'Struct' do begin raise SpecNamespace::Xception, :message => "something happened", :code => 5 rescue Thrift::Exception => e - e.message.should == "something happened" - e.code.should == 5 - prot = Thrift::BaseProtocol.new(mock("trans")) - prot.should_receive(:write_struct_begin).with("SpecNamespace::Xception") - prot.should_receive(:write_struct_end) - prot.should_receive(:write_field_begin).with('message', Thrift::Types::STRING, 1) - prot.should_receive(:write_string).with("something happened") - prot.should_receive(:write_field_begin).with('code', Thrift::Types::I32, 2) - prot.should_receive(:write_i32).with(5) - prot.should_receive(:write_field_stop) - prot.should_receive(:write_field_end).twice + expect(e.message).to eq("something happened") + expect(e.code).to eq(5) + prot = Thrift::BaseProtocol.new(double("trans")) + expect(prot).to receive(:write_struct_begin).with("SpecNamespace::Xception") + expect(prot).to receive(:write_struct_end) + expect(prot).to receive(:write_field_begin).with('message', Thrift::Types::STRING, 1) + expect(prot).to receive(:write_string).with("something happened") + expect(prot).to receive(:write_field_begin).with('code', Thrift::Types::I32, 2) + expect(prot).to receive(:write_i32).with(5) + expect(prot).to receive(:write_field_stop) + expect(prot).to receive(:write_field_end).twice e.write(prot) end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/thin_http_server_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/thin_http_server_spec.rb index 5520839..665391b 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/thin_http_server_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/thin_http_server_spec.rb @@ -23,24 +23,24 @@ require 'thrift/server/thin_http_server' describe Thrift::ThinHTTPServer do - let(:processor) { mock('processor') } + let(:processor) { double('processor') } describe "#initialize" do context "when using the defaults" do it "binds to port 80, with host 0.0.0.0, a path of '/'" do - Thin::Server.should_receive(:new).with('0.0.0.0', 80, an_instance_of(Rack::Builder)) + expect(Thin::Server).to receive(:new).with('0.0.0.0', 80, an_instance_of(Rack::Builder)) Thrift::ThinHTTPServer.new(processor) end it 'creates a ThinHTTPServer::RackApplicationContext' do - Thrift::ThinHTTPServer::RackApplication.should_receive(:for).with("/", processor, an_instance_of(Thrift::BinaryProtocolFactory)).and_return(anything) + expect(Thrift::ThinHTTPServer::RackApplication).to receive(:for).with("/", processor, an_instance_of(Thrift::BinaryProtocolFactory)).and_return(anything) Thrift::ThinHTTPServer.new(processor) end it "uses the BinaryProtocolFactory" do - Thrift::BinaryProtocolFactory.should_receive(:new) + expect(Thrift::BinaryProtocolFactory).to receive(:new) Thrift::ThinHTTPServer.new(processor) end @@ -52,7 +52,7 @@ describe Thrift::ThinHTTPServer do ip = "192.168.0.1" port = 3000 path = "/thin" - Thin::Server.should_receive(:new).with(ip, port, an_instance_of(Rack::Builder)) + expect(Thin::Server).to receive(:new).with(ip, port, an_instance_of(Rack::Builder)) Thrift::ThinHTTPServer.new(processor, :ip => ip, :port => port, @@ -60,7 +60,7 @@ describe Thrift::ThinHTTPServer do end it 'creates a ThinHTTPServer::RackApplicationContext with a different protocol factory' do - Thrift::ThinHTTPServer::RackApplication.should_receive(:for).with("/", processor, an_instance_of(Thrift::JsonProtocolFactory)).and_return(anything) + expect(Thrift::ThinHTTPServer::RackApplication).to receive(:for).with("/", processor, an_instance_of(Thrift::JsonProtocolFactory)).and_return(anything) Thrift::ThinHTTPServer.new(processor, :protocol_factory => Thrift::JsonProtocolFactory.new) end @@ -72,12 +72,12 @@ describe Thrift::ThinHTTPServer do describe "#serve" do it 'starts the Thin server' do - underlying_thin_server = mock('thin server', :start => true) - Thin::Server.stub(:new).and_return(underlying_thin_server) + underlying_thin_server = double('thin server', :start => true) + allow(Thin::Server).to receive(:new).and_return(underlying_thin_server) thin_thrift_server = Thrift::ThinHTTPServer.new(processor) - underlying_thin_server.should_receive(:start) + expect(underlying_thin_server).to receive(:start) thin_thrift_server.serve end end @@ -87,8 +87,8 @@ end describe Thrift::ThinHTTPServer::RackApplication do include Rack::Test::Methods - let(:processor) { mock('processor') } - let(:protocol_factory) { mock('protocol factory') } + let(:processor) { double('processor') } + let(:protocol_factory) { double('protocol factory') } def app Thrift::ThinHTTPServer::RackApplication.for("/", processor, protocol_factory) @@ -99,13 +99,13 @@ describe Thrift::ThinHTTPServer::RackApplication do it 'receives a non-POST' do header('Content-Type', "application/x-thrift") get "/" - last_response.status.should be 404 + expect(last_response.status).to be 404 end it 'receives a header other than application/x-thrift' do header('Content-Type', "application/json") post "/" - last_response.status.should be 404 + expect(last_response.status).to be 404 end end @@ -113,26 +113,26 @@ describe Thrift::ThinHTTPServer::RackApplication do context "200 response" do before do - protocol_factory.stub(:get_protocol) - processor.stub(:process) + allow(protocol_factory).to receive(:get_protocol) + allow(processor).to receive(:process) end it 'creates an IOStreamTransport' do header('Content-Type', "application/x-thrift") - Thrift::IOStreamTransport.should_receive(:new).with(an_instance_of(Rack::Lint::InputWrapper), an_instance_of(Rack::Response)) + expect(Thrift::IOStreamTransport).to receive(:new).with(an_instance_of(Rack::Lint::InputWrapper), an_instance_of(Rack::Response)) post "/" end it 'fetches the right protocol based on the Transport' do header('Content-Type', "application/x-thrift") - protocol_factory.should_receive(:get_protocol).with(an_instance_of(Thrift::IOStreamTransport)) + expect(protocol_factory).to receive(:get_protocol).with(an_instance_of(Thrift::IOStreamTransport)) post "/" end it 'status code 200' do header('Content-Type', "application/x-thrift") post "/" - last_response.ok?.should be_true + expect(last_response.ok?).to be_truthy end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/types_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/types_spec.rb index b2c3a20..d595ab5 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/types_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/types_spec.rb @@ -31,85 +31,88 @@ describe Thrift::Types do context 'type checking' do it "should return the proper name for each type" do - Thrift.type_name(Thrift::Types::I16).should == "Types::I16" - Thrift.type_name(Thrift::Types::VOID).should == "Types::VOID" - Thrift.type_name(Thrift::Types::LIST).should == "Types::LIST" - Thrift.type_name(42).should be_nil + expect(Thrift.type_name(Thrift::Types::I16)).to eq("Types::I16") + expect(Thrift.type_name(Thrift::Types::VOID)).to eq("Types::VOID") + expect(Thrift.type_name(Thrift::Types::LIST)).to eq("Types::LIST") + expect(Thrift.type_name(42)).to be_nil end it "should check types properly" do # lambda { Thrift.check_type(nil, Thrift::Types::STOP) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type(3, {:type => Thrift::Types::STOP}, :foo) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type(nil, {:type => Thrift::Types::VOID}, :foo) }.should_not raise_error(Thrift::TypeError) - lambda { Thrift.check_type(3, {:type => Thrift::Types::VOID}, :foo) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type(true, {:type => Thrift::Types::BOOL}, :foo) }.should_not raise_error(Thrift::TypeError) - lambda { Thrift.check_type(3, {:type => Thrift::Types::BOOL}, :foo) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type(42, {:type => Thrift::Types::BYTE}, :foo) }.should_not raise_error(Thrift::TypeError) - lambda { Thrift.check_type(42, {:type => Thrift::Types::I16}, :foo) }.should_not raise_error(Thrift::TypeError) - lambda { Thrift.check_type(42, {:type => Thrift::Types::I32}, :foo) }.should_not raise_error(Thrift::TypeError) - lambda { Thrift.check_type(42, {:type => Thrift::Types::I64}, :foo) }.should_not raise_error(Thrift::TypeError) - lambda { Thrift.check_type(3.14, {:type => Thrift::Types::I32}, :foo) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type(3.14, {:type => Thrift::Types::DOUBLE}, :foo) }.should_not raise_error(Thrift::TypeError) - lambda { Thrift.check_type(3, {:type => Thrift::Types::DOUBLE}, :foo) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type("3", {:type => Thrift::Types::STRING}, :foo) }.should_not raise_error(Thrift::TypeError) - lambda { Thrift.check_type(3, {:type => Thrift::Types::STRING}, :foo) }.should raise_error(Thrift::TypeError) + expect { Thrift.check_type(3, {:type => Thrift::Types::STOP}, :foo) }.to raise_error(Thrift::TypeError) + expect { Thrift.check_type(nil, {:type => Thrift::Types::VOID}, :foo) }.not_to raise_error + expect { Thrift.check_type(3, {:type => Thrift::Types::VOID}, :foo) }.to raise_error(Thrift::TypeError) + expect { Thrift.check_type(true, {:type => Thrift::Types::BOOL}, :foo) }.not_to raise_error + expect { Thrift.check_type(3, {:type => Thrift::Types::BOOL}, :foo) }.to raise_error(Thrift::TypeError) + expect { Thrift.check_type(42, {:type => Thrift::Types::BYTE}, :foo) }.not_to raise_error + expect { Thrift.check_type(42, {:type => Thrift::Types::I16}, :foo) }.not_to raise_error + expect { Thrift.check_type(42, {:type => Thrift::Types::I32}, :foo) }.not_to raise_error + expect { Thrift.check_type(42, {:type => Thrift::Types::I64}, :foo) }.not_to raise_error + expect { Thrift.check_type(3.14, {:type => Thrift::Types::I32}, :foo) }.to raise_error(Thrift::TypeError) + expect { Thrift.check_type(3.14, {:type => Thrift::Types::DOUBLE}, :foo) }.not_to raise_error + expect { Thrift.check_type(3, {:type => Thrift::Types::DOUBLE}, :foo) }.to raise_error(Thrift::TypeError) + expect { Thrift.check_type("3", {:type => Thrift::Types::STRING}, :foo) }.not_to raise_error + expect { Thrift.check_type(3, {:type => Thrift::Types::STRING}, :foo) }.to raise_error(Thrift::TypeError) hello = SpecNamespace::Hello.new - lambda { Thrift.check_type(hello, {:type => Thrift::Types::STRUCT, :class => SpecNamespace::Hello}, :foo) }.should_not raise_error(Thrift::TypeError) - lambda { Thrift.check_type("foo", {:type => Thrift::Types::STRUCT}, :foo) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type({:foo => 1}, {:type => Thrift::Types::MAP}, :foo) }.should_not raise_error(Thrift::TypeError) - lambda { Thrift.check_type([1], {:type => Thrift::Types::MAP}, :foo) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type([1], {:type => Thrift::Types::LIST}, :foo) }.should_not raise_error(Thrift::TypeError) - lambda { Thrift.check_type({:foo => 1}, {:type => Thrift::Types::LIST}, :foo) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type(Set.new([1,2]), {:type => Thrift::Types::SET}, :foo) }.should_not raise_error(Thrift::TypeError) - lambda { Thrift.check_type([1,2], {:type => Thrift::Types::SET}, :foo) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type({:foo => true}, {:type => Thrift::Types::SET}, :foo) }.should raise_error(Thrift::TypeError) + expect { Thrift.check_type(hello, {:type => Thrift::Types::STRUCT, :class => SpecNamespace::Hello}, :foo) }.not_to raise_error + expect { Thrift.check_type("foo", {:type => Thrift::Types::STRUCT}, :foo) }.to raise_error(Thrift::TypeError) + field = {:type => Thrift::Types::MAP, :key => {:type => Thrift::Types::I32}, :value => {:type => Thrift::Types::STRING}} + expect { Thrift.check_type({1 => "one"}, field, :foo) }.not_to raise_error + expect { Thrift.check_type([1], field, :foo) }.to raise_error(Thrift::TypeError) + field = {:type => Thrift::Types::LIST, :element => {:type => Thrift::Types::I32}} + expect { Thrift.check_type([1], field, :foo) }.not_to raise_error + expect { Thrift.check_type({:foo => 1}, field, :foo) }.to raise_error(Thrift::TypeError) + field = {:type => Thrift::Types::SET, :element => {:type => Thrift::Types::I32}} + expect { Thrift.check_type(Set.new([1,2]), field, :foo) }.not_to raise_error + expect { Thrift.check_type([1,2], field, :foo) }.to raise_error(Thrift::TypeError) + expect { Thrift.check_type({:foo => true}, field, :foo) }.to raise_error(Thrift::TypeError) end it "should error out if nil is passed and skip_types is false" do - lambda { Thrift.check_type(nil, {:type => Thrift::Types::BOOL}, :foo, false) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type(nil, {:type => Thrift::Types::BYTE}, :foo, false) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type(nil, {:type => Thrift::Types::I16}, :foo, false) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type(nil, {:type => Thrift::Types::I32}, :foo, false) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type(nil, {:type => Thrift::Types::I64}, :foo, false) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type(nil, {:type => Thrift::Types::DOUBLE}, :foo, false) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type(nil, {:type => Thrift::Types::STRING}, :foo, false) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type(nil, {:type => Thrift::Types::STRUCT}, :foo, false) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type(nil, {:type => Thrift::Types::LIST}, :foo, false) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type(nil, {:type => Thrift::Types::SET}, :foo, false) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type(nil, {:type => Thrift::Types::MAP}, :foo, false) }.should raise_error(Thrift::TypeError) + expect { Thrift.check_type(nil, {:type => Thrift::Types::BOOL}, :foo, false) }.to raise_error(Thrift::TypeError) + expect { Thrift.check_type(nil, {:type => Thrift::Types::BYTE}, :foo, false) }.to raise_error(Thrift::TypeError) + expect { Thrift.check_type(nil, {:type => Thrift::Types::I16}, :foo, false) }.to raise_error(Thrift::TypeError) + expect { Thrift.check_type(nil, {:type => Thrift::Types::I32}, :foo, false) }.to raise_error(Thrift::TypeError) + expect { Thrift.check_type(nil, {:type => Thrift::Types::I64}, :foo, false) }.to raise_error(Thrift::TypeError) + expect { Thrift.check_type(nil, {:type => Thrift::Types::DOUBLE}, :foo, false) }.to raise_error(Thrift::TypeError) + expect { Thrift.check_type(nil, {:type => Thrift::Types::STRING}, :foo, false) }.to raise_error(Thrift::TypeError) + expect { Thrift.check_type(nil, {:type => Thrift::Types::STRUCT}, :foo, false) }.to raise_error(Thrift::TypeError) + expect { Thrift.check_type(nil, {:type => Thrift::Types::LIST}, :foo, false) }.to raise_error(Thrift::TypeError) + expect { Thrift.check_type(nil, {:type => Thrift::Types::SET}, :foo, false) }.to raise_error(Thrift::TypeError) + expect { Thrift.check_type(nil, {:type => Thrift::Types::MAP}, :foo, false) }.to raise_error(Thrift::TypeError) end it "should check element types on containers" do field = {:type => Thrift::Types::LIST, :element => {:type => Thrift::Types::I32}} - lambda { Thrift.check_type([1, 2], field, :foo) }.should_not raise_error(Thrift::TypeError) - lambda { Thrift.check_type([1, nil, 2], field, :foo) }.should raise_error(Thrift::TypeError) + expect { Thrift.check_type([1, 2], field, :foo) }.not_to raise_error + expect { Thrift.check_type([1, nil, 2], field, :foo) }.to raise_error(Thrift::TypeError) field = {:type => Thrift::Types::MAP, :key => {:type => Thrift::Types::I32}, :value => {:type => Thrift::Types::STRING}} - lambda { Thrift.check_type({1 => "one", 2 => "two"}, field, :foo) }.should_not raise_error(Thrift::TypeError) - lambda { Thrift.check_type({1 => "one", nil => "nil"}, field, :foo) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type({1 => nil, 2 => "two"}, field, :foo) }.should raise_error(Thrift::TypeError) + expect { Thrift.check_type({1 => "one", 2 => "two"}, field, :foo) }.not_to raise_error + expect { Thrift.check_type({1 => "one", nil => "nil"}, field, :foo) }.to raise_error(Thrift::TypeError) + expect { Thrift.check_type({1 => nil, 2 => "two"}, field, :foo) }.to raise_error(Thrift::TypeError) field = {:type => Thrift::Types::SET, :element => {:type => Thrift::Types::I32}} - lambda { Thrift.check_type(Set.new([1, 2]), field, :foo) }.should_not raise_error(Thrift::TypeError) - lambda { Thrift.check_type(Set.new([1, nil, 2]), field, :foo) }.should raise_error(Thrift::TypeError) - lambda { Thrift.check_type(Set.new([1, 2.3, 2]), field, :foo) }.should raise_error(Thrift::TypeError) + expect { Thrift.check_type(Set.new([1, 2]), field, :foo) }.not_to raise_error + expect { Thrift.check_type(Set.new([1, nil, 2]), field, :foo) }.to raise_error(Thrift::TypeError) + expect { Thrift.check_type(Set.new([1, 2.3, 2]), field, :foo) }.to raise_error(Thrift::TypeError) field = {:type => Thrift::Types::STRUCT, :class => SpecNamespace::Hello} - lambda { Thrift.check_type(SpecNamespace::BoolStruct, field, :foo) }.should raise_error(Thrift::TypeError) + expect { Thrift.check_type(SpecNamespace::BoolStruct, field, :foo) }.to raise_error(Thrift::TypeError) end it "should give the Thrift::TypeError a readable message" do - msg = "Expected Types::STRING, received Fixnum for field foo" - lambda { Thrift.check_type(3, {:type => Thrift::Types::STRING}, :foo) }.should raise_error(Thrift::TypeError, msg) - msg = "Expected Types::STRING, received Fixnum for field foo.element" + msg = /Expected Types::STRING, received (Integer|Fixnum) for field foo/ + expect { Thrift.check_type(3, {:type => Thrift::Types::STRING}, :foo) }.to raise_error(Thrift::TypeError, msg) + msg = /Expected Types::STRING, received (Integer|Fixnum) for field foo.element/ field = {:type => Thrift::Types::LIST, :element => {:type => Thrift::Types::STRING}} - lambda { Thrift.check_type([3], field, :foo) }.should raise_error(Thrift::TypeError, msg) + expect { Thrift.check_type([3], field, :foo) }.to raise_error(Thrift::TypeError, msg) msg = "Expected Types::I32, received NilClass for field foo.element.key" field = {:type => Thrift::Types::LIST, :element => {:type => Thrift::Types::MAP, :key => {:type => Thrift::Types::I32}, :value => {:type => Thrift::Types::I32}}} - lambda { Thrift.check_type([{nil => 3}], field, :foo) }.should raise_error(Thrift::TypeError, msg) + expect { Thrift.check_type([{nil => 3}], field, :foo) }.to raise_error(Thrift::TypeError, msg) msg = "Expected Types::I32, received NilClass for field foo.element.value" - lambda { Thrift.check_type([{1 => nil}], field, :foo) }.should raise_error(Thrift::TypeError, msg) + expect { Thrift.check_type([{1 => nil}], field, :foo) }.to raise_error(Thrift::TypeError, msg) end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/union_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/union_spec.rb index 6ad3194..0ce6306 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/union_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/union_spec.rb @@ -24,85 +24,85 @@ describe 'Union' do describe Thrift::Union do it "should return nil value in unset union" do union = SpecNamespace::My_union.new - union.get_set_field.should == nil - union.get_value.should == nil + expect(union.get_set_field).to eq(nil) + expect(union.get_value).to eq(nil) end it "should set a field and be accessible through get_value and the named field accessor" do union = SpecNamespace::My_union.new union.integer32 = 25 - union.get_set_field.should == :integer32 - union.get_value.should == 25 - union.integer32.should == 25 + expect(union.get_set_field).to eq(:integer32) + expect(union.get_value).to eq(25) + expect(union.integer32).to eq(25) end it "should work correctly when instantiated with static field constructors" do union = SpecNamespace::My_union.integer32(5) - union.get_set_field.should == :integer32 - union.integer32.should == 5 + expect(union.get_set_field).to eq(:integer32) + expect(union.integer32).to eq(5) end it "should raise for wrong set field" do union = SpecNamespace::My_union.new union.integer32 = 25 - lambda { union.some_characters }.should raise_error(RuntimeError, "some_characters is not union's set field.") + expect { union.some_characters }.to raise_error(RuntimeError, "some_characters is not union's set field.") end it "should raise for wrong set field when hash initialized and type checking is off" do Thrift.type_checking = false union = SpecNamespace::My_union.new({incorrect_field: :incorrect}) example = lambda { Thrift::Serializer.new.serialize(union) } - example.should raise_error(RuntimeError, "set_field is not valid for this union!") + expect(example).to raise_error(RuntimeError, "set_field is not valid for this union!") end it "should not be equal to nil" do union = SpecNamespace::My_union.new - union.should_not == nil + expect(union).not_to eq(nil) end it "should not be equal with an empty String" do union = SpecNamespace::My_union.new - union.should_not == '' + expect(union).not_to eq('') end it "should not equate two different unions, i32 vs. string" do union = SpecNamespace::My_union.new(:integer32, 25) other_union = SpecNamespace::My_union.new(:some_characters, "blah!") - union.should_not == other_union + expect(union).not_to eq(other_union) end it "should properly reset setfield and setvalue" do union = SpecNamespace::My_union.new(:integer32, 25) - union.get_set_field.should == :integer32 + expect(union.get_set_field).to eq(:integer32) union.some_characters = "blah!" - union.get_set_field.should == :some_characters - union.get_value.should == "blah!" - lambda { union.integer32 }.should raise_error(RuntimeError, "integer32 is not union's set field.") + expect(union.get_set_field).to eq(:some_characters) + expect(union.get_value).to eq("blah!") + expect { union.integer32 }.to raise_error(RuntimeError, "integer32 is not union's set field.") end it "should not equate two different unions with different values" do union = SpecNamespace::My_union.new(:integer32, 25) other_union = SpecNamespace::My_union.new(:integer32, 400) - union.should_not == other_union + expect(union).not_to eq(other_union) end it "should not equate two different unions with different fields" do union = SpecNamespace::My_union.new(:integer32, 25) other_union = SpecNamespace::My_union.new(:other_i32, 25) - union.should_not == other_union + expect(union).not_to eq(other_union) end it "should inspect properly" do union = SpecNamespace::My_union.new(:integer32, 25) - union.inspect.should == "" + expect(union.inspect).to eq("") end it "should not allow setting with instance_variable_set" do union = SpecNamespace::My_union.new(:integer32, 27) union.instance_variable_set(:@some_characters, "hallo!") - union.get_set_field.should == :integer32 - union.get_value.should == 27 - lambda { union.some_characters }.should raise_error(RuntimeError, "some_characters is not union's set field.") + expect(union.get_set_field).to eq(:integer32) + expect(union.get_value).to eq(27) + expect { union.some_characters }.to raise_error(RuntimeError, "some_characters is not union's set field.") end it "should serialize to binary correctly" do @@ -114,7 +114,7 @@ describe 'Union' do other_union = SpecNamespace::My_union.new(:integer32, 25) other_union.read(proto) - other_union.should == union + expect(other_union).to eq(union) end it "should serialize to json correctly" do @@ -126,24 +126,24 @@ describe 'Union' do other_union = SpecNamespace::My_union.new(:integer32, 25) other_union.read(proto) - other_union.should == union + expect(other_union).to eq(union) end it "should raise when validating unset union" do union = SpecNamespace::My_union.new - lambda { union.validate }.should raise_error(StandardError, "Union fields are not set.") + expect { union.validate }.to raise_error(StandardError, "Union fields are not set.") other_union = SpecNamespace::My_union.new(:integer32, 1) - lambda { other_union.validate }.should_not raise_error(StandardError, "Union fields are not set.") + expect { other_union.validate }.not_to raise_error end it "should validate an enum field properly" do union = SpecNamespace::TestUnion.new(:enum_field, 3) - union.get_set_field.should == :enum_field - lambda { union.validate }.should raise_error(Thrift::ProtocolException, "Invalid value of field enum_field!") + expect(union.get_set_field).to eq(:enum_field) + expect { union.validate }.to raise_error(Thrift::ProtocolException, "Invalid value of field enum_field!") other_union = SpecNamespace::TestUnion.new(:enum_field, 1) - lambda { other_union.validate }.should_not raise_error(Thrift::ProtocolException, "Invalid value of field enum_field!") + expect { other_union.validate }.not_to raise_error end it "should properly serialize and match structs with a union" do @@ -158,37 +158,37 @@ describe 'Union' do other_union = SpecNamespace::My_union.new(:some_characters, "hello there") swu2 = SpecNamespace::Struct_with_union.new(:fun_union => other_union) - swu2.should_not == swu + expect(swu2).not_to eq(swu) swu2.read(proto) - swu2.should == swu + expect(swu2).to eq(swu) end it "should support old style constructor" do union = SpecNamespace::My_union.new(:integer32 => 26) - union.get_set_field.should == :integer32 - union.get_value.should == 26 + expect(union.get_set_field).to eq(:integer32) + expect(union.get_value).to eq(26) end it "should not throw an error when inspected and unset" do - lambda{SpecNamespace::TestUnion.new().inspect}.should_not raise_error + expect{SpecNamespace::TestUnion.new().inspect}.not_to raise_error end it "should print enum value name when inspected" do - SpecNamespace::My_union.new(:some_enum => SpecNamespace::SomeEnum::ONE).inspect.should == "" + expect(SpecNamespace::My_union.new(:some_enum => SpecNamespace::SomeEnum::ONE).inspect).to eq("") - SpecNamespace::My_union.new(:my_map => {SpecNamespace::SomeEnum::ONE => [SpecNamespace::SomeEnum::TWO]}).inspect.should == "" + expect(SpecNamespace::My_union.new(:my_map => {SpecNamespace::SomeEnum::ONE => [SpecNamespace::SomeEnum::TWO]}).inspect).to eq("") end it "should offer field? methods" do - SpecNamespace::My_union.new.some_enum?.should be_false - SpecNamespace::My_union.new(:some_enum => SpecNamespace::SomeEnum::ONE).some_enum?.should be_true - SpecNamespace::My_union.new(:im_true => false).im_true?.should be_true - SpecNamespace::My_union.new(:im_true => true).im_true?.should be_true + expect(SpecNamespace::My_union.new.some_enum?).to be_falsey + expect(SpecNamespace::My_union.new(:some_enum => SpecNamespace::SomeEnum::ONE).some_enum?).to be_truthy + expect(SpecNamespace::My_union.new(:im_true => false).im_true?).to be_truthy + expect(SpecNamespace::My_union.new(:im_true => true).im_true?).to be_truthy end it "should pretty print binary fields" do - SpecNamespace::TestUnion.new(:binary_field => "\001\002\003").inspect.should == "" + expect(SpecNamespace::TestUnion.new(:binary_field => "\001\002\003").inspect).to eq("") end it "should be comparable" do @@ -207,7 +207,7 @@ describe 'Union' do for y in 0..3 for x in 0..3 # puts "#{objs[y].inspect} <=> #{objs[x].inspect} should == #{relationships[y][x]}" - (objs[y] <=> objs[x]).should == relationships[y][x] + expect(objs[y] <=> objs[x]).to eq(relationships[y][x]) end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/spec/unix_socket_spec.rb b/vendor/git.apache.org/thrift.git/lib/rb/spec/unix_socket_spec.rb index cb6cff3..8623e95 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/spec/unix_socket_spec.rb +++ b/vendor/git.apache.org/thrift.git/lib/rb/spec/unix_socket_spec.rb @@ -26,21 +26,26 @@ describe 'UNIXSocket' do before(:each) do @path = '/tmp/thrift_spec_socket' @socket = Thrift::UNIXSocket.new(@path) - @handle = mock("Handle", :closed? => false) - @handle.stub!(:close) - ::UNIXSocket.stub!(:new).and_return(@handle) + @handle = double("Handle", :closed? => false) + allow(@handle).to receive(:close) + allow(::UNIXSocket).to receive(:new).and_return(@handle) end it_should_behave_like "a socket" it "should raise a TransportException when it cannot open a socket" do - ::UNIXSocket.should_receive(:new).and_raise(StandardError) - lambda { @socket.open }.should raise_error(Thrift::TransportException) { |e| e.type.should == Thrift::TransportException::NOT_OPEN } + expect(::UNIXSocket).to receive(:new).and_raise(StandardError) + expect { @socket.open }.to raise_error(Thrift::TransportException) { |e| expect(e.type).to eq(Thrift::TransportException::NOT_OPEN) } end it "should accept an optional timeout" do - ::UNIXSocket.stub!(:new) - Thrift::UNIXSocket.new(@path, 5).timeout.should == 5 + allow(::UNIXSocket).to receive(:new) + expect(Thrift::UNIXSocket.new(@path, 5).timeout).to eq(5) + end + + it "should provide a reasonable to_s" do + allow(::UNIXSocket).to receive(:new) + expect(Thrift::UNIXSocket.new(@path).to_s).to eq("domain(#{@path})") end end @@ -51,57 +56,61 @@ describe 'UNIXSocket' do end it "should create a handle when calling listen" do - UNIXServer.should_receive(:new).with(@path) + expect(UNIXServer).to receive(:new).with(@path) @socket.listen end it "should create a Thrift::UNIXSocket to wrap accepted sockets" do - handle = mock("UNIXServer") - UNIXServer.should_receive(:new).with(@path).and_return(handle) + handle = double("UNIXServer") + expect(UNIXServer).to receive(:new).with(@path).and_return(handle) @socket.listen - sock = mock("sock") - handle.should_receive(:accept).and_return(sock) - trans = mock("UNIXSocket") - Thrift::UNIXSocket.should_receive(:new).and_return(trans) - trans.should_receive(:handle=).with(sock) - @socket.accept.should == trans + sock = double("sock") + expect(handle).to receive(:accept).and_return(sock) + trans = double("UNIXSocket") + expect(Thrift::UNIXSocket).to receive(:new).and_return(trans) + expect(trans).to receive(:handle=).with(sock) + expect(@socket.accept).to eq(trans) end it "should close the handle when closed" do - handle = mock("UNIXServer", :closed? => false) - UNIXServer.should_receive(:new).with(@path).and_return(handle) + handle = double("UNIXServer", :closed? => false) + expect(UNIXServer).to receive(:new).with(@path).and_return(handle) @socket.listen - handle.should_receive(:close) - File.stub!(:delete) + expect(handle).to receive(:close) + allow(File).to receive(:delete) @socket.close end it "should delete the socket when closed" do - handle = mock("UNIXServer", :closed? => false) - UNIXServer.should_receive(:new).with(@path).and_return(handle) + handle = double("UNIXServer", :closed? => false) + expect(UNIXServer).to receive(:new).with(@path).and_return(handle) @socket.listen - handle.stub!(:close) - File.should_receive(:delete).with(@path) + allow(handle).to receive(:close) + expect(File).to receive(:delete).with(@path) @socket.close end it "should return nil when accepting if there is no handle" do - @socket.accept.should be_nil + expect(@socket.accept).to be_nil end it "should return true for closed? when appropriate" do - handle = mock("UNIXServer", :closed? => false) - UNIXServer.stub!(:new).and_return(handle) - File.stub!(:delete) + handle = double("UNIXServer", :closed? => false) + allow(UNIXServer).to receive(:new).and_return(handle) + allow(File).to receive(:delete) @socket.listen - @socket.should_not be_closed - handle.stub!(:close) + expect(@socket).not_to be_closed + allow(handle).to receive(:close) @socket.close - @socket.should be_closed + expect(@socket).to be_closed @socket.listen - @socket.should_not be_closed - handle.stub!(:closed?).and_return(true) - @socket.should be_closed + expect(@socket).not_to be_closed + allow(handle).to receive(:closed?).and_return(true) + expect(@socket).to be_closed + end + + it "should provide a reasonable to_s" do + expect(@socket.to_s).to eq("domain(#{@path})") end end end diff --git a/vendor/git.apache.org/thrift.git/lib/rb/thrift.gemspec b/vendor/git.apache.org/thrift.git/lib/rb/thrift.gemspec index 0ceebd2..5a3a0ae 100644 --- a/vendor/git.apache.org/thrift.git/lib/rb/thrift.gemspec +++ b/vendor/git.apache.org/thrift.git/lib/rb/thrift.gemspec @@ -3,14 +3,14 @@ $:.push File.expand_path("../lib", __FILE__) Gem::Specification.new do |s| s.name = 'thrift' - s.version = '0.10.0.0' + s.version = '0.12.0' s.authors = ['Thrift Developers'] s.email = ['dev@thrift.apache.org'] s.homepage = 'http://thrift.apache.org' s.summary = %q{Ruby bindings for Apache Thrift} s.description = %q{Ruby bindings for the Apache Thrift RPC system} - s.license = 'Apache 2.0' - s.extensions = ['ext/extconf.rb'] + s.license = 'Apache-2.0' + s.extensions = ['ext/extconf.rb'] s.has_rdoc = true s.rdoc_options = %w[--line-numbers --inline-source --title Thrift --main README] @@ -27,11 +27,14 @@ Gem::Specification.new do |s| s.require_paths = %w[lib ext] - s.add_development_dependency 'rspec', ['>= 2.10.0', '< 2.14.0'] - s.add_development_dependency "rack", "~> 1.5" - s.add_development_dependency "rack-test", "~> 0.6" - s.add_development_dependency "thin", "~> 1.5" - s.add_development_dependency "bundler", "~> 1" - s.add_development_dependency 'rake', '~> 10.5' + s.add_development_dependency 'bundler', '~> 1.11' + s.add_development_dependency 'pry', '~> 0.11.3' + s.add_development_dependency 'pry-byebug', '~> 3.6' + s.add_development_dependency 'pry-stack_explorer', '~> 0.4.9.2' + s.add_development_dependency 'rack', '~> 2.0' + s.add_development_dependency 'rack-test', '~> 0.8.3' + s.add_development_dependency 'rake', '~> 12.3' + s.add_development_dependency 'rspec', '~> 3.7' + s.add_development_dependency 'thin', '~> 1.7' end diff --git a/vendor/git.apache.org/thrift.git/lib/rs/Cargo.toml b/vendor/git.apache.org/thrift.git/lib/rs/Cargo.toml new file mode 100644 index 0000000..e79198d --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "thrift" +description = "Rust bindings for the Apache Thrift RPC system" +version = "0.12.0" +license = "Apache-2.0" +authors = ["Apache Thrift Developers "] +homepage = "http://thrift.apache.org" +documentation = "https://thrift.apache.org" +readme = "README.md" +exclude = ["Makefile*", "test/**"] +keywords = ["thrift"] + +[dependencies] +byteorder = "~1.2.1" +integer-encoding = "~1.0.4" +log = "~0.3.8" +threadpool = "~1.7.1" +try_from = "~0.2.2" + diff --git a/vendor/git.apache.org/thrift.git/lib/rs/Makefile.am b/vendor/git.apache.org/thrift.git/lib/rs/Makefile.am new file mode 100644 index 0000000..0a34120 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/Makefile.am @@ -0,0 +1,46 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +SUBDIRS = . + +if WITH_TESTS +SUBDIRS += test +endif + +install: + @echo '##############################################################' + @echo '##############################################################' + @echo 'The Rust client library should be installed via a Cargo.toml dependency - please see /lib/rs/README.md' + @echo '##############################################################' + @echo '##############################################################' + +check-local: + $(CARGO) test + +all-local: + $(CARGO) build + +clean-local: + $(CARGO) clean + -$(RM) Cargo.lock + +EXTRA_DIST = \ + src \ + Cargo.toml \ + README.md diff --git a/vendor/git.apache.org/thrift.git/lib/rs/README.md b/vendor/git.apache.org/thrift.git/lib/rs/README.md new file mode 100644 index 0000000..7c37a10 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/README.md @@ -0,0 +1,111 @@ +# Rust Thrift library + +## Overview + +This crate implements the components required to build a working Thrift server +and client. It is divided into the following modules: + + 1. errors + 2. protocol + 3. transport + 4. server + 5. autogen + +The modules are layered as shown. The `generated` layer is code generated by the +Thrift compiler's Rust plugin. It uses the components defined in this crate to +serialize and deserialize types and implement RPC. Users interact with these +types and services by writing their own code on top. + + ```text + +-----------+ + | app dev | + +-----------+ + | generated | <-> errors/results + +-----------+ + | protocol | + +-----------+ + | transport | + +-----------+ + ``` + +## Using this crate + +Add `thrift = "x.y.z"` to your `Cargo.toml`, where `x.y.z` is the version of the +Thrift compiler you're using. + +## API Documentation + +Full [Rustdoc](https://docs.rs/thrift/) + +## Compatibility + +The Rust library and auto-generated code targets Rust versions 1.28+. +It does not currently use any Rust 2018 features. + +### Breaking Changes + +Breaking changes are minimized. When they are made they will be outlined below with transition guidelines. + +##### Thrift 0.12.0 + +* **[THRIFT-4529]** - Rust enum variants are now camel-cased instead of uppercased to conform to Rust naming conventions + + Previously, enum variants were uppercased in the auto-generated code. + For example, the following thrift enum: + + ```thrift + // THRIFT + enum Operation { + ADD, + SUBTRACT, + MULTIPLY, + DIVIDE, + } + ``` + + used to generate: + + ```rust + // OLD AUTO-GENERATED RUST + pub enum Operation { + ADD, + SUBTRACT, + MULTIPLY, + DIVIDE, + } + ``` + It *now* generates: + ```rust + // NEW AUTO-GENERATED RUST + pub enum Operation { + Add, + Subtract, + Multiply, + Divide, + } + ``` + + You will have to change all enum variants in your code to use camel-cased names. + This should be a search and replace. + +## Contributing + +Bug reports and PRs are always welcome! Please see the +[Thrift website](https://thrift.apache.org/) for more details. + +Thrift Rust support requires code in several directories: + +* `compiler/cpp/src/thrift/generate/t_rs_generator.cc`: binding code generator +* `lib/rs`: runtime library +* `lib/rs/test`: supplemental tests +* `tutorial/rs`: tutorial client and server +* `test/rs`: cross-language test client and server + +All library code, test code and auto-generated code compiles and passes clippy +without warnings. All new code must do the same! When making changes ensure that: + +* `rustc` does does output any warnings +* `clippy` with default settings does not output any warnings (includes auto-generated code) +* `cargo test` is successful +* `make precross` and `make check` are successful +* `tutorial/bin/tutorial_client` and `tutorial/bin/tutorial_server` communicate diff --git a/vendor/git.apache.org/thrift.git/lib/rs/src/autogen.rs b/vendor/git.apache.org/thrift.git/lib/rs/src/autogen.rs new file mode 100644 index 0000000..54d4080 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/src/autogen.rs @@ -0,0 +1,45 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +//! Thrift compiler auto-generated support. +//! +//! +//! Types and functions used internally by the Thrift compiler's Rust plugin +//! to implement required functionality. Users should never have to use code +//! in this module directly. + +use protocol::{TInputProtocol, TOutputProtocol}; + +/// Specifies the minimum functionality an auto-generated client should provide +/// to communicate with a Thrift server. +pub trait TThriftClient { + /// Returns the input protocol used to read serialized Thrift messages + /// from the Thrift server. + fn i_prot_mut(&mut self) -> &mut TInputProtocol; + /// Returns the output protocol used to write serialized Thrift messages + /// to the Thrift server. + fn o_prot_mut(&mut self) -> &mut TOutputProtocol; + /// Returns the sequence number of the last message written to the Thrift + /// server. Returns `0` if no messages have been written. Sequence + /// numbers should *never* be negative, and this method returns an `i32` + /// simply because the Thrift protocol encodes sequence numbers as `i32` on + /// the wire. + fn sequence_number(&self) -> i32; // FIXME: consider returning a u32 + /// Increments the sequence number, indicating that a message with that + /// number has been sent to the Thrift server. + fn increment_sequence_number(&mut self) -> i32; +} diff --git a/vendor/git.apache.org/thrift.git/lib/rs/src/errors.rs b/vendor/git.apache.org/thrift.git/lib/rs/src/errors.rs new file mode 100644 index 0000000..16a2576 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/src/errors.rs @@ -0,0 +1,670 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +use std::convert::{From, Into}; +use std::error::Error as StdError; +use std::fmt::{Debug, Display, Formatter}; +use std::{error, fmt, io, string}; +use try_from::TryFrom; + +use protocol::{TFieldIdentifier, TInputProtocol, TOutputProtocol, TStructIdentifier, TType}; + +// FIXME: should all my error structs impl error::Error as well? +// FIXME: should all fields in TransportError, ProtocolError and ApplicationError be optional? + +/// Error type returned by all runtime library functions. +/// +/// `thrift::Error` is used throughout this crate as well as in auto-generated +/// Rust code. It consists of four variants defined by convention across Thrift +/// implementations: +/// +/// 1. `Transport`: errors encountered while operating on I/O channels +/// 2. `Protocol`: errors encountered during runtime-library processing +/// 3. `Application`: errors encountered within auto-generated code +/// 4. `User`: IDL-defined exception structs +/// +/// The `Application` variant also functions as a catch-all: all handler errors +/// are automatically turned into application errors. +/// +/// All error variants except `Error::User` take an eponymous struct with two +/// required fields: +/// +/// 1. `kind`: variant-specific enum identifying the error sub-type +/// 2. `message`: human-readable error info string +/// +/// `kind` is defined by convention while `message` is freeform. If none of the +/// enumerated kinds are suitable use `Unknown`. +/// +/// To simplify error creation convenience constructors are defined for all +/// variants, and conversions from their structs (`thrift::TransportError`, +/// `thrift::ProtocolError` and `thrift::ApplicationError` into `thrift::Error`. +/// +/// # Examples +/// +/// Create a `TransportError`. +/// +/// ``` +/// use thrift; +/// use thrift::{TransportError, TransportErrorKind}; +/// +/// // explicit +/// let err0: thrift::Result<()> = Err( +/// thrift::Error::Transport( +/// TransportError { +/// kind: TransportErrorKind::TimedOut, +/// message: format!("connection to server timed out") +/// } +/// ) +/// ); +/// +/// // use conversion +/// let err1: thrift::Result<()> = Err( +/// thrift::Error::from( +/// TransportError { +/// kind: TransportErrorKind::TimedOut, +/// message: format!("connection to server timed out") +/// } +/// ) +/// ); +/// +/// // use struct constructor +/// let err2: thrift::Result<()> = Err( +/// thrift::Error::Transport( +/// TransportError::new( +/// TransportErrorKind::TimedOut, +/// "connection to server timed out" +/// ) +/// ) +/// ); +/// +/// +/// // use error variant constructor +/// let err3: thrift::Result<()> = Err( +/// thrift::new_transport_error( +/// TransportErrorKind::TimedOut, +/// "connection to server timed out" +/// ) +/// ); +/// ``` +/// +/// Create an error from a string. +/// +/// ``` +/// use thrift; +/// use thrift::{ApplicationError, ApplicationErrorKind}; +/// +/// // we just use `From::from` to convert a `String` into a `thrift::Error` +/// let err0: thrift::Result<()> = Err( +/// thrift::Error::from("This is an error") +/// ); +/// +/// // err0 is equivalent to... +/// let err1: thrift::Result<()> = Err( +/// thrift::Error::Application( +/// ApplicationError { +/// kind: ApplicationErrorKind::Unknown, +/// message: format!("This is an error") +/// } +/// ) +/// ); +/// ``` +/// +/// Return an IDL-defined exception. +/// +/// ```text +/// // Thrift IDL exception definition. +/// exception Xception { +/// 1: i32 errorCode, +/// 2: string message +/// } +/// ``` +/// +/// ``` +/// use std::convert::From; +/// use std::error::Error; +/// use std::fmt; +/// use std::fmt::{Display, Formatter}; +/// +/// // auto-generated by the Thrift compiler +/// #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] +/// pub struct Xception { +/// pub error_code: Option, +/// pub message: Option, +/// } +/// +/// // auto-generated by the Thrift compiler +/// impl Error for Xception { +/// fn description(&self) -> &str { +/// "remote service threw Xception" +/// } +/// } +/// +/// // auto-generated by the Thrift compiler +/// impl From for thrift::Error { +/// fn from(e: Xception) -> Self { +/// thrift::Error::User(Box::new(e)) +/// } +/// } +/// +/// // auto-generated by the Thrift compiler +/// impl Display for Xception { +/// fn fmt(&self, f: &mut Formatter) -> fmt::Result { +/// self.description().fmt(f) +/// } +/// } +/// +/// // in user code... +/// let err: thrift::Result<()> = Err( +/// thrift::Error::from(Xception { error_code: Some(1), message: None }) +/// ); +/// ``` +pub enum Error { + /// Errors encountered while operating on I/O channels. + /// + /// These include *connection closed* and *bind failure*. + Transport(TransportError), + /// Errors encountered during runtime-library processing. + /// + /// These include *message too large* and *unsupported protocol version*. + Protocol(ProtocolError), + /// Errors encountered within auto-generated code, or when incoming + /// or outgoing messages violate the Thrift spec. + /// + /// These include *out-of-order messages* and *missing required struct + /// fields*. + /// + /// This variant also functions as a catch-all: errors from handler + /// functions are automatically returned as an `ApplicationError`. + Application(ApplicationError), + /// IDL-defined exception structs. + User(Box), +} + +impl Error { + /// Create an `ApplicationError` from its wire representation. + /// + /// Application code **should never** call this method directly. + pub fn read_application_error_from_in_protocol( + i: &mut TInputProtocol, + ) -> ::Result { + let mut message = "general remote error".to_owned(); + let mut kind = ApplicationErrorKind::Unknown; + + i.read_struct_begin()?; + + loop { + let field_ident = i.read_field_begin()?; + + if field_ident.field_type == TType::Stop { + break; + } + + let id = field_ident + .id + .expect("sender should always specify id for non-STOP field"); + + match id { + 1 => { + let remote_message = i.read_string()?; + i.read_field_end()?; + message = remote_message; + } + 2 => { + let remote_type_as_int = i.read_i32()?; + let remote_kind: ApplicationErrorKind = TryFrom::try_from(remote_type_as_int) + .unwrap_or(ApplicationErrorKind::Unknown); + i.read_field_end()?; + kind = remote_kind; + } + _ => { + i.skip(field_ident.field_type)?; + } + } + } + + i.read_struct_end()?; + + Ok(ApplicationError { + kind: kind, + message: message, + }) + } + + /// Convert an `ApplicationError` into its wire representation and write + /// it to the remote. + /// + /// Application code **should never** call this method directly. + pub fn write_application_error_to_out_protocol( + e: &ApplicationError, + o: &mut TOutputProtocol, + ) -> ::Result<()> { + o.write_struct_begin(&TStructIdentifier { + name: "TApplicationException".to_owned(), + })?; + + let message_field = TFieldIdentifier::new("message", TType::String, 1); + let type_field = TFieldIdentifier::new("type", TType::I32, 2); + + o.write_field_begin(&message_field)?; + o.write_string(&e.message)?; + o.write_field_end()?; + + o.write_field_begin(&type_field)?; + o.write_i32(e.kind as i32)?; + o.write_field_end()?; + + o.write_field_stop()?; + o.write_struct_end()?; + + o.flush() + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::Transport(ref e) => TransportError::description(e), + Error::Protocol(ref e) => ProtocolError::description(e), + Error::Application(ref e) => ApplicationError::description(e), + Error::User(ref e) => e.description(), + } + } +} + +impl Debug for Error { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + match *self { + Error::Transport(ref e) => Debug::fmt(e, f), + Error::Protocol(ref e) => Debug::fmt(e, f), + Error::Application(ref e) => Debug::fmt(e, f), + Error::User(ref e) => Debug::fmt(e, f), + } + } +} + +impl Display for Error { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + match *self { + Error::Transport(ref e) => Display::fmt(e, f), + Error::Protocol(ref e) => Display::fmt(e, f), + Error::Application(ref e) => Display::fmt(e, f), + Error::User(ref e) => Display::fmt(e, f), + } + } +} + +impl From for Error { + fn from(s: String) -> Self { + Error::Application(ApplicationError { + kind: ApplicationErrorKind::Unknown, + message: s, + }) + } +} + +impl<'a> From<&'a str> for Error { + fn from(s: &'a str) -> Self { + Error::Application(ApplicationError { + kind: ApplicationErrorKind::Unknown, + message: String::from(s), + }) + } +} + +impl From for Error { + fn from(e: TransportError) -> Self { + Error::Transport(e) + } +} + +impl From for Error { + fn from(e: ProtocolError) -> Self { + Error::Protocol(e) + } +} + +impl From for Error { + fn from(e: ApplicationError) -> Self { + Error::Application(e) + } +} + +/// Create a new `Error` instance of type `Transport` that wraps a +/// `TransportError`. +pub fn new_transport_error>(kind: TransportErrorKind, message: S) -> Error { + Error::Transport(TransportError::new(kind, message)) +} + +/// Information about I/O errors. +#[derive(Debug, Eq, PartialEq)] +pub struct TransportError { + /// I/O error variant. + /// + /// If a specific `TransportErrorKind` does not apply use + /// `TransportErrorKind::Unknown`. + pub kind: TransportErrorKind, + /// Human-readable error message. + pub message: String, +} + +impl TransportError { + /// Create a new `TransportError`. + pub fn new>(kind: TransportErrorKind, message: S) -> TransportError { + TransportError { + kind: kind, + message: message.into(), + } + } +} + +/// I/O error categories. +/// +/// This list may grow, and it is not recommended to match against it. +#[derive(Clone, Copy, Eq, Debug, PartialEq)] +pub enum TransportErrorKind { + /// Catch-all I/O error. + Unknown = 0, + /// An I/O operation was attempted when the transport channel was not open. + NotOpen = 1, + /// The transport channel cannot be opened because it was opened previously. + AlreadyOpen = 2, + /// An I/O operation timed out. + TimedOut = 3, + /// A read could not complete because no bytes were available. + EndOfFile = 4, + /// An invalid (buffer/message) size was requested or received. + NegativeSize = 5, + /// Too large a buffer or message size was requested or received. + SizeLimit = 6, +} + +impl TransportError { + fn description(&self) -> &str { + match self.kind { + TransportErrorKind::Unknown => "transport error", + TransportErrorKind::NotOpen => "not open", + TransportErrorKind::AlreadyOpen => "already open", + TransportErrorKind::TimedOut => "timed out", + TransportErrorKind::EndOfFile => "end of file", + TransportErrorKind::NegativeSize => "negative size message", + TransportErrorKind::SizeLimit => "message too long", + } + } +} + +impl Display for TransportError { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + write!(f, "{}", self.description()) + } +} + +impl TryFrom for TransportErrorKind { + type Err = Error; + fn try_from(from: i32) -> Result { + match from { + 0 => Ok(TransportErrorKind::Unknown), + 1 => Ok(TransportErrorKind::NotOpen), + 2 => Ok(TransportErrorKind::AlreadyOpen), + 3 => Ok(TransportErrorKind::TimedOut), + 4 => Ok(TransportErrorKind::EndOfFile), + 5 => Ok(TransportErrorKind::NegativeSize), + 6 => Ok(TransportErrorKind::SizeLimit), + _ => Err(Error::Protocol(ProtocolError { + kind: ProtocolErrorKind::Unknown, + message: format!("cannot convert {} to TransportErrorKind", from), + })), + } + } +} + +impl From for Error { + fn from(err: io::Error) -> Self { + match err.kind() { + io::ErrorKind::ConnectionReset + | io::ErrorKind::ConnectionRefused + | io::ErrorKind::NotConnected => Error::Transport(TransportError { + kind: TransportErrorKind::NotOpen, + message: err.description().to_owned(), + }), + io::ErrorKind::AlreadyExists => Error::Transport(TransportError { + kind: TransportErrorKind::AlreadyOpen, + message: err.description().to_owned(), + }), + io::ErrorKind::TimedOut => Error::Transport(TransportError { + kind: TransportErrorKind::TimedOut, + message: err.description().to_owned(), + }), + io::ErrorKind::UnexpectedEof => Error::Transport(TransportError { + kind: TransportErrorKind::EndOfFile, + message: err.description().to_owned(), + }), + _ => { + Error::Transport(TransportError { + kind: TransportErrorKind::Unknown, + message: err.description().to_owned(), // FIXME: use io error's debug string + }) + } + } + } +} + +impl From for Error { + fn from(err: string::FromUtf8Error) -> Self { + Error::Protocol(ProtocolError { + kind: ProtocolErrorKind::InvalidData, + message: err.description().to_owned(), // FIXME: use fmt::Error's debug string + }) + } +} + +/// Create a new `Error` instance of type `Protocol` that wraps a +/// `ProtocolError`. +pub fn new_protocol_error>(kind: ProtocolErrorKind, message: S) -> Error { + Error::Protocol(ProtocolError::new(kind, message)) +} + +/// Information about errors that occur in the runtime library. +#[derive(Debug, Eq, PartialEq)] +pub struct ProtocolError { + /// Protocol error variant. + /// + /// If a specific `ProtocolErrorKind` does not apply use + /// `ProtocolErrorKind::Unknown`. + pub kind: ProtocolErrorKind, + /// Human-readable error message. + pub message: String, +} + +impl ProtocolError { + /// Create a new `ProtocolError`. + pub fn new>(kind: ProtocolErrorKind, message: S) -> ProtocolError { + ProtocolError { + kind: kind, + message: message.into(), + } + } +} + +/// Runtime library error categories. +/// +/// This list may grow, and it is not recommended to match against it. +#[derive(Clone, Copy, Eq, Debug, PartialEq)] +pub enum ProtocolErrorKind { + /// Catch-all runtime-library error. + Unknown = 0, + /// An invalid argument was supplied to a library function, or invalid data + /// was received from a Thrift endpoint. + InvalidData = 1, + /// An invalid size was received in an encoded field. + NegativeSize = 2, + /// Thrift message or field was too long. + SizeLimit = 3, + /// Unsupported or unknown Thrift protocol version. + BadVersion = 4, + /// Unsupported Thrift protocol, server or field type. + NotImplemented = 5, + /// Reached the maximum nested depth to which an encoded Thrift field could + /// be skipped. + DepthLimit = 6, +} + +impl ProtocolError { + fn description(&self) -> &str { + match self.kind { + ProtocolErrorKind::Unknown => "protocol error", + ProtocolErrorKind::InvalidData => "bad data", + ProtocolErrorKind::NegativeSize => "negative message size", + ProtocolErrorKind::SizeLimit => "message too long", + ProtocolErrorKind::BadVersion => "invalid thrift version", + ProtocolErrorKind::NotImplemented => "not implemented", + ProtocolErrorKind::DepthLimit => "maximum skip depth reached", + } + } +} + +impl Display for ProtocolError { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + write!(f, "{}", self.description()) + } +} + +impl TryFrom for ProtocolErrorKind { + type Err = Error; + fn try_from(from: i32) -> Result { + match from { + 0 => Ok(ProtocolErrorKind::Unknown), + 1 => Ok(ProtocolErrorKind::InvalidData), + 2 => Ok(ProtocolErrorKind::NegativeSize), + 3 => Ok(ProtocolErrorKind::SizeLimit), + 4 => Ok(ProtocolErrorKind::BadVersion), + 5 => Ok(ProtocolErrorKind::NotImplemented), + 6 => Ok(ProtocolErrorKind::DepthLimit), + _ => Err(Error::Protocol(ProtocolError { + kind: ProtocolErrorKind::Unknown, + message: format!("cannot convert {} to ProtocolErrorKind", from), + })), + } + } +} + +/// Create a new `Error` instance of type `Application` that wraps an +/// `ApplicationError`. +pub fn new_application_error>(kind: ApplicationErrorKind, message: S) -> Error { + Error::Application(ApplicationError::new(kind, message)) +} + +/// Information about errors in auto-generated code or in user-implemented +/// service handlers. +#[derive(Debug, Eq, PartialEq)] +pub struct ApplicationError { + /// Application error variant. + /// + /// If a specific `ApplicationErrorKind` does not apply use + /// `ApplicationErrorKind::Unknown`. + pub kind: ApplicationErrorKind, + /// Human-readable error message. + pub message: String, +} + +impl ApplicationError { + /// Create a new `ApplicationError`. + pub fn new>(kind: ApplicationErrorKind, message: S) -> ApplicationError { + ApplicationError { + kind: kind, + message: message.into(), + } + } +} + +/// Auto-generated or user-implemented code error categories. +/// +/// This list may grow, and it is not recommended to match against it. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ApplicationErrorKind { + /// Catch-all application error. + Unknown = 0, + /// Made service call to an unknown service method. + UnknownMethod = 1, + /// Received an unknown Thrift message type. That is, not one of the + /// `thrift::protocol::TMessageType` variants. + InvalidMessageType = 2, + /// Method name in a service reply does not match the name of the + /// receiving service method. + WrongMethodName = 3, + /// Received an out-of-order Thrift message. + BadSequenceId = 4, + /// Service reply is missing required fields. + MissingResult = 5, + /// Auto-generated code failed unexpectedly. + InternalError = 6, + /// Thrift protocol error. When possible use `Error::ProtocolError` with a + /// specific `ProtocolErrorKind` instead. + ProtocolError = 7, + /// *Unknown*. Included only for compatibility with existing Thrift implementations. + InvalidTransform = 8, // ?? + /// Thrift endpoint requested, or is using, an unsupported encoding. + InvalidProtocol = 9, // ?? + /// Thrift endpoint requested, or is using, an unsupported auto-generated client type. + UnsupportedClientType = 10, // ?? +} + +impl ApplicationError { + fn description(&self) -> &str { + match self.kind { + ApplicationErrorKind::Unknown => "service error", + ApplicationErrorKind::UnknownMethod => "unknown service method", + ApplicationErrorKind::InvalidMessageType => "wrong message type received", + ApplicationErrorKind::WrongMethodName => "unknown method reply received", + ApplicationErrorKind::BadSequenceId => "out of order sequence id", + ApplicationErrorKind::MissingResult => "missing method result", + ApplicationErrorKind::InternalError => "remote service threw exception", + ApplicationErrorKind::ProtocolError => "protocol error", + ApplicationErrorKind::InvalidTransform => "invalid transform", + ApplicationErrorKind::InvalidProtocol => "invalid protocol requested", + ApplicationErrorKind::UnsupportedClientType => "unsupported protocol client", + } + } +} + +impl Display for ApplicationError { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + write!(f, "{}", self.description()) + } +} + +impl TryFrom for ApplicationErrorKind { + type Err = Error; + fn try_from(from: i32) -> Result { + match from { + 0 => Ok(ApplicationErrorKind::Unknown), + 1 => Ok(ApplicationErrorKind::UnknownMethod), + 2 => Ok(ApplicationErrorKind::InvalidMessageType), + 3 => Ok(ApplicationErrorKind::WrongMethodName), + 4 => Ok(ApplicationErrorKind::BadSequenceId), + 5 => Ok(ApplicationErrorKind::MissingResult), + 6 => Ok(ApplicationErrorKind::InternalError), + 7 => Ok(ApplicationErrorKind::ProtocolError), + 8 => Ok(ApplicationErrorKind::InvalidTransform), + 9 => Ok(ApplicationErrorKind::InvalidProtocol), + 10 => Ok(ApplicationErrorKind::UnsupportedClientType), + _ => Err(Error::Application(ApplicationError { + kind: ApplicationErrorKind::Unknown, + message: format!("cannot convert {} to ApplicationErrorKind", from), + })), + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/rs/src/lib.rs b/vendor/git.apache.org/thrift.git/lib/rs/src/lib.rs new file mode 100644 index 0000000..ca5c7d6 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/src/lib.rs @@ -0,0 +1,87 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +//! Rust runtime library for the Apache Thrift RPC system. +//! +//! This crate implements the components required to build a working +//! Thrift server and client. It is divided into the following modules: +//! +//! 1. errors +//! 2. protocol +//! 3. transport +//! 4. server +//! 5. autogen +//! +//! The modules are layered as shown in the diagram below. The `autogen'd` +//! layer is generated by the Thrift compiler's Rust plugin. It uses the +//! types and functions defined in this crate to serialize and deserialize +//! messages and implement RPC. Users interact with these types and services +//! by writing their own code that uses the auto-generated clients and +//! servers. +//! +//! ```text +//! +-----------+ +//! | user app | +//! +-----------+ +//! | autogen'd | (uses errors, autogen) +//! +-----------+ +//! | protocol | +//! +-----------+ +//! | transport | +//! +-----------+ +//! ``` + +#![crate_type = "lib"] +#![doc(test(attr(allow(unused_variables), deny(warnings))))] + +extern crate byteorder; +extern crate integer_encoding; +extern crate threadpool; +extern crate try_from; + +#[macro_use] +extern crate log; + +// NOTE: this macro has to be defined before any modules. See: +// https://danielkeep.github.io/quick-intro-to-macros.html#some-more-gotchas + +/// Assert that an expression returning a `Result` is a success. If it is, +/// return the value contained in the result, i.e. `expr.unwrap()`. +#[cfg(test)] +macro_rules! assert_success { + ($e: expr) => {{ + let res = $e; + assert!(res.is_ok()); + res.unwrap() + }}; +} + +pub mod protocol; +pub mod server; +pub mod transport; + +mod errors; +pub use errors::*; + +mod autogen; +pub use autogen::*; + +/// Result type returned by all runtime library functions. +/// +/// As is convention this is a typedef of `std::result::Result` +/// with `E` defined as the `thrift::Error` type. +pub type Result = std::result::Result; diff --git a/vendor/git.apache.org/thrift.git/lib/rs/src/protocol/binary.rs b/vendor/git.apache.org/thrift.git/lib/rs/src/protocol/binary.rs new file mode 100644 index 0000000..19aff3d --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/src/protocol/binary.rs @@ -0,0 +1,957 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +use byteorder::{BigEndian, ByteOrder, ReadBytesExt, WriteBytesExt}; +use std::convert::From; +use try_from::TryFrom; + +use super::{ + TFieldIdentifier, TInputProtocol, TInputProtocolFactory, TListIdentifier, TMapIdentifier, + TMessageIdentifier, TMessageType, +}; +use super::{TOutputProtocol, TOutputProtocolFactory, TSetIdentifier, TStructIdentifier, TType}; +use transport::{TReadTransport, TWriteTransport}; +use {ProtocolError, ProtocolErrorKind}; + +const BINARY_PROTOCOL_VERSION_1: u32 = 0x80010000; + +/// Read messages encoded in the Thrift simple binary encoding. +/// +/// There are two available modes: `strict` and `non-strict`, where the +/// `non-strict` version does not check for the protocol version in the +/// received message header. +/// +/// # Examples +/// +/// Create and use a `TBinaryInputProtocol`. +/// +/// ```no_run +/// use thrift::protocol::{TBinaryInputProtocol, TInputProtocol}; +/// use thrift::transport::TTcpChannel; +/// +/// let mut channel = TTcpChannel::new(); +/// channel.open("localhost:9090").unwrap(); +/// +/// let mut protocol = TBinaryInputProtocol::new(channel, true); +/// +/// let recvd_bool = protocol.read_bool().unwrap(); +/// let recvd_string = protocol.read_string().unwrap(); +/// ``` +#[derive(Debug)] +pub struct TBinaryInputProtocol +where + T: TReadTransport, +{ + strict: bool, + pub transport: T, // FIXME: shouldn't be public +} + +impl<'a, T> TBinaryInputProtocol +where + T: TReadTransport, +{ + /// Create a `TBinaryInputProtocol` that reads bytes from `transport`. + /// + /// Set `strict` to `true` if all incoming messages contain the protocol + /// version number in the protocol header. + pub fn new(transport: T, strict: bool) -> TBinaryInputProtocol { + TBinaryInputProtocol { + strict: strict, + transport: transport, + } + } +} + +impl TInputProtocol for TBinaryInputProtocol +where + T: TReadTransport, +{ + #[cfg_attr(feature = "cargo-clippy", allow(collapsible_if))] + fn read_message_begin(&mut self) -> ::Result { + let mut first_bytes = vec![0; 4]; + self.transport.read_exact(&mut first_bytes[..])?; + + // the thrift version header is intentionally negative + // so the first check we'll do is see if the sign bit is set + // and if so - assume it's the protocol-version header + if first_bytes[0] >= 8 { + // apparently we got a protocol-version header - check + // it, and if it matches, read the rest of the fields + if first_bytes[0..2] != [0x80, 0x01] { + Err(::Error::Protocol(ProtocolError { + kind: ProtocolErrorKind::BadVersion, + message: format!("received bad version: {:?}", &first_bytes[0..2]), + })) + } else { + let message_type: TMessageType = TryFrom::try_from(first_bytes[3])?; + let name = self.read_string()?; + let sequence_number = self.read_i32()?; + Ok(TMessageIdentifier::new(name, message_type, sequence_number)) + } + } else { + // apparently we didn't get a protocol-version header, + // which happens if the sender is not using the strict protocol + if self.strict { + // we're in strict mode however, and that always + // requires the protocol-version header to be written first + Err(::Error::Protocol(ProtocolError { + kind: ProtocolErrorKind::BadVersion, + message: format!("received bad version: {:?}", &first_bytes[0..2]), + })) + } else { + // in the non-strict version the first message field + // is the message name. strings (byte arrays) are length-prefixed, + // so we've just read the length in the first 4 bytes + let name_size = BigEndian::read_i32(&first_bytes) as usize; + let mut name_buf: Vec = vec![0; name_size]; + self.transport.read_exact(&mut name_buf)?; + let name = String::from_utf8(name_buf)?; + + // read the rest of the fields + let message_type: TMessageType = self.read_byte().and_then(TryFrom::try_from)?; + let sequence_number = self.read_i32()?; + Ok(TMessageIdentifier::new(name, message_type, sequence_number)) + } + } + } + + fn read_message_end(&mut self) -> ::Result<()> { + Ok(()) + } + + fn read_struct_begin(&mut self) -> ::Result> { + Ok(None) + } + + fn read_struct_end(&mut self) -> ::Result<()> { + Ok(()) + } + + fn read_field_begin(&mut self) -> ::Result { + let field_type_byte = self.read_byte()?; + let field_type = field_type_from_u8(field_type_byte)?; + let id = match field_type { + TType::Stop => Ok(0), + _ => self.read_i16(), + }?; + Ok(TFieldIdentifier::new::, String, i16>( + None, field_type, id, + )) + } + + fn read_field_end(&mut self) -> ::Result<()> { + Ok(()) + } + + fn read_bytes(&mut self) -> ::Result> { + let num_bytes = self.transport.read_i32::()? as usize; + let mut buf = vec![0u8; num_bytes]; + self.transport + .read_exact(&mut buf) + .map(|_| buf) + .map_err(From::from) + } + + fn read_bool(&mut self) -> ::Result { + let b = self.read_i8()?; + match b { + 0 => Ok(false), + _ => Ok(true), + } + } + + fn read_i8(&mut self) -> ::Result { + self.transport.read_i8().map_err(From::from) + } + + fn read_i16(&mut self) -> ::Result { + self.transport.read_i16::().map_err(From::from) + } + + fn read_i32(&mut self) -> ::Result { + self.transport.read_i32::().map_err(From::from) + } + + fn read_i64(&mut self) -> ::Result { + self.transport.read_i64::().map_err(From::from) + } + + fn read_double(&mut self) -> ::Result { + self.transport.read_f64::().map_err(From::from) + } + + fn read_string(&mut self) -> ::Result { + let bytes = self.read_bytes()?; + String::from_utf8(bytes).map_err(From::from) + } + + fn read_list_begin(&mut self) -> ::Result { + let element_type: TType = self.read_byte().and_then(field_type_from_u8)?; + let size = self.read_i32()?; + Ok(TListIdentifier::new(element_type, size)) + } + + fn read_list_end(&mut self) -> ::Result<()> { + Ok(()) + } + + fn read_set_begin(&mut self) -> ::Result { + let element_type: TType = self.read_byte().and_then(field_type_from_u8)?; + let size = self.read_i32()?; + Ok(TSetIdentifier::new(element_type, size)) + } + + fn read_set_end(&mut self) -> ::Result<()> { + Ok(()) + } + + fn read_map_begin(&mut self) -> ::Result { + let key_type: TType = self.read_byte().and_then(field_type_from_u8)?; + let value_type: TType = self.read_byte().and_then(field_type_from_u8)?; + let size = self.read_i32()?; + Ok(TMapIdentifier::new(key_type, value_type, size)) + } + + fn read_map_end(&mut self) -> ::Result<()> { + Ok(()) + } + + // utility + // + + fn read_byte(&mut self) -> ::Result { + self.transport.read_u8().map_err(From::from) + } +} + +/// Factory for creating instances of `TBinaryInputProtocol`. +#[derive(Default)] +pub struct TBinaryInputProtocolFactory; + +impl TBinaryInputProtocolFactory { + /// Create a `TBinaryInputProtocolFactory`. + pub fn new() -> TBinaryInputProtocolFactory { + TBinaryInputProtocolFactory {} + } +} + +impl TInputProtocolFactory for TBinaryInputProtocolFactory { + fn create(&self, transport: Box) -> Box { + Box::new(TBinaryInputProtocol::new(transport, true)) + } +} + +/// Write messages using the Thrift simple binary encoding. +/// +/// There are two available modes: `strict` and `non-strict`, where the +/// `strict` version writes the protocol version number in the outgoing message +/// header and the `non-strict` version does not. +/// +/// # Examples +/// +/// Create and use a `TBinaryOutputProtocol`. +/// +/// ```no_run +/// use thrift::protocol::{TBinaryOutputProtocol, TOutputProtocol}; +/// use thrift::transport::TTcpChannel; +/// +/// let mut channel = TTcpChannel::new(); +/// channel.open("localhost:9090").unwrap(); +/// +/// let mut protocol = TBinaryOutputProtocol::new(channel, true); +/// +/// protocol.write_bool(true).unwrap(); +/// protocol.write_string("test_string").unwrap(); +/// ``` +#[derive(Debug)] +pub struct TBinaryOutputProtocol +where + T: TWriteTransport, +{ + strict: bool, + pub transport: T, // FIXME: do not make public; only public for testing! +} + +impl TBinaryOutputProtocol +where + T: TWriteTransport, +{ + /// Create a `TBinaryOutputProtocol` that writes bytes to `transport`. + /// + /// Set `strict` to `true` if all outgoing messages should contain the + /// protocol version number in the protocol header. + pub fn new(transport: T, strict: bool) -> TBinaryOutputProtocol { + TBinaryOutputProtocol { + strict: strict, + transport: transport, + } + } +} + +impl TOutputProtocol for TBinaryOutputProtocol +where + T: TWriteTransport, +{ + fn write_message_begin(&mut self, identifier: &TMessageIdentifier) -> ::Result<()> { + if self.strict { + let message_type: u8 = identifier.message_type.into(); + let header = BINARY_PROTOCOL_VERSION_1 | (message_type as u32); + self.transport.write_u32::(header)?; + self.write_string(&identifier.name)?; + self.write_i32(identifier.sequence_number) + } else { + self.write_string(&identifier.name)?; + self.write_byte(identifier.message_type.into())?; + self.write_i32(identifier.sequence_number) + } + } + + fn write_message_end(&mut self) -> ::Result<()> { + Ok(()) + } + + fn write_struct_begin(&mut self, _: &TStructIdentifier) -> ::Result<()> { + Ok(()) + } + + fn write_struct_end(&mut self) -> ::Result<()> { + Ok(()) + } + + fn write_field_begin(&mut self, identifier: &TFieldIdentifier) -> ::Result<()> { + if identifier.id.is_none() && identifier.field_type != TType::Stop { + return Err(::Error::Protocol(ProtocolError { + kind: ProtocolErrorKind::Unknown, + message: format!( + "cannot write identifier {:?} without sequence number", + &identifier + ), + })); + } + + self.write_byte(field_type_to_u8(identifier.field_type))?; + if let Some(id) = identifier.id { + self.write_i16(id) + } else { + Ok(()) + } + } + + fn write_field_end(&mut self) -> ::Result<()> { + Ok(()) + } + + fn write_field_stop(&mut self) -> ::Result<()> { + self.write_byte(field_type_to_u8(TType::Stop)) + } + + fn write_bytes(&mut self, b: &[u8]) -> ::Result<()> { + self.write_i32(b.len() as i32)?; + self.transport.write_all(b).map_err(From::from) + } + + fn write_bool(&mut self, b: bool) -> ::Result<()> { + if b { + self.write_i8(1) + } else { + self.write_i8(0) + } + } + + fn write_i8(&mut self, i: i8) -> ::Result<()> { + self.transport.write_i8(i).map_err(From::from) + } + + fn write_i16(&mut self, i: i16) -> ::Result<()> { + self.transport.write_i16::(i).map_err(From::from) + } + + fn write_i32(&mut self, i: i32) -> ::Result<()> { + self.transport.write_i32::(i).map_err(From::from) + } + + fn write_i64(&mut self, i: i64) -> ::Result<()> { + self.transport.write_i64::(i).map_err(From::from) + } + + fn write_double(&mut self, d: f64) -> ::Result<()> { + self.transport.write_f64::(d).map_err(From::from) + } + + fn write_string(&mut self, s: &str) -> ::Result<()> { + self.write_bytes(s.as_bytes()) + } + + fn write_list_begin(&mut self, identifier: &TListIdentifier) -> ::Result<()> { + self.write_byte(field_type_to_u8(identifier.element_type))?; + self.write_i32(identifier.size) + } + + fn write_list_end(&mut self) -> ::Result<()> { + Ok(()) + } + + fn write_set_begin(&mut self, identifier: &TSetIdentifier) -> ::Result<()> { + self.write_byte(field_type_to_u8(identifier.element_type))?; + self.write_i32(identifier.size) + } + + fn write_set_end(&mut self) -> ::Result<()> { + Ok(()) + } + + fn write_map_begin(&mut self, identifier: &TMapIdentifier) -> ::Result<()> { + let key_type = identifier + .key_type + .expect("map identifier to write should contain key type"); + self.write_byte(field_type_to_u8(key_type))?; + let val_type = identifier + .value_type + .expect("map identifier to write should contain value type"); + self.write_byte(field_type_to_u8(val_type))?; + self.write_i32(identifier.size) + } + + fn write_map_end(&mut self) -> ::Result<()> { + Ok(()) + } + + fn flush(&mut self) -> ::Result<()> { + self.transport.flush().map_err(From::from) + } + + // utility + // + + fn write_byte(&mut self, b: u8) -> ::Result<()> { + self.transport.write_u8(b).map_err(From::from) + } +} + +/// Factory for creating instances of `TBinaryOutputProtocol`. +#[derive(Default)] +pub struct TBinaryOutputProtocolFactory; + +impl TBinaryOutputProtocolFactory { + /// Create a `TBinaryOutputProtocolFactory`. + pub fn new() -> TBinaryOutputProtocolFactory { + TBinaryOutputProtocolFactory {} + } +} + +impl TOutputProtocolFactory for TBinaryOutputProtocolFactory { + fn create(&self, transport: Box) -> Box { + Box::new(TBinaryOutputProtocol::new(transport, true)) + } +} + +fn field_type_to_u8(field_type: TType) -> u8 { + match field_type { + TType::Stop => 0x00, + TType::Void => 0x01, + TType::Bool => 0x02, + TType::I08 => 0x03, // equivalent to TType::Byte + TType::Double => 0x04, + TType::I16 => 0x06, + TType::I32 => 0x08, + TType::I64 => 0x0A, + TType::String | TType::Utf7 => 0x0B, + TType::Struct => 0x0C, + TType::Map => 0x0D, + TType::Set => 0x0E, + TType::List => 0x0F, + TType::Utf8 => 0x10, + TType::Utf16 => 0x11, + } +} + +fn field_type_from_u8(b: u8) -> ::Result { + match b { + 0x00 => Ok(TType::Stop), + 0x01 => Ok(TType::Void), + 0x02 => Ok(TType::Bool), + 0x03 => Ok(TType::I08), // Equivalent to TType::Byte + 0x04 => Ok(TType::Double), + 0x06 => Ok(TType::I16), + 0x08 => Ok(TType::I32), + 0x0A => Ok(TType::I64), + 0x0B => Ok(TType::String), // technically, also a UTF7, but we'll treat it as string + 0x0C => Ok(TType::Struct), + 0x0D => Ok(TType::Map), + 0x0E => Ok(TType::Set), + 0x0F => Ok(TType::List), + 0x10 => Ok(TType::Utf8), + 0x11 => Ok(TType::Utf16), + unkn => Err(::Error::Protocol(ProtocolError { + kind: ProtocolErrorKind::InvalidData, + message: format!("cannot convert {} to TType", unkn), + })), + } +} + +#[cfg(test)] +mod tests { + + use protocol::{ + TFieldIdentifier, TInputProtocol, TListIdentifier, TMapIdentifier, TMessageIdentifier, + TMessageType, TOutputProtocol, TSetIdentifier, TStructIdentifier, TType, + }; + use transport::{ReadHalf, TBufferChannel, TIoChannel, WriteHalf}; + + use super::*; + + #[test] + fn must_write_strict_message_call_begin() { + let (_, mut o_prot) = test_objects(true); + + let ident = TMessageIdentifier::new("test", TMessageType::Call, 1); + assert!(o_prot.write_message_begin(&ident).is_ok()); + + #[cfg_attr(rustfmt, rustfmt::skip)] + let expected: [u8; 16] = [ + 0x80, + 0x01, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x04, + 0x74, + 0x65, + 0x73, + 0x74, + 0x00, + 0x00, + 0x00, + 0x01, + ]; + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_write_non_strict_message_call_begin() { + let (_, mut o_prot) = test_objects(false); + + let ident = TMessageIdentifier::new("test", TMessageType::Call, 1); + assert!(o_prot.write_message_begin(&ident).is_ok()); + + #[cfg_attr(rustfmt, rustfmt::skip)] + let expected: [u8; 13] = [ + 0x00, + 0x00, + 0x00, + 0x04, + 0x74, + 0x65, + 0x73, + 0x74, + 0x01, + 0x00, + 0x00, + 0x00, + 0x01, + ]; + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_write_strict_message_reply_begin() { + let (_, mut o_prot) = test_objects(true); + + let ident = TMessageIdentifier::new("test", TMessageType::Reply, 10); + assert!(o_prot.write_message_begin(&ident).is_ok()); + + #[cfg_attr(rustfmt, rustfmt::skip)] + let expected: [u8; 16] = [ + 0x80, + 0x01, + 0x00, + 0x02, + 0x00, + 0x00, + 0x00, + 0x04, + 0x74, + 0x65, + 0x73, + 0x74, + 0x00, + 0x00, + 0x00, + 0x0A, + ]; + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_write_non_strict_message_reply_begin() { + let (_, mut o_prot) = test_objects(false); + + let ident = TMessageIdentifier::new("test", TMessageType::Reply, 10); + assert!(o_prot.write_message_begin(&ident).is_ok()); + + #[cfg_attr(rustfmt, rustfmt::skip)] + let expected: [u8; 13] = [ + 0x00, + 0x00, + 0x00, + 0x04, + 0x74, + 0x65, + 0x73, + 0x74, + 0x02, + 0x00, + 0x00, + 0x00, + 0x0A, + ]; + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_strict_message_begin() { + let (mut i_prot, mut o_prot) = test_objects(true); + + let sent_ident = TMessageIdentifier::new("test", TMessageType::Call, 1); + assert!(o_prot.write_message_begin(&sent_ident).is_ok()); + + copy_write_buffer_to_read_buffer!(o_prot); + + let received_ident = assert_success!(i_prot.read_message_begin()); + assert_eq!(&received_ident, &sent_ident); + } + + #[test] + fn must_round_trip_non_strict_message_begin() { + let (mut i_prot, mut o_prot) = test_objects(false); + + let sent_ident = TMessageIdentifier::new("test", TMessageType::Call, 1); + assert!(o_prot.write_message_begin(&sent_ident).is_ok()); + + copy_write_buffer_to_read_buffer!(o_prot); + + let received_ident = assert_success!(i_prot.read_message_begin()); + assert_eq!(&received_ident, &sent_ident); + } + + #[test] + fn must_write_message_end() { + assert_no_write(|o| o.write_message_end(), true); + } + + #[test] + fn must_write_struct_begin() { + assert_no_write( + |o| o.write_struct_begin(&TStructIdentifier::new("foo")), + true, + ); + } + + #[test] + fn must_write_struct_end() { + assert_no_write(|o| o.write_struct_end(), true); + } + + #[test] + fn must_write_field_begin() { + let (_, mut o_prot) = test_objects(true); + + assert!(o_prot + .write_field_begin(&TFieldIdentifier::new("some_field", TType::String, 22)) + .is_ok()); + + let expected: [u8; 3] = [0x0B, 0x00, 0x16]; + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_field_begin() { + let (mut i_prot, mut o_prot) = test_objects(true); + + let sent_field_ident = TFieldIdentifier::new("foo", TType::I64, 20); + assert!(o_prot.write_field_begin(&sent_field_ident).is_ok()); + + copy_write_buffer_to_read_buffer!(o_prot); + + let expected_ident = TFieldIdentifier { + name: None, + field_type: TType::I64, + id: Some(20), + }; // no name + let received_ident = assert_success!(i_prot.read_field_begin()); + assert_eq!(&received_ident, &expected_ident); + } + + #[test] + fn must_write_stop_field() { + let (_, mut o_prot) = test_objects(true); + + assert!(o_prot.write_field_stop().is_ok()); + + let expected: [u8; 1] = [0x00]; + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_field_stop() { + let (mut i_prot, mut o_prot) = test_objects(true); + + assert!(o_prot.write_field_stop().is_ok()); + + copy_write_buffer_to_read_buffer!(o_prot); + + let expected_ident = TFieldIdentifier { + name: None, + field_type: TType::Stop, + id: Some(0), + }; // we get id 0 + + let received_ident = assert_success!(i_prot.read_field_begin()); + assert_eq!(&received_ident, &expected_ident); + } + + #[test] + fn must_write_field_end() { + assert_no_write(|o| o.write_field_end(), true); + } + + #[test] + fn must_write_list_begin() { + let (_, mut o_prot) = test_objects(true); + + assert!(o_prot + .write_list_begin(&TListIdentifier::new(TType::Bool, 5)) + .is_ok()); + + let expected: [u8; 5] = [0x02, 0x00, 0x00, 0x00, 0x05]; + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_list_begin() { + let (mut i_prot, mut o_prot) = test_objects(true); + + let ident = TListIdentifier::new(TType::List, 900); + assert!(o_prot.write_list_begin(&ident).is_ok()); + + copy_write_buffer_to_read_buffer!(o_prot); + + let received_ident = assert_success!(i_prot.read_list_begin()); + assert_eq!(&received_ident, &ident); + } + + #[test] + fn must_write_list_end() { + assert_no_write(|o| o.write_list_end(), true); + } + + #[test] + fn must_write_set_begin() { + let (_, mut o_prot) = test_objects(true); + + assert!(o_prot + .write_set_begin(&TSetIdentifier::new(TType::I16, 7)) + .is_ok()); + + let expected: [u8; 5] = [0x06, 0x00, 0x00, 0x00, 0x07]; + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_set_begin() { + let (mut i_prot, mut o_prot) = test_objects(true); + + let ident = TSetIdentifier::new(TType::I64, 2000); + assert!(o_prot.write_set_begin(&ident).is_ok()); + + copy_write_buffer_to_read_buffer!(o_prot); + + let received_ident_result = i_prot.read_set_begin(); + assert!(received_ident_result.is_ok()); + assert_eq!(&received_ident_result.unwrap(), &ident); + } + + #[test] + fn must_write_set_end() { + assert_no_write(|o| o.write_set_end(), true); + } + + #[test] + fn must_write_map_begin() { + let (_, mut o_prot) = test_objects(true); + + assert!(o_prot + .write_map_begin(&TMapIdentifier::new(TType::I64, TType::Struct, 32)) + .is_ok()); + + let expected: [u8; 6] = [0x0A, 0x0C, 0x00, 0x00, 0x00, 0x20]; + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_map_begin() { + let (mut i_prot, mut o_prot) = test_objects(true); + + let ident = TMapIdentifier::new(TType::Map, TType::Set, 100); + assert!(o_prot.write_map_begin(&ident).is_ok()); + + copy_write_buffer_to_read_buffer!(o_prot); + + let received_ident = assert_success!(i_prot.read_map_begin()); + assert_eq!(&received_ident, &ident); + } + + #[test] + fn must_write_map_end() { + assert_no_write(|o| o.write_map_end(), true); + } + + #[test] + fn must_write_bool_true() { + let (_, mut o_prot) = test_objects(true); + + assert!(o_prot.write_bool(true).is_ok()); + + let expected: [u8; 1] = [0x01]; + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_write_bool_false() { + let (_, mut o_prot) = test_objects(true); + + assert!(o_prot.write_bool(false).is_ok()); + + let expected: [u8; 1] = [0x00]; + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_read_bool_true() { + let (mut i_prot, _) = test_objects(true); + + set_readable_bytes!(i_prot, &[0x01]); + + let read_bool = assert_success!(i_prot.read_bool()); + assert_eq!(read_bool, true); + } + + #[test] + fn must_read_bool_false() { + let (mut i_prot, _) = test_objects(true); + + set_readable_bytes!(i_prot, &[0x00]); + + let read_bool = assert_success!(i_prot.read_bool()); + assert_eq!(read_bool, false); + } + + #[test] + fn must_allow_any_non_zero_value_to_be_interpreted_as_bool_true() { + let (mut i_prot, _) = test_objects(true); + + set_readable_bytes!(i_prot, &[0xAC]); + + let read_bool = assert_success!(i_prot.read_bool()); + assert_eq!(read_bool, true); + } + + #[test] + fn must_write_bytes() { + let (_, mut o_prot) = test_objects(true); + + let bytes: [u8; 10] = [0x0A, 0xCC, 0xD1, 0x84, 0x99, 0x12, 0xAB, 0xBB, 0x45, 0xDF]; + + assert!(o_prot.write_bytes(&bytes).is_ok()); + + let buf = o_prot.transport.write_bytes(); + assert_eq!(&buf[0..4], [0x00, 0x00, 0x00, 0x0A]); // length + assert_eq!(&buf[4..], bytes); // actual bytes + } + + #[test] + fn must_round_trip_bytes() { + let (mut i_prot, mut o_prot) = test_objects(true); + + #[cfg_attr(rustfmt, rustfmt::skip)] + let bytes: [u8; 25] = [ + 0x20, + 0xFD, + 0x18, + 0x84, + 0x99, + 0x12, + 0xAB, + 0xBB, + 0x45, + 0xDF, + 0x34, + 0xDC, + 0x98, + 0xA4, + 0x6D, + 0xF3, + 0x99, + 0xB4, + 0xB7, + 0xD4, + 0x9C, + 0xA5, + 0xB3, + 0xC9, + 0x88, + ]; + + assert!(o_prot.write_bytes(&bytes).is_ok()); + + copy_write_buffer_to_read_buffer!(o_prot); + + let received_bytes = assert_success!(i_prot.read_bytes()); + assert_eq!(&received_bytes, &bytes); + } + + fn test_objects( + strict: bool, + ) -> ( + TBinaryInputProtocol>, + TBinaryOutputProtocol>, + ) { + let mem = TBufferChannel::with_capacity(40, 40); + + let (r_mem, w_mem) = mem.split().unwrap(); + + let i_prot = TBinaryInputProtocol::new(r_mem, strict); + let o_prot = TBinaryOutputProtocol::new(w_mem, strict); + + (i_prot, o_prot) + } + + fn assert_no_write(mut write_fn: F, strict: bool) + where + F: FnMut(&mut TBinaryOutputProtocol>) -> ::Result<()>, + { + let (_, mut o_prot) = test_objects(strict); + assert!(write_fn(&mut o_prot).is_ok()); + assert_eq!(o_prot.transport.write_bytes().len(), 0); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/rs/src/protocol/compact.rs b/vendor/git.apache.org/thrift.git/lib/rs/src/protocol/compact.rs new file mode 100644 index 0000000..df5edaa --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/src/protocol/compact.rs @@ -0,0 +1,2386 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; +use integer_encoding::{VarIntReader, VarIntWriter}; +use std::convert::From; +use std::io; +use try_from::TryFrom; + +use super::{ + TFieldIdentifier, TInputProtocol, TInputProtocolFactory, TListIdentifier, TMapIdentifier, + TMessageIdentifier, TMessageType, +}; +use super::{TOutputProtocol, TOutputProtocolFactory, TSetIdentifier, TStructIdentifier, TType}; +use transport::{TReadTransport, TWriteTransport}; + +const COMPACT_PROTOCOL_ID: u8 = 0x82; +const COMPACT_VERSION: u8 = 0x01; +const COMPACT_VERSION_MASK: u8 = 0x1F; + +/// Read messages encoded in the Thrift compact protocol. +/// +/// # Examples +/// +/// Create and use a `TCompactInputProtocol`. +/// +/// ```no_run +/// use thrift::protocol::{TCompactInputProtocol, TInputProtocol}; +/// use thrift::transport::TTcpChannel; +/// +/// let mut channel = TTcpChannel::new(); +/// channel.open("localhost:9090").unwrap(); +/// +/// let mut protocol = TCompactInputProtocol::new(channel); +/// +/// let recvd_bool = protocol.read_bool().unwrap(); +/// let recvd_string = protocol.read_string().unwrap(); +/// ``` +#[derive(Debug)] +pub struct TCompactInputProtocol +where + T: TReadTransport, +{ + // Identifier of the last field deserialized for a struct. + last_read_field_id: i16, + // Stack of the last read field ids (a new entry is added each time a nested struct is read). + read_field_id_stack: Vec, + // Boolean value for a field. + // Saved because boolean fields and their value are encoded in a single byte, + // and reading the field only occurs after the field id is read. + pending_read_bool_value: Option, + // Underlying transport used for byte-level operations. + transport: T, +} + +impl TCompactInputProtocol +where + T: TReadTransport, +{ + /// Create a `TCompactInputProtocol` that reads bytes from `transport`. + pub fn new(transport: T) -> TCompactInputProtocol { + TCompactInputProtocol { + last_read_field_id: 0, + read_field_id_stack: Vec::new(), + pending_read_bool_value: None, + transport: transport, + } + } + + fn read_list_set_begin(&mut self) -> ::Result<(TType, i32)> { + let header = self.read_byte()?; + let element_type = collection_u8_to_type(header & 0x0F)?; + + let element_count; + let possible_element_count = (header & 0xF0) >> 4; + if possible_element_count != 15 { + // high bits set high if count and type encoded separately + element_count = possible_element_count as i32; + } else { + element_count = self.transport.read_varint::()? as i32; + } + + Ok((element_type, element_count)) + } +} + +impl TInputProtocol for TCompactInputProtocol +where + T: TReadTransport, +{ + fn read_message_begin(&mut self) -> ::Result { + let compact_id = self.read_byte()?; + if compact_id != COMPACT_PROTOCOL_ID { + Err(::Error::Protocol(::ProtocolError { + kind: ::ProtocolErrorKind::BadVersion, + message: format!("invalid compact protocol header {:?}", compact_id), + })) + } else { + Ok(()) + }?; + + let type_and_byte = self.read_byte()?; + let received_version = type_and_byte & COMPACT_VERSION_MASK; + if received_version != COMPACT_VERSION { + Err(::Error::Protocol(::ProtocolError { + kind: ::ProtocolErrorKind::BadVersion, + message: format!( + "cannot process compact protocol version {:?}", + received_version + ), + })) + } else { + Ok(()) + }?; + + // NOTE: unsigned right shift will pad with 0s + let message_type: TMessageType = TMessageType::try_from(type_and_byte >> 5)?; + let sequence_number = self.read_i32()?; + let service_call_name = self.read_string()?; + + self.last_read_field_id = 0; + + Ok(TMessageIdentifier::new( + service_call_name, + message_type, + sequence_number, + )) + } + + fn read_message_end(&mut self) -> ::Result<()> { + Ok(()) + } + + fn read_struct_begin(&mut self) -> ::Result> { + self.read_field_id_stack.push(self.last_read_field_id); + self.last_read_field_id = 0; + Ok(None) + } + + fn read_struct_end(&mut self) -> ::Result<()> { + self.last_read_field_id = self + .read_field_id_stack + .pop() + .expect("should have previous field ids"); + Ok(()) + } + + fn read_field_begin(&mut self) -> ::Result { + // we can read at least one byte, which is: + // - the type + // - the field delta and the type + let field_type = self.read_byte()?; + let field_delta = (field_type & 0xF0) >> 4; + let field_type = match field_type & 0x0F { + 0x01 => { + self.pending_read_bool_value = Some(true); + Ok(TType::Bool) + } + 0x02 => { + self.pending_read_bool_value = Some(false); + Ok(TType::Bool) + } + ttu8 => u8_to_type(ttu8), + }?; + + match field_type { + TType::Stop => Ok( + TFieldIdentifier::new::, String, Option>( + None, + TType::Stop, + None, + ), + ), + _ => { + if field_delta != 0 { + self.last_read_field_id += field_delta as i16; + } else { + self.last_read_field_id = self.read_i16()?; + }; + + Ok(TFieldIdentifier { + name: None, + field_type: field_type, + id: Some(self.last_read_field_id), + }) + } + } + } + + fn read_field_end(&mut self) -> ::Result<()> { + Ok(()) + } + + fn read_bool(&mut self) -> ::Result { + match self.pending_read_bool_value.take() { + Some(b) => Ok(b), + None => { + let b = self.read_byte()?; + match b { + 0x01 => Ok(true), + 0x02 => Ok(false), + unkn => Err(::Error::Protocol(::ProtocolError { + kind: ::ProtocolErrorKind::InvalidData, + message: format!("cannot convert {} into bool", unkn), + })), + } + } + } + } + + fn read_bytes(&mut self) -> ::Result> { + let len = self.transport.read_varint::()?; + let mut buf = vec![0u8; len as usize]; + self.transport + .read_exact(&mut buf) + .map_err(From::from) + .map(|_| buf) + } + + fn read_i8(&mut self) -> ::Result { + self.read_byte().map(|i| i as i8) + } + + fn read_i16(&mut self) -> ::Result { + self.transport.read_varint::().map_err(From::from) + } + + fn read_i32(&mut self) -> ::Result { + self.transport.read_varint::().map_err(From::from) + } + + fn read_i64(&mut self) -> ::Result { + self.transport.read_varint::().map_err(From::from) + } + + fn read_double(&mut self) -> ::Result { + self.transport.read_f64::().map_err(From::from) + } + + fn read_string(&mut self) -> ::Result { + let bytes = self.read_bytes()?; + String::from_utf8(bytes).map_err(From::from) + } + + fn read_list_begin(&mut self) -> ::Result { + let (element_type, element_count) = self.read_list_set_begin()?; + Ok(TListIdentifier::new(element_type, element_count)) + } + + fn read_list_end(&mut self) -> ::Result<()> { + Ok(()) + } + + fn read_set_begin(&mut self) -> ::Result { + let (element_type, element_count) = self.read_list_set_begin()?; + Ok(TSetIdentifier::new(element_type, element_count)) + } + + fn read_set_end(&mut self) -> ::Result<()> { + Ok(()) + } + + fn read_map_begin(&mut self) -> ::Result { + let element_count = self.transport.read_varint::()? as i32; + if element_count == 0 { + Ok(TMapIdentifier::new(None, None, 0)) + } else { + let type_header = self.read_byte()?; + let key_type = collection_u8_to_type((type_header & 0xF0) >> 4)?; + let val_type = collection_u8_to_type(type_header & 0x0F)?; + Ok(TMapIdentifier::new(key_type, val_type, element_count)) + } + } + + fn read_map_end(&mut self) -> ::Result<()> { + Ok(()) + } + + // utility + // + + fn read_byte(&mut self) -> ::Result { + let mut buf = [0u8; 1]; + self.transport + .read_exact(&mut buf) + .map_err(From::from) + .map(|_| buf[0]) + } +} + +impl io::Seek for TCompactInputProtocol +where + T: io::Seek + TReadTransport, +{ + fn seek(&mut self, pos: io::SeekFrom) -> io::Result { + self.transport.seek(pos) + } +} + +/// Factory for creating instances of `TCompactInputProtocol`. +#[derive(Default)] +pub struct TCompactInputProtocolFactory; + +impl TCompactInputProtocolFactory { + /// Create a `TCompactInputProtocolFactory`. + pub fn new() -> TCompactInputProtocolFactory { + TCompactInputProtocolFactory {} + } +} + +impl TInputProtocolFactory for TCompactInputProtocolFactory { + fn create(&self, transport: Box) -> Box { + Box::new(TCompactInputProtocol::new(transport)) + } +} + +/// Write messages using the Thrift compact protocol. +/// +/// # Examples +/// +/// Create and use a `TCompactOutputProtocol`. +/// +/// ```no_run +/// use thrift::protocol::{TCompactOutputProtocol, TOutputProtocol}; +/// use thrift::transport::TTcpChannel; +/// +/// let mut channel = TTcpChannel::new(); +/// channel.open("localhost:9090").unwrap(); +/// +/// let mut protocol = TCompactOutputProtocol::new(channel); +/// +/// protocol.write_bool(true).unwrap(); +/// protocol.write_string("test_string").unwrap(); +/// ``` +#[derive(Debug)] +pub struct TCompactOutputProtocol +where + T: TWriteTransport, +{ + // Identifier of the last field serialized for a struct. + last_write_field_id: i16, + // Stack of the last written field ids (new entry added each time a nested struct is written). + write_field_id_stack: Vec, + // Field identifier of the boolean field to be written. + // Saved because boolean fields and their value are encoded in a single byte + pending_write_bool_field_identifier: Option, + // Underlying transport used for byte-level operations. + transport: T, +} + +impl TCompactOutputProtocol +where + T: TWriteTransport, +{ + /// Create a `TCompactOutputProtocol` that writes bytes to `transport`. + pub fn new(transport: T) -> TCompactOutputProtocol { + TCompactOutputProtocol { + last_write_field_id: 0, + write_field_id_stack: Vec::new(), + pending_write_bool_field_identifier: None, + transport: transport, + } + } + + // FIXME: field_type as unconstrained u8 is bad + fn write_field_header(&mut self, field_type: u8, field_id: i16) -> ::Result<()> { + let field_delta = field_id - self.last_write_field_id; + if field_delta > 0 && field_delta < 15 { + self.write_byte(((field_delta as u8) << 4) | field_type)?; + } else { + self.write_byte(field_type)?; + self.write_i16(field_id)?; + } + self.last_write_field_id = field_id; + Ok(()) + } + + fn write_list_set_begin(&mut self, element_type: TType, element_count: i32) -> ::Result<()> { + let elem_identifier = collection_type_to_u8(element_type); + if element_count <= 14 { + let header = (element_count as u8) << 4 | elem_identifier; + self.write_byte(header) + } else { + let header = 0xF0 | elem_identifier; + self.write_byte(header)?; + self.transport + .write_varint(element_count as u32) + .map_err(From::from) + .map(|_| ()) + } + } + + fn assert_no_pending_bool_write(&self) { + if let Some(ref f) = self.pending_write_bool_field_identifier { + panic!("pending bool field {:?} not written", f) + } + } +} + +impl TOutputProtocol for TCompactOutputProtocol +where + T: TWriteTransport, +{ + fn write_message_begin(&mut self, identifier: &TMessageIdentifier) -> ::Result<()> { + self.write_byte(COMPACT_PROTOCOL_ID)?; + self.write_byte((u8::from(identifier.message_type) << 5) | COMPACT_VERSION)?; + self.write_i32(identifier.sequence_number)?; + self.write_string(&identifier.name)?; + Ok(()) + } + + fn write_message_end(&mut self) -> ::Result<()> { + self.assert_no_pending_bool_write(); + Ok(()) + } + + fn write_struct_begin(&mut self, _: &TStructIdentifier) -> ::Result<()> { + self.write_field_id_stack.push(self.last_write_field_id); + self.last_write_field_id = 0; + Ok(()) + } + + fn write_struct_end(&mut self) -> ::Result<()> { + self.assert_no_pending_bool_write(); + self.last_write_field_id = self + .write_field_id_stack + .pop() + .expect("should have previous field ids"); + Ok(()) + } + + fn write_field_begin(&mut self, identifier: &TFieldIdentifier) -> ::Result<()> { + match identifier.field_type { + TType::Bool => { + if self.pending_write_bool_field_identifier.is_some() { + panic!( + "should not have a pending bool while writing another bool with id: \ + {:?}", + identifier + ) + } + self.pending_write_bool_field_identifier = Some(identifier.clone()); + Ok(()) + } + _ => { + let field_type = type_to_u8(identifier.field_type); + let field_id = identifier.id.expect("non-stop field should have field id"); + self.write_field_header(field_type, field_id) + } + } + } + + fn write_field_end(&mut self) -> ::Result<()> { + self.assert_no_pending_bool_write(); + Ok(()) + } + + fn write_field_stop(&mut self) -> ::Result<()> { + self.assert_no_pending_bool_write(); + self.write_byte(type_to_u8(TType::Stop)) + } + + fn write_bool(&mut self, b: bool) -> ::Result<()> { + match self.pending_write_bool_field_identifier.take() { + Some(pending) => { + let field_id = pending.id.expect("bool field should have a field id"); + let field_type_as_u8 = if b { 0x01 } else { 0x02 }; + self.write_field_header(field_type_as_u8, field_id) + } + None => { + if b { + self.write_byte(0x01) + } else { + self.write_byte(0x02) + } + } + } + } + + fn write_bytes(&mut self, b: &[u8]) -> ::Result<()> { + self.transport.write_varint(b.len() as u32)?; + self.transport.write_all(b).map_err(From::from) + } + + fn write_i8(&mut self, i: i8) -> ::Result<()> { + self.write_byte(i as u8) + } + + fn write_i16(&mut self, i: i16) -> ::Result<()> { + self.transport + .write_varint(i) + .map_err(From::from) + .map(|_| ()) + } + + fn write_i32(&mut self, i: i32) -> ::Result<()> { + self.transport + .write_varint(i) + .map_err(From::from) + .map(|_| ()) + } + + fn write_i64(&mut self, i: i64) -> ::Result<()> { + self.transport + .write_varint(i) + .map_err(From::from) + .map(|_| ()) + } + + fn write_double(&mut self, d: f64) -> ::Result<()> { + self.transport.write_f64::(d).map_err(From::from) + } + + fn write_string(&mut self, s: &str) -> ::Result<()> { + self.write_bytes(s.as_bytes()) + } + + fn write_list_begin(&mut self, identifier: &TListIdentifier) -> ::Result<()> { + self.write_list_set_begin(identifier.element_type, identifier.size) + } + + fn write_list_end(&mut self) -> ::Result<()> { + Ok(()) + } + + fn write_set_begin(&mut self, identifier: &TSetIdentifier) -> ::Result<()> { + self.write_list_set_begin(identifier.element_type, identifier.size) + } + + fn write_set_end(&mut self) -> ::Result<()> { + Ok(()) + } + + fn write_map_begin(&mut self, identifier: &TMapIdentifier) -> ::Result<()> { + if identifier.size == 0 { + self.write_byte(0) + } else { + self.transport.write_varint(identifier.size as u32)?; + + let key_type = identifier + .key_type + .expect("map identifier to write should contain key type"); + let key_type_byte = collection_type_to_u8(key_type) << 4; + + let val_type = identifier + .value_type + .expect("map identifier to write should contain value type"); + let val_type_byte = collection_type_to_u8(val_type); + + let map_type_header = key_type_byte | val_type_byte; + self.write_byte(map_type_header) + } + } + + fn write_map_end(&mut self) -> ::Result<()> { + Ok(()) + } + + fn flush(&mut self) -> ::Result<()> { + self.transport.flush().map_err(From::from) + } + + // utility + // + + fn write_byte(&mut self, b: u8) -> ::Result<()> { + self.transport.write(&[b]).map_err(From::from).map(|_| ()) + } +} + +/// Factory for creating instances of `TCompactOutputProtocol`. +#[derive(Default)] +pub struct TCompactOutputProtocolFactory; + +impl TCompactOutputProtocolFactory { + /// Create a `TCompactOutputProtocolFactory`. + pub fn new() -> TCompactOutputProtocolFactory { + TCompactOutputProtocolFactory {} + } +} + +impl TOutputProtocolFactory for TCompactOutputProtocolFactory { + fn create(&self, transport: Box) -> Box { + Box::new(TCompactOutputProtocol::new(transport)) + } +} + +fn collection_type_to_u8(field_type: TType) -> u8 { + match field_type { + TType::Bool => 0x01, + f => type_to_u8(f), + } +} + +fn type_to_u8(field_type: TType) -> u8 { + match field_type { + TType::Stop => 0x00, + TType::I08 => 0x03, // equivalent to TType::Byte + TType::I16 => 0x04, + TType::I32 => 0x05, + TType::I64 => 0x06, + TType::Double => 0x07, + TType::String => 0x08, + TType::List => 0x09, + TType::Set => 0x0A, + TType::Map => 0x0B, + TType::Struct => 0x0C, + _ => panic!(format!( + "should not have attempted to convert {} to u8", + field_type + )), + } +} + +fn collection_u8_to_type(b: u8) -> ::Result { + match b { + 0x01 => Ok(TType::Bool), + o => u8_to_type(o), + } +} + +fn u8_to_type(b: u8) -> ::Result { + match b { + 0x00 => Ok(TType::Stop), + 0x03 => Ok(TType::I08), // equivalent to TType::Byte + 0x04 => Ok(TType::I16), + 0x05 => Ok(TType::I32), + 0x06 => Ok(TType::I64), + 0x07 => Ok(TType::Double), + 0x08 => Ok(TType::String), + 0x09 => Ok(TType::List), + 0x0A => Ok(TType::Set), + 0x0B => Ok(TType::Map), + 0x0C => Ok(TType::Struct), + unkn => Err(::Error::Protocol(::ProtocolError { + kind: ::ProtocolErrorKind::InvalidData, + message: format!("cannot convert {} into TType", unkn), + })), + } +} + +#[cfg(test)] +mod tests { + + use protocol::{ + TFieldIdentifier, TInputProtocol, TListIdentifier, TMapIdentifier, TMessageIdentifier, + TMessageType, TOutputProtocol, TSetIdentifier, TStructIdentifier, TType, + }; + use transport::{ReadHalf, TBufferChannel, TIoChannel, WriteHalf}; + + use super::*; + + #[test] + fn must_write_message_begin_0() { + let (_, mut o_prot) = test_objects(); + + assert_success!(o_prot.write_message_begin(&TMessageIdentifier::new( + "foo", + TMessageType::Call, + 431 + ))); + + #[cfg_attr(rustfmt, rustfmt::skip)] + let expected: [u8; 8] = [ + 0x82, /* protocol ID */ + 0x21, /* message type | protocol version */ + 0xDE, + 0x06, /* zig-zag varint sequence number */ + 0x03, /* message-name length */ + 0x66, + 0x6F, + 0x6F /* "foo" */, + ]; + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_write_message_begin_1() { + let (_, mut o_prot) = test_objects(); + + assert_success!(o_prot.write_message_begin(&TMessageIdentifier::new( + "bar", + TMessageType::Reply, + 991828 + ))); + + #[cfg_attr(rustfmt, rustfmt::skip)] + let expected: [u8; 9] = [ + 0x82, /* protocol ID */ + 0x41, /* message type | protocol version */ + 0xA8, + 0x89, + 0x79, /* zig-zag varint sequence number */ + 0x03, /* message-name length */ + 0x62, + 0x61, + 0x72 /* "bar" */, + ]; + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_message_begin() { + let (mut i_prot, mut o_prot) = test_objects(); + + let ident = TMessageIdentifier::new("service_call", TMessageType::Call, 1283948); + + assert_success!(o_prot.write_message_begin(&ident)); + + copy_write_buffer_to_read_buffer!(o_prot); + + let res = assert_success!(i_prot.read_message_begin()); + assert_eq!(&res, &ident); + } + + #[test] + fn must_write_message_end() { + assert_no_write(|o| o.write_message_end()); + } + + // NOTE: structs and fields are tested together + // + + #[test] + fn must_write_struct_with_delta_fields() { + let (_, mut o_prot) = test_objects(); + + // no bytes should be written however + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // write three fields with tiny field ids + // since they're small the field ids will be encoded as deltas + + // since this is the first field (and it's zero) it gets the full varint write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::I08, 0))); + assert_success!(o_prot.write_field_end()); + + // since this delta > 0 and < 15 it can be encoded as a delta + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::I16, 4))); + assert_success!(o_prot.write_field_end()); + + // since this delta > 0 and < 15 it can be encoded as a delta + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::List, 9))); + assert_success!(o_prot.write_field_end()); + + // now, finish the struct off + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + #[cfg_attr(rustfmt, rustfmt::skip)] + let expected: [u8; 5] = [ + 0x03, /* field type */ + 0x00, /* first field id */ + 0x44, /* field delta (4) | field type */ + 0x59, /* field delta (5) | field type */ + 0x00 /* field stop */, + ]; + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_struct_with_delta_fields() { + let (mut i_prot, mut o_prot) = test_objects(); + + // no bytes should be written however + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // write three fields with tiny field ids + // since they're small the field ids will be encoded as deltas + + // since this is the first field (and it's zero) it gets the full varint write + let field_ident_1 = TFieldIdentifier::new("foo", TType::I08, 0); + assert_success!(o_prot.write_field_begin(&field_ident_1)); + assert_success!(o_prot.write_field_end()); + + // since this delta > 0 and < 15 it can be encoded as a delta + let field_ident_2 = TFieldIdentifier::new("foo", TType::I16, 4); + assert_success!(o_prot.write_field_begin(&field_ident_2)); + assert_success!(o_prot.write_field_end()); + + // since this delta > 0 and < 15 it can be encoded as a delta + let field_ident_3 = TFieldIdentifier::new("foo", TType::List, 9); + assert_success!(o_prot.write_field_begin(&field_ident_3)); + assert_success!(o_prot.write_field_end()); + + // now, finish the struct off + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + copy_write_buffer_to_read_buffer!(o_prot); + + // read the struct back + assert_success!(i_prot.read_struct_begin()); + + let read_ident_1 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_1, + TFieldIdentifier { + name: None, + ..field_ident_1 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_2 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_2, + TFieldIdentifier { + name: None, + ..field_ident_2 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_3 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_3, + TFieldIdentifier { + name: None, + ..field_ident_3 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_4 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_4, + TFieldIdentifier { + name: None, + field_type: TType::Stop, + id: None, + } + ); + + assert_success!(i_prot.read_struct_end()); + } + + #[test] + fn must_write_struct_with_non_zero_initial_field_and_delta_fields() { + let (_, mut o_prot) = test_objects(); + + // no bytes should be written however + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // write three fields with tiny field ids + // since they're small the field ids will be encoded as deltas + + // gets a delta write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::I32, 1))); + assert_success!(o_prot.write_field_end()); + + // since this delta > 0 and < 15 it can be encoded as a delta + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::Set, 2))); + assert_success!(o_prot.write_field_end()); + + // since this delta > 0 and < 15 it can be encoded as a delta + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::String, 6))); + assert_success!(o_prot.write_field_end()); + + // now, finish the struct off + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + #[cfg_attr(rustfmt, rustfmt::skip)] + let expected: [u8; 4] = [ + 0x15, /* field delta (1) | field type */ + 0x1A, /* field delta (1) | field type */ + 0x48, /* field delta (4) | field type */ + 0x00 /* field stop */, + ]; + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_struct_with_non_zero_initial_field_and_delta_fields() { + let (mut i_prot, mut o_prot) = test_objects(); + + // no bytes should be written however + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // write three fields with tiny field ids + // since they're small the field ids will be encoded as deltas + + // gets a delta write + let field_ident_1 = TFieldIdentifier::new("foo", TType::I32, 1); + assert_success!(o_prot.write_field_begin(&field_ident_1)); + assert_success!(o_prot.write_field_end()); + + // since this delta > 0 and < 15 it can be encoded as a delta + let field_ident_2 = TFieldIdentifier::new("foo", TType::Set, 2); + assert_success!(o_prot.write_field_begin(&field_ident_2)); + assert_success!(o_prot.write_field_end()); + + // since this delta > 0 and < 15 it can be encoded as a delta + let field_ident_3 = TFieldIdentifier::new("foo", TType::String, 6); + assert_success!(o_prot.write_field_begin(&field_ident_3)); + assert_success!(o_prot.write_field_end()); + + // now, finish the struct off + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + copy_write_buffer_to_read_buffer!(o_prot); + + // read the struct back + assert_success!(i_prot.read_struct_begin()); + + let read_ident_1 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_1, + TFieldIdentifier { + name: None, + ..field_ident_1 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_2 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_2, + TFieldIdentifier { + name: None, + ..field_ident_2 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_3 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_3, + TFieldIdentifier { + name: None, + ..field_ident_3 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_4 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_4, + TFieldIdentifier { + name: None, + field_type: TType::Stop, + id: None, + } + ); + + assert_success!(i_prot.read_struct_end()); + } + + #[test] + fn must_write_struct_with_long_fields() { + let (_, mut o_prot) = test_objects(); + + // no bytes should be written however + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // write three fields with field ids that cannot be encoded as deltas + + // since this is the first field (and it's zero) it gets the full varint write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::I32, 0))); + assert_success!(o_prot.write_field_end()); + + // since this delta is > 15 it is encoded as a zig-zag varint + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::I64, 16))); + assert_success!(o_prot.write_field_end()); + + // since this delta is > 15 it is encoded as a zig-zag varint + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::Set, 99))); + assert_success!(o_prot.write_field_end()); + + // now, finish the struct off + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + #[cfg_attr(rustfmt, rustfmt::skip)] + let expected: [u8; 8] = [ + 0x05, /* field type */ + 0x00, /* first field id */ + 0x06, /* field type */ + 0x20, /* zig-zag varint field id */ + 0x0A, /* field type */ + 0xC6, + 0x01, /* zig-zag varint field id */ + 0x00 /* field stop */, + ]; + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_struct_with_long_fields() { + let (mut i_prot, mut o_prot) = test_objects(); + + // no bytes should be written however + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // write three fields with field ids that cannot be encoded as deltas + + // since this is the first field (and it's zero) it gets the full varint write + let field_ident_1 = TFieldIdentifier::new("foo", TType::I32, 0); + assert_success!(o_prot.write_field_begin(&field_ident_1)); + assert_success!(o_prot.write_field_end()); + + // since this delta is > 15 it is encoded as a zig-zag varint + let field_ident_2 = TFieldIdentifier::new("foo", TType::I64, 16); + assert_success!(o_prot.write_field_begin(&field_ident_2)); + assert_success!(o_prot.write_field_end()); + + // since this delta is > 15 it is encoded as a zig-zag varint + let field_ident_3 = TFieldIdentifier::new("foo", TType::Set, 99); + assert_success!(o_prot.write_field_begin(&field_ident_3)); + assert_success!(o_prot.write_field_end()); + + // now, finish the struct off + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + copy_write_buffer_to_read_buffer!(o_prot); + + // read the struct back + assert_success!(i_prot.read_struct_begin()); + + let read_ident_1 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_1, + TFieldIdentifier { + name: None, + ..field_ident_1 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_2 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_2, + TFieldIdentifier { + name: None, + ..field_ident_2 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_3 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_3, + TFieldIdentifier { + name: None, + ..field_ident_3 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_4 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_4, + TFieldIdentifier { + name: None, + field_type: TType::Stop, + id: None, + } + ); + + assert_success!(i_prot.read_struct_end()); + } + + #[test] + fn must_write_struct_with_mix_of_long_and_delta_fields() { + let (_, mut o_prot) = test_objects(); + + // no bytes should be written however + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // write three fields with field ids that cannot be encoded as deltas + + // since the delta is > 0 and < 15 it gets a delta write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::I64, 1))); + assert_success!(o_prot.write_field_end()); + + // since this delta > 0 and < 15 it gets a delta write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::I32, 9))); + assert_success!(o_prot.write_field_end()); + + // since this delta is > 15 it is encoded as a zig-zag varint + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::Set, 1000))); + assert_success!(o_prot.write_field_end()); + + // since this delta is > 15 it is encoded as a zig-zag varint + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::Set, 2001))); + assert_success!(o_prot.write_field_end()); + + // since this is only 3 up from the previous it is recorded as a delta + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::Set, 2004))); + assert_success!(o_prot.write_field_end()); + + // now, finish the struct off + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + #[cfg_attr(rustfmt, rustfmt::skip)] + let expected: [u8; 10] = [ + 0x16, /* field delta (1) | field type */ + 0x85, /* field delta (8) | field type */ + 0x0A, /* field type */ + 0xD0, + 0x0F, /* zig-zag varint field id */ + 0x0A, /* field type */ + 0xA2, + 0x1F, /* zig-zag varint field id */ + 0x3A, /* field delta (3) | field type */ + 0x00 /* field stop */, + ]; + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_struct_with_mix_of_long_and_delta_fields() { + let (mut i_prot, mut o_prot) = test_objects(); + + // no bytes should be written however + let struct_ident = TStructIdentifier::new("foo"); + assert_success!(o_prot.write_struct_begin(&struct_ident)); + + // write three fields with field ids that cannot be encoded as deltas + + // since the delta is > 0 and < 15 it gets a delta write + let field_ident_1 = TFieldIdentifier::new("foo", TType::I64, 1); + assert_success!(o_prot.write_field_begin(&field_ident_1)); + assert_success!(o_prot.write_field_end()); + + // since this delta > 0 and < 15 it gets a delta write + let field_ident_2 = TFieldIdentifier::new("foo", TType::I32, 9); + assert_success!(o_prot.write_field_begin(&field_ident_2)); + assert_success!(o_prot.write_field_end()); + + // since this delta is > 15 it is encoded as a zig-zag varint + let field_ident_3 = TFieldIdentifier::new("foo", TType::Set, 1000); + assert_success!(o_prot.write_field_begin(&field_ident_3)); + assert_success!(o_prot.write_field_end()); + + // since this delta is > 15 it is encoded as a zig-zag varint + let field_ident_4 = TFieldIdentifier::new("foo", TType::Set, 2001); + assert_success!(o_prot.write_field_begin(&field_ident_4)); + assert_success!(o_prot.write_field_end()); + + // since this is only 3 up from the previous it is recorded as a delta + let field_ident_5 = TFieldIdentifier::new("foo", TType::Set, 2004); + assert_success!(o_prot.write_field_begin(&field_ident_5)); + assert_success!(o_prot.write_field_end()); + + // now, finish the struct off + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + copy_write_buffer_to_read_buffer!(o_prot); + + // read the struct back + assert_success!(i_prot.read_struct_begin()); + + let read_ident_1 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_1, + TFieldIdentifier { + name: None, + ..field_ident_1 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_2 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_2, + TFieldIdentifier { + name: None, + ..field_ident_2 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_3 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_3, + TFieldIdentifier { + name: None, + ..field_ident_3 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_4 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_4, + TFieldIdentifier { + name: None, + ..field_ident_4 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_5 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_5, + TFieldIdentifier { + name: None, + ..field_ident_5 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_6 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_6, + TFieldIdentifier { + name: None, + field_type: TType::Stop, + id: None, + } + ); + + assert_success!(i_prot.read_struct_end()); + } + + #[test] + fn must_write_nested_structs_0() { + // last field of the containing struct is a delta + // first field of the the contained struct is a delta + + let (_, mut o_prot) = test_objects(); + + // start containing struct + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // containing struct + // since the delta is > 0 and < 15 it gets a delta write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::I64, 1))); + assert_success!(o_prot.write_field_end()); + + // containing struct + // since this delta > 0 and < 15 it gets a delta write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::I32, 9))); + assert_success!(o_prot.write_field_end()); + + // start contained struct + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // contained struct + // since the delta is > 0 and < 15 it gets a delta write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::I08, 7))); + assert_success!(o_prot.write_field_end()); + + // contained struct + // since this delta > 15 it gets a full write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::Double, 24))); + assert_success!(o_prot.write_field_end()); + + // end contained struct + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + // end containing struct + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + #[cfg_attr(rustfmt, rustfmt::skip)] + let expected: [u8; 7] = [ + 0x16, /* field delta (1) | field type */ + 0x85, /* field delta (8) | field type */ + 0x73, /* field delta (7) | field type */ + 0x07, /* field type */ + 0x30, /* zig-zag varint field id */ + 0x00, /* field stop - contained */ + 0x00 /* field stop - containing */, + ]; + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_nested_structs_0() { + // last field of the containing struct is a delta + // first field of the the contained struct is a delta + + let (mut i_prot, mut o_prot) = test_objects(); + + // start containing struct + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // containing struct + // since the delta is > 0 and < 15 it gets a delta write + let field_ident_1 = TFieldIdentifier::new("foo", TType::I64, 1); + assert_success!(o_prot.write_field_begin(&field_ident_1)); + assert_success!(o_prot.write_field_end()); + + // containing struct + // since this delta > 0 and < 15 it gets a delta write + let field_ident_2 = TFieldIdentifier::new("foo", TType::I32, 9); + assert_success!(o_prot.write_field_begin(&field_ident_2)); + assert_success!(o_prot.write_field_end()); + + // start contained struct + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // contained struct + // since the delta is > 0 and < 15 it gets a delta write + let field_ident_3 = TFieldIdentifier::new("foo", TType::I08, 7); + assert_success!(o_prot.write_field_begin(&field_ident_3)); + assert_success!(o_prot.write_field_end()); + + // contained struct + // since this delta > 15 it gets a full write + let field_ident_4 = TFieldIdentifier::new("foo", TType::Double, 24); + assert_success!(o_prot.write_field_begin(&field_ident_4)); + assert_success!(o_prot.write_field_end()); + + // end contained struct + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + // end containing struct + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + copy_write_buffer_to_read_buffer!(o_prot); + + // read containing struct back + assert_success!(i_prot.read_struct_begin()); + + let read_ident_1 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_1, + TFieldIdentifier { + name: None, + ..field_ident_1 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_2 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_2, + TFieldIdentifier { + name: None, + ..field_ident_2 + } + ); + assert_success!(i_prot.read_field_end()); + + // read contained struct back + assert_success!(i_prot.read_struct_begin()); + + let read_ident_3 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_3, + TFieldIdentifier { + name: None, + ..field_ident_3 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_4 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_4, + TFieldIdentifier { + name: None, + ..field_ident_4 + } + ); + assert_success!(i_prot.read_field_end()); + + // end contained struct + let read_ident_6 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_6, + TFieldIdentifier { + name: None, + field_type: TType::Stop, + id: None, + } + ); + assert_success!(i_prot.read_struct_end()); + + // end containing struct + let read_ident_7 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_7, + TFieldIdentifier { + name: None, + field_type: TType::Stop, + id: None, + } + ); + assert_success!(i_prot.read_struct_end()); + } + + #[test] + fn must_write_nested_structs_1() { + // last field of the containing struct is a delta + // first field of the the contained struct is a full write + + let (_, mut o_prot) = test_objects(); + + // start containing struct + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // containing struct + // since the delta is > 0 and < 15 it gets a delta write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::I64, 1))); + assert_success!(o_prot.write_field_end()); + + // containing struct + // since this delta > 0 and < 15 it gets a delta write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::I32, 9))); + assert_success!(o_prot.write_field_end()); + + // start contained struct + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // contained struct + // since this delta > 15 it gets a full write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::Double, 24))); + assert_success!(o_prot.write_field_end()); + + // contained struct + // since the delta is > 0 and < 15 it gets a delta write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::I08, 27))); + assert_success!(o_prot.write_field_end()); + + // end contained struct + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + // end containing struct + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + #[cfg_attr(rustfmt, rustfmt::skip)] + let expected: [u8; 7] = [ + 0x16, /* field delta (1) | field type */ + 0x85, /* field delta (8) | field type */ + 0x07, /* field type */ + 0x30, /* zig-zag varint field id */ + 0x33, /* field delta (3) | field type */ + 0x00, /* field stop - contained */ + 0x00 /* field stop - containing */, + ]; + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_nested_structs_1() { + // last field of the containing struct is a delta + // first field of the the contained struct is a full write + + let (mut i_prot, mut o_prot) = test_objects(); + + // start containing struct + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // containing struct + // since the delta is > 0 and < 15 it gets a delta write + let field_ident_1 = TFieldIdentifier::new("foo", TType::I64, 1); + assert_success!(o_prot.write_field_begin(&field_ident_1)); + assert_success!(o_prot.write_field_end()); + + // containing struct + // since this delta > 0 and < 15 it gets a delta write + let field_ident_2 = TFieldIdentifier::new("foo", TType::I32, 9); + assert_success!(o_prot.write_field_begin(&field_ident_2)); + assert_success!(o_prot.write_field_end()); + + // start contained struct + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // contained struct + // since this delta > 15 it gets a full write + let field_ident_3 = TFieldIdentifier::new("foo", TType::Double, 24); + assert_success!(o_prot.write_field_begin(&field_ident_3)); + assert_success!(o_prot.write_field_end()); + + // contained struct + // since the delta is > 0 and < 15 it gets a delta write + let field_ident_4 = TFieldIdentifier::new("foo", TType::I08, 27); + assert_success!(o_prot.write_field_begin(&field_ident_4)); + assert_success!(o_prot.write_field_end()); + + // end contained struct + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + // end containing struct + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + copy_write_buffer_to_read_buffer!(o_prot); + + // read containing struct back + assert_success!(i_prot.read_struct_begin()); + + let read_ident_1 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_1, + TFieldIdentifier { + name: None, + ..field_ident_1 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_2 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_2, + TFieldIdentifier { + name: None, + ..field_ident_2 + } + ); + assert_success!(i_prot.read_field_end()); + + // read contained struct back + assert_success!(i_prot.read_struct_begin()); + + let read_ident_3 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_3, + TFieldIdentifier { + name: None, + ..field_ident_3 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_4 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_4, + TFieldIdentifier { + name: None, + ..field_ident_4 + } + ); + assert_success!(i_prot.read_field_end()); + + // end contained struct + let read_ident_6 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_6, + TFieldIdentifier { + name: None, + field_type: TType::Stop, + id: None, + } + ); + assert_success!(i_prot.read_struct_end()); + + // end containing struct + let read_ident_7 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_7, + TFieldIdentifier { + name: None, + field_type: TType::Stop, + id: None, + } + ); + assert_success!(i_prot.read_struct_end()); + } + + #[test] + fn must_write_nested_structs_2() { + // last field of the containing struct is a full write + // first field of the the contained struct is a delta write + + let (_, mut o_prot) = test_objects(); + + // start containing struct + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // containing struct + // since the delta is > 0 and < 15 it gets a delta write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::I64, 1))); + assert_success!(o_prot.write_field_end()); + + // containing struct + // since this delta > 15 it gets a full write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::String, 21))); + assert_success!(o_prot.write_field_end()); + + // start contained struct + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // contained struct + // since this delta > 0 and < 15 it gets a delta write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::Double, 7))); + assert_success!(o_prot.write_field_end()); + + // contained struct + // since the delta is > 0 and < 15 it gets a delta write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::I08, 10))); + assert_success!(o_prot.write_field_end()); + + // end contained struct + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + // end containing struct + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + #[cfg_attr(rustfmt, rustfmt::skip)] + let expected: [u8; 7] = [ + 0x16, /* field delta (1) | field type */ + 0x08, /* field type */ + 0x2A, /* zig-zag varint field id */ + 0x77, /* field delta(7) | field type */ + 0x33, /* field delta (3) | field type */ + 0x00, /* field stop - contained */ + 0x00 /* field stop - containing */, + ]; + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_nested_structs_2() { + let (mut i_prot, mut o_prot) = test_objects(); + + // start containing struct + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // containing struct + // since the delta is > 0 and < 15 it gets a delta write + let field_ident_1 = TFieldIdentifier::new("foo", TType::I64, 1); + assert_success!(o_prot.write_field_begin(&field_ident_1)); + assert_success!(o_prot.write_field_end()); + + // containing struct + // since this delta > 15 it gets a full write + let field_ident_2 = TFieldIdentifier::new("foo", TType::String, 21); + assert_success!(o_prot.write_field_begin(&field_ident_2)); + assert_success!(o_prot.write_field_end()); + + // start contained struct + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // contained struct + // since this delta > 0 and < 15 it gets a delta write + let field_ident_3 = TFieldIdentifier::new("foo", TType::Double, 7); + assert_success!(o_prot.write_field_begin(&field_ident_3)); + assert_success!(o_prot.write_field_end()); + + // contained struct + // since the delta is > 0 and < 15 it gets a delta write + let field_ident_4 = TFieldIdentifier::new("foo", TType::I08, 10); + assert_success!(o_prot.write_field_begin(&field_ident_4)); + assert_success!(o_prot.write_field_end()); + + // end contained struct + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + // end containing struct + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + copy_write_buffer_to_read_buffer!(o_prot); + + // read containing struct back + assert_success!(i_prot.read_struct_begin()); + + let read_ident_1 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_1, + TFieldIdentifier { + name: None, + ..field_ident_1 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_2 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_2, + TFieldIdentifier { + name: None, + ..field_ident_2 + } + ); + assert_success!(i_prot.read_field_end()); + + // read contained struct back + assert_success!(i_prot.read_struct_begin()); + + let read_ident_3 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_3, + TFieldIdentifier { + name: None, + ..field_ident_3 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_4 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_4, + TFieldIdentifier { + name: None, + ..field_ident_4 + } + ); + assert_success!(i_prot.read_field_end()); + + // end contained struct + let read_ident_6 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_6, + TFieldIdentifier { + name: None, + field_type: TType::Stop, + id: None, + } + ); + assert_success!(i_prot.read_struct_end()); + + // end containing struct + let read_ident_7 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_7, + TFieldIdentifier { + name: None, + field_type: TType::Stop, + id: None, + } + ); + assert_success!(i_prot.read_struct_end()); + } + + #[test] + fn must_write_nested_structs_3() { + // last field of the containing struct is a full write + // first field of the the contained struct is a full write + + let (_, mut o_prot) = test_objects(); + + // start containing struct + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // containing struct + // since the delta is > 0 and < 15 it gets a delta write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::I64, 1))); + assert_success!(o_prot.write_field_end()); + + // containing struct + // since this delta > 15 it gets a full write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::String, 21))); + assert_success!(o_prot.write_field_end()); + + // start contained struct + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // contained struct + // since this delta > 15 it gets a full write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::Double, 21))); + assert_success!(o_prot.write_field_end()); + + // contained struct + // since the delta is > 0 and < 15 it gets a delta write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::I08, 27))); + assert_success!(o_prot.write_field_end()); + + // end contained struct + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + // end containing struct + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + #[cfg_attr(rustfmt, rustfmt::skip)] + let expected: [u8; 8] = [ + 0x16, /* field delta (1) | field type */ + 0x08, /* field type */ + 0x2A, /* zig-zag varint field id */ + 0x07, /* field type */ + 0x2A, /* zig-zag varint field id */ + 0x63, /* field delta (6) | field type */ + 0x00, /* field stop - contained */ + 0x00 /* field stop - containing */, + ]; + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_nested_structs_3() { + // last field of the containing struct is a full write + // first field of the the contained struct is a full write + + let (mut i_prot, mut o_prot) = test_objects(); + + // start containing struct + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // containing struct + // since the delta is > 0 and < 15 it gets a delta write + let field_ident_1 = TFieldIdentifier::new("foo", TType::I64, 1); + assert_success!(o_prot.write_field_begin(&field_ident_1)); + assert_success!(o_prot.write_field_end()); + + // containing struct + // since this delta > 15 it gets a full write + let field_ident_2 = TFieldIdentifier::new("foo", TType::String, 21); + assert_success!(o_prot.write_field_begin(&field_ident_2)); + assert_success!(o_prot.write_field_end()); + + // start contained struct + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // contained struct + // since this delta > 15 it gets a full write + let field_ident_3 = TFieldIdentifier::new("foo", TType::Double, 21); + assert_success!(o_prot.write_field_begin(&field_ident_3)); + assert_success!(o_prot.write_field_end()); + + // contained struct + // since the delta is > 0 and < 15 it gets a delta write + let field_ident_4 = TFieldIdentifier::new("foo", TType::I08, 27); + assert_success!(o_prot.write_field_begin(&field_ident_4)); + assert_success!(o_prot.write_field_end()); + + // end contained struct + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + // end containing struct + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + copy_write_buffer_to_read_buffer!(o_prot); + + // read containing struct back + assert_success!(i_prot.read_struct_begin()); + + let read_ident_1 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_1, + TFieldIdentifier { + name: None, + ..field_ident_1 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_2 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_2, + TFieldIdentifier { + name: None, + ..field_ident_2 + } + ); + assert_success!(i_prot.read_field_end()); + + // read contained struct back + assert_success!(i_prot.read_struct_begin()); + + let read_ident_3 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_3, + TFieldIdentifier { + name: None, + ..field_ident_3 + } + ); + assert_success!(i_prot.read_field_end()); + + let read_ident_4 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_4, + TFieldIdentifier { + name: None, + ..field_ident_4 + } + ); + assert_success!(i_prot.read_field_end()); + + // end contained struct + let read_ident_6 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_6, + TFieldIdentifier { + name: None, + field_type: TType::Stop, + id: None, + } + ); + assert_success!(i_prot.read_struct_end()); + + // end containing struct + let read_ident_7 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_7, + TFieldIdentifier { + name: None, + field_type: TType::Stop, + id: None, + } + ); + assert_success!(i_prot.read_struct_end()); + } + + #[test] + fn must_write_bool_field() { + let (_, mut o_prot) = test_objects(); + + // no bytes should be written however + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + + // write three fields with field ids that cannot be encoded as deltas + + // since the delta is > 0 and < 16 it gets a delta write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::Bool, 1))); + assert_success!(o_prot.write_bool(true)); + assert_success!(o_prot.write_field_end()); + + // since this delta > 0 and < 15 it gets a delta write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::Bool, 9))); + assert_success!(o_prot.write_bool(false)); + assert_success!(o_prot.write_field_end()); + + // since this delta > 15 it gets a full write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::Bool, 26))); + assert_success!(o_prot.write_bool(true)); + assert_success!(o_prot.write_field_end()); + + // since this delta > 15 it gets a full write + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::Bool, 45))); + assert_success!(o_prot.write_bool(false)); + assert_success!(o_prot.write_field_end()); + + // now, finish the struct off + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + #[cfg_attr(rustfmt, rustfmt::skip)] + let expected: [u8; 7] = [ + 0x11, /* field delta (1) | true */ + 0x82, /* field delta (8) | false */ + 0x01, /* true */ + 0x34, /* field id */ + 0x02, /* false */ + 0x5A, /* field id */ + 0x00 /* stop field */, + ]; + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_bool_field() { + let (mut i_prot, mut o_prot) = test_objects(); + + // no bytes should be written however + let struct_ident = TStructIdentifier::new("foo"); + assert_success!(o_prot.write_struct_begin(&struct_ident)); + + // write two fields + + // since the delta is > 0 and < 16 it gets a delta write + let field_ident_1 = TFieldIdentifier::new("foo", TType::Bool, 1); + assert_success!(o_prot.write_field_begin(&field_ident_1)); + assert_success!(o_prot.write_bool(true)); + assert_success!(o_prot.write_field_end()); + + // since this delta > 0 and < 15 it gets a delta write + let field_ident_2 = TFieldIdentifier::new("foo", TType::Bool, 9); + assert_success!(o_prot.write_field_begin(&field_ident_2)); + assert_success!(o_prot.write_bool(false)); + assert_success!(o_prot.write_field_end()); + + // since this delta > 15 it gets a full write + let field_ident_3 = TFieldIdentifier::new("foo", TType::Bool, 26); + assert_success!(o_prot.write_field_begin(&field_ident_3)); + assert_success!(o_prot.write_bool(true)); + assert_success!(o_prot.write_field_end()); + + // since this delta > 15 it gets a full write + let field_ident_4 = TFieldIdentifier::new("foo", TType::Bool, 45); + assert_success!(o_prot.write_field_begin(&field_ident_4)); + assert_success!(o_prot.write_bool(false)); + assert_success!(o_prot.write_field_end()); + + // now, finish the struct off + assert_success!(o_prot.write_field_stop()); + assert_success!(o_prot.write_struct_end()); + + copy_write_buffer_to_read_buffer!(o_prot); + + // read the struct back + assert_success!(i_prot.read_struct_begin()); + + let read_ident_1 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_1, + TFieldIdentifier { + name: None, + ..field_ident_1 + } + ); + let read_value_1 = assert_success!(i_prot.read_bool()); + assert_eq!(read_value_1, true); + assert_success!(i_prot.read_field_end()); + + let read_ident_2 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_2, + TFieldIdentifier { + name: None, + ..field_ident_2 + } + ); + let read_value_2 = assert_success!(i_prot.read_bool()); + assert_eq!(read_value_2, false); + assert_success!(i_prot.read_field_end()); + + let read_ident_3 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_3, + TFieldIdentifier { + name: None, + ..field_ident_3 + } + ); + let read_value_3 = assert_success!(i_prot.read_bool()); + assert_eq!(read_value_3, true); + assert_success!(i_prot.read_field_end()); + + let read_ident_4 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_4, + TFieldIdentifier { + name: None, + ..field_ident_4 + } + ); + let read_value_4 = assert_success!(i_prot.read_bool()); + assert_eq!(read_value_4, false); + assert_success!(i_prot.read_field_end()); + + let read_ident_5 = assert_success!(i_prot.read_field_begin()); + assert_eq!( + read_ident_5, + TFieldIdentifier { + name: None, + field_type: TType::Stop, + id: None, + } + ); + + assert_success!(i_prot.read_struct_end()); + } + + #[test] + #[should_panic] + fn must_fail_if_write_field_end_without_writing_bool_value() { + let (_, mut o_prot) = test_objects(); + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::Bool, 1))); + o_prot.write_field_end().unwrap(); + } + + #[test] + #[should_panic] + fn must_fail_if_write_stop_field_without_writing_bool_value() { + let (_, mut o_prot) = test_objects(); + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::Bool, 1))); + o_prot.write_field_stop().unwrap(); + } + + #[test] + #[should_panic] + fn must_fail_if_write_struct_end_without_writing_bool_value() { + let (_, mut o_prot) = test_objects(); + assert_success!(o_prot.write_struct_begin(&TStructIdentifier::new("foo"))); + assert_success!(o_prot.write_field_begin(&TFieldIdentifier::new("foo", TType::Bool, 1))); + o_prot.write_struct_end().unwrap(); + } + + #[test] + #[should_panic] + fn must_fail_if_write_struct_end_without_any_fields() { + let (_, mut o_prot) = test_objects(); + o_prot.write_struct_end().unwrap(); + } + + #[test] + fn must_write_field_end() { + assert_no_write(|o| o.write_field_end()); + } + + #[test] + fn must_write_small_sized_list_begin() { + let (_, mut o_prot) = test_objects(); + + assert_success!(o_prot.write_list_begin(&TListIdentifier::new(TType::I64, 4))); + + let expected: [u8; 1] = [0x46 /* size | elem_type */]; + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_small_sized_list_begin() { + let (mut i_prot, mut o_prot) = test_objects(); + + let ident = TListIdentifier::new(TType::I08, 10); + + assert_success!(o_prot.write_list_begin(&ident)); + + copy_write_buffer_to_read_buffer!(o_prot); + + let res = assert_success!(i_prot.read_list_begin()); + assert_eq!(&res, &ident); + } + + #[test] + fn must_write_large_sized_list_begin() { + let (_, mut o_prot) = test_objects(); + + let res = o_prot.write_list_begin(&TListIdentifier::new(TType::List, 9999)); + assert!(res.is_ok()); + + let expected: [u8; 3] = [ + 0xF9, /* 0xF0 | elem_type */ + 0x8F, 0x4E, /* size as varint */ + ]; + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_large_sized_list_begin() { + let (mut i_prot, mut o_prot) = test_objects(); + + let ident = TListIdentifier::new(TType::Set, 47381); + + assert_success!(o_prot.write_list_begin(&ident)); + + copy_write_buffer_to_read_buffer!(o_prot); + + let res = assert_success!(i_prot.read_list_begin()); + assert_eq!(&res, &ident); + } + + #[test] + fn must_write_list_end() { + assert_no_write(|o| o.write_list_end()); + } + + #[test] + fn must_write_small_sized_set_begin() { + let (_, mut o_prot) = test_objects(); + + assert_success!(o_prot.write_set_begin(&TSetIdentifier::new(TType::Struct, 2))); + + let expected: [u8; 1] = [0x2C /* size | elem_type */]; + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_small_sized_set_begin() { + let (mut i_prot, mut o_prot) = test_objects(); + + let ident = TSetIdentifier::new(TType::I16, 7); + + assert_success!(o_prot.write_set_begin(&ident)); + + copy_write_buffer_to_read_buffer!(o_prot); + + let res = assert_success!(i_prot.read_set_begin()); + assert_eq!(&res, &ident); + } + + #[test] + fn must_write_large_sized_set_begin() { + let (_, mut o_prot) = test_objects(); + + assert_success!(o_prot.write_set_begin(&TSetIdentifier::new(TType::Double, 23891))); + + let expected: [u8; 4] = [ + 0xF7, /* 0xF0 | elem_type */ + 0xD3, 0xBA, 0x01, /* size as varint */ + ]; + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_large_sized_set_begin() { + let (mut i_prot, mut o_prot) = test_objects(); + + let ident = TSetIdentifier::new(TType::Map, 3928429); + + assert_success!(o_prot.write_set_begin(&ident)); + + copy_write_buffer_to_read_buffer!(o_prot); + + let res = assert_success!(i_prot.read_set_begin()); + assert_eq!(&res, &ident); + } + + #[test] + fn must_write_set_end() { + assert_no_write(|o| o.write_set_end()); + } + + #[test] + fn must_write_zero_sized_map_begin() { + let (_, mut o_prot) = test_objects(); + + assert_success!(o_prot.write_map_begin(&TMapIdentifier::new(TType::String, TType::I32, 0))); + + let expected: [u8; 1] = [0x00]; // since size is zero we don't write anything + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_read_zero_sized_map_begin() { + let (mut i_prot, mut o_prot) = test_objects(); + + assert_success!(o_prot.write_map_begin(&TMapIdentifier::new(TType::Double, TType::I32, 0))); + + copy_write_buffer_to_read_buffer!(o_prot); + + let res = assert_success!(i_prot.read_map_begin()); + assert_eq!( + &res, + &TMapIdentifier { + key_type: None, + value_type: None, + size: 0, + } + ); + } + + #[test] + fn must_write_map_begin() { + let (_, mut o_prot) = test_objects(); + + assert_success!(o_prot.write_map_begin(&TMapIdentifier::new( + TType::Double, + TType::String, + 238 + ))); + + let expected: [u8; 3] = [ + 0xEE, 0x01, /* size as varint */ + 0x78, /* key type | val type */ + ]; + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_map_begin() { + let (mut i_prot, mut o_prot) = test_objects(); + + let ident = TMapIdentifier::new(TType::Map, TType::List, 1928349); + + assert_success!(o_prot.write_map_begin(&ident)); + + copy_write_buffer_to_read_buffer!(o_prot); + + let res = assert_success!(i_prot.read_map_begin()); + assert_eq!(&res, &ident); + } + + #[test] + fn must_write_map_end() { + assert_no_write(|o| o.write_map_end()); + } + + #[test] + fn must_write_map_with_bool_key_and_value() { + let (_, mut o_prot) = test_objects(); + + assert_success!(o_prot.write_map_begin(&TMapIdentifier::new(TType::Bool, TType::Bool, 1))); + assert_success!(o_prot.write_bool(true)); + assert_success!(o_prot.write_bool(false)); + assert_success!(o_prot.write_map_end()); + + let expected: [u8; 4] = [ + 0x01, /* size as varint */ + 0x11, /* key type | val type */ + 0x01, /* key: true */ + 0x02, /* val: false */ + ]; + + assert_eq_written_bytes!(o_prot, expected); + } + + #[test] + fn must_round_trip_map_with_bool_value() { + let (mut i_prot, mut o_prot) = test_objects(); + + let map_ident = TMapIdentifier::new(TType::Bool, TType::Bool, 2); + assert_success!(o_prot.write_map_begin(&map_ident)); + assert_success!(o_prot.write_bool(true)); + assert_success!(o_prot.write_bool(false)); + assert_success!(o_prot.write_bool(false)); + assert_success!(o_prot.write_bool(true)); + assert_success!(o_prot.write_map_end()); + + copy_write_buffer_to_read_buffer!(o_prot); + + // map header + let rcvd_ident = assert_success!(i_prot.read_map_begin()); + assert_eq!(&rcvd_ident, &map_ident); + // key 1 + let b = assert_success!(i_prot.read_bool()); + assert_eq!(b, true); + // val 1 + let b = assert_success!(i_prot.read_bool()); + assert_eq!(b, false); + // key 2 + let b = assert_success!(i_prot.read_bool()); + assert_eq!(b, false); + // val 2 + let b = assert_success!(i_prot.read_bool()); + assert_eq!(b, true); + // map end + assert_success!(i_prot.read_map_end()); + } + + #[test] + fn must_read_map_end() { + let (mut i_prot, _) = test_objects(); + assert!(i_prot.read_map_end().is_ok()); // will blow up if we try to read from empty buffer + } + + fn test_objects() -> ( + TCompactInputProtocol>, + TCompactOutputProtocol>, + ) { + let mem = TBufferChannel::with_capacity(80, 80); + + let (r_mem, w_mem) = mem.split().unwrap(); + + let i_prot = TCompactInputProtocol::new(r_mem); + let o_prot = TCompactOutputProtocol::new(w_mem); + + (i_prot, o_prot) + } + + fn assert_no_write(mut write_fn: F) + where + F: FnMut(&mut TCompactOutputProtocol>) -> ::Result<()>, + { + let (_, mut o_prot) = test_objects(); + assert!(write_fn(&mut o_prot).is_ok()); + assert_eq!(o_prot.transport.write_bytes().len(), 0); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/rs/src/protocol/mod.rs b/vendor/git.apache.org/thrift.git/lib/rs/src/protocol/mod.rs new file mode 100644 index 0000000..11c0289 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/src/protocol/mod.rs @@ -0,0 +1,969 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +//! Types used to send and receive primitives between a Thrift client and server. +//! +//! # Examples +//! +//! Create and use a `TInputProtocol`. +//! +//! ```no_run +//! use thrift::protocol::{TBinaryInputProtocol, TInputProtocol}; +//! use thrift::transport::TTcpChannel; +//! +//! // create the I/O channel +//! let mut channel = TTcpChannel::new(); +//! channel.open("127.0.0.1:9090").unwrap(); +//! +//! // create the protocol to decode bytes into types +//! let mut protocol = TBinaryInputProtocol::new(channel, true); +//! +//! // read types from the wire +//! let field_identifier = protocol.read_field_begin().unwrap(); +//! let field_contents = protocol.read_string().unwrap(); +//! let field_end = protocol.read_field_end().unwrap(); +//! ``` +//! +//! Create and use a `TOutputProtocol`. +//! +//! ```no_run +//! use thrift::protocol::{TBinaryOutputProtocol, TFieldIdentifier, TOutputProtocol, TType}; +//! use thrift::transport::TTcpChannel; +//! +//! // create the I/O channel +//! let mut channel = TTcpChannel::new(); +//! channel.open("127.0.0.1:9090").unwrap(); +//! +//! // create the protocol to encode types into bytes +//! let mut protocol = TBinaryOutputProtocol::new(channel, true); +//! +//! // write types +//! protocol.write_field_begin(&TFieldIdentifier::new("string_thing", TType::String, 1)).unwrap(); +//! protocol.write_string("foo").unwrap(); +//! protocol.write_field_end().unwrap(); +//! ``` + +use std::convert::From; +use std::fmt; +use std::fmt::{Display, Formatter}; +use try_from::TryFrom; + +use transport::{TReadTransport, TWriteTransport}; +use {ProtocolError, ProtocolErrorKind}; + +#[cfg(test)] +macro_rules! assert_eq_written_bytes { + ($o_prot:ident, $expected_bytes:ident) => {{ + assert_eq!($o_prot.transport.write_bytes(), &$expected_bytes); + }}; +} + +// FIXME: should take both read and write +#[cfg(test)] +macro_rules! copy_write_buffer_to_read_buffer { + ($o_prot:ident) => {{ + $o_prot.transport.copy_write_buffer_to_read_buffer(); + }}; +} + +#[cfg(test)] +macro_rules! set_readable_bytes { + ($i_prot:ident, $bytes:expr) => { + $i_prot.transport.set_readable_bytes($bytes); + }; +} + +mod binary; +mod compact; +mod multiplexed; +mod stored; + +pub use self::binary::{ + TBinaryInputProtocol, TBinaryInputProtocolFactory, TBinaryOutputProtocol, + TBinaryOutputProtocolFactory, +}; +pub use self::compact::{ + TCompactInputProtocol, TCompactInputProtocolFactory, TCompactOutputProtocol, + TCompactOutputProtocolFactory, +}; +pub use self::multiplexed::TMultiplexedOutputProtocol; +pub use self::stored::TStoredInputProtocol; + +// Default maximum depth to which `TInputProtocol::skip` will skip a Thrift +// field. A default is necessary because Thrift structs or collections may +// contain nested structs and collections, which could result in indefinite +// recursion. +const MAXIMUM_SKIP_DEPTH: i8 = 64; + +/// Converts a stream of bytes into Thrift identifiers, primitives, +/// containers, or structs. +/// +/// This trait does not deal with higher-level Thrift concepts like structs or +/// exceptions - only with primitives and message or container boundaries. Once +/// bytes are read they are deserialized and an identifier (for example +/// `TMessageIdentifier`) or a primitive is returned. +/// +/// All methods return a `thrift::Result`. If an `Err` is returned the protocol +/// instance and its underlying transport should be terminated. +/// +/// # Examples +/// +/// Create and use a `TInputProtocol` +/// +/// ```no_run +/// use thrift::protocol::{TBinaryInputProtocol, TInputProtocol}; +/// use thrift::transport::TTcpChannel; +/// +/// let mut channel = TTcpChannel::new(); +/// channel.open("127.0.0.1:9090").unwrap(); +/// +/// let mut protocol = TBinaryInputProtocol::new(channel, true); +/// +/// let field_identifier = protocol.read_field_begin().unwrap(); +/// let field_contents = protocol.read_string().unwrap(); +/// let field_end = protocol.read_field_end().unwrap(); +/// ``` +pub trait TInputProtocol { + /// Read the beginning of a Thrift message. + fn read_message_begin(&mut self) -> ::Result; + /// Read the end of a Thrift message. + fn read_message_end(&mut self) -> ::Result<()>; + /// Read the beginning of a Thrift struct. + fn read_struct_begin(&mut self) -> ::Result>; + /// Read the end of a Thrift struct. + fn read_struct_end(&mut self) -> ::Result<()>; + /// Read the beginning of a Thrift struct field. + fn read_field_begin(&mut self) -> ::Result; + /// Read the end of a Thrift struct field. + fn read_field_end(&mut self) -> ::Result<()>; + /// Read a bool. + fn read_bool(&mut self) -> ::Result; + /// Read a fixed-length byte array. + fn read_bytes(&mut self) -> ::Result>; + /// Read a word. + fn read_i8(&mut self) -> ::Result; + /// Read a 16-bit signed integer. + fn read_i16(&mut self) -> ::Result; + /// Read a 32-bit signed integer. + fn read_i32(&mut self) -> ::Result; + /// Read a 64-bit signed integer. + fn read_i64(&mut self) -> ::Result; + /// Read a 64-bit float. + fn read_double(&mut self) -> ::Result; + /// Read a fixed-length string (not null terminated). + fn read_string(&mut self) -> ::Result; + /// Read the beginning of a list. + fn read_list_begin(&mut self) -> ::Result; + /// Read the end of a list. + fn read_list_end(&mut self) -> ::Result<()>; + /// Read the beginning of a set. + fn read_set_begin(&mut self) -> ::Result; + /// Read the end of a set. + fn read_set_end(&mut self) -> ::Result<()>; + /// Read the beginning of a map. + fn read_map_begin(&mut self) -> ::Result; + /// Read the end of a map. + fn read_map_end(&mut self) -> ::Result<()>; + /// Skip a field with type `field_type` recursively until the default + /// maximum skip depth is reached. + fn skip(&mut self, field_type: TType) -> ::Result<()> { + self.skip_till_depth(field_type, MAXIMUM_SKIP_DEPTH) + } + /// Skip a field with type `field_type` recursively up to `depth` levels. + fn skip_till_depth(&mut self, field_type: TType, depth: i8) -> ::Result<()> { + if depth == 0 { + return Err(::Error::Protocol(ProtocolError { + kind: ProtocolErrorKind::DepthLimit, + message: format!("cannot parse past {:?}", field_type), + })); + } + + match field_type { + TType::Bool => self.read_bool().map(|_| ()), + TType::I08 => self.read_i8().map(|_| ()), + TType::I16 => self.read_i16().map(|_| ()), + TType::I32 => self.read_i32().map(|_| ()), + TType::I64 => self.read_i64().map(|_| ()), + TType::Double => self.read_double().map(|_| ()), + TType::String => self.read_string().map(|_| ()), + TType::Struct => { + self.read_struct_begin()?; + loop { + let field_ident = self.read_field_begin()?; + if field_ident.field_type == TType::Stop { + break; + } + self.skip_till_depth(field_ident.field_type, depth - 1)?; + } + self.read_struct_end() + } + TType::List => { + let list_ident = self.read_list_begin()?; + for _ in 0..list_ident.size { + self.skip_till_depth(list_ident.element_type, depth - 1)?; + } + self.read_list_end() + } + TType::Set => { + let set_ident = self.read_set_begin()?; + for _ in 0..set_ident.size { + self.skip_till_depth(set_ident.element_type, depth - 1)?; + } + self.read_set_end() + } + TType::Map => { + let map_ident = self.read_map_begin()?; + for _ in 0..map_ident.size { + let key_type = map_ident + .key_type + .expect("non-zero sized map should contain key type"); + let val_type = map_ident + .value_type + .expect("non-zero sized map should contain value type"); + self.skip_till_depth(key_type, depth - 1)?; + self.skip_till_depth(val_type, depth - 1)?; + } + self.read_map_end() + } + u => Err(::Error::Protocol(ProtocolError { + kind: ProtocolErrorKind::Unknown, + message: format!("cannot skip field type {:?}", &u), + })), + } + } + + // utility (DO NOT USE IN GENERATED CODE!!!!) + // + + /// Read an unsigned byte. + /// + /// This method should **never** be used in generated code. + fn read_byte(&mut self) -> ::Result; +} + +/// Converts Thrift identifiers, primitives, containers or structs into a +/// stream of bytes. +/// +/// This trait does not deal with higher-level Thrift concepts like structs or +/// exceptions - only with primitives and message or container boundaries. +/// Write methods take an identifier (for example, `TMessageIdentifier`) or a +/// primitive. Any or all of the fields in an identifier may be omitted when +/// writing to the transport. Write methods may even be noops. All of this is +/// transparent to the caller; as long as a matching `TInputProtocol` +/// implementation is used, received messages will be decoded correctly. +/// +/// All methods return a `thrift::Result`. If an `Err` is returned the protocol +/// instance and its underlying transport should be terminated. +/// +/// # Examples +/// +/// Create and use a `TOutputProtocol` +/// +/// ```no_run +/// use thrift::protocol::{TBinaryOutputProtocol, TFieldIdentifier, TOutputProtocol, TType}; +/// use thrift::transport::TTcpChannel; +/// +/// let mut channel = TTcpChannel::new(); +/// channel.open("127.0.0.1:9090").unwrap(); +/// +/// let mut protocol = TBinaryOutputProtocol::new(channel, true); +/// +/// protocol.write_field_begin(&TFieldIdentifier::new("string_thing", TType::String, 1)).unwrap(); +/// protocol.write_string("foo").unwrap(); +/// protocol.write_field_end().unwrap(); +/// ``` +pub trait TOutputProtocol { + /// Write the beginning of a Thrift message. + fn write_message_begin(&mut self, identifier: &TMessageIdentifier) -> ::Result<()>; + /// Write the end of a Thrift message. + fn write_message_end(&mut self) -> ::Result<()>; + /// Write the beginning of a Thrift struct. + fn write_struct_begin(&mut self, identifier: &TStructIdentifier) -> ::Result<()>; + /// Write the end of a Thrift struct. + fn write_struct_end(&mut self) -> ::Result<()>; + /// Write the beginning of a Thrift field. + fn write_field_begin(&mut self, identifier: &TFieldIdentifier) -> ::Result<()>; + /// Write the end of a Thrift field. + fn write_field_end(&mut self) -> ::Result<()>; + /// Write a STOP field indicating that all the fields in a struct have been + /// written. + fn write_field_stop(&mut self) -> ::Result<()>; + /// Write a bool. + fn write_bool(&mut self, b: bool) -> ::Result<()>; + /// Write a fixed-length byte array. + fn write_bytes(&mut self, b: &[u8]) -> ::Result<()>; + /// Write an 8-bit signed integer. + fn write_i8(&mut self, i: i8) -> ::Result<()>; + /// Write a 16-bit signed integer. + fn write_i16(&mut self, i: i16) -> ::Result<()>; + /// Write a 32-bit signed integer. + fn write_i32(&mut self, i: i32) -> ::Result<()>; + /// Write a 64-bit signed integer. + fn write_i64(&mut self, i: i64) -> ::Result<()>; + /// Write a 64-bit float. + fn write_double(&mut self, d: f64) -> ::Result<()>; + /// Write a fixed-length string. + fn write_string(&mut self, s: &str) -> ::Result<()>; + /// Write the beginning of a list. + fn write_list_begin(&mut self, identifier: &TListIdentifier) -> ::Result<()>; + /// Write the end of a list. + fn write_list_end(&mut self) -> ::Result<()>; + /// Write the beginning of a set. + fn write_set_begin(&mut self, identifier: &TSetIdentifier) -> ::Result<()>; + /// Write the end of a set. + fn write_set_end(&mut self) -> ::Result<()>; + /// Write the beginning of a map. + fn write_map_begin(&mut self, identifier: &TMapIdentifier) -> ::Result<()>; + /// Write the end of a map. + fn write_map_end(&mut self) -> ::Result<()>; + /// Flush buffered bytes to the underlying transport. + fn flush(&mut self) -> ::Result<()>; + + // utility (DO NOT USE IN GENERATED CODE!!!!) + // + + /// Write an unsigned byte. + /// + /// This method should **never** be used in generated code. + fn write_byte(&mut self, b: u8) -> ::Result<()>; // FIXME: REMOVE +} + +impl

    TInputProtocol for Box

    +where + P: TInputProtocol + ?Sized, +{ + fn read_message_begin(&mut self) -> ::Result { + (**self).read_message_begin() + } + + fn read_message_end(&mut self) -> ::Result<()> { + (**self).read_message_end() + } + + fn read_struct_begin(&mut self) -> ::Result> { + (**self).read_struct_begin() + } + + fn read_struct_end(&mut self) -> ::Result<()> { + (**self).read_struct_end() + } + + fn read_field_begin(&mut self) -> ::Result { + (**self).read_field_begin() + } + + fn read_field_end(&mut self) -> ::Result<()> { + (**self).read_field_end() + } + + fn read_bool(&mut self) -> ::Result { + (**self).read_bool() + } + + fn read_bytes(&mut self) -> ::Result> { + (**self).read_bytes() + } + + fn read_i8(&mut self) -> ::Result { + (**self).read_i8() + } + + fn read_i16(&mut self) -> ::Result { + (**self).read_i16() + } + + fn read_i32(&mut self) -> ::Result { + (**self).read_i32() + } + + fn read_i64(&mut self) -> ::Result { + (**self).read_i64() + } + + fn read_double(&mut self) -> ::Result { + (**self).read_double() + } + + fn read_string(&mut self) -> ::Result { + (**self).read_string() + } + + fn read_list_begin(&mut self) -> ::Result { + (**self).read_list_begin() + } + + fn read_list_end(&mut self) -> ::Result<()> { + (**self).read_list_end() + } + + fn read_set_begin(&mut self) -> ::Result { + (**self).read_set_begin() + } + + fn read_set_end(&mut self) -> ::Result<()> { + (**self).read_set_end() + } + + fn read_map_begin(&mut self) -> ::Result { + (**self).read_map_begin() + } + + fn read_map_end(&mut self) -> ::Result<()> { + (**self).read_map_end() + } + + fn read_byte(&mut self) -> ::Result { + (**self).read_byte() + } +} + +impl

    TOutputProtocol for Box

    +where + P: TOutputProtocol + ?Sized, +{ + fn write_message_begin(&mut self, identifier: &TMessageIdentifier) -> ::Result<()> { + (**self).write_message_begin(identifier) + } + + fn write_message_end(&mut self) -> ::Result<()> { + (**self).write_message_end() + } + + fn write_struct_begin(&mut self, identifier: &TStructIdentifier) -> ::Result<()> { + (**self).write_struct_begin(identifier) + } + + fn write_struct_end(&mut self) -> ::Result<()> { + (**self).write_struct_end() + } + + fn write_field_begin(&mut self, identifier: &TFieldIdentifier) -> ::Result<()> { + (**self).write_field_begin(identifier) + } + + fn write_field_end(&mut self) -> ::Result<()> { + (**self).write_field_end() + } + + fn write_field_stop(&mut self) -> ::Result<()> { + (**self).write_field_stop() + } + + fn write_bool(&mut self, b: bool) -> ::Result<()> { + (**self).write_bool(b) + } + + fn write_bytes(&mut self, b: &[u8]) -> ::Result<()> { + (**self).write_bytes(b) + } + + fn write_i8(&mut self, i: i8) -> ::Result<()> { + (**self).write_i8(i) + } + + fn write_i16(&mut self, i: i16) -> ::Result<()> { + (**self).write_i16(i) + } + + fn write_i32(&mut self, i: i32) -> ::Result<()> { + (**self).write_i32(i) + } + + fn write_i64(&mut self, i: i64) -> ::Result<()> { + (**self).write_i64(i) + } + + fn write_double(&mut self, d: f64) -> ::Result<()> { + (**self).write_double(d) + } + + fn write_string(&mut self, s: &str) -> ::Result<()> { + (**self).write_string(s) + } + + fn write_list_begin(&mut self, identifier: &TListIdentifier) -> ::Result<()> { + (**self).write_list_begin(identifier) + } + + fn write_list_end(&mut self) -> ::Result<()> { + (**self).write_list_end() + } + + fn write_set_begin(&mut self, identifier: &TSetIdentifier) -> ::Result<()> { + (**self).write_set_begin(identifier) + } + + fn write_set_end(&mut self) -> ::Result<()> { + (**self).write_set_end() + } + + fn write_map_begin(&mut self, identifier: &TMapIdentifier) -> ::Result<()> { + (**self).write_map_begin(identifier) + } + + fn write_map_end(&mut self) -> ::Result<()> { + (**self).write_map_end() + } + + fn flush(&mut self) -> ::Result<()> { + (**self).flush() + } + + fn write_byte(&mut self, b: u8) -> ::Result<()> { + (**self).write_byte(b) + } +} + +/// Helper type used by servers to create `TInputProtocol` instances for +/// accepted client connections. +/// +/// # Examples +/// +/// Create a `TInputProtocolFactory` and use it to create a `TInputProtocol`. +/// +/// ```no_run +/// use thrift::protocol::{TBinaryInputProtocolFactory, TInputProtocolFactory}; +/// use thrift::transport::TTcpChannel; +/// +/// let mut channel = TTcpChannel::new(); +/// channel.open("127.0.0.1:9090").unwrap(); +/// +/// let factory = TBinaryInputProtocolFactory::new(); +/// let protocol = factory.create(Box::new(channel)); +/// ``` +pub trait TInputProtocolFactory { + // Create a `TInputProtocol` that reads bytes from `transport`. + fn create(&self, transport: Box) -> Box; +} + +impl TInputProtocolFactory for Box +where + T: TInputProtocolFactory + ?Sized, +{ + fn create(&self, transport: Box) -> Box { + (**self).create(transport) + } +} + +/// Helper type used by servers to create `TOutputProtocol` instances for +/// accepted client connections. +/// +/// # Examples +/// +/// Create a `TOutputProtocolFactory` and use it to create a `TOutputProtocol`. +/// +/// ```no_run +/// use thrift::protocol::{TBinaryOutputProtocolFactory, TOutputProtocolFactory}; +/// use thrift::transport::TTcpChannel; +/// +/// let mut channel = TTcpChannel::new(); +/// channel.open("127.0.0.1:9090").unwrap(); +/// +/// let factory = TBinaryOutputProtocolFactory::new(); +/// let protocol = factory.create(Box::new(channel)); +/// ``` +pub trait TOutputProtocolFactory { + /// Create a `TOutputProtocol` that writes bytes to `transport`. + fn create(&self, transport: Box) -> Box; +} + +impl TOutputProtocolFactory for Box +where + T: TOutputProtocolFactory + ?Sized, +{ + fn create(&self, transport: Box) -> Box { + (**self).create(transport) + } +} + +/// Thrift message identifier. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct TMessageIdentifier { + /// Service call the message is associated with. + pub name: String, + /// Message type. + pub message_type: TMessageType, + /// Ordered sequence number identifying the message. + pub sequence_number: i32, +} + +impl TMessageIdentifier { + /// Create a `TMessageIdentifier` for a Thrift service-call named `name` + /// with message type `message_type` and sequence number `sequence_number`. + pub fn new>( + name: S, + message_type: TMessageType, + sequence_number: i32, + ) -> TMessageIdentifier { + TMessageIdentifier { + name: name.into(), + message_type: message_type, + sequence_number: sequence_number, + } + } +} + +/// Thrift struct identifier. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct TStructIdentifier { + /// Name of the encoded Thrift struct. + pub name: String, +} + +impl TStructIdentifier { + /// Create a `TStructIdentifier` for a struct named `name`. + pub fn new>(name: S) -> TStructIdentifier { + TStructIdentifier { name: name.into() } + } +} + +/// Thrift field identifier. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct TFieldIdentifier { + /// Name of the Thrift field. + /// + /// `None` if it's not sent over the wire. + pub name: Option, + /// Field type. + /// + /// This may be a primitive, container, or a struct. + pub field_type: TType, + /// Thrift field id. + /// + /// `None` only if `field_type` is `TType::Stop`. + pub id: Option, +} + +impl TFieldIdentifier { + /// Create a `TFieldIdentifier` for a field named `name` with type + /// `field_type` and field id `id`. + /// + /// `id` should be `None` if `field_type` is `TType::Stop`. + pub fn new(name: N, field_type: TType, id: I) -> TFieldIdentifier + where + N: Into>, + S: Into, + I: Into>, + { + TFieldIdentifier { + name: name.into().map(|n| n.into()), + field_type: field_type, + id: id.into(), + } + } +} + +/// Thrift list identifier. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct TListIdentifier { + /// Type of the elements in the list. + pub element_type: TType, + /// Number of elements in the list. + pub size: i32, +} + +impl TListIdentifier { + /// Create a `TListIdentifier` for a list with `size` elements of type + /// `element_type`. + pub fn new(element_type: TType, size: i32) -> TListIdentifier { + TListIdentifier { + element_type: element_type, + size: size, + } + } +} + +/// Thrift set identifier. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct TSetIdentifier { + /// Type of the elements in the set. + pub element_type: TType, + /// Number of elements in the set. + pub size: i32, +} + +impl TSetIdentifier { + /// Create a `TSetIdentifier` for a set with `size` elements of type + /// `element_type`. + pub fn new(element_type: TType, size: i32) -> TSetIdentifier { + TSetIdentifier { + element_type: element_type, + size: size, + } + } +} + +/// Thrift map identifier. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct TMapIdentifier { + /// Map key type. + pub key_type: Option, + /// Map value type. + pub value_type: Option, + /// Number of entries in the map. + pub size: i32, +} + +impl TMapIdentifier { + /// Create a `TMapIdentifier` for a map with `size` entries of type + /// `key_type -> value_type`. + pub fn new(key_type: K, value_type: V, size: i32) -> TMapIdentifier + where + K: Into>, + V: Into>, + { + TMapIdentifier { + key_type: key_type.into(), + value_type: value_type.into(), + size: size, + } + } +} + +/// Thrift message types. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum TMessageType { + /// Service-call request. + Call, + /// Service-call response. + Reply, + /// Unexpected error in the remote service. + Exception, + /// One-way service-call request (no response is expected). + OneWay, +} + +impl Display for TMessageType { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + match *self { + TMessageType::Call => write!(f, "Call"), + TMessageType::Reply => write!(f, "Reply"), + TMessageType::Exception => write!(f, "Exception"), + TMessageType::OneWay => write!(f, "OneWay"), + } + } +} + +impl From for u8 { + fn from(message_type: TMessageType) -> Self { + match message_type { + TMessageType::Call => 0x01, + TMessageType::Reply => 0x02, + TMessageType::Exception => 0x03, + TMessageType::OneWay => 0x04, + } + } +} + +impl TryFrom for TMessageType { + type Err = ::Error; + fn try_from(b: u8) -> ::Result { + match b { + 0x01 => Ok(TMessageType::Call), + 0x02 => Ok(TMessageType::Reply), + 0x03 => Ok(TMessageType::Exception), + 0x04 => Ok(TMessageType::OneWay), + unkn => Err(::Error::Protocol(ProtocolError { + kind: ProtocolErrorKind::InvalidData, + message: format!("cannot convert {} to TMessageType", unkn), + })), + } + } +} + +/// Thrift struct-field types. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum TType { + /// Indicates that there are no more serialized fields in this Thrift struct. + Stop, + /// Void (`()`) field. + Void, + /// Boolean. + Bool, + /// Signed 8-bit int. + I08, + /// Double-precision number. + Double, + /// Signed 16-bit int. + I16, + /// Signed 32-bit int. + I32, + /// Signed 64-bit int. + I64, + /// UTF-8 string. + String, + /// UTF-7 string. *Unsupported*. + Utf7, + /// Thrift struct. + Struct, + /// Map. + Map, + /// Set. + Set, + /// List. + List, + /// UTF-8 string. + Utf8, + /// UTF-16 string. *Unsupported*. + Utf16, +} + +impl Display for TType { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + match *self { + TType::Stop => write!(f, "STOP"), + TType::Void => write!(f, "void"), + TType::Bool => write!(f, "bool"), + TType::I08 => write!(f, "i08"), + TType::Double => write!(f, "double"), + TType::I16 => write!(f, "i16"), + TType::I32 => write!(f, "i32"), + TType::I64 => write!(f, "i64"), + TType::String => write!(f, "string"), + TType::Utf7 => write!(f, "UTF7"), + TType::Struct => write!(f, "struct"), + TType::Map => write!(f, "map"), + TType::Set => write!(f, "set"), + TType::List => write!(f, "list"), + TType::Utf8 => write!(f, "UTF8"), + TType::Utf16 => write!(f, "UTF16"), + } + } +} + +/// Compare the expected message sequence number `expected` with the received +/// message sequence number `actual`. +/// +/// Return `()` if `actual == expected`, `Err` otherwise. +pub fn verify_expected_sequence_number(expected: i32, actual: i32) -> ::Result<()> { + if expected == actual { + Ok(()) + } else { + Err(::Error::Application(::ApplicationError { + kind: ::ApplicationErrorKind::BadSequenceId, + message: format!("expected {} got {}", expected, actual), + })) + } +} + +/// Compare the expected service-call name `expected` with the received +/// service-call name `actual`. +/// +/// Return `()` if `actual == expected`, `Err` otherwise. +pub fn verify_expected_service_call(expected: &str, actual: &str) -> ::Result<()> { + if expected == actual { + Ok(()) + } else { + Err(::Error::Application(::ApplicationError { + kind: ::ApplicationErrorKind::WrongMethodName, + message: format!("expected {} got {}", expected, actual), + })) + } +} + +/// Compare the expected message type `expected` with the received message type +/// `actual`. +/// +/// Return `()` if `actual == expected`, `Err` otherwise. +pub fn verify_expected_message_type(expected: TMessageType, actual: TMessageType) -> ::Result<()> { + if expected == actual { + Ok(()) + } else { + Err(::Error::Application(::ApplicationError { + kind: ::ApplicationErrorKind::InvalidMessageType, + message: format!("expected {} got {}", expected, actual), + })) + } +} + +/// Check if a required Thrift struct field exists. +/// +/// Return `()` if it does, `Err` otherwise. +pub fn verify_required_field_exists(field_name: &str, field: &Option) -> ::Result<()> { + match *field { + Some(_) => Ok(()), + None => Err(::Error::Protocol(::ProtocolError { + kind: ::ProtocolErrorKind::Unknown, + message: format!("missing required field {}", field_name), + })), + } +} + +/// Extract the field id from a Thrift field identifier. +/// +/// `field_ident` must *not* have `TFieldIdentifier.field_type` of type `TType::Stop`. +/// +/// Return `TFieldIdentifier.id` if an id exists, `Err` otherwise. +pub fn field_id(field_ident: &TFieldIdentifier) -> ::Result { + field_ident.id.ok_or_else(|| { + ::Error::Protocol(::ProtocolError { + kind: ::ProtocolErrorKind::Unknown, + message: format!("missing field in in {:?}", field_ident), + }) + }) +} + +#[cfg(test)] +mod tests { + + use std::io::Cursor; + + use super::*; + use transport::{TReadTransport, TWriteTransport}; + + #[test] + fn must_create_usable_input_protocol_from_concrete_input_protocol() { + let r: Box = Box::new(Cursor::new([0, 1, 2])); + let mut t = TCompactInputProtocol::new(r); + takes_input_protocol(&mut t) + } + + #[test] + fn must_create_usable_input_protocol_from_boxed_input() { + let r: Box = Box::new(Cursor::new([0, 1, 2])); + let mut t: Box = Box::new(TCompactInputProtocol::new(r)); + takes_input_protocol(&mut t) + } + + #[test] + fn must_create_usable_output_protocol_from_concrete_output_protocol() { + let w: Box = Box::new(vec![0u8; 10]); + let mut t = TCompactOutputProtocol::new(w); + takes_output_protocol(&mut t) + } + + #[test] + fn must_create_usable_output_protocol_from_boxed_output() { + let w: Box = Box::new(vec![0u8; 10]); + let mut t: Box = Box::new(TCompactOutputProtocol::new(w)); + takes_output_protocol(&mut t) + } + + fn takes_input_protocol(t: &mut R) + where + R: TInputProtocol, + { + t.read_byte().unwrap(); + } + + fn takes_output_protocol(t: &mut W) + where + W: TOutputProtocol, + { + t.flush().unwrap(); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/rs/src/protocol/multiplexed.rs b/vendor/git.apache.org/thrift.git/lib/rs/src/protocol/multiplexed.rs new file mode 100644 index 0000000..aaee44f --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/src/protocol/multiplexed.rs @@ -0,0 +1,239 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +use super::{ + TFieldIdentifier, TListIdentifier, TMapIdentifier, TMessageIdentifier, TMessageType, + TOutputProtocol, TSetIdentifier, TStructIdentifier, +}; + +/// `TOutputProtocol` that prefixes the service name to all outgoing Thrift +/// messages. +/// +/// A `TMultiplexedOutputProtocol` should be used when multiple Thrift services +/// send messages over a single I/O channel. By prefixing service identifiers +/// to outgoing messages receivers are able to demux them and route them to the +/// appropriate service processor. Rust receivers must use a `TMultiplexedProcessor` +/// to process incoming messages, while other languages must use their +/// corresponding multiplexed processor implementations. +/// +/// For example, given a service `TestService` and a service call `test_call`, +/// this implementation would identify messages as originating from +/// `TestService:test_call`. +/// +/// # Examples +/// +/// Create and use a `TMultiplexedOutputProtocol`. +/// +/// ```no_run +/// use thrift::protocol::{TMessageIdentifier, TMessageType, TOutputProtocol}; +/// use thrift::protocol::{TBinaryOutputProtocol, TMultiplexedOutputProtocol}; +/// use thrift::transport::TTcpChannel; +/// +/// let mut channel = TTcpChannel::new(); +/// channel.open("localhost:9090").unwrap(); +/// +/// let protocol = TBinaryOutputProtocol::new(channel, true); +/// let mut protocol = TMultiplexedOutputProtocol::new("service_name", protocol); +/// +/// let ident = TMessageIdentifier::new("svc_call", TMessageType::Call, 1); +/// protocol.write_message_begin(&ident).unwrap(); +/// ``` +#[derive(Debug)] +pub struct TMultiplexedOutputProtocol

    +where + P: TOutputProtocol, +{ + service_name: String, + inner: P, +} + +impl

    TMultiplexedOutputProtocol

    +where + P: TOutputProtocol, +{ + /// Create a `TMultiplexedOutputProtocol` that identifies outgoing messages + /// as originating from a service named `service_name` and sends them over + /// the `wrapped` `TOutputProtocol`. Outgoing messages are encoded and sent + /// by `wrapped`, not by this instance. + pub fn new(service_name: &str, wrapped: P) -> TMultiplexedOutputProtocol

    { + TMultiplexedOutputProtocol { + service_name: service_name.to_owned(), + inner: wrapped, + } + } +} + +// FIXME: avoid passthrough methods +impl

    TOutputProtocol for TMultiplexedOutputProtocol

    +where + P: TOutputProtocol, +{ + fn write_message_begin(&mut self, identifier: &TMessageIdentifier) -> ::Result<()> { + match identifier.message_type { + // FIXME: is there a better way to override identifier here? + TMessageType::Call | TMessageType::OneWay => { + let identifier = TMessageIdentifier { + name: format!("{}:{}", self.service_name, identifier.name), + ..*identifier + }; + self.inner.write_message_begin(&identifier) + } + _ => self.inner.write_message_begin(identifier), + } + } + + fn write_message_end(&mut self) -> ::Result<()> { + self.inner.write_message_end() + } + + fn write_struct_begin(&mut self, identifier: &TStructIdentifier) -> ::Result<()> { + self.inner.write_struct_begin(identifier) + } + + fn write_struct_end(&mut self) -> ::Result<()> { + self.inner.write_struct_end() + } + + fn write_field_begin(&mut self, identifier: &TFieldIdentifier) -> ::Result<()> { + self.inner.write_field_begin(identifier) + } + + fn write_field_end(&mut self) -> ::Result<()> { + self.inner.write_field_end() + } + + fn write_field_stop(&mut self) -> ::Result<()> { + self.inner.write_field_stop() + } + + fn write_bytes(&mut self, b: &[u8]) -> ::Result<()> { + self.inner.write_bytes(b) + } + + fn write_bool(&mut self, b: bool) -> ::Result<()> { + self.inner.write_bool(b) + } + + fn write_i8(&mut self, i: i8) -> ::Result<()> { + self.inner.write_i8(i) + } + + fn write_i16(&mut self, i: i16) -> ::Result<()> { + self.inner.write_i16(i) + } + + fn write_i32(&mut self, i: i32) -> ::Result<()> { + self.inner.write_i32(i) + } + + fn write_i64(&mut self, i: i64) -> ::Result<()> { + self.inner.write_i64(i) + } + + fn write_double(&mut self, d: f64) -> ::Result<()> { + self.inner.write_double(d) + } + + fn write_string(&mut self, s: &str) -> ::Result<()> { + self.inner.write_string(s) + } + + fn write_list_begin(&mut self, identifier: &TListIdentifier) -> ::Result<()> { + self.inner.write_list_begin(identifier) + } + + fn write_list_end(&mut self) -> ::Result<()> { + self.inner.write_list_end() + } + + fn write_set_begin(&mut self, identifier: &TSetIdentifier) -> ::Result<()> { + self.inner.write_set_begin(identifier) + } + + fn write_set_end(&mut self) -> ::Result<()> { + self.inner.write_set_end() + } + + fn write_map_begin(&mut self, identifier: &TMapIdentifier) -> ::Result<()> { + self.inner.write_map_begin(identifier) + } + + fn write_map_end(&mut self) -> ::Result<()> { + self.inner.write_map_end() + } + + fn flush(&mut self) -> ::Result<()> { + self.inner.flush() + } + + // utility + // + + fn write_byte(&mut self, b: u8) -> ::Result<()> { + self.inner.write_byte(b) + } +} + +#[cfg(test)] +mod tests { + + use protocol::{TBinaryOutputProtocol, TMessageIdentifier, TMessageType, TOutputProtocol}; + use transport::{TBufferChannel, TIoChannel, WriteHalf}; + + use super::*; + + #[test] + fn must_write_message_begin_with_prefixed_service_name() { + let mut o_prot = test_objects(); + + let ident = TMessageIdentifier::new("bar", TMessageType::Call, 2); + assert_success!(o_prot.write_message_begin(&ident)); + + #[cfg_attr(rustfmt, rustfmt::skip)] + let expected: [u8; 19] = [ + 0x80, + 0x01, /* protocol identifier */ + 0x00, + 0x01, /* message type */ + 0x00, + 0x00, + 0x00, + 0x07, + 0x66, + 0x6F, + 0x6F, /* "foo" */ + 0x3A, /* ":" */ + 0x62, + 0x61, + 0x72, /* "bar" */ + 0x00, + 0x00, + 0x00, + 0x02 /* sequence number */, + ]; + + assert_eq!(o_prot.inner.transport.write_bytes(), expected); + } + + fn test_objects() -> TMultiplexedOutputProtocol>> + { + let c = TBufferChannel::with_capacity(40, 40); + let (_, w_chan) = c.split().unwrap(); + let prot = TBinaryOutputProtocol::new(w_chan, true); + TMultiplexedOutputProtocol::new("foo", prot) + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/rs/src/protocol/stored.rs b/vendor/git.apache.org/thrift.git/lib/rs/src/protocol/stored.rs new file mode 100644 index 0000000..8c55978 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/src/protocol/stored.rs @@ -0,0 +1,196 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +use std::convert::Into; + +use super::{ + TFieldIdentifier, TInputProtocol, TListIdentifier, TMapIdentifier, TMessageIdentifier, + TSetIdentifier, TStructIdentifier, +}; +use ProtocolErrorKind; + +/// `TInputProtocol` required to use a `TMultiplexedProcessor`. +/// +/// A `TMultiplexedProcessor` reads incoming message identifiers to determine to +/// which `TProcessor` requests should be forwarded. However, once read, those +/// message identifier bytes are no longer on the wire. Since downstream +/// processors expect to read message identifiers from the given input protocol +/// we need some way of supplying a `TMessageIdentifier` with the service-name +/// stripped. This implementation stores the received `TMessageIdentifier` +/// (without the service name) and passes it to the wrapped `TInputProtocol` +/// when `TInputProtocol::read_message_begin(...)` is called. It delegates all +/// other calls directly to the wrapped `TInputProtocol`. +/// +/// This type **should not** be used by application code. +/// +/// # Examples +/// +/// Create and use a `TStoredInputProtocol`. +/// +/// ```no_run +/// use thrift; +/// use thrift::protocol::{TInputProtocol, TMessageIdentifier, TMessageType, TOutputProtocol}; +/// use thrift::protocol::{TBinaryInputProtocol, TBinaryOutputProtocol, TStoredInputProtocol}; +/// use thrift::server::TProcessor; +/// use thrift::transport::{TIoChannel, TTcpChannel}; +/// +/// // sample processor +/// struct ActualProcessor; +/// impl TProcessor for ActualProcessor { +/// fn process( +/// &self, +/// _: &mut TInputProtocol, +/// _: &mut TOutputProtocol +/// ) -> thrift::Result<()> { +/// unimplemented!() +/// } +/// } +/// let processor = ActualProcessor {}; +/// +/// // construct the shared transport +/// let mut channel = TTcpChannel::new(); +/// channel.open("localhost:9090").unwrap(); +/// +/// let (i_chan, o_chan) = channel.split().unwrap(); +/// +/// // construct the actual input and output protocols +/// let mut i_prot = TBinaryInputProtocol::new(i_chan, true); +/// let mut o_prot = TBinaryOutputProtocol::new(o_chan, true); +/// +/// // message identifier received from remote and modified to remove the service name +/// let new_msg_ident = TMessageIdentifier::new("service_call", TMessageType::Call, 1); +/// +/// // construct the proxy input protocol +/// let mut proxy_i_prot = TStoredInputProtocol::new(&mut i_prot, new_msg_ident); +/// let res = processor.process(&mut proxy_i_prot, &mut o_prot); +/// ``` +// FIXME: implement Debug +pub struct TStoredInputProtocol<'a> { + inner: &'a mut TInputProtocol, + message_ident: Option, +} + +impl<'a> TStoredInputProtocol<'a> { + /// Create a `TStoredInputProtocol` that delegates all calls other than + /// `TInputProtocol::read_message_begin(...)` to a `wrapped` + /// `TInputProtocol`. `message_ident` is the modified message identifier - + /// with service name stripped - that will be passed to + /// `wrapped.read_message_begin(...)`. + pub fn new( + wrapped: &mut TInputProtocol, + message_ident: TMessageIdentifier, + ) -> TStoredInputProtocol { + TStoredInputProtocol { + inner: wrapped, + message_ident: message_ident.into(), + } + } +} + +impl<'a> TInputProtocol for TStoredInputProtocol<'a> { + fn read_message_begin(&mut self) -> ::Result { + self.message_ident.take().ok_or_else(|| { + ::errors::new_protocol_error( + ProtocolErrorKind::Unknown, + "message identifier already read", + ) + }) + } + + fn read_message_end(&mut self) -> ::Result<()> { + self.inner.read_message_end() + } + + fn read_struct_begin(&mut self) -> ::Result> { + self.inner.read_struct_begin() + } + + fn read_struct_end(&mut self) -> ::Result<()> { + self.inner.read_struct_end() + } + + fn read_field_begin(&mut self) -> ::Result { + self.inner.read_field_begin() + } + + fn read_field_end(&mut self) -> ::Result<()> { + self.inner.read_field_end() + } + + fn read_bytes(&mut self) -> ::Result> { + self.inner.read_bytes() + } + + fn read_bool(&mut self) -> ::Result { + self.inner.read_bool() + } + + fn read_i8(&mut self) -> ::Result { + self.inner.read_i8() + } + + fn read_i16(&mut self) -> ::Result { + self.inner.read_i16() + } + + fn read_i32(&mut self) -> ::Result { + self.inner.read_i32() + } + + fn read_i64(&mut self) -> ::Result { + self.inner.read_i64() + } + + fn read_double(&mut self) -> ::Result { + self.inner.read_double() + } + + fn read_string(&mut self) -> ::Result { + self.inner.read_string() + } + + fn read_list_begin(&mut self) -> ::Result { + self.inner.read_list_begin() + } + + fn read_list_end(&mut self) -> ::Result<()> { + self.inner.read_list_end() + } + + fn read_set_begin(&mut self) -> ::Result { + self.inner.read_set_begin() + } + + fn read_set_end(&mut self) -> ::Result<()> { + self.inner.read_set_end() + } + + fn read_map_begin(&mut self) -> ::Result { + self.inner.read_map_begin() + } + + fn read_map_end(&mut self) -> ::Result<()> { + self.inner.read_map_end() + } + + // utility + // + + fn read_byte(&mut self) -> ::Result { + self.inner.read_byte() + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/rs/src/server/mod.rs b/vendor/git.apache.org/thrift.git/lib/rs/src/server/mod.rs new file mode 100644 index 0000000..70b381a --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/src/server/mod.rs @@ -0,0 +1,124 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +//! Types used to implement a Thrift server. + +use protocol::{TInputProtocol, TMessageIdentifier, TMessageType, TOutputProtocol}; +use {ApplicationError, ApplicationErrorKind}; + +mod multiplexed; +mod threaded; + +pub use self::multiplexed::TMultiplexedProcessor; +pub use self::threaded::TServer; + +/// Handles incoming Thrift messages and dispatches them to the user-defined +/// handler functions. +/// +/// An implementation is auto-generated for each Thrift service. When used by a +/// server (for example, a `TSimpleServer`), it will demux incoming service +/// calls and invoke the corresponding user-defined handler function. +/// +/// # Examples +/// +/// Create and start a server using the auto-generated `TProcessor` for +/// a Thrift service `SimpleService`. +/// +/// ```no_run +/// use thrift; +/// use thrift::protocol::{TInputProtocol, TOutputProtocol}; +/// use thrift::server::TProcessor; +/// +/// // +/// // auto-generated +/// // +/// +/// // processor for `SimpleService` +/// struct SimpleServiceSyncProcessor; +/// impl SimpleServiceSyncProcessor { +/// fn new(processor: H) -> SimpleServiceSyncProcessor { +/// unimplemented!(); +/// } +/// } +/// +/// // `TProcessor` implementation for `SimpleService` +/// impl TProcessor for SimpleServiceSyncProcessor { +/// fn process(&self, i: &mut TInputProtocol, o: &mut TOutputProtocol) -> thrift::Result<()> { +/// unimplemented!(); +/// } +/// } +/// +/// // service functions for SimpleService +/// trait SimpleServiceSyncHandler { +/// fn service_call(&self) -> thrift::Result<()>; +/// } +/// +/// // +/// // user-code follows +/// // +/// +/// // define a handler that will be invoked when `service_call` is received +/// struct SimpleServiceHandlerImpl; +/// impl SimpleServiceSyncHandler for SimpleServiceHandlerImpl { +/// fn service_call(&self) -> thrift::Result<()> { +/// unimplemented!(); +/// } +/// } +/// +/// // instantiate the processor +/// let processor = SimpleServiceSyncProcessor::new(SimpleServiceHandlerImpl {}); +/// +/// // at this point you can pass the processor to the server +/// // let server = TServer::new(..., processor); +/// ``` +pub trait TProcessor { + /// Process a Thrift service call. + /// + /// Reads arguments from `i`, executes the user's handler code, and writes + /// the response to `o`. + /// + /// Returns `()` if the handler was executed; `Err` otherwise. + fn process(&self, i: &mut TInputProtocol, o: &mut TOutputProtocol) -> ::Result<()>; +} + +/// Convenience function used in generated `TProcessor` implementations to +/// return an `ApplicationError` if thrift message processing failed. +pub fn handle_process_result( + msg_ident: &TMessageIdentifier, + res: ::Result<()>, + o_prot: &mut TOutputProtocol, +) -> ::Result<()> { + if let Err(e) = res { + let e = match e { + ::Error::Application(a) => a, + _ => ApplicationError::new(ApplicationErrorKind::Unknown, format!("{:?}", e)), + }; + + let ident = TMessageIdentifier::new( + msg_ident.name.clone(), + TMessageType::Exception, + msg_ident.sequence_number, + ); + + o_prot.write_message_begin(&ident)?; + ::Error::write_application_error_to_out_protocol(&e, o_prot)?; + o_prot.write_message_end()?; + o_prot.flush() + } else { + Ok(()) + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/rs/src/server/multiplexed.rs b/vendor/git.apache.org/thrift.git/lib/rs/src/server/multiplexed.rs new file mode 100644 index 0000000..e433794 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/src/server/multiplexed.rs @@ -0,0 +1,351 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +use std::collections::HashMap; +use std::convert::Into; +use std::fmt; +use std::fmt::{Debug, Formatter}; +use std::sync::{Arc, Mutex}; + +use protocol::{TInputProtocol, TMessageIdentifier, TOutputProtocol, TStoredInputProtocol}; + +use super::{handle_process_result, TProcessor}; + +const MISSING_SEPARATOR_AND_NO_DEFAULT: &'static str = + "missing service separator and no default processor set"; +type ThreadSafeProcessor = Box; + +/// A `TProcessor` that can demux service calls to multiple underlying +/// Thrift services. +/// +/// Users register service-specific `TProcessor` instances with a +/// `TMultiplexedProcessor`, and then register that processor with a server +/// implementation. Following that, all incoming service calls are automatically +/// routed to the service-specific `TProcessor`. +/// +/// A `TMultiplexedProcessor` can only handle messages sent by a +/// `TMultiplexedOutputProtocol`. +#[derive(Default)] +pub struct TMultiplexedProcessor { + stored: Mutex, +} + +#[derive(Default)] +struct StoredProcessors { + processors: HashMap>, + default_processor: Option>, +} + +impl TMultiplexedProcessor { + /// Create a new `TMultiplexedProcessor` with no registered service-specific + /// processors. + pub fn new() -> TMultiplexedProcessor { + TMultiplexedProcessor { + stored: Mutex::new(StoredProcessors { + processors: HashMap::new(), + default_processor: None, + }), + } + } + + /// Register a service-specific `processor` for the service named + /// `service_name`. This implementation is also backwards-compatible with + /// non-multiplexed clients. Set `as_default` to `true` to allow + /// non-namespaced requests to be dispatched to a default processor. + /// + /// Returns success if a new entry was inserted. Returns an error if: + /// * A processor exists for `service_name` + /// * You attempt to register a processor as default, and an existing default exists + #[cfg_attr(feature = "cargo-clippy", allow(map_entry))] + pub fn register>( + &mut self, + service_name: S, + processor: Box, + as_default: bool, + ) -> ::Result<()> { + let mut stored = self.stored.lock().unwrap(); + + let name = service_name.into(); + if !stored.processors.contains_key(&name) { + let processor = Arc::new(processor); + + if as_default { + if stored.default_processor.is_none() { + stored.processors.insert(name, processor.clone()); + stored.default_processor = Some(processor.clone()); + Ok(()) + } else { + Err("cannot reset default processor".into()) + } + } else { + stored.processors.insert(name, processor); + Ok(()) + } + } else { + Err(format!("cannot overwrite existing processor for service {}", name).into()) + } + } + + fn process_message( + &self, + msg_ident: &TMessageIdentifier, + i_prot: &mut TInputProtocol, + o_prot: &mut TOutputProtocol, + ) -> ::Result<()> { + let (svc_name, svc_call) = split_ident_name(&msg_ident.name); + debug!("routing svc_name {:?} svc_call {}", &svc_name, &svc_call); + + let processor: Option> = { + let stored = self.stored.lock().unwrap(); + if let Some(name) = svc_name { + stored.processors.get(name).cloned() + } else { + stored.default_processor.clone() + } + }; + + match processor { + Some(arc) => { + let new_msg_ident = TMessageIdentifier::new( + svc_call, + msg_ident.message_type, + msg_ident.sequence_number, + ); + let mut proxy_i_prot = TStoredInputProtocol::new(i_prot, new_msg_ident); + (*arc).process(&mut proxy_i_prot, o_prot) + } + None => Err(missing_processor_message(svc_name).into()), + } + } +} + +impl TProcessor for TMultiplexedProcessor { + fn process(&self, i_prot: &mut TInputProtocol, o_prot: &mut TOutputProtocol) -> ::Result<()> { + let msg_ident = i_prot.read_message_begin()?; + + debug!("process incoming msg id:{:?}", &msg_ident); + let res = self.process_message(&msg_ident, i_prot, o_prot); + + handle_process_result(&msg_ident, res, o_prot) + } +} + +impl Debug for TMultiplexedProcessor { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + let stored = self.stored.lock().unwrap(); + write!( + f, + "TMultiplexedProcess {{ registered_count: {:?} default: {:?} }}", + stored.processors.keys().len(), + stored.default_processor.is_some() + ) + } +} + +fn split_ident_name(ident_name: &str) -> (Option<&str>, &str) { + ident_name + .find(':') + .map(|pos| { + let (svc_name, svc_call) = ident_name.split_at(pos); + let (_, svc_call) = svc_call.split_at(1); // remove colon from service call name + (Some(svc_name), svc_call) + }) + .or_else(|| Some((None, ident_name))) + .unwrap() +} + +fn missing_processor_message(svc_name: Option<&str>) -> String { + match svc_name { + Some(name) => format!("no processor found for service {}", name), + None => MISSING_SEPARATOR_AND_NO_DEFAULT.to_owned(), + } +} + +#[cfg(test)] +mod tests { + use std::convert::Into; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::Arc; + + use protocol::{TBinaryInputProtocol, TBinaryOutputProtocol, TMessageIdentifier, TMessageType}; + use transport::{ReadHalf, TBufferChannel, TIoChannel, WriteHalf}; + use {ApplicationError, ApplicationErrorKind}; + + use super::*; + + #[test] + fn should_split_name_into_proper_separator_and_service_call() { + let ident_name = "foo:bar_call"; + let (serv, call) = split_ident_name(&ident_name); + assert_eq!(serv, Some("foo")); + assert_eq!(call, "bar_call"); + } + + #[test] + fn should_return_full_ident_if_no_separator_exists() { + let ident_name = "bar_call"; + let (serv, call) = split_ident_name(&ident_name); + assert_eq!(serv, None); + assert_eq!(call, "bar_call"); + } + + #[test] + fn should_write_error_if_no_separator_found_and_no_default_processor_exists() { + let (mut i, mut o) = build_objects(); + + let sent_ident = TMessageIdentifier::new("foo", TMessageType::Call, 10); + o.write_message_begin(&sent_ident).unwrap(); + o.flush().unwrap(); + o.transport.copy_write_buffer_to_read_buffer(); + o.transport.empty_write_buffer(); + + let p = TMultiplexedProcessor::new(); + p.process(&mut i, &mut o).unwrap(); // at this point an error should be written out + + i.transport.set_readable_bytes(&o.transport.write_bytes()); + let rcvd_ident = i.read_message_begin().unwrap(); + let expected_ident = TMessageIdentifier::new("foo", TMessageType::Exception, 10); + assert_eq!(rcvd_ident, expected_ident); + let rcvd_err = ::Error::read_application_error_from_in_protocol(&mut i).unwrap(); + let expected_err = ApplicationError::new( + ApplicationErrorKind::Unknown, + MISSING_SEPARATOR_AND_NO_DEFAULT, + ); + assert_eq!(rcvd_err, expected_err); + } + + #[test] + fn should_write_error_if_separator_exists_and_no_processor_found() { + let (mut i, mut o) = build_objects(); + + let sent_ident = TMessageIdentifier::new("missing:call", TMessageType::Call, 10); + o.write_message_begin(&sent_ident).unwrap(); + o.flush().unwrap(); + o.transport.copy_write_buffer_to_read_buffer(); + o.transport.empty_write_buffer(); + + let p = TMultiplexedProcessor::new(); + p.process(&mut i, &mut o).unwrap(); // at this point an error should be written out + + i.transport.set_readable_bytes(&o.transport.write_bytes()); + let rcvd_ident = i.read_message_begin().unwrap(); + let expected_ident = TMessageIdentifier::new("missing:call", TMessageType::Exception, 10); + assert_eq!(rcvd_ident, expected_ident); + let rcvd_err = ::Error::read_application_error_from_in_protocol(&mut i).unwrap(); + let expected_err = ApplicationError::new( + ApplicationErrorKind::Unknown, + missing_processor_message(Some("missing")), + ); + assert_eq!(rcvd_err, expected_err); + } + + #[derive(Default)] + struct Service { + pub invoked: Arc, + } + + impl TProcessor for Service { + fn process(&self, _: &mut TInputProtocol, _: &mut TOutputProtocol) -> ::Result<()> { + let res = self + .invoked + .compare_and_swap(false, true, Ordering::Relaxed); + if res { + Ok(()) + } else { + Err("failed swap".into()) + } + } + } + + #[test] + fn should_route_call_to_correct_processor() { + let (mut i, mut o) = build_objects(); + + // build the services + let svc_1 = Service { + invoked: Arc::new(AtomicBool::new(false)), + }; + let atm_1 = svc_1.invoked.clone(); + let svc_2 = Service { + invoked: Arc::new(AtomicBool::new(false)), + }; + let atm_2 = svc_2.invoked.clone(); + + // register them + let mut p = TMultiplexedProcessor::new(); + p.register("service_1", Box::new(svc_1), false).unwrap(); + p.register("service_2", Box::new(svc_2), false).unwrap(); + + // make the service call + let sent_ident = TMessageIdentifier::new("service_1:call", TMessageType::Call, 10); + o.write_message_begin(&sent_ident).unwrap(); + o.flush().unwrap(); + o.transport.copy_write_buffer_to_read_buffer(); + o.transport.empty_write_buffer(); + + p.process(&mut i, &mut o).unwrap(); + + // service 1 should have been invoked, not service 2 + assert_eq!(atm_1.load(Ordering::Relaxed), true); + assert_eq!(atm_2.load(Ordering::Relaxed), false); + } + + #[test] + fn should_route_call_to_correct_processor_if_no_separator_exists_and_default_processor_set() { + let (mut i, mut o) = build_objects(); + + // build the services + let svc_1 = Service { + invoked: Arc::new(AtomicBool::new(false)), + }; + let atm_1 = svc_1.invoked.clone(); + let svc_2 = Service { + invoked: Arc::new(AtomicBool::new(false)), + }; + let atm_2 = svc_2.invoked.clone(); + + // register them + let mut p = TMultiplexedProcessor::new(); + p.register("service_1", Box::new(svc_1), false).unwrap(); + p.register("service_2", Box::new(svc_2), true).unwrap(); // second processor is default + + // make the service call (it's an old client, so we have to be backwards compatible) + let sent_ident = TMessageIdentifier::new("old_call", TMessageType::Call, 10); + o.write_message_begin(&sent_ident).unwrap(); + o.flush().unwrap(); + o.transport.copy_write_buffer_to_read_buffer(); + o.transport.empty_write_buffer(); + + p.process(&mut i, &mut o).unwrap(); + + // service 2 should have been invoked, not service 1 + assert_eq!(atm_1.load(Ordering::Relaxed), false); + assert_eq!(atm_2.load(Ordering::Relaxed), true); + } + + fn build_objects() -> ( + TBinaryInputProtocol>, + TBinaryOutputProtocol>, + ) { + let c = TBufferChannel::with_capacity(128, 128); + let (r_c, w_c) = c.split().unwrap(); + ( + TBinaryInputProtocol::new(r_c, true), + TBinaryOutputProtocol::new(w_c, true), + ) + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/rs/src/server/threaded.rs b/vendor/git.apache.org/thrift.git/lib/rs/src/server/threaded.rs new file mode 100644 index 0000000..8139a4e --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/src/server/threaded.rs @@ -0,0 +1,234 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +use std::net::{TcpListener, TcpStream}; +use std::sync::Arc; +use threadpool::ThreadPool; + +use protocol::{TInputProtocol, TInputProtocolFactory, TOutputProtocol, TOutputProtocolFactory}; +use transport::{TIoChannel, TReadTransportFactory, TTcpChannel, TWriteTransportFactory}; +use {ApplicationError, ApplicationErrorKind}; + +use super::TProcessor; + +/// Fixed-size thread-pool blocking Thrift server. +/// +/// A `TServer` listens on a given address and submits accepted connections +/// to an **unbounded** queue. Connections from this queue are serviced by +/// the first available worker thread from a **fixed-size** thread pool. Each +/// accepted connection is handled by that worker thread, and communication +/// over this thread occurs sequentially and synchronously (i.e. calls block). +/// Accepted connections have an input half and an output half, each of which +/// uses a `TTransport` and `TInputProtocol`/`TOutputProtocol` to translate +/// messages to and from byes. Any combination of `TInputProtocol`, `TOutputProtocol` +/// and `TTransport` may be used. +/// +/// # Examples +/// +/// Creating and running a `TServer` using Thrift-compiler-generated +/// service code. +/// +/// ```no_run +/// use thrift; +/// use thrift::protocol::{TInputProtocolFactory, TOutputProtocolFactory}; +/// use thrift::protocol::{TBinaryInputProtocolFactory, TBinaryOutputProtocolFactory}; +/// use thrift::protocol::{TInputProtocol, TOutputProtocol}; +/// use thrift::transport::{TBufferedReadTransportFactory, TBufferedWriteTransportFactory, +/// TReadTransportFactory, TWriteTransportFactory}; +/// use thrift::server::{TProcessor, TServer}; +/// +/// // +/// // auto-generated +/// // +/// +/// // processor for `SimpleService` +/// struct SimpleServiceSyncProcessor; +/// impl SimpleServiceSyncProcessor { +/// fn new(processor: H) -> SimpleServiceSyncProcessor { +/// unimplemented!(); +/// } +/// } +/// +/// // `TProcessor` implementation for `SimpleService` +/// impl TProcessor for SimpleServiceSyncProcessor { +/// fn process(&self, i: &mut TInputProtocol, o: &mut TOutputProtocol) -> thrift::Result<()> { +/// unimplemented!(); +/// } +/// } +/// +/// // service functions for SimpleService +/// trait SimpleServiceSyncHandler { +/// fn service_call(&self) -> thrift::Result<()>; +/// } +/// +/// // +/// // user-code follows +/// // +/// +/// // define a handler that will be invoked when `service_call` is received +/// struct SimpleServiceHandlerImpl; +/// impl SimpleServiceSyncHandler for SimpleServiceHandlerImpl { +/// fn service_call(&self) -> thrift::Result<()> { +/// unimplemented!(); +/// } +/// } +/// +/// // instantiate the processor +/// let processor = SimpleServiceSyncProcessor::new(SimpleServiceHandlerImpl {}); +/// +/// // instantiate the server +/// let i_tr_fact: Box = Box::new(TBufferedReadTransportFactory::new()); +/// let i_pr_fact: Box = Box::new(TBinaryInputProtocolFactory::new()); +/// let o_tr_fact: Box = Box::new(TBufferedWriteTransportFactory::new()); +/// let o_pr_fact: Box = Box::new(TBinaryOutputProtocolFactory::new()); +/// +/// let mut server = TServer::new( +/// i_tr_fact, +/// i_pr_fact, +/// o_tr_fact, +/// o_pr_fact, +/// processor, +/// 10 +/// ); +/// +/// // start listening for incoming connections +/// match server.listen("127.0.0.1:8080") { +/// Ok(_) => println!("listen completed"), +/// Err(e) => println!("listen failed with error {:?}", e), +/// } +/// ``` +#[derive(Debug)] +pub struct TServer +where + PRC: TProcessor + Send + Sync + 'static, + RTF: TReadTransportFactory + 'static, + IPF: TInputProtocolFactory + 'static, + WTF: TWriteTransportFactory + 'static, + OPF: TOutputProtocolFactory + 'static, +{ + r_trans_factory: RTF, + i_proto_factory: IPF, + w_trans_factory: WTF, + o_proto_factory: OPF, + processor: Arc, + worker_pool: ThreadPool, +} + +impl TServer +where + PRC: TProcessor + Send + Sync + 'static, + RTF: TReadTransportFactory + 'static, + IPF: TInputProtocolFactory + 'static, + WTF: TWriteTransportFactory + 'static, + OPF: TOutputProtocolFactory + 'static, +{ + /// Create a `TServer`. + /// + /// Each accepted connection has an input and output half, each of which + /// requires a `TTransport` and `TProtocol`. `TServer` uses + /// `read_transport_factory` and `input_protocol_factory` to create + /// implementations for the input, and `write_transport_factory` and + /// `output_protocol_factory` to create implementations for the output. + pub fn new( + read_transport_factory: RTF, + input_protocol_factory: IPF, + write_transport_factory: WTF, + output_protocol_factory: OPF, + processor: PRC, + num_workers: usize, + ) -> TServer { + TServer { + r_trans_factory: read_transport_factory, + i_proto_factory: input_protocol_factory, + w_trans_factory: write_transport_factory, + o_proto_factory: output_protocol_factory, + processor: Arc::new(processor), + worker_pool: ThreadPool::with_name("Thrift service processor".to_owned(), num_workers), + } + } + + /// Listen for incoming connections on `listen_address`. + /// + /// `listen_address` should be in the form `host:port`, + /// for example: `127.0.0.1:8080`. + /// + /// Return `()` if successful. + /// + /// Return `Err` when the server cannot bind to `listen_address` or there + /// is an unrecoverable error. + pub fn listen(&mut self, listen_address: &str) -> ::Result<()> { + let listener = TcpListener::bind(listen_address)?; + for stream in listener.incoming() { + match stream { + Ok(s) => { + let (i_prot, o_prot) = self.new_protocols_for_connection(s)?; + let processor = self.processor.clone(); + self.worker_pool + .execute(move || handle_incoming_connection(processor, i_prot, o_prot)); + } + Err(e) => { + warn!("failed to accept remote connection with error {:?}", e); + } + } + } + + Err(::Error::Application(ApplicationError { + kind: ApplicationErrorKind::Unknown, + message: "aborted listen loop".into(), + })) + } + + fn new_protocols_for_connection( + &mut self, + stream: TcpStream, + ) -> ::Result<(Box, Box)> { + // create the shared tcp stream + let channel = TTcpChannel::with_stream(stream); + + // split it into two - one to be owned by the + // input tran/proto and the other by the output + let (r_chan, w_chan) = channel.split()?; + + // input protocol and transport + let r_tran = self.r_trans_factory.create(Box::new(r_chan)); + let i_prot = self.i_proto_factory.create(r_tran); + + // output protocol and transport + let w_tran = self.w_trans_factory.create(Box::new(w_chan)); + let o_prot = self.o_proto_factory.create(w_tran); + + Ok((i_prot, o_prot)) + } +} + +fn handle_incoming_connection( + processor: Arc, + i_prot: Box, + o_prot: Box, +) where + PRC: TProcessor, +{ + let mut i_prot = i_prot; + let mut o_prot = o_prot; + loop { + let r = processor.process(&mut *i_prot, &mut *o_prot); + if let Err(e) = r { + warn!("processor completed with error: {:?}", e); + break; + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/rs/src/transport/buffered.rs b/vendor/git.apache.org/thrift.git/lib/rs/src/transport/buffered.rs new file mode 100644 index 0000000..87cfeff --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/src/transport/buffered.rs @@ -0,0 +1,483 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +use std::cmp; +use std::io; +use std::io::{Read, Write}; + +use super::{TReadTransport, TReadTransportFactory, TWriteTransport, TWriteTransportFactory}; + +/// Default capacity of the read buffer in bytes. +const READ_CAPACITY: usize = 4096; + +/// Default capacity of the write buffer in bytes.. +const WRITE_CAPACITY: usize = 4096; + +/// Transport that reads messages via an internal buffer. +/// +/// A `TBufferedReadTransport` maintains a fixed-size internal read buffer. +/// On a call to `TBufferedReadTransport::read(...)` one full message - both +/// fixed-length header and bytes - is read from the wrapped channel and buffered. +/// Subsequent read calls are serviced from the internal buffer until it is +/// exhausted, at which point the next full message is read from the wrapped +/// channel. +/// +/// # Examples +/// +/// Create and use a `TBufferedReadTransport`. +/// +/// ```no_run +/// use std::io::Read; +/// use thrift::transport::{TBufferedReadTransport, TTcpChannel}; +/// +/// let mut c = TTcpChannel::new(); +/// c.open("localhost:9090").unwrap(); +/// +/// let mut t = TBufferedReadTransport::new(c); +/// +/// t.read(&mut vec![0u8; 1]).unwrap(); +/// ``` +#[derive(Debug)] +pub struct TBufferedReadTransport +where + C: Read, +{ + buf: Box<[u8]>, + pos: usize, + cap: usize, + chan: C, +} + +impl TBufferedReadTransport +where + C: Read, +{ + /// Create a `TBufferedTransport` with default-sized internal read and + /// write buffers that wraps the given `TIoChannel`. + pub fn new(channel: C) -> TBufferedReadTransport { + TBufferedReadTransport::with_capacity(READ_CAPACITY, channel) + } + + /// Create a `TBufferedTransport` with an internal read buffer of size + /// `read_capacity` and an internal write buffer of size + /// `write_capacity` that wraps the given `TIoChannel`. + pub fn with_capacity(read_capacity: usize, channel: C) -> TBufferedReadTransport { + TBufferedReadTransport { + buf: vec![0; read_capacity].into_boxed_slice(), + pos: 0, + cap: 0, + chan: channel, + } + } + + fn get_bytes(&mut self) -> io::Result<&[u8]> { + if self.cap - self.pos == 0 { + self.pos = 0; + self.cap = self.chan.read(&mut self.buf)?; + } + + Ok(&self.buf[self.pos..self.cap]) + } + + fn consume(&mut self, consumed: usize) { + // TODO: was a bug here += <-- test somehow + self.pos = cmp::min(self.cap, self.pos + consumed); + } +} + +impl Read for TBufferedReadTransport +where + C: Read, +{ + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let mut bytes_read = 0; + + loop { + let nread = { + let avail_bytes = self.get_bytes()?; + let avail_space = buf.len() - bytes_read; + let nread = cmp::min(avail_space, avail_bytes.len()); + buf[bytes_read..(bytes_read + nread)].copy_from_slice(&avail_bytes[..nread]); + nread + }; + + self.consume(nread); + bytes_read += nread; + + if bytes_read == buf.len() || nread == 0 { + break; + } + } + + Ok(bytes_read) + } +} + +/// Factory for creating instances of `TBufferedReadTransport`. +#[derive(Default)] +pub struct TBufferedReadTransportFactory; + +impl TBufferedReadTransportFactory { + pub fn new() -> TBufferedReadTransportFactory { + TBufferedReadTransportFactory {} + } +} + +impl TReadTransportFactory for TBufferedReadTransportFactory { + /// Create a `TBufferedReadTransport`. + fn create(&self, channel: Box) -> Box { + Box::new(TBufferedReadTransport::new(channel)) + } +} + +/// Transport that writes messages via an internal buffer. +/// +/// A `TBufferedWriteTransport` maintains a fixed-size internal write buffer. +/// All writes are made to this buffer and are sent to the wrapped channel only +/// when `TBufferedWriteTransport::flush()` is called. On a flush a fixed-length +/// header with a count of the buffered bytes is written, followed by the bytes +/// themselves. +/// +/// # Examples +/// +/// Create and use a `TBufferedWriteTransport`. +/// +/// ```no_run +/// use std::io::Write; +/// use thrift::transport::{TBufferedWriteTransport, TTcpChannel}; +/// +/// let mut c = TTcpChannel::new(); +/// c.open("localhost:9090").unwrap(); +/// +/// let mut t = TBufferedWriteTransport::new(c); +/// +/// t.write(&[0x00]).unwrap(); +/// t.flush().unwrap(); +/// ``` +#[derive(Debug)] +pub struct TBufferedWriteTransport +where + C: Write, +{ + buf: Vec, + cap: usize, + channel: C, +} + +impl TBufferedWriteTransport +where + C: Write, +{ + /// Create a `TBufferedTransport` with default-sized internal read and + /// write buffers that wraps the given `TIoChannel`. + pub fn new(channel: C) -> TBufferedWriteTransport { + TBufferedWriteTransport::with_capacity(WRITE_CAPACITY, channel) + } + + /// Create a `TBufferedTransport` with an internal read buffer of size + /// `read_capacity` and an internal write buffer of size + /// `write_capacity` that wraps the given `TIoChannel`. + pub fn with_capacity(write_capacity: usize, channel: C) -> TBufferedWriteTransport { + assert!( + write_capacity > 0, + "write buffer size must be a positive integer" + ); + + TBufferedWriteTransport { + buf: Vec::with_capacity(write_capacity), + cap: write_capacity, + channel: channel, + } + } +} + +impl Write for TBufferedWriteTransport +where + C: Write, +{ + fn write(&mut self, buf: &[u8]) -> io::Result { + if !buf.is_empty() { + let mut avail_bytes; + + loop { + avail_bytes = cmp::min(buf.len(), self.cap - self.buf.len()); + + if avail_bytes == 0 { + self.flush()?; + } else { + break; + } + } + + let avail_bytes = avail_bytes; + + self.buf.extend_from_slice(&buf[..avail_bytes]); + assert!(self.buf.len() <= self.cap, "copy overflowed buffer"); + + Ok(avail_bytes) + } else { + Ok(0) + } + } + + fn flush(&mut self) -> io::Result<()> { + self.channel.write_all(&self.buf)?; + self.channel.flush()?; + self.buf.clear(); + Ok(()) + } +} + +/// Factory for creating instances of `TBufferedWriteTransport`. +#[derive(Default)] +pub struct TBufferedWriteTransportFactory; + +impl TBufferedWriteTransportFactory { + pub fn new() -> TBufferedWriteTransportFactory { + TBufferedWriteTransportFactory {} + } +} + +impl TWriteTransportFactory for TBufferedWriteTransportFactory { + /// Create a `TBufferedWriteTransport`. + fn create(&self, channel: Box) -> Box { + Box::new(TBufferedWriteTransport::new(channel)) + } +} + +#[cfg(test)] +mod tests { + use std::io::{Read, Write}; + + use super::*; + use transport::TBufferChannel; + + #[test] + fn must_return_zero_if_read_buffer_is_empty() { + let mem = TBufferChannel::with_capacity(10, 0); + let mut t = TBufferedReadTransport::with_capacity(10, mem); + + let mut b = vec![0; 10]; + let read_result = t.read(&mut b); + + assert_eq!(read_result.unwrap(), 0); + } + + #[test] + fn must_return_zero_if_caller_reads_into_zero_capacity_buffer() { + let mem = TBufferChannel::with_capacity(10, 0); + let mut t = TBufferedReadTransport::with_capacity(10, mem); + + let read_result = t.read(&mut []); + + assert_eq!(read_result.unwrap(), 0); + } + + #[test] + fn must_return_zero_if_nothing_more_can_be_read() { + let mem = TBufferChannel::with_capacity(4, 0); + let mut t = TBufferedReadTransport::with_capacity(4, mem); + + t.chan.set_readable_bytes(&[0, 1, 2, 3]); + + // read buffer is exactly the same size as bytes available + let mut buf = vec![0u8; 4]; + let read_result = t.read(&mut buf); + + // we've read exactly 4 bytes + assert_eq!(read_result.unwrap(), 4); + assert_eq!(&buf, &[0, 1, 2, 3]); + + // try read again + let buf_again = vec![0u8; 4]; + let read_result = t.read(&mut buf); + + // this time, 0 bytes and we haven't changed the buffer + assert_eq!(read_result.unwrap(), 0); + assert_eq!(&buf_again, &[0, 0, 0, 0]) + } + + #[test] + fn must_fill_user_buffer_with_only_as_many_bytes_as_available() { + let mem = TBufferChannel::with_capacity(4, 0); + let mut t = TBufferedReadTransport::with_capacity(4, mem); + + t.chan.set_readable_bytes(&[0, 1, 2, 3]); + + // read buffer is much larger than the bytes available + let mut buf = vec![0u8; 8]; + let read_result = t.read(&mut buf); + + // we've read exactly 4 bytes + assert_eq!(read_result.unwrap(), 4); + assert_eq!(&buf[..4], &[0, 1, 2, 3]); + + // try read again + let read_result = t.read(&mut buf[4..]); + + // this time, 0 bytes and we haven't changed the buffer + assert_eq!(read_result.unwrap(), 0); + assert_eq!(&buf, &[0, 1, 2, 3, 0, 0, 0, 0]) + } + + #[test] + fn must_read_successfully() { + // this test involves a few loops within the buffered transport + // itself where it has to drain the underlying transport in order + // to service a read + + // we have a much smaller buffer than the + // underlying transport has bytes available + let mem = TBufferChannel::with_capacity(10, 0); + let mut t = TBufferedReadTransport::with_capacity(2, mem); + + // fill the underlying transport's byte buffer + let mut readable_bytes = [0u8; 10]; + for i in 0..10 { + readable_bytes[i] = i as u8; + } + + t.chan.set_readable_bytes(&readable_bytes); + + // we ask to read into a buffer that's much larger + // than the one the buffered transport has; as a result + // it's going to have to keep asking the underlying + // transport for more bytes + let mut buf = [0u8; 8]; + let read_result = t.read(&mut buf); + + // we should have read 8 bytes + assert_eq!(read_result.unwrap(), 8); + assert_eq!(&buf, &[0, 1, 2, 3, 4, 5, 6, 7]); + + // let's clear out the buffer and try read again + for i in 0..8 { + buf[i] = 0; + } + let read_result = t.read(&mut buf); + + // this time we were only able to read 2 bytes + // (all that's remaining from the underlying transport) + // let's also check that the remaining bytes are untouched + assert_eq!(read_result.unwrap(), 2); + assert_eq!(&buf[0..2], &[8, 9]); + assert_eq!(&buf[2..], &[0, 0, 0, 0, 0, 0]); + + // try read again (we should get 0) + // and all the existing bytes were untouched + let read_result = t.read(&mut buf); + assert_eq!(read_result.unwrap(), 0); + assert_eq!(&buf[0..2], &[8, 9]); + assert_eq!(&buf[2..], &[0, 0, 0, 0, 0, 0]); + } + + #[test] + fn must_return_error_when_nothing_can_be_written_to_underlying_channel() { + let mem = TBufferChannel::with_capacity(0, 0); + let mut t = TBufferedWriteTransport::with_capacity(1, mem); + + let b = vec![0; 10]; + let r = t.write(&b); + + // should have written 1 byte + assert_eq!(r.unwrap(), 1); + + // let's try again... + let r = t.write(&b[1..]); + + // this time we'll error out because the auto-flush failed + assert!(r.is_err()); + } + + #[test] + fn must_return_zero_if_caller_calls_write_with_empty_buffer() { + let mem = TBufferChannel::with_capacity(0, 10); + let mut t = TBufferedWriteTransport::with_capacity(10, mem); + + let r = t.write(&[]); + let expected: [u8; 0] = []; + + assert_eq!(r.unwrap(), 0); + assert_eq_transport_written_bytes!(t, expected); + } + + #[test] + fn must_auto_flush_if_write_buffer_full() { + let mem = TBufferChannel::with_capacity(0, 8); + let mut t = TBufferedWriteTransport::with_capacity(4, mem); + + let b0 = [0x00, 0x01, 0x02, 0x03]; + let b1 = [0x04, 0x05, 0x06, 0x07]; + + // write the first 4 bytes; we've now filled the transport's write buffer + let r = t.write(&b0); + assert_eq!(r.unwrap(), 4); + + // try write the next 4 bytes; this causes the transport to auto-flush the first 4 bytes + let r = t.write(&b1); + assert_eq!(r.unwrap(), 4); + + // check that in writing the second 4 bytes we auto-flushed the first 4 bytes + assert_eq_transport_num_written_bytes!(t, 4); + assert_eq_transport_written_bytes!(t, b0); + t.channel.empty_write_buffer(); + + // now flush the transport to push the second 4 bytes to the underlying channel + assert!(t.flush().is_ok()); + + // check that we wrote out the second 4 bytes + assert_eq_transport_written_bytes!(t, b1); + } + + #[test] + fn must_write_to_inner_transport_on_flush() { + let mem = TBufferChannel::with_capacity(10, 10); + let mut t = TBufferedWriteTransport::new(mem); + + let b: [u8; 5] = [0, 1, 2, 3, 4]; + assert_eq!(t.write(&b).unwrap(), 5); + assert_eq_transport_num_written_bytes!(t, 0); + + assert!(t.flush().is_ok()); + + assert_eq_transport_written_bytes!(t, b); + } + + #[test] + fn must_write_successfully_after_flush() { + let mem = TBufferChannel::with_capacity(0, 5); + let mut t = TBufferedWriteTransport::with_capacity(5, mem); + + // write and flush + let b: [u8; 5] = [0, 1, 2, 3, 4]; + assert_eq!(t.write(&b).unwrap(), 5); + assert!(t.flush().is_ok()); + + // check the flushed bytes + assert_eq_transport_written_bytes!(t, b); + + // reset our underlying transport + t.channel.empty_write_buffer(); + + // write and flush again + assert_eq!(t.write(&b).unwrap(), 5); + assert!(t.flush().is_ok()); + + // check the flushed bytes + assert_eq_transport_written_bytes!(t, b); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/rs/src/transport/framed.rs b/vendor/git.apache.org/thrift.git/lib/rs/src/transport/framed.rs new file mode 100644 index 0000000..a009307 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/src/transport/framed.rs @@ -0,0 +1,459 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; +use std::cmp; +use std::io; +use std::io::{Read, Write}; + +use super::{TReadTransport, TReadTransportFactory, TWriteTransport, TWriteTransportFactory}; + +/// Default capacity of the read buffer in bytes. +const READ_CAPACITY: usize = 4096; + +/// Default capacity of the write buffer in bytes. +const WRITE_CAPACITY: usize = 4096; + +/// Transport that reads framed messages. +/// +/// A `TFramedReadTransport` maintains a fixed-size internal read buffer. +/// On a call to `TFramedReadTransport::read(...)` one full message - both +/// fixed-length header and bytes - is read from the wrapped channel and +/// buffered. Subsequent read calls are serviced from the internal buffer +/// until it is exhausted, at which point the next full message is read +/// from the wrapped channel. +/// +/// # Examples +/// +/// Create and use a `TFramedReadTransport`. +/// +/// ```no_run +/// use std::io::Read; +/// use thrift::transport::{TFramedReadTransport, TTcpChannel}; +/// +/// let mut c = TTcpChannel::new(); +/// c.open("localhost:9090").unwrap(); +/// +/// let mut t = TFramedReadTransport::new(c); +/// +/// t.read(&mut vec![0u8; 1]).unwrap(); +/// ``` +#[derive(Debug)] +pub struct TFramedReadTransport +where + C: Read, +{ + buf: Vec, + pos: usize, + cap: usize, + chan: C, +} + +impl TFramedReadTransport +where + C: Read, +{ + /// Create a `TFramedReadTransport` with a default-sized + /// internal read buffer that wraps the given `TIoChannel`. + pub fn new(channel: C) -> TFramedReadTransport { + TFramedReadTransport::with_capacity(READ_CAPACITY, channel) + } + + /// Create a `TFramedTransport` with an internal read buffer + /// of size `read_capacity` that wraps the given `TIoChannel`. + pub fn with_capacity(read_capacity: usize, channel: C) -> TFramedReadTransport { + TFramedReadTransport { + buf: vec![0; read_capacity], // FIXME: do I actually have to do this? + pos: 0, + cap: 0, + chan: channel, + } + } +} + +impl Read for TFramedReadTransport +where + C: Read, +{ + fn read(&mut self, b: &mut [u8]) -> io::Result { + if self.cap - self.pos == 0 { + let message_size = self.chan.read_i32::()? as usize; + + let buf_capacity = cmp::max(message_size, READ_CAPACITY); + self.buf.resize(buf_capacity, 0); + + self.chan.read_exact(&mut self.buf[..message_size])?; + self.cap = message_size as usize; + self.pos = 0; + } + + let nread = cmp::min(b.len(), self.cap - self.pos); + b[..nread].clone_from_slice(&self.buf[self.pos..self.pos + nread]); + self.pos += nread; + + Ok(nread) + } +} + +/// Factory for creating instances of `TFramedReadTransport`. +#[derive(Default)] +pub struct TFramedReadTransportFactory; + +impl TFramedReadTransportFactory { + pub fn new() -> TFramedReadTransportFactory { + TFramedReadTransportFactory {} + } +} + +impl TReadTransportFactory for TFramedReadTransportFactory { + /// Create a `TFramedReadTransport`. + fn create(&self, channel: Box) -> Box { + Box::new(TFramedReadTransport::new(channel)) + } +} + +/// Transport that writes framed messages. +/// +/// A `TFramedWriteTransport` maintains a fixed-size internal write buffer. All +/// writes are made to this buffer and are sent to the wrapped channel only +/// when `TFramedWriteTransport::flush()` is called. On a flush a fixed-length +/// header with a count of the buffered bytes is written, followed by the bytes +/// themselves. +/// +/// # Examples +/// +/// Create and use a `TFramedWriteTransport`. +/// +/// ```no_run +/// use std::io::Write; +/// use thrift::transport::{TFramedWriteTransport, TTcpChannel}; +/// +/// let mut c = TTcpChannel::new(); +/// c.open("localhost:9090").unwrap(); +/// +/// let mut t = TFramedWriteTransport::new(c); +/// +/// t.write(&[0x00]).unwrap(); +/// t.flush().unwrap(); +/// ``` +#[derive(Debug)] +pub struct TFramedWriteTransport +where + C: Write, +{ + buf: Vec, + channel: C, +} + +impl TFramedWriteTransport +where + C: Write, +{ + /// Create a `TFramedWriteTransport` with default-sized internal + /// write buffer that wraps the given `TIoChannel`. + pub fn new(channel: C) -> TFramedWriteTransport { + TFramedWriteTransport::with_capacity(WRITE_CAPACITY, channel) + } + + /// Create a `TFramedWriteTransport` with an internal write buffer + /// of size `write_capacity` that wraps the given `TIoChannel`. + pub fn with_capacity(write_capacity: usize, channel: C) -> TFramedWriteTransport { + TFramedWriteTransport { + buf: Vec::with_capacity(write_capacity), + channel, + } + } +} + +impl Write for TFramedWriteTransport +where + C: Write, +{ + fn write(&mut self, b: &[u8]) -> io::Result { + let current_capacity = self.buf.capacity(); + let available_space = current_capacity - self.buf.len(); + if b.len() > available_space { + let additional_space = cmp::max(b.len() - available_space, current_capacity); + self.buf.reserve(additional_space); + } + + self.buf.extend_from_slice(b); + Ok(b.len()) + } + + fn flush(&mut self) -> io::Result<()> { + let message_size = self.buf.len(); + + if let 0 = message_size { + return Ok(()); + } else { + self.channel.write_i32::(message_size as i32)?; + } + + // will spin if the underlying channel can't be written to + let mut byte_index = 0; + while byte_index < message_size { + let nwrite = self.channel.write(&self.buf[byte_index..message_size])?; + byte_index = cmp::min(byte_index + nwrite, message_size); + } + + let buf_capacity = cmp::min(self.buf.capacity(), WRITE_CAPACITY); + self.buf.resize(buf_capacity, 0); + self.buf.clear(); + + self.channel.flush() + } +} + +/// Factory for creating instances of `TFramedWriteTransport`. +#[derive(Default)] +pub struct TFramedWriteTransportFactory; + +impl TFramedWriteTransportFactory { + pub fn new() -> TFramedWriteTransportFactory { + TFramedWriteTransportFactory {} + } +} + +impl TWriteTransportFactory for TFramedWriteTransportFactory { + /// Create a `TFramedWriteTransport`. + fn create(&self, channel: Box) -> Box { + Box::new(TFramedWriteTransport::new(channel)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use transport::mem::TBufferChannel; + + // FIXME: test a forced reserve + + #[test] + fn must_read_message_smaller_than_initial_buffer_size() { + let c = TBufferChannel::with_capacity(10, 10); + let mut t = TFramedReadTransport::with_capacity(8, c); + + t.chan.set_readable_bytes(&[ + 0x00, 0x00, 0x00, 0x04, /* message size */ + 0x00, 0x01, 0x02, 0x03, /* message body */ + ]); + + let mut buf = vec![0; 8]; + + // we've read exactly 4 bytes + assert_eq!(t.read(&mut buf).unwrap(), 4); + assert_eq!(&buf[..4], &[0x00, 0x01, 0x02, 0x03]); + } + + #[test] + fn must_read_message_greater_than_initial_buffer_size() { + let c = TBufferChannel::with_capacity(10, 10); + let mut t = TFramedReadTransport::with_capacity(2, c); + + t.chan.set_readable_bytes(&[ + 0x00, 0x00, 0x00, 0x04, /* message size */ + 0x00, 0x01, 0x02, 0x03, /* message body */ + ]); + + let mut buf = vec![0; 8]; + + // we've read exactly 4 bytes + assert_eq!(t.read(&mut buf).unwrap(), 4); + assert_eq!(&buf[..4], &[0x00, 0x01, 0x02, 0x03]); + } + + #[test] + fn must_read_multiple_messages_in_sequence_correctly() { + let c = TBufferChannel::with_capacity(10, 10); + let mut t = TFramedReadTransport::with_capacity(2, c); + + // + // 1st message + // + + t.chan.set_readable_bytes(&[ + 0x00, 0x00, 0x00, 0x04, /* message size */ + 0x00, 0x01, 0x02, 0x03, /* message body */ + ]); + + let mut buf = vec![0; 8]; + + // we've read exactly 4 bytes + assert_eq!(t.read(&mut buf).unwrap(), 4); + assert_eq!(&buf, &[0x00, 0x01, 0x02, 0x03, 0x00, 0x00, 0x00, 0x00]); + + // + // 2nd message + // + + t.chan.set_readable_bytes(&[ + 0x00, 0x00, 0x00, 0x01, /* message size */ + 0x04, /* message body */ + ]); + + let mut buf = vec![0; 8]; + + // we've read exactly 1 byte + assert_eq!(t.read(&mut buf).unwrap(), 1); + assert_eq!(&buf, &[0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); + } + + #[test] + fn must_write_message_smaller_than_buffer_size() { + let mem = TBufferChannel::with_capacity(0, 0); + let mut t = TFramedWriteTransport::with_capacity(20, mem); + + let b = vec![0; 10]; + + // should have written 10 bytes + assert_eq!(t.write(&b).unwrap(), 10); + } + + #[test] + fn must_return_zero_if_caller_calls_write_with_empty_buffer() { + let mem = TBufferChannel::with_capacity(0, 10); + let mut t = TFramedWriteTransport::with_capacity(10, mem); + + let expected: [u8; 0] = []; + + assert_eq!(t.write(&[]).unwrap(), 0); + assert_eq_transport_written_bytes!(t, expected); + } + + #[test] + fn must_write_to_inner_transport_on_flush() { + let mem = TBufferChannel::with_capacity(10, 10); + let mut t = TFramedWriteTransport::new(mem); + + let b: [u8; 5] = [0x00, 0x01, 0x02, 0x03, 0x04]; + assert_eq!(t.write(&b).unwrap(), 5); + assert_eq_transport_num_written_bytes!(t, 0); + + assert!(t.flush().is_ok()); + + let expected_bytes = [ + 0x00, 0x00, 0x00, 0x05, /* message size */ + 0x00, 0x01, 0x02, 0x03, 0x04, /* message body */ + ]; + + assert_eq_transport_written_bytes!(t, expected_bytes); + } + + #[test] + fn must_write_message_greater_than_buffer_size_00() { + let mem = TBufferChannel::with_capacity(0, 10); + + // IMPORTANT: DO **NOT** CHANGE THE WRITE_CAPACITY OR THE NUMBER OF BYTES TO BE WRITTEN! + // these lengths were chosen to be just long enough + // that doubling the capacity is a **worse** choice than + // simply resizing the buffer to b.len() + + let mut t = TFramedWriteTransport::with_capacity(1, mem); + let b = [0x00, 0x01, 0x02]; + + // should have written 3 bytes + assert_eq!(t.write(&b).unwrap(), 3); + assert_eq_transport_num_written_bytes!(t, 0); + + assert!(t.flush().is_ok()); + + let expected_bytes = [ + 0x00, 0x00, 0x00, 0x03, /* message size */ + 0x00, 0x01, 0x02, /* message body */ + ]; + + assert_eq_transport_written_bytes!(t, expected_bytes); + } + + #[test] + fn must_write_message_greater_than_buffer_size_01() { + let mem = TBufferChannel::with_capacity(0, 10); + + // IMPORTANT: DO **NOT** CHANGE THE WRITE_CAPACITY OR THE NUMBER OF BYTES TO BE WRITTEN! + // these lengths were chosen to be just long enough + // that doubling the capacity is a **better** choice than + // simply resizing the buffer to b.len() + + let mut t = TFramedWriteTransport::with_capacity(2, mem); + let b = [0x00, 0x01, 0x02]; + + // should have written 3 bytes + assert_eq!(t.write(&b).unwrap(), 3); + assert_eq_transport_num_written_bytes!(t, 0); + + assert!(t.flush().is_ok()); + + let expected_bytes = [ + 0x00, 0x00, 0x00, 0x03, /* message size */ + 0x00, 0x01, 0x02, /* message body */ + ]; + + assert_eq_transport_written_bytes!(t, expected_bytes); + } + + #[test] + fn must_return_error_if_nothing_can_be_written_to_inner_transport_on_flush() { + let mem = TBufferChannel::with_capacity(0, 0); + let mut t = TFramedWriteTransport::with_capacity(1, mem); + + let b = vec![0; 10]; + + // should have written 10 bytes + assert_eq!(t.write(&b).unwrap(), 10); + + // let's flush + let r = t.flush(); + + // this time we'll error out because the flush can't write to the underlying channel + assert!(r.is_err()); + } + + #[test] + fn must_write_successfully_after_flush() { + // IMPORTANT: write capacity *MUST* be greater + // than message sizes used in this test + 4-byte frame header + let mem = TBufferChannel::with_capacity(0, 10); + let mut t = TFramedWriteTransport::with_capacity(5, mem); + + // write and flush + let first_message: [u8; 5] = [0x00, 0x01, 0x02, 0x03, 0x04]; + assert_eq!(t.write(&first_message).unwrap(), 5); + assert!(t.flush().is_ok()); + + let mut expected = Vec::new(); + expected.write_all(&[0x00, 0x00, 0x00, 0x05]).unwrap(); // message size + expected.extend_from_slice(&first_message); + + // check the flushed bytes + assert_eq!(t.channel.write_bytes(), expected); + + // reset our underlying transport + t.channel.empty_write_buffer(); + + let second_message: [u8; 3] = [0x05, 0x06, 0x07]; + assert_eq!(t.write(&second_message).unwrap(), 3); + assert!(t.flush().is_ok()); + + expected.clear(); + expected.write_all(&[0x00, 0x00, 0x00, 0x03]).unwrap(); // message size + expected.extend_from_slice(&second_message); + + // check the flushed bytes + assert_eq!(t.channel.write_bytes(), expected); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/rs/src/transport/mem.rs b/vendor/git.apache.org/thrift.git/lib/rs/src/transport/mem.rs new file mode 100644 index 0000000..82c4b57 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/src/transport/mem.rs @@ -0,0 +1,385 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +use std::cmp; +use std::io; +use std::sync::{Arc, Mutex}; + +use super::{ReadHalf, TIoChannel, WriteHalf}; + +/// In-memory read and write channel with fixed-size read and write buffers. +/// +/// On a `write` bytes are written to the internal write buffer. Writes are no +/// longer accepted once this buffer is full. Callers must `empty_write_buffer()` +/// before subsequent writes are accepted. +/// +/// You can set readable bytes in the internal read buffer by filling it with +/// `set_readable_bytes(...)`. Callers can then read until the buffer is +/// depleted. No further reads are accepted until the internal read buffer is +/// replenished again. +#[derive(Debug)] +pub struct TBufferChannel { + read: Arc>, + write: Arc>, +} + +#[derive(Debug)] +struct ReadData { + buf: Box<[u8]>, + pos: usize, + idx: usize, + cap: usize, +} + +#[derive(Debug)] +struct WriteData { + buf: Box<[u8]>, + pos: usize, + cap: usize, +} + +impl TBufferChannel { + /// Constructs a new, empty `TBufferChannel` with the given + /// read buffer capacity and write buffer capacity. + pub fn with_capacity(read_capacity: usize, write_capacity: usize) -> TBufferChannel { + TBufferChannel { + read: Arc::new(Mutex::new(ReadData { + buf: vec![0; read_capacity].into_boxed_slice(), + idx: 0, + pos: 0, + cap: read_capacity, + })), + write: Arc::new(Mutex::new(WriteData { + buf: vec![0; write_capacity].into_boxed_slice(), + pos: 0, + cap: write_capacity, + })), + } + } + + /// Return a copy of the bytes held by the internal read buffer. + /// Returns an empty vector if no readable bytes are present. + pub fn read_bytes(&self) -> Vec { + let rdata = self.read.as_ref().lock().unwrap(); + let mut buf = vec![0u8; rdata.idx]; + buf.copy_from_slice(&rdata.buf[..rdata.idx]); + buf + } + + // FIXME: do I really need this API call? + // FIXME: should this simply reset to the last set of readable bytes? + /// Reset the number of readable bytes to zero. + /// + /// Subsequent calls to `read` will return nothing. + pub fn empty_read_buffer(&mut self) { + let mut rdata = self.read.as_ref().lock().unwrap(); + rdata.pos = 0; + rdata.idx = 0; + } + + /// Copy bytes from the source buffer `buf` into the internal read buffer, + /// overwriting any existing bytes. Returns the number of bytes copied, + /// which is `min(buf.len(), internal_read_buf.len())`. + pub fn set_readable_bytes(&mut self, buf: &[u8]) -> usize { + self.empty_read_buffer(); + let mut rdata = self.read.as_ref().lock().unwrap(); + let max_bytes = cmp::min(rdata.cap, buf.len()); + rdata.buf[..max_bytes].clone_from_slice(&buf[..max_bytes]); + rdata.idx = max_bytes; + max_bytes + } + + /// Return a copy of the bytes held by the internal write buffer. + /// Returns an empty vector if no bytes were written. + pub fn write_bytes(&self) -> Vec { + let wdata = self.write.as_ref().lock().unwrap(); + let mut buf = vec![0u8; wdata.pos]; + buf.copy_from_slice(&wdata.buf[..wdata.pos]); + buf + } + + /// Resets the internal write buffer, making it seem like no bytes were + /// written. Calling `write_buffer` after this returns an empty vector. + pub fn empty_write_buffer(&mut self) { + let mut wdata = self.write.as_ref().lock().unwrap(); + wdata.pos = 0; + } + + /// Overwrites the contents of the read buffer with the contents of the + /// write buffer. The write buffer is emptied after this operation. + pub fn copy_write_buffer_to_read_buffer(&mut self) { + // FIXME: redo this entire method + let buf = { + let wdata = self.write.as_ref().lock().unwrap(); + let b = &wdata.buf[..wdata.pos]; + let mut b_ret = vec![0; b.len()]; + b_ret.copy_from_slice(b); + b_ret + }; + + let bytes_copied = self.set_readable_bytes(&buf); + assert_eq!(bytes_copied, buf.len()); + + self.empty_write_buffer(); + } +} + +impl TIoChannel for TBufferChannel { + fn split(self) -> ::Result<(ReadHalf, WriteHalf)> + where + Self: Sized, + { + Ok(( + ReadHalf { + handle: TBufferChannel { + read: self.read.clone(), + write: self.write.clone(), + }, + }, + WriteHalf { + handle: TBufferChannel { + read: self.read.clone(), + write: self.write.clone(), + }, + }, + )) + } +} + +impl io::Read for TBufferChannel { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let mut rdata = self.read.as_ref().lock().unwrap(); + let nread = cmp::min(buf.len(), rdata.idx - rdata.pos); + buf[..nread].clone_from_slice(&rdata.buf[rdata.pos..rdata.pos + nread]); + rdata.pos += nread; + Ok(nread) + } +} + +impl io::Write for TBufferChannel { + fn write(&mut self, buf: &[u8]) -> io::Result { + let mut wdata = self.write.as_ref().lock().unwrap(); + let nwrite = cmp::min(buf.len(), wdata.cap - wdata.pos); + let (start, end) = (wdata.pos, wdata.pos + nwrite); + wdata.buf[start..end].clone_from_slice(&buf[..nwrite]); + wdata.pos += nwrite; + Ok(nwrite) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) // nothing to do on flush + } +} + +#[cfg(test)] +mod tests { + use std::io::{Read, Write}; + + use super::TBufferChannel; + + #[test] + fn must_empty_write_buffer() { + let mut t = TBufferChannel::with_capacity(0, 1); + + let bytes_to_write: [u8; 1] = [0x01]; + let result = t.write(&bytes_to_write); + assert_eq!(result.unwrap(), 1); + assert_eq!(&t.write_bytes(), &bytes_to_write); + + t.empty_write_buffer(); + assert_eq!(t.write_bytes().len(), 0); + } + + #[test] + fn must_accept_writes_after_buffer_emptied() { + let mut t = TBufferChannel::with_capacity(0, 2); + + let bytes_to_write: [u8; 2] = [0x01, 0x02]; + + // first write (all bytes written) + let result = t.write(&bytes_to_write); + assert_eq!(result.unwrap(), 2); + assert_eq!(&t.write_bytes(), &bytes_to_write); + + // try write again (nothing should be written) + let result = t.write(&bytes_to_write); + assert_eq!(result.unwrap(), 0); + assert_eq!(&t.write_bytes(), &bytes_to_write); // still the same as before + + // now reset the buffer + t.empty_write_buffer(); + assert_eq!(t.write_bytes().len(), 0); + + // now try write again - the write should succeed + let result = t.write(&bytes_to_write); + assert_eq!(result.unwrap(), 2); + assert_eq!(&t.write_bytes(), &bytes_to_write); + } + + #[test] + fn must_accept_multiple_writes_until_buffer_is_full() { + let mut t = TBufferChannel::with_capacity(0, 10); + + // first write (all bytes written) + let bytes_to_write_0: [u8; 2] = [0x01, 0x41]; + let write_0_result = t.write(&bytes_to_write_0); + assert_eq!(write_0_result.unwrap(), 2); + assert_eq!(t.write_bytes(), &bytes_to_write_0); + + // second write (all bytes written, starting at index 2) + let bytes_to_write_1: [u8; 7] = [0x24, 0x41, 0x32, 0x33, 0x11, 0x98, 0xAF]; + let write_1_result = t.write(&bytes_to_write_1); + assert_eq!(write_1_result.unwrap(), 7); + assert_eq!(&t.write_bytes()[2..], &bytes_to_write_1); + + // third write (only 1 byte written - that's all we have space for) + let bytes_to_write_2: [u8; 3] = [0xBF, 0xDA, 0x98]; + let write_2_result = t.write(&bytes_to_write_2); + assert_eq!(write_2_result.unwrap(), 1); + assert_eq!(&t.write_bytes()[9..], &bytes_to_write_2[0..1]); // how does this syntax work?! + + // fourth write (no writes are accepted) + let bytes_to_write_3: [u8; 3] = [0xBF, 0xAA, 0xFD]; + let write_3_result = t.write(&bytes_to_write_3); + assert_eq!(write_3_result.unwrap(), 0); + + // check the full write buffer + let mut expected: Vec = Vec::with_capacity(10); + expected.extend_from_slice(&bytes_to_write_0); + expected.extend_from_slice(&bytes_to_write_1); + expected.extend_from_slice(&bytes_to_write_2[0..1]); + assert_eq!(t.write_bytes(), &expected[..]); + } + + #[test] + fn must_empty_read_buffer() { + let mut t = TBufferChannel::with_capacity(1, 0); + + let bytes_to_read: [u8; 1] = [0x01]; + let result = t.set_readable_bytes(&bytes_to_read); + assert_eq!(result, 1); + assert_eq!(t.read_bytes(), &bytes_to_read); + + t.empty_read_buffer(); + assert_eq!(t.read_bytes().len(), 0); + } + + #[test] + fn must_allow_readable_bytes_to_be_set_after_read_buffer_emptied() { + let mut t = TBufferChannel::with_capacity(1, 0); + + let bytes_to_read_0: [u8; 1] = [0x01]; + let result = t.set_readable_bytes(&bytes_to_read_0); + assert_eq!(result, 1); + assert_eq!(t.read_bytes(), &bytes_to_read_0); + + t.empty_read_buffer(); + assert_eq!(t.read_bytes().len(), 0); + + let bytes_to_read_1: [u8; 1] = [0x02]; + let result = t.set_readable_bytes(&bytes_to_read_1); + assert_eq!(result, 1); + assert_eq!(t.read_bytes(), &bytes_to_read_1); + } + + #[test] + fn must_accept_multiple_reads_until_all_bytes_read() { + let mut t = TBufferChannel::with_capacity(10, 0); + + let readable_bytes: [u8; 10] = [0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0x00, 0x1A, 0x2B, 0x3C, 0x4D]; + + // check that we're able to set the bytes to be read + let result = t.set_readable_bytes(&readable_bytes); + assert_eq!(result, 10); + assert_eq!(t.read_bytes(), &readable_bytes); + + // first read + let mut read_buf_0 = vec![0; 5]; + let read_result = t.read(&mut read_buf_0); + assert_eq!(read_result.unwrap(), 5); + assert_eq!(read_buf_0.as_slice(), &(readable_bytes[0..5])); + + // second read + let mut read_buf_1 = vec![0; 4]; + let read_result = t.read(&mut read_buf_1); + assert_eq!(read_result.unwrap(), 4); + assert_eq!(read_buf_1.as_slice(), &(readable_bytes[5..9])); + + // third read (only 1 byte remains to be read) + let mut read_buf_2 = vec![0; 3]; + let read_result = t.read(&mut read_buf_2); + assert_eq!(read_result.unwrap(), 1); + read_buf_2.truncate(1); // FIXME: does the caller have to do this? + assert_eq!(read_buf_2.as_slice(), &(readable_bytes[9..])); + + // fourth read (nothing should be readable) + let mut read_buf_3 = vec![0; 10]; + let read_result = t.read(&mut read_buf_3); + assert_eq!(read_result.unwrap(), 0); + read_buf_3.truncate(0); + + // check that all the bytes we received match the original (again!) + let mut bytes_read = Vec::with_capacity(10); + bytes_read.extend_from_slice(&read_buf_0); + bytes_read.extend_from_slice(&read_buf_1); + bytes_read.extend_from_slice(&read_buf_2); + bytes_read.extend_from_slice(&read_buf_3); + assert_eq!(&bytes_read, &readable_bytes); + } + + #[test] + fn must_allow_reads_to_succeed_after_read_buffer_replenished() { + let mut t = TBufferChannel::with_capacity(3, 0); + + let readable_bytes_0: [u8; 3] = [0x02, 0xAB, 0x33]; + + // check that we're able to set the bytes to be read + let result = t.set_readable_bytes(&readable_bytes_0); + assert_eq!(result, 3); + assert_eq!(t.read_bytes(), &readable_bytes_0); + + let mut read_buf = vec![0; 4]; + + // drain the read buffer + let read_result = t.read(&mut read_buf); + assert_eq!(read_result.unwrap(), 3); + assert_eq!(t.read_bytes(), &read_buf[0..3]); + + // check that a subsequent read fails + let read_result = t.read(&mut read_buf); + assert_eq!(read_result.unwrap(), 0); + + // we don't modify the read buffer on failure + let mut expected_bytes = Vec::with_capacity(4); + expected_bytes.extend_from_slice(&readable_bytes_0); + expected_bytes.push(0x00); + assert_eq!(&read_buf, &expected_bytes); + + // replenish the read buffer again + let readable_bytes_1: [u8; 2] = [0x91, 0xAA]; + + // check that we're able to set the bytes to be read + let result = t.set_readable_bytes(&readable_bytes_1); + assert_eq!(result, 2); + assert_eq!(t.read_bytes(), &readable_bytes_1); + + // read again + let read_result = t.read(&mut read_buf); + assert_eq!(read_result.unwrap(), 2); + assert_eq!(t.read_bytes(), &read_buf[0..2]); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/rs/src/transport/mod.rs b/vendor/git.apache.org/thrift.git/lib/rs/src/transport/mod.rs new file mode 100644 index 0000000..a623350 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/src/transport/mod.rs @@ -0,0 +1,291 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +//! Types used to send and receive bytes over an I/O channel. +//! +//! The core types are the `TReadTransport`, `TWriteTransport` and the +//! `TIoChannel` traits, through which `TInputProtocol` or +//! `TOutputProtocol` can receive and send primitives over the wire. While +//! `TInputProtocol` and `TOutputProtocol` instances deal with language primitives +//! the types in this module understand only bytes. + +use std::io; +use std::io::{Read, Write}; +use std::ops::{Deref, DerefMut}; + +#[cfg(test)] +macro_rules! assert_eq_transport_num_written_bytes { + ($transport:ident, $num_written_bytes:expr) => {{ + assert_eq!($transport.channel.write_bytes().len(), $num_written_bytes); + }}; +} + +#[cfg(test)] +macro_rules! assert_eq_transport_written_bytes { + ($transport:ident, $expected_bytes:ident) => {{ + assert_eq!($transport.channel.write_bytes(), &$expected_bytes); + }}; +} + +mod buffered; +mod framed; +mod mem; +mod socket; + +pub use self::buffered::{ + TBufferedReadTransport, TBufferedReadTransportFactory, TBufferedWriteTransport, + TBufferedWriteTransportFactory, +}; +pub use self::framed::{ + TFramedReadTransport, TFramedReadTransportFactory, TFramedWriteTransport, + TFramedWriteTransportFactory, +}; +pub use self::mem::TBufferChannel; +pub use self::socket::TTcpChannel; + +/// Identifies a transport used by a `TInputProtocol` to receive bytes. +pub trait TReadTransport: Read {} + +/// Helper type used by a server to create `TReadTransport` instances for +/// accepted client connections. +pub trait TReadTransportFactory { + /// Create a `TTransport` that wraps a channel over which bytes are to be read. + fn create(&self, channel: Box) -> Box; +} + +/// Identifies a transport used by `TOutputProtocol` to send bytes. +pub trait TWriteTransport: Write {} + +/// Helper type used by a server to create `TWriteTransport` instances for +/// accepted client connections. +pub trait TWriteTransportFactory { + /// Create a `TTransport` that wraps a channel over which bytes are to be sent. + fn create(&self, channel: Box) -> Box; +} + +impl TReadTransport for T where T: Read {} + +impl TWriteTransport for T where T: Write {} + +// FIXME: implement the Debug trait for boxed transports + +impl TReadTransportFactory for Box +where + T: TReadTransportFactory + ?Sized, +{ + fn create(&self, channel: Box) -> Box { + (**self).create(channel) + } +} + +impl TWriteTransportFactory for Box +where + T: TWriteTransportFactory + ?Sized, +{ + fn create(&self, channel: Box) -> Box { + (**self).create(channel) + } +} + +/// Identifies a splittable bidirectional I/O channel used to send and receive bytes. +pub trait TIoChannel: Read + Write { + /// Split the channel into a readable half and a writable half, where the + /// readable half implements `io::Read` and the writable half implements + /// `io::Write`. Returns `None` if the channel was not initialized, or if it + /// cannot be split safely. + /// + /// Returned halves may share the underlying OS channel or buffer resources. + /// Implementations **should ensure** that these two halves can be safely + /// used independently by concurrent threads. + fn split(self) -> ::Result<(::transport::ReadHalf, ::transport::WriteHalf)> + where + Self: Sized; +} + +/// The readable half of an object returned from `TIoChannel::split`. +#[derive(Debug)] +pub struct ReadHalf +where + C: Read, +{ + handle: C, +} + +/// The writable half of an object returned from `TIoChannel::split`. +#[derive(Debug)] +pub struct WriteHalf +where + C: Write, +{ + handle: C, +} + +impl ReadHalf +where + C: Read, +{ + /// Create a `ReadHalf` associated with readable `handle` + pub fn new(handle: C) -> ReadHalf { + ReadHalf { handle } + } +} + +impl WriteHalf +where + C: Write, +{ + /// Create a `WriteHalf` associated with writable `handle` + pub fn new(handle: C) -> WriteHalf { + WriteHalf { handle } + } +} + +impl Read for ReadHalf +where + C: Read, +{ + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.handle.read(buf) + } +} + +impl Write for WriteHalf +where + C: Write, +{ + fn write(&mut self, buf: &[u8]) -> io::Result { + self.handle.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.handle.flush() + } +} + +impl Deref for ReadHalf +where + C: Read, +{ + type Target = C; + + fn deref(&self) -> &Self::Target { + &self.handle + } +} + +impl DerefMut for ReadHalf +where + C: Read, +{ + fn deref_mut(&mut self) -> &mut C { + &mut self.handle + } +} + +impl Deref for WriteHalf +where + C: Write, +{ + type Target = C; + + fn deref(&self) -> &Self::Target { + &self.handle + } +} + +impl DerefMut for WriteHalf +where + C: Write, +{ + fn deref_mut(&mut self) -> &mut C { + &mut self.handle + } +} + +#[cfg(test)] +mod tests { + + use std::io::Cursor; + + use super::*; + + #[test] + fn must_create_usable_read_channel_from_concrete_read_type() { + let r = Cursor::new([0, 1, 2]); + let _ = TBufferedReadTransport::new(r); + } + + #[test] + fn must_create_usable_read_channel_from_boxed_read() { + let r: Box = Box::new(Cursor::new([0, 1, 2])); + let _ = TBufferedReadTransport::new(r); + } + + #[test] + fn must_create_usable_write_channel_from_concrete_write_type() { + let w = vec![0u8; 10]; + let _ = TBufferedWriteTransport::new(w); + } + + #[test] + fn must_create_usable_write_channel_from_boxed_write() { + let w: Box = Box::new(vec![0u8; 10]); + let _ = TBufferedWriteTransport::new(w); + } + + #[test] + fn must_create_usable_read_transport_from_concrete_read_transport() { + let r = Cursor::new([0, 1, 2]); + let mut t = TBufferedReadTransport::new(r); + takes_read_transport(&mut t) + } + + #[test] + fn must_create_usable_read_transport_from_boxed_read() { + let r = Cursor::new([0, 1, 2]); + let mut t: Box = Box::new(TBufferedReadTransport::new(r)); + takes_read_transport(&mut t) + } + + #[test] + fn must_create_usable_write_transport_from_concrete_write_transport() { + let w = vec![0u8; 10]; + let mut t = TBufferedWriteTransport::new(w); + takes_write_transport(&mut t) + } + + #[test] + fn must_create_usable_write_transport_from_boxed_write() { + let w = vec![0u8; 10]; + let mut t: Box = Box::new(TBufferedWriteTransport::new(w)); + takes_write_transport(&mut t) + } + + fn takes_read_transport(t: &mut R) + where + R: TReadTransport, + { + t.bytes(); + } + + fn takes_write_transport(t: &mut W) + where + W: TWriteTransport, + { + t.flush().unwrap(); + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/rs/src/transport/socket.rs b/vendor/git.apache.org/thrift.git/lib/rs/src/transport/socket.rs new file mode 100644 index 0000000..0bef67b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/src/transport/socket.rs @@ -0,0 +1,168 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +use std::convert::From; +use std::io; +use std::io::{ErrorKind, Read, Write}; +use std::net::{Shutdown, TcpStream}; + +use super::{ReadHalf, TIoChannel, WriteHalf}; +use {new_transport_error, TransportErrorKind}; + +/// Bidirectional TCP/IP channel. +/// +/// # Examples +/// +/// Create a `TTcpChannel`. +/// +/// ```no_run +/// use std::io::{Read, Write}; +/// use thrift::transport::TTcpChannel; +/// +/// let mut c = TTcpChannel::new(); +/// c.open("localhost:9090").unwrap(); +/// +/// let mut buf = vec![0u8; 4]; +/// c.read(&mut buf).unwrap(); +/// c.write(&vec![0, 1, 2]).unwrap(); +/// ``` +/// +/// Create a `TTcpChannel` by wrapping an existing `TcpStream`. +/// +/// ```no_run +/// use std::io::{Read, Write}; +/// use std::net::TcpStream; +/// use thrift::transport::TTcpChannel; +/// +/// let stream = TcpStream::connect("127.0.0.1:9189").unwrap(); +/// +/// // no need to call c.open() since we've already connected above +/// let mut c = TTcpChannel::with_stream(stream); +/// +/// let mut buf = vec![0u8; 4]; +/// c.read(&mut buf).unwrap(); +/// c.write(&vec![0, 1, 2]).unwrap(); +/// ``` +#[derive(Debug, Default)] +pub struct TTcpChannel { + stream: Option, +} + +impl TTcpChannel { + /// Create an uninitialized `TTcpChannel`. + /// + /// The returned instance must be opened using `TTcpChannel::open(...)` + /// before it can be used. + pub fn new() -> TTcpChannel { + TTcpChannel { stream: None } + } + + /// Create a `TTcpChannel` that wraps an existing `TcpStream`. + /// + /// The passed-in stream is assumed to have been opened before being wrapped + /// by the created `TTcpChannel` instance. + pub fn with_stream(stream: TcpStream) -> TTcpChannel { + TTcpChannel { + stream: Some(stream), + } + } + + /// Connect to `remote_address`, which should have the form `host:port`. + pub fn open(&mut self, remote_address: &str) -> ::Result<()> { + if self.stream.is_some() { + Err(new_transport_error( + TransportErrorKind::AlreadyOpen, + "tcp connection previously opened", + )) + } else { + match TcpStream::connect(&remote_address) { + Ok(s) => { + self.stream = Some(s); + Ok(()) + } + Err(e) => Err(From::from(e)), + } + } + } + + /// Shut down this channel. + /// + /// Both send and receive halves are closed, and this instance can no + /// longer be used to communicate with another endpoint. + pub fn close(&mut self) -> ::Result<()> { + self.if_set(|s| s.shutdown(Shutdown::Both)) + .map_err(From::from) + } + + fn if_set(&mut self, mut stream_operation: F) -> io::Result + where + F: FnMut(&mut TcpStream) -> io::Result, + { + if let Some(ref mut s) = self.stream { + stream_operation(s) + } else { + Err(io::Error::new( + ErrorKind::NotConnected, + "tcp endpoint not connected", + )) + } + } +} + +impl TIoChannel for TTcpChannel { + fn split(self) -> ::Result<(ReadHalf, WriteHalf)> + where + Self: Sized, + { + let mut s = self; + + s.stream + .as_mut() + .and_then(|s| s.try_clone().ok()) + .map(|cloned| { + let read_half = ReadHalf::new(TTcpChannel { + stream: s.stream.take(), + }); + let write_half = WriteHalf::new(TTcpChannel { + stream: Some(cloned), + }); + (read_half, write_half) + }) + .ok_or_else(|| { + new_transport_error( + TransportErrorKind::Unknown, + "cannot clone underlying tcp stream", + ) + }) + } +} + +impl Read for TTcpChannel { + fn read(&mut self, b: &mut [u8]) -> io::Result { + self.if_set(|s| s.read(b)) + } +} + +impl Write for TTcpChannel { + fn write(&mut self, b: &[u8]) -> io::Result { + self.if_set(|s| s.write(b)) + } + + fn flush(&mut self) -> io::Result<()> { + self.if_set(|s| s.flush()) + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/rs/test/Cargo.toml b/vendor/git.apache.org/thrift.git/lib/rs/test/Cargo.toml new file mode 100644 index 0000000..50dec19 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/test/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "kitchen-sink" +version = "0.1.0" +license = "Apache-2.0" +authors = ["Apache Thrift Developers "] +publish = false + +[dependencies] +clap = "<2.28.0" +ordered-float = "0.3.0" +try_from = "0.2.0" + +[dependencies.thrift] +path = "../" + diff --git a/vendor/git.apache.org/thrift.git/lib/rs/test/Makefile.am b/vendor/git.apache.org/thrift.git/lib/rs/test/Makefile.am new file mode 100644 index 0000000..8edd756 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/test/Makefile.am @@ -0,0 +1,54 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +THRIFT = $(top_builddir)/compiler/cpp/thrift + +stubs: thrifts/Base_One.thrift thrifts/Base_Two.thrift thrifts/Midlayer.thrift thrifts/Ultimate.thrift $(top_builddir)/test/Recursive.thrift $(THRIFT) + $(THRIFT) -I ./thrifts -out src --gen rs thrifts/Base_One.thrift + $(THRIFT) -I ./thrifts -out src --gen rs thrifts/Base_Two.thrift + $(THRIFT) -I ./thrifts -out src --gen rs thrifts/Midlayer.thrift + $(THRIFT) -I ./thrifts -out src --gen rs thrifts/Ultimate.thrift + $(THRIFT) -out src --gen rs $(top_builddir)/test/Recursive.thrift + +check: stubs + $(CARGO) build + $(CARGO) test + [ -d bin ] || mkdir bin + cp target/debug/kitchen_sink_server bin/kitchen_sink_server + cp target/debug/kitchen_sink_client bin/kitchen_sink_client + +clean-local: + $(CARGO) clean + -$(RM) Cargo.lock + -$(RM) src/base_one.rs + -$(RM) src/base_two.rs + -$(RM) src/midlayer.rs + -$(RM) src/ultimate.rs + -$(RM) -r bin + +EXTRA_DIST = \ + Cargo.toml \ + thrifts/Base_One.thrift \ + thrifts/Base_Two.thrift \ + thrifts/Midlayer.thrift \ + thrifts/Ultimate.thrift \ + src/lib.rs \ + src/bin/kitchen_sink_server.rs \ + src/bin/kitchen_sink_client.rs + diff --git a/vendor/git.apache.org/thrift.git/lib/rs/test/src/bin/kitchen_sink_client.rs b/vendor/git.apache.org/thrift.git/lib/rs/test/src/bin/kitchen_sink_client.rs new file mode 100644 index 0000000..d295c88 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/test/src/bin/kitchen_sink_client.rs @@ -0,0 +1,239 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +#[macro_use] +extern crate clap; + +extern crate kitchen_sink; +extern crate thrift; + +use std::convert::Into; + +use kitchen_sink::base_two::{TNapkinServiceSyncClient, TRamenServiceSyncClient}; +use kitchen_sink::midlayer::{MealServiceSyncClient, TMealServiceSyncClient}; +use kitchen_sink::recursive; +use kitchen_sink::recursive::{CoRec, CoRec2, RecList, RecTree, TTestServiceSyncClient}; +use kitchen_sink::ultimate::{FullMealServiceSyncClient, TFullMealServiceSyncClient}; +use thrift::protocol::{ + TBinaryInputProtocol, TBinaryOutputProtocol, TCompactInputProtocol, TCompactOutputProtocol, + TInputProtocol, TOutputProtocol, +}; +use thrift::transport::{ + ReadHalf, TFramedReadTransport, TFramedWriteTransport, TIoChannel, TTcpChannel, WriteHalf, +}; + +fn main() { + match run() { + Ok(()) => println!("kitchen sink client completed successfully"), + Err(e) => { + println!("kitchen sink client failed with error {:?}", e); + std::process::exit(1); + } + } +} + +fn run() -> thrift::Result<()> { + let matches = clap_app!(rust_kitchen_sink_client => + (version: "0.1.0") + (author: "Apache Thrift Developers ") + (about: "Thrift Rust kitchen sink client") + (@arg host: --host +takes_value "Host on which the Thrift test server is located") + (@arg port: --port +takes_value "Port on which the Thrift test server is listening") + (@arg protocol: --protocol +takes_value "Thrift protocol implementation to use (\"binary\", \"compact\")") + (@arg service: --service +takes_value "Service type to contact (\"part\", \"full\", \"recursive\")") + ) + .get_matches(); + + let host = matches.value_of("host").unwrap_or("127.0.0.1"); + let port = value_t!(matches, "port", u16).unwrap_or(9090); + let protocol = matches.value_of("protocol").unwrap_or("compact"); + let service = matches.value_of("service").unwrap_or("part"); + + let (i_chan, o_chan) = tcp_channel(host, port)?; + let (i_tran, o_tran) = ( + TFramedReadTransport::new(i_chan), + TFramedWriteTransport::new(o_chan), + ); + + let (i_prot, o_prot): (Box, Box) = match protocol { + "binary" => ( + Box::new(TBinaryInputProtocol::new(i_tran, true)), + Box::new(TBinaryOutputProtocol::new(o_tran, true)), + ), + "compact" => ( + Box::new(TCompactInputProtocol::new(i_tran)), + Box::new(TCompactOutputProtocol::new(o_tran)), + ), + unmatched => return Err(format!("unsupported protocol {}", unmatched).into()), + }; + + run_client(service, i_prot, o_prot) +} + +fn run_client( + service: &str, + i_prot: Box, + o_prot: Box, +) -> thrift::Result<()> { + match service { + "full" => exec_full_meal_client(i_prot, o_prot), + "part" => exec_meal_client(i_prot, o_prot), + "recursive" => exec_recursive_client(i_prot, o_prot), + _ => Err(thrift::Error::from(format!( + "unknown service type {}", + service + ))), + } +} + +fn tcp_channel( + host: &str, + port: u16, +) -> thrift::Result<(ReadHalf, WriteHalf)> { + let mut c = TTcpChannel::new(); + c.open(&format!("{}:{}", host, port))?; + c.split() +} + +fn exec_meal_client( + i_prot: Box, + o_prot: Box, +) -> thrift::Result<()> { + let mut client = MealServiceSyncClient::new(i_prot, o_prot); + + // client.full_meal(); // <-- IMPORTANT: if you uncomment this, compilation *should* fail + // this is because the MealService struct does not contain the appropriate service marker + + // only the following three calls work + execute_call("part", "ramen", || client.ramen(50)).map(|_| ())?; + execute_call("part", "meal", || client.meal()).map(|_| ())?; + execute_call("part", "napkin", || client.napkin()).map(|_| ())?; + + Ok(()) +} + +fn exec_full_meal_client( + i_prot: Box, + o_prot: Box, +) -> thrift::Result<()> { + let mut client = FullMealServiceSyncClient::new(i_prot, o_prot); + + execute_call("full", "ramen", || client.ramen(100)).map(|_| ())?; + execute_call("full", "meal", || client.meal()).map(|_| ())?; + execute_call("full", "napkin", || client.napkin()).map(|_| ())?; + execute_call("full", "full meal", || client.full_meal()).map(|_| ())?; + + Ok(()) +} + +fn exec_recursive_client( + i_prot: Box, + o_prot: Box, +) -> thrift::Result<()> { + let mut client = recursive::TestServiceSyncClient::new(i_prot, o_prot); + + let tree = RecTree { + children: Some(vec![Box::new(RecTree { + children: Some(vec![ + Box::new(RecTree { + children: None, + item: Some(3), + }), + Box::new(RecTree { + children: None, + item: Some(4), + }), + ]), + item: Some(2), + })]), + item: Some(1), + }; + + let expected_tree = RecTree { + children: Some(vec![Box::new(RecTree { + children: Some(vec![ + Box::new(RecTree { + children: Some(Vec::new()), // remote returns an empty list + item: Some(3), + }), + Box::new(RecTree { + children: Some(Vec::new()), // remote returns an empty list + item: Some(4), + }), + ]), + item: Some(2), + })]), + item: Some(1), + }; + + let returned_tree = execute_call("recursive", "echo_tree", || client.echo_tree(tree.clone()))?; + if returned_tree != expected_tree { + return Err(format!( + "mismatched recursive tree {:?} {:?}", + expected_tree, returned_tree + ) + .into()); + } + + let list = RecList { + nextitem: Some(Box::new(RecList { + nextitem: Some(Box::new(RecList { + nextitem: None, + item: Some(3), + })), + item: Some(2), + })), + item: Some(1), + }; + let returned_list = execute_call("recursive", "echo_list", || client.echo_list(list.clone()))?; + if returned_list != list { + return Err(format!("mismatched recursive list {:?} {:?}", list, returned_list).into()); + } + + let co_rec = CoRec { + other: Some(Box::new(CoRec2 { + other: Some(CoRec { + other: Some(Box::new(CoRec2 { other: None })), + }), + })), + }; + let returned_co_rec = execute_call("recursive", "echo_co_rec", || { + client.echo_co_rec(co_rec.clone()) + })?; + if returned_co_rec != co_rec { + return Err(format!("mismatched co_rec {:?} {:?}", co_rec, returned_co_rec).into()); + } + + Ok(()) +} + +fn execute_call(service_type: &str, call_name: &str, mut f: F) -> thrift::Result +where + F: FnMut() -> thrift::Result, +{ + let res = f(); + + match res { + Ok(_) => println!("{}: completed {} call", service_type, call_name), + Err(ref e) => println!( + "{}: failed {} call with error {:?}", + service_type, call_name, e + ), + } + + res +} diff --git a/vendor/git.apache.org/thrift.git/lib/rs/test/src/bin/kitchen_sink_server.rs b/vendor/git.apache.org/thrift.git/lib/rs/test/src/bin/kitchen_sink_server.rs new file mode 100644 index 0000000..73801ea --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/test/src/bin/kitchen_sink_server.rs @@ -0,0 +1,313 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +#[macro_use] +extern crate clap; +extern crate kitchen_sink; +extern crate thrift; + +use thrift::protocol::{ + TBinaryInputProtocolFactory, TBinaryOutputProtocolFactory, TCompactInputProtocolFactory, + TCompactOutputProtocolFactory, TInputProtocolFactory, TOutputProtocolFactory, +}; +use thrift::server::TServer; +use thrift::transport::{ + TFramedReadTransportFactory, TFramedWriteTransportFactory, TReadTransportFactory, + TWriteTransportFactory, +}; + +use kitchen_sink::base_one::Noodle; +use kitchen_sink::base_two::{ + BrothType, Napkin, NapkinServiceSyncHandler, Ramen, RamenServiceSyncHandler, +}; +use kitchen_sink::midlayer::{ + Dessert, Meal, MealServiceSyncHandler, MealServiceSyncProcessor, Pie, +}; +use kitchen_sink::recursive; +use kitchen_sink::ultimate::FullMealAndDrinksServiceSyncHandler; +use kitchen_sink::ultimate::{ + Drink, FullMeal, FullMealAndDrinks, FullMealAndDrinksServiceSyncProcessor, + FullMealServiceSyncHandler, +}; + +fn main() { + match run() { + Ok(()) => println!("kitchen sink server completed successfully"), + Err(e) => { + println!("kitchen sink server failed with error {:?}", e); + std::process::exit(1); + } + } +} + +fn run() -> thrift::Result<()> { + let matches = clap_app!(rust_kitchen_sink_server => + (version: "0.1.0") + (author: "Apache Thrift Developers ") + (about: "Thrift Rust kitchen sink test server") + (@arg port: --port +takes_value "port on which the test server listens") + (@arg protocol: --protocol +takes_value "Thrift protocol implementation to use (\"binary\", \"compact\")") + (@arg service: --service +takes_value "Service type to contact (\"part\", \"full\", \"recursive\")") + ) + .get_matches(); + + let port = value_t!(matches, "port", u16).unwrap_or(9090); + let protocol = matches.value_of("protocol").unwrap_or("compact"); + let service = matches.value_of("service").unwrap_or("part"); + let listen_address = format!("127.0.0.1:{}", port); + + println!("binding to {}", listen_address); + + let r_transport_factory = TFramedReadTransportFactory::new(); + let w_transport_factory = TFramedWriteTransportFactory::new(); + + let (i_protocol_factory, o_protocol_factory): ( + Box, + Box, + ) = match &*protocol { + "binary" => ( + Box::new(TBinaryInputProtocolFactory::new()), + Box::new(TBinaryOutputProtocolFactory::new()), + ), + "compact" => ( + Box::new(TCompactInputProtocolFactory::new()), + Box::new(TCompactOutputProtocolFactory::new()), + ), + unknown => { + return Err(format!("unsupported transport type {}", unknown).into()); + } + }; + + // FIXME: should processor be boxed as well? + // + // [sigh] I hate Rust generics implementation + // + // I would have preferred to build a server here, return it, and then do + // the common listen-and-handle stuff, but since the server doesn't have a + // common type (because each match arm instantiates a server with a + // different processor) this isn't possible. + // + // Since what I'm doing is uncommon I'm just going to duplicate the code + match &*service { + "part" => run_meal_server( + &listen_address, + r_transport_factory, + i_protocol_factory, + w_transport_factory, + o_protocol_factory, + ), + "full" => run_full_meal_server( + &listen_address, + r_transport_factory, + i_protocol_factory, + w_transport_factory, + o_protocol_factory, + ), + "recursive" => run_recursive_server( + &listen_address, + r_transport_factory, + i_protocol_factory, + w_transport_factory, + o_protocol_factory, + ), + unknown => Err(format!("unsupported service type {}", unknown).into()), + } +} + +fn run_meal_server( + listen_address: &str, + r_transport_factory: RTF, + i_protocol_factory: IPF, + w_transport_factory: WTF, + o_protocol_factory: OPF, +) -> thrift::Result<()> +where + RTF: TReadTransportFactory + 'static, + IPF: TInputProtocolFactory + 'static, + WTF: TWriteTransportFactory + 'static, + OPF: TOutputProtocolFactory + 'static, +{ + let processor = MealServiceSyncProcessor::new(PartHandler {}); + let mut server = TServer::new( + r_transport_factory, + i_protocol_factory, + w_transport_factory, + o_protocol_factory, + processor, + 1, + ); + + server.listen(listen_address) +} + +fn run_full_meal_server( + listen_address: &str, + r_transport_factory: RTF, + i_protocol_factory: IPF, + w_transport_factory: WTF, + o_protocol_factory: OPF, +) -> thrift::Result<()> +where + RTF: TReadTransportFactory + 'static, + IPF: TInputProtocolFactory + 'static, + WTF: TWriteTransportFactory + 'static, + OPF: TOutputProtocolFactory + 'static, +{ + let processor = FullMealAndDrinksServiceSyncProcessor::new(FullHandler {}); + let mut server = TServer::new( + r_transport_factory, + i_protocol_factory, + w_transport_factory, + o_protocol_factory, + processor, + 1, + ); + + server.listen(listen_address) +} + +struct PartHandler; + +impl MealServiceSyncHandler for PartHandler { + fn handle_meal(&self) -> thrift::Result { + println!("part: handling meal call"); + Ok(meal()) + } +} + +impl RamenServiceSyncHandler for PartHandler { + fn handle_ramen(&self, _: i32) -> thrift::Result { + println!("part: handling ramen call"); + Ok(ramen()) + } +} + +impl NapkinServiceSyncHandler for PartHandler { + fn handle_napkin(&self) -> thrift::Result { + println!("part: handling napkin call"); + Ok(napkin()) + } +} + +// full service +// + +struct FullHandler; + +impl FullMealAndDrinksServiceSyncHandler for FullHandler { + fn handle_full_meal_and_drinks(&self) -> thrift::Result { + println!("full_meal_and_drinks: handling full meal and drinks call"); + Ok(FullMealAndDrinks::new(full_meal(), Drink::CanadianWhisky)) + } + + fn handle_best_pie(&self) -> thrift::Result { + println!("full_meal_and_drinks: handling pie call"); + Ok(Pie::MississippiMud) // I prefer Pie::Pumpkin, but I have to check that casing works + } +} + +impl FullMealServiceSyncHandler for FullHandler { + fn handle_full_meal(&self) -> thrift::Result { + println!("full: handling full meal call"); + Ok(full_meal()) + } +} + +impl MealServiceSyncHandler for FullHandler { + fn handle_meal(&self) -> thrift::Result { + println!("full: handling meal call"); + Ok(meal()) + } +} + +impl RamenServiceSyncHandler for FullHandler { + fn handle_ramen(&self, _: i32) -> thrift::Result { + println!("full: handling ramen call"); + Ok(ramen()) + } +} + +impl NapkinServiceSyncHandler for FullHandler { + fn handle_napkin(&self) -> thrift::Result { + println!("full: handling napkin call"); + Ok(napkin()) + } +} + +fn full_meal() -> FullMeal { + FullMeal::new(meal(), Dessert::Port("Graham's Tawny".to_owned())) +} + +fn meal() -> Meal { + Meal::new(noodle(), ramen()) +} + +fn noodle() -> Noodle { + Noodle::new("spelt".to_owned(), 100) +} + +fn ramen() -> Ramen { + Ramen::new("Mr Ramen".to_owned(), 72, BrothType::Miso) +} + +fn napkin() -> Napkin { + Napkin {} +} + +fn run_recursive_server( + listen_address: &str, + r_transport_factory: RTF, + i_protocol_factory: IPF, + w_transport_factory: WTF, + o_protocol_factory: OPF, +) -> thrift::Result<()> +where + RTF: TReadTransportFactory + 'static, + IPF: TInputProtocolFactory + 'static, + WTF: TWriteTransportFactory + 'static, + OPF: TOutputProtocolFactory + 'static, +{ + let processor = recursive::TestServiceSyncProcessor::new(RecursiveTestServerHandler {}); + let mut server = TServer::new( + r_transport_factory, + i_protocol_factory, + w_transport_factory, + o_protocol_factory, + processor, + 1, + ); + + server.listen(listen_address) +} + +struct RecursiveTestServerHandler; +impl recursive::TestServiceSyncHandler for RecursiveTestServerHandler { + fn handle_echo_tree(&self, tree: recursive::RecTree) -> thrift::Result { + println!("{:?}", tree); + Ok(tree) + } + + fn handle_echo_list(&self, lst: recursive::RecList) -> thrift::Result { + println!("{:?}", lst); + Ok(lst) + } + + fn handle_echo_co_rec(&self, item: recursive::CoRec) -> thrift::Result { + println!("{:?}", item); + Ok(item) + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/rs/test/src/lib.rs b/vendor/git.apache.org/thrift.git/lib/rs/test/src/lib.rs new file mode 100644 index 0000000..e5e176e --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/test/src/lib.rs @@ -0,0 +1,57 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +extern crate ordered_float; +extern crate thrift; +extern crate try_from; + +pub mod base_one; +pub mod base_two; +pub mod midlayer; +pub mod ultimate; +pub mod recursive; + +#[cfg(test)] +mod tests { + + use std::default::Default; + + use super::*; + + #[test] + fn must_be_able_to_use_constructor() { + let _ = midlayer::Meal::new(Some(base_one::Noodle::default()), None); + } + + #[test] + fn must_be_able_to_use_constructor_with_no_fields() { + let _ = midlayer::Meal::new(None, None); + } + + #[test] + fn must_be_able_to_use_constructor_without_option_wrap() { + let _ = midlayer::Meal::new(base_one::Noodle::default(), None); + } + + #[test] + fn must_be_able_to_use_defaults() { + let _ = midlayer::Meal { + noodle: Some(base_one::Noodle::default()), + ..Default::default() + }; + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/rs/test/thrifts/Base_One.thrift b/vendor/git.apache.org/thrift.git/lib/rs/test/thrifts/Base_One.thrift new file mode 100644 index 0000000..c5fa6c2 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/test/thrifts/Base_One.thrift @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + * + * Contains some contributions under the Thrift Software License. + * Please see doc/old-thrift-license.txt in the Thrift distribution for + * details. + */ + +typedef i64 Temperature + +typedef i8 Size + +typedef string Location + +const i32 BoilingPoint = 100 + +const list Temperatures = [10, 11, 22, 33] + +// IMPORTANT: temps should end with ".0" because this tests +// that we don't have a problem with const float list generation +const list CommonTemperatures = [300.0, 450.0] + +const double MealsPerDay = 2.5; + +const string DefaultRecipeName = "Soup-rise of the Day" +const binary DefaultRecipeBinary = "Soup-rise of the 01010101" + +struct Noodle { + 1: string flourType + 2: Temperature cookTemp +} + +struct Spaghetti { + 1: optional list noodles +} + +const Noodle SpeltNoodle = { "flourType": "spelt", "cookTemp": 110 } + +struct MeasuringSpoon { + 1: Size size +} + +struct MeasuringCup { + 1: double millis +} + +union MeasuringAids { + 1: MeasuringSpoon spoon + 2: MeasuringCup cup +} + +struct CookingTemperatures { + 1: set commonTemperatures + 2: list usedTemperatures + 3: map fahrenheitToCentigradeConversions +} + +struct Recipe { + 1: string recipeName + 2: string cuisine + 3: i8 page +} + +union CookingTools { + 1: set measuringSpoons + 2: map measuringCups, + 3: list recipes +} + diff --git a/vendor/git.apache.org/thrift.git/lib/rs/test/thrifts/Base_Two.thrift b/vendor/git.apache.org/thrift.git/lib/rs/test/thrifts/Base_Two.thrift new file mode 100644 index 0000000..caa6acb --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/test/thrifts/Base_Two.thrift @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + * + * Contains some contributions under the Thrift Software License. + * Please see doc/old-thrift-license.txt in the Thrift distribution for + * details. + */ + +const i32 WaterWeight = 200 + +enum brothType { + Miso, + shouyu, +} + +struct Ramen { + 1: optional string ramenType + 2: required i32 noodleCount + 3: brothType broth +} + +struct Napkin { + // empty +} + +service NapkinService { + Napkin napkin() +} + +service RamenService extends NapkinService { + Ramen ramen(1: i32 requestedNoodleCount) +} + +/* const struct CookedRamen = { "bar": 10 } */ + diff --git a/vendor/git.apache.org/thrift.git/lib/rs/test/thrifts/Midlayer.thrift b/vendor/git.apache.org/thrift.git/lib/rs/test/thrifts/Midlayer.thrift new file mode 100644 index 0000000..16ff49b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/test/thrifts/Midlayer.thrift @@ -0,0 +1,71 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + * + * Contains some contributions under the Thrift Software License. + * Please see doc/old-thrift-license.txt in the Thrift distribution for + * details. + */ + +include "Base_One.thrift" +include "Base_Two.thrift" + +const i32 WaterBoilingPoint = Base_One.BoilingPoint + +const map TemperatureNames = { "freezing": 0, "boiling": 100 } + +const map, map, string>> MyConstNestedMap = { + [0, 1, 2, 3]: { ["foo"]: "bar" }, + [20]: { ["nut", "ton"] : "bar" }, + [30, 40]: { ["bouncy", "tinkly"]: "castle" } +} + +const list> MyConstNestedList = [ + [0, 1, 2], + [3, 4, 5], + [6, 7, 8] +] + +const set> MyConstNestedSet = [ + [0, 1, 2], + [3, 4, 5], + [6, 7, 8] +] + +enum Pie { + PUMPKIN, + apple, // intentionally poorly cased + STRAWBERRY_RHUBARB, + Key_Lime, // intentionally poorly cased + coconut_Cream, // intentionally poorly cased + mississippi_mud, // intentionally poorly cased +} + +struct Meal { + 1: Base_One.Noodle noodle + 2: Base_Two.Ramen ramen +} + +union Dessert { + 1: string port + 2: string iceWine +} + +service MealService extends Base_Two.RamenService { + Meal meal() +} + diff --git a/vendor/git.apache.org/thrift.git/lib/rs/test/thrifts/Ultimate.thrift b/vendor/git.apache.org/thrift.git/lib/rs/test/thrifts/Ultimate.thrift new file mode 100644 index 0000000..72fa100 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/rs/test/thrifts/Ultimate.thrift @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + * + * Contains some contributions under the Thrift Software License. + * Please see doc/old-thrift-license.txt in the Thrift distribution for + * details. + */ + +include "Midlayer.thrift" + +enum Drink { + WATER, + WHISKEY, + WINE, + scotch, // intentionally poorly cased + LATE_HARVEST_WINE, + India_Pale_Ale, // intentionally poorly cased + apple_cider, // intentially poorly cased + belgian_Ale, // intentionally poorly cased + Canadian_whisky, // intentionally poorly cased +} + +const map RankedPies = { + 1: Midlayer.Pie.PUMPKIN, + 2: Midlayer.Pie.STRAWBERRY_RHUBARB, + 3: Midlayer.Pie.apple, + 4: Midlayer.Pie.mississippi_mud, + 5: Midlayer.Pie.coconut_Cream, + 6: Midlayer.Pie.Key_Lime, +} + +struct FullMeal { + 1: required Midlayer.Meal meal + 2: required Midlayer.Dessert dessert +} + +struct FullMealAndDrinks { + 1: required FullMeal fullMeal + 2: optional Drink drink +} + +service FullMealService extends Midlayer.MealService { + FullMeal fullMeal() +} + +service FullMealAndDrinksService extends FullMealService { + FullMealAndDrinks fullMealAndDrinks() + + Midlayer.Pie bestPie() +} + diff --git a/vendor/git.apache.org/thrift.git/lib/st/package.xml b/vendor/git.apache.org/thrift.git/lib/st/package.xml index 8a7fe17..7f6b234 100644 --- a/vendor/git.apache.org/thrift.git/lib/st/package.xml +++ b/vendor/git.apache.org/thrift.git/lib/st/package.xml @@ -7,9 +7,9 @@ to you 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 @@ -17,7 +17,7 @@ specific language governing permissions and limitations under the License. --> - + libthrift-st thrift.st diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Package.swift b/vendor/git.apache.org/thrift.git/lib/swift/Package.swift new file mode 100644 index 0000000..b533f60 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Package.swift @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +import PackageDescription + +let package = Package( + name: "Thrift" +) diff --git a/vendor/git.apache.org/thrift.git/lib/swift/README.md b/vendor/git.apache.org/thrift.git/lib/swift/README.md new file mode 100644 index 0000000..4fdeacf --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/README.md @@ -0,0 +1,216 @@ +Thrift Swift Library +========================= + +License +------- +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you 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. + + +## Build + + swift build + +## Test + swift test + +## Install Library +##### Cocoapods +Add the following to your podfile +```ruby + pod 'Thrift-swift3', :git => 'git@github.com:apache/thrift.git', :branch => 'master' +``` + +##### SPM +Unfortunately due to some limitations in SPM, the Package manifest and Sources directory must be at the root of the project. +To get around that for the time being, you can use this mirrored repo. +Add the following to your Package.swift +```swift +dependencies: [ + .Package(url: "https://github.com/apocolipse/Thrift-Swift.git", majorVersion: 1) +] +``` + +## Thrift Compiler + +You can compile IDL sources for Swift 3 with the following command: + + thrift --gen swift thrift_file + +## Client Example +```swift +let transport = TSocketTransport(hostname: "localhost", port: 9090)! + +// var proto = TCompactProtocol(transport: transport) +let proto = TBinaryProtocol(on: transport) +// var client = HermesClient(inoutProtocol: proto) +let client = ThriftTestClient(inoutProtocol: proto) +do { + try client.testVoid() +} catch let error { + print("\(error)") +} +``` + +## Library Notes +- Eliminated Protocol Factories, They were only used in async clients and server implementations, where Generics provide a better alternative. +- Swifty Errors, All `TError` types have a nested `ErrorCode` Enum as well as some extra flavor where needed. +- Value typed everything. `TTransport` operates on value typed `Data` rather than reference typed `NSData` or `UnsafeBufferPointer`s +- Swift 3 Named protocols. Swift 3 naming conventions suggest the elimination of redundant words that can be inferred from variable/function signatures. This renaming is applied throughout the Swift 3 library converting most naming conventions used in the Swift2/Cocoa library to Swift 3-esque naming conventions. eg. +```swift +func readString() throws -> String +func writeString(_ val: String) throws +``` +have been renamed to eliminate redundant words: +```swift +func read() throws -> String +func write(_ val: String) throws +``` + +- Eliminated `THTTPTransport` that uses `NSURLConnection` due to it being deprecated and not available at all in Swift 3 for Linux. `THTTPSessionTransport` from the Swift2/Cocoa library that uses `NSURLSession` has been renamed to `THTTPTransport` for this library and leverages `URLSession`, providing both synchronous (with semaphores) and asynchronous behavior. +- Probably some More things I've missed here. + +## Generator Notes +#### Generator Flags +| Flag | Description | +| ------------- |:-------------:| +| async_clients | Generate clients which invoke asynchronously via block syntax. Asynchronous classes are appended with `_Async` | +| no_strict* | Generates non-strict structs | +| debug_descriptions | Allow use of debugDescription so the app can add description via a cateogory/extension | +| log_unexpected | Log every time an unexpected field ID or type is encountered. | +| safe_enums | Generate enum types with an unknown case to handle unspecified values rather than throw a serialization error | + + + +*Most thrift libraries allow empty initialization of Structs, initializing `required` fields with nil/null/None (Python and Node generators). Swift on the other hand requires initializers to initialize all non-Optional fields, and thus the Swift 3 generator does not provide default values (unlike the Swift 2/Cocoa generator). In other languages, this allows the sending of NULL values in fields that are marked `required`, and thus will throw an error in Swift clients attempting to validate fields. The `no_strict` option here will ignore the validation check, as well as behave similar to the Swift2/Cocoa generator and initialize required fields with empty initializers (where possible). + + +## Whats implemented +#### Library +##### Transports +- [x] TSocketTransport - CFSocket and PosixSocket variants available. CFSocket variant only currently available for Darwin platforms +- [x] THTTPTransport - Currently only available for Darwin platforms, Swift Foundation URLSession implementation needs completion on linux. +- [x] TSocketServer - Uses CFSockets only for binding, should be working on linux +- [x] TFramedTransport +- [x] TMemoryBufferTransport +- [x] TFileTransport - A few variants using File handles and file descriptors. +- [x] TStreamTransport - Fully functional in Darwin, Foundation backing not yet completed in Linux (This limits TCFSocketTransport to Darwin) +- [ ] HTTPServer - Currently there is no lightweight HTTPServer implementation the Swift Standard Library, so other 3rd party alternatives are required and out of scope for the Thrift library. Examples using Perfect will be provided. +- [ ] Other (gz, etc) + +##### Protocols +- [x] TBinaryProtocol +- [x] TCompactProtocol +- [ ] TJSONProtocol - This will need to be implemented + +##### Generator +- [x] Code Complete Generator +- [x] Async clients +- [x] Documentation Generation - Generator will transplant IDL docs to Swift code for easy lookup in Xcode +- [ ] Default Values - TODO +- [ ] no_strict mode - TODO +- [ ] Namespacing - Still haven't nailed down a good paradigm for namespacing. It will likely involve creating subdirectories for different namespaces and expecting the developer to import each subdirectory as separate modules. It could extend to creating SPM Package manifests with sub-modules within the generated module + + + +## Example HTTP Server with Perfect +```swift +import PerfectLib +import PerfectHTTP +import PerfectHTTPServer +import Dispatch + +let logQueue = DispatchQueue(label: "log", qos: .background, attributes: .concurrent) +let pQueue = DispatchQueue(label: "log", qos: .userInitiated, attributes: .concurrent) + + +class TPerfectServer { + + private var server = HTTPServer() + private var processor: TProcessor + + init(address: String? = nil, + path: String? = nil, + port: Int, + processor: TProcessor, + inProtocol: InProtocol.Type, + outProtocol: OutProtocol.Type) throws { + + self.processor = processor + + if let address = address { + server.serverAddress = address + } + server.serverPort = UInt16(port) + + var routes = Routes() + var uri = "/" + if let path = path { + uri += path + } + routes.add(method: .post, uri: uri) { request, response in + pQueue.async { + response.setHeader(.contentType, value: "application/x-thrift") + + let itrans = TMemoryBufferTransport() + if let bytes = request.postBodyBytes { + let data = Data(bytes: bytes) + itrans.reset(readBuffer: data) + } + + let otrans = TMemoryBufferTransport(flushHandler: { trans, buff in + let array = buff.withUnsafeBytes { + Array(UnsafeBufferPointer(start: $0, count: buff.count)) + } + response.status = .ok + response.setBody(bytes: array) + response.completed() + }) + + let inproto = InProtocol(on: itrans) + let outproto = OutProtocol(on: otrans) + + do { + try processor.process(on: inproto, outProtocol: outproto) + try otrans.flush() + } catch { + response.status = .badRequest + response.completed() + } + } + } + server.addRoutes(routes) + } + + func serve() throws { + try server.start() + } +} +``` + +#### Example Usage +```swift +class ServiceHandler : Service { + ... +} +let server = try? TPerfectServer(port: 9090, + processor: ServiceProcessor(service: ServiceHandler()), + inProtocol: TBinaryProtocol.self, + outProtocol: TBinaryProtocol.self) + +try? server?.serve() +``` diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/LinuxHelper.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/LinuxHelper.swift new file mode 100644 index 0000000..66d92bb --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/LinuxHelper.swift @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + + +import Foundation +import CoreFoundation + +#if os(Linux) +/// Extensions for Linux for incomplete Foundation API's. +/// swift-corelibs-foundation is not yet 1:1 with OSX/iOS Foundation + +extension CFSocketError { + public static let success = kCFSocketSuccess +} + +extension UInt { + public static func &(lhs: UInt, rhs: Int) -> UInt { + let cast = unsafeBitCast(rhs, to: UInt.self) + return lhs & cast + } +} + +#else +extension CFStreamPropertyKey { + static let shouldCloseNativeSocket = CFStreamPropertyKey(kCFStreamPropertyShouldCloseNativeSocket) + // Exists as Stream.PropertyKey.socketSecuritylevelKey but doesn't work with CFReadStreamSetProperty + static let socketSecurityLevel = CFStreamPropertyKey(kCFStreamPropertySocketSecurityLevel) + static let SSLSettings = CFStreamPropertyKey(kCFStreamPropertySSLSettings) +} +#endif diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TApplicationError.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TApplicationError.swift new file mode 100644 index 0000000..bc39396 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TApplicationError.swift @@ -0,0 +1,157 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you 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. +*/ + + +public struct TApplicationError : TError { + public enum Code : TErrorCode { + case unknown + case unknownMethod(methodName: String?) + case invalidMessageType + case wrongMethodName(methodName: String?) + case badSequenceId + case missingResult(methodName: String?) + case internalError + case protocolError + case invalidTransform + case invalidProtocol + case unsupportedClientType + + + /// Initialize a TApplicationError with a Thrift error code + /// Normally this would be achieved with RawRepresentable however + /// by doing this we can allow for associated properties on enum cases for + /// case specific context data in a Swifty, type-safe manner. + /// + /// - parameter thriftErrorCode: Integer TApplicationError(exception) error code. + /// Default to 0 (.unknown) + public init(thriftErrorCode: Int) { + switch thriftErrorCode { + case 1: self = .unknownMethod(methodName: nil) + case 2: self = .invalidMessageType + case 3: self = .wrongMethodName(methodName: nil) + case 4: self = .badSequenceId + case 5: self = .missingResult(methodName: nil) + case 6: self = .internalError + case 7: self = .protocolError + case 8: self = .invalidProtocol + case 9: self = .invalidTransform + case 10: self = .unsupportedClientType + default: self = .unknown + } + } + public var thriftErrorCode: Int { + switch self { + case .unknown: return 0 + case .unknownMethod: return 1 + case .invalidMessageType: return 2 + case .wrongMethodName: return 3 + case .badSequenceId: return 4 + case .missingResult: return 5 + case .internalError: return 6 + case .protocolError: return 7 + case .invalidProtocol: return 8 + case .invalidTransform: return 9 + case .unsupportedClientType: return 10 + } + } + + public var description: String { + /// Output "for #methodName" if method is not nil else empty + let methodUnwrap: (String?) -> String = { method in + return "\(method == nil ? "" : " for \(method ?? "")")" + } + switch self { + case .unknown: return "Unknown TApplicationError" + case .unknownMethod(let method): return "Unknown Method\(methodUnwrap(method))" + case .invalidMessageType: return "Invalid Message Type" + case .wrongMethodName(let method): return "Wrong Method Name\(methodUnwrap(method))" + case .badSequenceId: return "Bad Sequence ID" + case .missingResult(let method): return "Missing Result\(methodUnwrap(method))" + case .internalError: return "Internal Error" + case .protocolError: return "Protocol Error" + case .invalidProtocol: return "Invalid Protocol" + case .invalidTransform: return "Invalid Transform" + case .unsupportedClientType: return "Unsupported Client Type" + } + } + } + + public init() { } + + public init(thriftErrorCode code: Int, message: String? = nil) { + self.error = Code(thriftErrorCode: code) + self.message = message + } + + public var error: Code = .unknown + public var message: String? = nil + public static var defaultCase: Code { return .unknown } +} + +extension TApplicationError : TSerializable { + public static var thriftType: TType { return .struct } + + public static func read(from proto: TProtocol) throws -> TApplicationError { + var errorCode: Int = 0 + var message: String? = nil + _ = try proto.readStructBegin() + fields: while true { + let (_, fieldType, fieldID) = try proto.readFieldBegin() + + switch (fieldID, fieldType) { + case (_, .stop): + break fields + case (1, .string): + message = try proto.read() + case (2, .i32): + errorCode = Int(try proto.read() as Int32) + + case let (_, unknownType): + try proto.skip(type: unknownType) + } + + try proto.readFieldEnd() + } + try proto.readStructEnd() + return TApplicationError(thriftErrorCode: errorCode, message: message) + } + + public func write(to proto: TProtocol) throws { + try proto.writeStructBegin(name: "TApplicationException") + + try proto.writeFieldBegin(name: "message", type: .string, fieldID: 1) + try proto.write(message ?? "") + try proto.writeFieldEnd() + + try proto.writeFieldBegin(name: "type", type: .i32, fieldID: 2) + let val = Int32(error.thriftErrorCode) + try proto.write(val) + try proto.writeFieldEnd() + try proto.writeFieldStop() + try proto.writeStructEnd() + } + + public var hashValue: Int { + return error.thriftErrorCode &+ (message?.hashValue ?? 0) + } +} + +public func ==(lhs: TApplicationError, rhs: TApplicationError) -> Bool { + return lhs.error.thriftErrorCode == rhs.error.thriftErrorCode && lhs.message == rhs.message +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TBinary.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TBinary.swift new file mode 100644 index 0000000..4be5644 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TBinary.swift @@ -0,0 +1,32 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +import Foundation + +extension Data : TSerializable { + public static var thriftType: TType { return .string } + + public static func read(from proto: TProtocol) throws -> Data { + return try proto.read() as Data + } + + public func write(to proto: TProtocol) throws { + try proto.write(self) + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TBinaryProtocol.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TBinaryProtocol.swift new file mode 100644 index 0000000..a97249a --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TBinaryProtocol.swift @@ -0,0 +1,384 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +import Foundation + +public struct TBinaryProtocolVersion { + static let version1 = Int32(bitPattern: 0x80010000) + static let versionMask = Int32(bitPattern: 0xffff0000) +} + +public class TBinaryProtocol: TProtocol { + public var messageSizeLimit: UInt32 = 0 + + public var transport: TTransport + + // class level properties for setting global config (useful for server in lieu of Factory design) + public static var strictRead: Bool = false + public static var strictWrite: Bool = true + + private var strictRead: Bool + private var strictWrite: Bool + + var currentMessageName: String? + var currentFieldName: String? + + + public convenience init(transport: TTransport, strictRead: Bool, strictWrite: Bool) { + self.init(on: transport) + self.strictRead = strictRead + self.strictWrite = strictWrite + } + + public required init(on transport: TTransport) { + self.transport = transport + self.strictWrite = TBinaryProtocol.strictWrite + self.strictRead = TBinaryProtocol.strictRead + } + + func readStringBody(_ size: Int) throws -> String { + + var data = Data() + try ProtocolTransportTry(error: TProtocolError(message: "Transport read failed")) { + data = try self.transport.readAll(size: size) + } + + return String(data: data, encoding: String.Encoding.utf8) ?? "" + } + + /// Mark: - TProtocol + + public func readMessageBegin() throws -> (String, TMessageType, Int32) { + let size: Int32 = try read() + var messageName = "" + var type = TMessageType.exception + + if size < 0 { + let version = size & TBinaryProtocolVersion.versionMask + if version != TBinaryProtocolVersion.version1 { + throw TProtocolError(error: .badVersion(expected: "\(TBinaryProtocolVersion.version1)", + got: "\(version)")) + } + type = TMessageType(rawValue: Int32(size) & 0x00FF) ?? type + messageName = try read() + } else { + if strictRead { + let errorMessage = "Missing message version, old client? Message Name: \(currentMessageName ?? "")" + throw TProtocolError(error: .invalidData, + message: errorMessage) + } + if messageSizeLimit > 0 && size > Int32(messageSizeLimit) { + throw TProtocolError(error: .sizeLimit(limit: Int(messageSizeLimit), got: Int(size))) + } + + messageName = try readStringBody(Int(size)) + type = TMessageType(rawValue: Int32(try read() as UInt8)) ?? type + } + + let seqID: Int32 = try read() + return (messageName, type, seqID) + } + + public func readMessageEnd() throws { + return + } + + public func readStructBegin() throws -> String { + return "" + } + + public func readStructEnd() throws { + return + } + + public func readFieldBegin() throws -> (String, TType, Int32) { + + let fieldType = TType(rawValue: Int32(try read() as UInt8)) ?? TType.stop + var fieldID: Int32 = 0 + + if fieldType != .stop { + fieldID = Int32(try read() as Int16) + } + + return ("", fieldType, fieldID) + } + + public func readFieldEnd() throws { + return + } + + public func readMapBegin() throws -> (TType, TType, Int32) { + var raw = Int32(try read() as UInt8) + guard let keyType = TType(rawValue: raw) else { + throw TProtocolError(message: "Unknown value for keyType TType: \(raw)") + } + + raw = Int32(try read() as UInt8) + guard let valueType = TType(rawValue: raw) else { + throw TProtocolError(message: "Unknown value for valueType TType: \(raw)") + } + let size: Int32 = try read() + + return (keyType, valueType, size) + } + + public func readMapEnd() throws { + return + } + + public func readSetBegin() throws -> (TType, Int32) { + let raw = Int32(try read() as UInt8) + guard let elementType = TType(rawValue: raw) else { + throw TProtocolError(message: "Unknown value for elementType TType: \(raw)") + } + + let size: Int32 = try read() + + return (elementType, size) + } + + public func readSetEnd() throws { + return + } + + public func readListBegin() throws -> (TType, Int32) { + let raw = Int32(try read() as UInt8) + guard let elementType = TType(rawValue: raw) else { + throw TProtocolError(message: "Unknown value for elementType TType: \(raw)") + } + let size: Int32 = try read() + + return (elementType, size) + } + + public func readListEnd() throws { + return + } + + public func read() throws -> String { + let data: Data = try read() + guard let str = String.init(data: data, encoding: .utf8) else { + throw TProtocolError(error: .invalidData, message: "Couldn't encode UTF-8 from data read") + } + return str + } + + public func read() throws -> Bool { + return (try read() as UInt8) == 1 + } + + public func read() throws -> UInt8 { + var buff = Data() + try ProtocolTransportTry(error: TProtocolError(message: "Transport Read Failed")) { + buff = try self.transport.readAll(size: 1) + } + return buff[0] + } + + public func read() throws -> Int16 { + var buff = Data() + try ProtocolTransportTry(error: TProtocolError(message: "Transport Read Failed")) { + buff = try self.transport.readAll(size: 2) + } + var ret = Int16(buff[0] & 0xff) << 8 + ret |= Int16(buff[1] & 0xff) + return ret + } + + public func read() throws -> Int32 { + var buff = Data() + try ProtocolTransportTry(error: TProtocolError(message: "Transport Read Failed")) { + buff = try self.transport.readAll(size: 4) + } + var ret = Int32(buff[0] & 0xff) << 24 + ret |= Int32(buff[1] & 0xff) << 16 + ret |= Int32(buff[2] & 0xff) << 8 + ret |= Int32(buff[3] & 0xff) + + return ret + } + + public func read() throws -> Int64 { + var buff = Data() + try ProtocolTransportTry(error: TProtocolError(message: "Transport Read Failed")) { + buff = try self.transport.readAll(size: 8) + } + var ret = Int64(buff[0] & 0xff) << 56 + ret |= Int64(buff[1] & 0xff) << 48 + ret |= Int64(buff[2] & 0xff) << 40 + ret |= Int64(buff[3] & 0xff) << 32 + ret |= Int64(buff[4] & 0xff) << 24 + ret |= Int64(buff[5] & 0xff) << 16 + ret |= Int64(buff[6] & 0xff) << 8 + ret |= Int64(buff[7] & 0xff) + + return ret + } + + public func read() throws -> Double { + let val = try read() as Int64 + return Double(bitPattern: UInt64(bitPattern: val)) + } + + public func read() throws -> Data { + let size = Int(try read() as Int32) + var data = Data() + try ProtocolTransportTry(error: TProtocolError(message: "Transport Read Failed")) { + data = try self.transport.readAll(size: size) + } + + return data + } + + // Write methods + + public func writeMessageBegin(name: String, type messageType: TMessageType, sequenceID: Int32) throws { + if strictWrite { + let version = TBinaryProtocolVersion.version1 | Int32(messageType.rawValue) + try write(version) + try write(name) + try write(sequenceID) + } else { + try write(name) + try write(UInt8(messageType.rawValue)) + try write(sequenceID) + } + currentMessageName = name + } + + public func writeMessageEnd() throws { + currentMessageName = nil + } + + public func writeStructBegin(name: String) throws { + return + } + + public func writeStructEnd() throws { + return + } + + public func writeFieldBegin(name: String, type fieldType: TType, fieldID: Int32) throws { + try write(UInt8(fieldType.rawValue)) + try write(Int16(fieldID)) + } + + public func writeFieldStop() throws { + try write(UInt8(TType.stop.rawValue)) + } + + public func writeFieldEnd() throws { + return + } + + public func writeMapBegin(keyType: TType, valueType: TType, size: Int32) throws { + try write(UInt8(keyType.rawValue)) + try write(UInt8(valueType.rawValue)) + try write(size) + } + + public func writeMapEnd() throws { + return + } + + public func writeSetBegin(elementType: TType, size: Int32) throws { + try write(UInt8(elementType.rawValue)) + try write(size) + } + + public func writeSetEnd() throws { + return + } + + public func writeListBegin(elementType: TType, size: Int32) throws { + try write(UInt8(elementType.rawValue)) + try write(size) + } + + public func writeListEnd() throws { + return + } + + public func write(_ value: String) throws { + try write(value.data(using: .utf8)!) + } + + public func write(_ value: Bool) throws { + let byteVal: UInt8 = value ? 1 : 0 + try write(byteVal) + } + + public func write(_ value: UInt8) throws { + let buff = Data(bytes: [value]) + + try ProtocolTransportTry(error: TProtocolError(message: "Transport write failed")) { + try self.transport.write(data: buff) + } + } + + public func write(_ value: Int16) throws { + var buff = Data() + buff.append(Data(bytes: [UInt8(0xff & (value >> 8))])) + buff.append(Data(bytes: [UInt8(0xff & (value))])) + try ProtocolTransportTry(error: TProtocolError(message: "Transport write failed")) { + try self.transport.write(data: buff) + } + } + + public func write(_ value: Int32) throws { + var buff = Data() + buff.append(Data(bytes: [UInt8(0xff & (value >> 24))])) + buff.append(Data(bytes: [UInt8(0xff & (value >> 16))])) + buff.append(Data(bytes: [UInt8(0xff & (value >> 8))])) + buff.append(Data(bytes: [UInt8(0xff & (value))])) + + try ProtocolTransportTry(error: TProtocolError(message: "Transport write failed")) { + try self.transport.write(data: buff) + } + } + + public func write(_ value: Int64) throws { + var buff = Data() + buff.append(Data(bytes: [UInt8(0xff & (value >> 56))])) + buff.append(Data(bytes: [UInt8(0xff & (value >> 48))])) + buff.append(Data(bytes: [UInt8(0xff & (value >> 40))])) + buff.append(Data(bytes: [UInt8(0xff & (value >> 32))])) + buff.append(Data(bytes: [UInt8(0xff & (value >> 24))])) + buff.append(Data(bytes: [UInt8(0xff & (value >> 16))])) + buff.append(Data(bytes: [UInt8(0xff & (value >> 8))])) + buff.append(Data(bytes: [UInt8(0xff & (value))])) + + try ProtocolTransportTry(error: TProtocolError(message: "Transport write failed")) { + try self.transport.write(data: buff) + } + } + + public func write(_ value: Double) throws { + // Notably unsafe, since Double and Int64 are the same size, this should work fine + try self.write(Int64(bitPattern: value.bitPattern)) + } + + public func write(_ data: Data) throws { + try write(Int32(data.count)) + + try ProtocolTransportTry(error: TProtocolError(message: "Transport write failed")) { + try self.transport.write(data: data) + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TClient.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TClient.swift new file mode 100644 index 0000000..cc3288a --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TClient.swift @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + + +open class TClient { + public let inProtocol: TProtocol + public let outProtocol: TProtocol + + required public init(inoutProtocol: TProtocol) { + self.inProtocol = inoutProtocol + self.outProtocol = inoutProtocol + } + + required public init(inProtocol: TProtocol, outProtocol: TProtocol) { + self.inProtocol = inProtocol + self.outProtocol = outProtocol + } +} + + +open class TAsyncClient { + public var factory: Factory + public init(with protocol: Protocol.Type, factory: Factory) { + self.factory = factory + } +} + + +public enum TAsyncResult { + case success(T) + case error(Swift.Error) + + public func value() throws -> T { + switch self { + case .success(let t): return t + case .error(let e): throw e + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TCompactProtocol.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TCompactProtocol.swift new file mode 100644 index 0000000..59773c3 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TCompactProtocol.swift @@ -0,0 +1,575 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you 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. +*/ + +import Foundation +import CoreFoundation + +public enum TCType: UInt8 { + case stop = 0x00 + case boolean_TRUE = 0x01 + case boolean_FALSE = 0x02 + case i8 = 0x03 + case i16 = 0x04 + case i32 = 0x05 + case i64 = 0x06 + case double = 0x07 + case binary = 0x08 + case list = 0x09 + case set = 0x0A + case map = 0x0B + case `struct` = 0x0C + + public static let typeMask: UInt8 = 0xE0 // 1110 0000 + public static let typeBits: UInt8 = 0x07 // 0000 0111 + public static let typeShiftAmount = 5 + +} + + +public class TCompactProtocol: TProtocol { + public static let protocolID: UInt8 = 0x82 + public static let version: UInt8 = 1 + public static let versionMask: UInt8 = 0x1F // 0001 1111 + + public var transport: TTransport + + var lastField: [UInt8] = [] + var lastFieldId: UInt8 = 0 + + var boolFieldName: String? + var boolFieldType: TType? + var boolFieldId: Int32? + var booleanValue: Bool? + + var currentMessageName: String? + + public required init(on transport: TTransport) { + self.transport = transport + } + + + /// Mark: - TCompactProtocol helpers + + func writebyteDirect(_ byte: UInt8) throws { + let byte = Data(bytes: [byte]) + try ProtocolTransportTry(error: TProtocolError(message: "Transport Write Failed")) { + try self.transport.write(data: byte) + } + } + + func writeVarint32(_ val: UInt32) throws { + var val = val + var i32buf = [UInt8](repeating: 0, count: 5) + var idx = 0 + while true { + if (val & ~0x7F) == 0 { + i32buf[idx] = UInt8(val) + idx += 1 + break + } else { + i32buf[idx] = UInt8((val & 0x7F) | 0x80) + idx += 1 + val >>= 7 + } + } + + try ProtocolTransportTry(error: TProtocolError(message: "Transport Write Failed")) { + try self.transport.write(data: Data(bytes: i32buf[0..>= 7 + } + } + + try ProtocolTransportTry(error: TProtocolError(message: "Transport Write Failed")) { + try self.transport.write(data: Data(bytes: varint64out[0.. Data { + var result = Data() + if size != 0 { + try ProtocolTransportTry(error: TProtocolError(message: "Transport Read Failed")) { + result = try self.transport.readAll(size: size) + } + } + return result + } + + func readVarint32() throws -> UInt32 { + var result: UInt32 = 0 + var shift: UInt32 = 0 + while true { + let byte: UInt8 = try read() + + result |= UInt32(byte & 0x7F) << shift + if (byte & 0x80) == 0 { + break + } + + shift += 7 + } + + return result + } + + func readVarint64() throws -> UInt64 { + var result: UInt64 = 0 + var shift: UInt64 = 0 + + while true { + let byte: UInt8 = try read() + + result |= UInt64(byte & 0x7F) << shift + if (byte & 0x80) == 0 { + break + } + + shift += 7 + } + return result + } + + + func ttype(_ compactTypeVal: UInt8) throws -> TType { + guard let compactType = TCType(rawValue: compactTypeVal) else { + throw TProtocolError(message: "Unknown TCType value: \(compactTypeVal)") + } + + switch compactType { + case .stop: return .stop; + case .boolean_FALSE, .boolean_TRUE: return .bool; + case .i8: return .i8; + case .i16: return .i16; + case .i32: return .i32; + case .i64: return .i64; + case .double: return .double; + case .binary: return .string; + case .list: return .list; + case .set: return .set; + case .map: return .map; + case .struct: return .struct; + } + } + + func compactType(_ ttype: TType) -> TCType { + switch ttype { + case .stop: return .stop + case .void: return .i8 + case .bool: return .boolean_FALSE + case .i8: return .i8 + case .double: return .double + case .i16: return .i16 + case .i32: return .i32 + case .i64: return .i64 + case .string: return .binary + case .struct: return .struct + case .map: return .map + case .set: return .set + case .list: return .list + case .utf8: return .binary + case .utf16: return .binary + } + } + + /// ZigZag encoding maps signed integers to unsigned integers so that + /// numbers with a small absolute value (for instance, -1) have + /// a small varint encoded value too. It does this in a way that + /// "zig-zags" back and forth through the positive and negative integers, + /// so that -1 is encoded as 1, 1 is encoded as 2, -2 is encoded as 3, and so + /// + /// - parameter n: number to zigzag + /// + /// - returns: zigzaged UInt32 + func i32ToZigZag(_ n : Int32) -> UInt32 { + return UInt32(bitPattern: Int32(n << 1) ^ Int32(n >> 31)) + } + + func i64ToZigZag(_ n : Int64) -> UInt64 { + return UInt64(bitPattern: Int64(n << 1) ^ Int64(n >> 63)) + } + + func zigZagToi32(_ n: UInt32) -> Int32 { + return Int32(n >> 1) ^ (-Int32(n & 1)) + } + + func zigZagToi64(_ n: UInt64) -> Int64 { + return Int64(n >> 1) ^ (-Int64(n & 1)) + } + + + + /// Mark: - TProtocol + + public func readMessageBegin() throws -> (String, TMessageType, Int32) { + let protocolId: UInt8 = try read() + + if protocolId != TCompactProtocol.protocolID { + let expected = String(format:"%2X", TCompactProtocol.protocolID) + let got = String(format:"%2X", protocolId) + throw TProtocolError(message: "Wrong Protocol ID \(got)", + extendedError: .mismatchedProtocol(expected: expected, got: got)) + + } + + let versionAndType: UInt8 = try read() + let version: UInt8 = versionAndType & TCompactProtocol.versionMask + if version != TCompactProtocol.version { + throw TProtocolError(error: .badVersion(expected: "\(TCompactProtocol.version)", + got:"\(version)")) + + } + + let type = (versionAndType >> UInt8(TCType.typeShiftAmount)) & TCType.typeBits + guard let mtype = TMessageType(rawValue: Int32(type)) else { + throw TProtocolError(message: "Unknown TMessageType value: \(type)") + } + let sequenceId = try readVarint32() + let name: String = try read() + + return (name, mtype, Int32(sequenceId)) + } + + public func readMessageEnd() throws { } + + public func readStructBegin() throws -> String { + lastField.append(lastFieldId) + lastFieldId = 0 + return "" + } + + public func readStructEnd() throws { + lastFieldId = lastField.last ?? 0 + lastField.removeLast() + } + + public func readFieldBegin() throws -> (String, TType, Int32) { + let byte: UInt8 = try read() + guard let type = TCType(rawValue: byte & 0x0F) else { + throw TProtocolError(message: "Unknown TCType \(byte & 0x0F)") + } + + // if it's a stop, then we can return immediately, as the struct is over + if type == .stop { + return ("", .stop, 0) + } + + var fieldId: Int16 = 0 + + // mask off the 4MSB of the type header. it could contain a field id delta + let modifier = (byte & 0xF0) >> 4 + if modifier == 0 { + // not a delta. look ahead for the zigzag varint field id + fieldId = try read() + } else { + // has a delta. add the delta to the last Read field id. + fieldId = Int16(lastFieldId + modifier) + } + + let fieldType = try ttype(type.rawValue) + + // if this happens to be a boolean field, the value is encoded in the type + if type == .boolean_TRUE || type == .boolean_FALSE { + // save the boolean value in a special instance variable + booleanValue = type == .boolean_TRUE + } + + // push the new field onto the field stack so we can keep the deltas going + lastFieldId = UInt8(fieldId) + return ("", fieldType, Int32(fieldId)) + } + + public func readFieldEnd() throws { } + + public func read() throws -> String { + let length = try readVarint32() + + var result: String + + if length != 0 { + let data = try readBinary(Int(length)) + result = String(data: data, encoding: String.Encoding.utf8) ?? "" + } else { + result = "" + } + + return result + } + + public func read() throws -> Bool { + if let val = booleanValue { + self.booleanValue = nil + return val + } else { + let result = try read() as UInt8 + return TCType(rawValue: result) == .boolean_TRUE + } + } + + public func read() throws -> UInt8 { + var buff: UInt8 = 0 + try ProtocolTransportTry(error: TProtocolError(message: "Transport Read Failed")) { + buff = try self.transport.readAll(size: 1)[0] + } + return buff + } + + public func read() throws -> Int16 { + let v = try readVarint32() + return Int16(zigZagToi32(v)) + } + + public func read() throws -> Int32 { + let v = try readVarint32() + return zigZagToi32(v) + } + + public func read() throws -> Int64 { + let v = try readVarint64() + return zigZagToi64(v) + } + + public func read() throws -> Double { + var buff = Data() + try ProtocolTransportTry(error: TProtocolError(message: "Transport Read Failed")) { + buff = try self.transport.readAll(size: 8) + } + + let i64: UInt64 = buff.withUnsafeBytes { (ptr: UnsafePointer) -> UInt64 in + return UnsafePointer(OpaquePointer(ptr)).pointee + } + let bits = CFSwapInt64LittleToHost(i64) + return Double(bitPattern: bits) + } + + public func read() throws -> Data { + let length = try readVarint32() + return try readBinary(Int(length)) + } + + public func readMapBegin() throws -> (TType, TType, Int32) { + var keyAndValueType: UInt8 = 8 + let size = try readVarint32() + if size != 0 { + keyAndValueType = try read() + } + + let keyType = try ttype(keyAndValueType >> 4) + let valueType = try ttype(keyAndValueType & 0xF) + + return (keyType, valueType, Int32(size)) + } + + public func readMapEnd() throws { } + + public func readSetBegin() throws -> (TType, Int32) { + return try readListBegin() + } + + public func readSetEnd() throws { } + + public func readListBegin() throws -> (TType, Int32) { + let sizeAndType: UInt8 = try read() + var size: UInt32 = UInt32(sizeAndType >> 4) & 0x0f + if size == 15 { + size = try readVarint32() + } + let elementType = try ttype(sizeAndType & 0x0F) + + return (elementType, Int32(size)) + } + + public func readListEnd() throws { } + + public func writeMessageBegin(name: String, + type messageType: TMessageType, + sequenceID: Int32) throws { + try writebyteDirect(TCompactProtocol.protocolID) + let nextByte: UInt8 = (TCompactProtocol.version & TCompactProtocol.versionMask) | + (UInt8((UInt32(messageType.rawValue) << UInt32(TCType.typeShiftAmount))) & + TCType.typeMask) + try writebyteDirect(nextByte) + try writeVarint32(UInt32(sequenceID)) + try write(name) + + currentMessageName = name + } + + public func writeMessageEnd() throws { + currentMessageName = nil + } + + public func writeStructBegin(name: String) throws { + lastField.append(lastFieldId) + lastFieldId = 0 + } + + public func writeStructEnd() throws { + lastFieldId = lastField.last ?? 0 + lastField.removeLast() + } + + public func writeFieldBegin(name: String, + type fieldType: TType, + fieldID: Int32) throws { + if fieldType == .bool { + boolFieldName = name + boolFieldType = fieldType + boolFieldId = fieldID + return + } else { + try writeFieldBeginInternal(name: name, + type: fieldType, + fieldID: fieldID, + typeOverride: 0xFF) + } + } + + func writeFieldBeginInternal(name: String, + type fieldType: TType, + fieldID: Int32, + typeOverride: UInt8) throws { + + let typeToWrite = typeOverride == 0xFF ? compactType(fieldType).rawValue : typeOverride + + // check if we can use delta encoding for the field id + let diff = UInt8(fieldID) - lastFieldId + if (UInt8(fieldID) > lastFieldId) && (diff <= 15) { + // Write them together + try writebyteDirect((UInt8(fieldID) - lastFieldId) << 4 | typeToWrite) + + } else { + // Write them separate + try writebyteDirect(typeToWrite) + try write(Int16(fieldID)) + } + + lastFieldId = UInt8(fieldID) + + } + + public func writeFieldStop() throws { + try writebyteDirect(TCType.stop.rawValue) + } + + public func writeFieldEnd() throws { } + + public func writeMapBegin(keyType: TType, valueType: TType, size: Int32) throws { + if size == 0 { + try writebyteDirect(0) + } else { + try writeVarint32(UInt32(size)) + + let compactedTypes = compactType(keyType).rawValue << 4 | compactType(valueType).rawValue + try writebyteDirect(compactedTypes) + } + } + + public func writeMapEnd() throws { } + + public func writeSetBegin(elementType: TType, size: Int32) throws { + try writeCollectionBegin(elementType, size: size) + } + + public func writeSetEnd() throws { } + + public func writeListBegin(elementType: TType, size: Int32) throws { + try writeCollectionBegin(elementType, size: size) + } + + public func writeListEnd() throws { } + + public func write(_ value: String) throws { + try write(value.data(using: String.Encoding.utf8)!) + } + + public func write(_ value: Bool) throws { + if let boolFieldId = boolFieldId, let boolFieldType = boolFieldType, + let boolFieldName = boolFieldName { + + // we haven't written the field header yet + let compactType: TCType = value ? .boolean_TRUE : .boolean_FALSE + try writeFieldBeginInternal(name: boolFieldName, type: boolFieldType, fieldID: boolFieldId, + typeOverride: compactType.rawValue) + self.boolFieldId = nil + self.boolFieldType = nil + self.boolFieldName = nil + } else { + // we're not part of a field, so just write the value. + try writebyteDirect(value ? TCType.boolean_TRUE.rawValue : TCType.boolean_FALSE.rawValue) + } + } + + public func write(_ value: UInt8) throws { + try writebyteDirect(value) + } + + public func write(_ value: Int16) throws { + try writeVarint32(i32ToZigZag(Int32(value))) + } + + public func write(_ value: Int32) throws { + try writeVarint32(i32ToZigZag(value)) + } + + public func write(_ value: Int64) throws { + try writeVarint64(i64ToZigZag(value)) + } + + public func write(_ value: Double) throws { + var bits = CFSwapInt64HostToLittle(value.bitPattern) + let data = withUnsafePointer(to: &bits) { + return Data(bytes: UnsafePointer(OpaquePointer($0)), count: MemoryLayout.size) + } + try ProtocolTransportTry(error: TProtocolError(message: "Transport Write Failed")) { + try self.transport.write(data: data) + } + } + + public func write(_ data: Data) throws { + try writeVarint32(UInt32(data.count)) + try ProtocolTransportTry(error: TProtocolError(message: "Transport Write Failed")) { + try self.transport.write(data: data) + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TEnum.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TEnum.swift new file mode 100644 index 0000000..fedfdb1 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TEnum.swift @@ -0,0 +1,32 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + + +public protocol TEnum : TSerializable, Hashable { + var rawValue: Int32 { get } +} + +extension TEnum { + public static var thriftType: TType { return .i32 } + public var hashValue: Int { return rawValue.hashValue } + + public func write(to proto: TProtocol) throws { + try proto.write(rawValue) + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TError.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TError.swift new file mode 100644 index 0000000..79edba6 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TError.swift @@ -0,0 +1,77 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you 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. +*/ + + +/// TErrorCode +/// +/// Protocol for TError conformers' enum's to conform to. +/// Generic Int Thrift error code to allow error cases to have +/// associated values. +public protocol TErrorCode : CustomStringConvertible { + var thriftErrorCode: Int { get } +} + +/// TError +/// +/// Base protocol for all Thrift Error(Exception) types to conform to +public protocol TError : Error, CustomStringConvertible { + + /// Enum for error cases. Can be typealiased to any conforming enum + /// or defined nested. + associatedtype Code: TErrorCode + + /// Error Case, value from internal enum + var error: Code { get set } + + /// Optional additional message + var message: String? { get set } + + /// Default error case for the error type, used for generic init() + static var defaultCase: Code { get } + + init() +} + +extension TError { + /// Human readable description of error. Default provided for you in the + /// format \(Self.self): \(error.errorDescription) \n message + /// eg: + /// + /// TApplicationError (1): Invalid Message Type + /// An unknown Error has occured. + public var description: String { + var out = "\(Self.self) (\(error.thriftErrorCode)): " + error.description + "\n" + if let message = message { + out += "Message: \(message)" + } + return out + } + + /// Simple default Initializer for TError's + /// + /// - parameter error: ErrorCode value. Default: defaultCase + /// - parameter message: Custom message with error. Optional + /// + /// - returns: <#return value description#> + public init(error: Code, message: String? = nil) { + self.init() + self.error = error + self.message = message + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TFileHandleTransport.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TFileHandleTransport.swift new file mode 100644 index 0000000..f315fef --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TFileHandleTransport.swift @@ -0,0 +1,56 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you 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. +*/ + +import Foundation + +public class TFileHandleTransport: TTransport { + var inputFileHandle: FileHandle + var outputFileHandle: FileHandle + + public init(inputFileHandle: FileHandle, outputFileHandle: FileHandle) { + self.inputFileHandle = inputFileHandle + self.outputFileHandle = outputFileHandle + } + + public convenience init(fileHandle: FileHandle) { + self.init(inputFileHandle: fileHandle, outputFileHandle: fileHandle) + } + + public func read(size: Int) throws -> Data { + var data = Data() + while data.count < size { + let read = inputFileHandle.readData(ofLength: size - data.count) + data.append(read) + if read.count == 0 { + break + } + } + return data + } + + public func write(data: Data) throws { + outputFileHandle.write(data) + } + + public func flush() throws { + return + } +} + + diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TFileTransport.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TFileTransport.swift new file mode 100644 index 0000000..fe2253d --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TFileTransport.swift @@ -0,0 +1,101 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you 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. +*/ + +import Foundation + +#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) + import Darwin +#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) + import Glibc +#endif + +/// TFileTransport +/// Foundation-less Swift File transport. +/// Uses C fopen/fread/fwrite, +/// provided by Glibc in linux and Darwin on OSX/iOS +public class TFileTransport: TTransport { + var fileHandle: UnsafeMutablePointer? = nil + + public init (fileHandle: UnsafeMutablePointer) { + self.fileHandle = fileHandle + } + + public convenience init(filename: String) throws { + var fileHandle: UnsafeMutablePointer? + filename.withCString({ cFilename in + "rw".withCString({ cMode in + fileHandle = fopen(cFilename, cMode) + }) + }) + if let fileHandle = fileHandle { + self.init(fileHandle: fileHandle) + } else { + throw TTransportError(error: .notOpen) + } + } + + deinit { + fclose(self.fileHandle) + } + + public func readAll(size: Int) throws -> Data { + let read = try self.read(size: size) + + if read.count != size { + throw TTransportError(error: .endOfFile) + } + return read + } + + public func read(size: Int) throws -> Data { + // set up read buffer, position 0 + var read = Data(capacity: size) + var position = 0 + + // read character buffer + var nextChar: UInt8 = 0 + + // continue until we've read size bytes + while read.count < size { + if fread(&nextChar, 1, 1, self.fileHandle) == 1 { + read[position] = nextChar + + // Increment output byte pointer + position += 1 + + } else { + throw TTransportError(error: .endOfFile) + } + } + return read + } + + public func write(data: Data) throws { + let bytesWritten = data.withUnsafeBytes { + fwrite($0, 1, data.count, self.fileHandle) + } + if bytesWritten != data.count { + throw TTransportError(error: .unknown) + } + } + + public func flush() throws { + return + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TFramedTransport.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TFramedTransport.swift new file mode 100644 index 0000000..ca385d6 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TFramedTransport.swift @@ -0,0 +1,123 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you 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. +*/ + +import Foundation + +public class TFramedTransport: TTransport { + public static let headerSize = 4 + public static let initFrameSize = 1024 + private static let defaultMaxLength = 16384000 + + public var transport: TTransport + private var writeBuffer = Data() + + private var maxSize = TFramedTransport.defaultMaxLength + private var remainingBytes = 0 + + + public init(transport: TTransport, maxSize: Int) { + self.transport = transport + self.maxSize = maxSize + } + + public convenience init(transport: TTransport) { + self.init(transport: transport, maxSize: TFramedTransport.defaultMaxLength) + } + + func readHeader() throws { + let read = try transport.readAll(size: TFramedTransport.headerSize) + remainingBytes = Int(decodeFrameSize(data: read)) + } + + /// Mark: - TTransport + + public func read(size: Int) throws -> Data { + while (remainingBytes <= 0) { + try readHeader() + } + + let toRead = min(size, remainingBytes) + + if toRead < 0 { + try close() + throw TTransportError(error: .negativeSize, + message: "Read a negative frame size (\(toRead))!") + } + + if toRead > maxSize { + try close() + throw TTransportError(error: .sizeLimit(limit: maxSize, got: toRead)) + } + + return try transport.readAll(size: toRead) + } + + public func flush() throws { + // copy buffer and reset + let buff = writeBuffer + writeBuffer = Data() + + if buff.count - TFramedTransport.headerSize < 0 { + throw TTransportError(error: .unknown) + } + + let frameSize = encodeFrameSize(size: UInt32(buff.count)) + + try transport.write(data: frameSize) + try transport.write(data: buff) + try transport.flush() + } + + public func write(data: Data) throws { + writeBuffer.append(data) + } + + + + private func encodeFrameSize(size: UInt32) -> Data { + var data = Data() + data.append(Data(bytes: [UInt8(0xff & (size >> 24))])) + data.append(Data(bytes: [UInt8(0xff & (size >> 16))])) + data.append(Data(bytes: [UInt8(0xff & (size >> 8))])) + data.append(Data(bytes: [UInt8(0xff & (size))])) + + return data + } + + private func decodeFrameSize(data: Data) -> UInt32 { + var size: UInt32 + size = (UInt32(data[0] & 0xff) << 24) + size |= (UInt32(data[1] & 0xff) << 16) + size |= (UInt32(data[2] & 0xff) << 8) + size |= (UInt32(data[3] & 0xff)) + return size + } + + public func close() throws { + try transport.close() + } + + public func open() throws { + try transport.open() + } + + public func isOpen() throws -> Bool { + return try transport.isOpen() + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/THTTPSessionTransport.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/THTTPSessionTransport.swift new file mode 100644 index 0000000..3c0af8e --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/THTTPSessionTransport.swift @@ -0,0 +1,184 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you 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. +*/ + +import Foundation +import Dispatch + + +public class THTTPSessionTransport: TAsyncTransport { + public class Factory : TAsyncTransportFactory { + public var responseValidate: ((HTTPURLResponse?, Data?) throws -> Void)? + + var session: URLSession + var url: URL + + public class func setupDefaultsForSessionConfiguration(_ config: URLSessionConfiguration, withProtocolName protocolName: String?) { + var thriftContentType = "application/x-thrift" + + if let protocolName = protocolName { + thriftContentType += "; p=\(protocolName)" + } + + config.requestCachePolicy = .reloadIgnoringLocalCacheData + config.urlCache = nil + + config.httpShouldUsePipelining = true + config.httpShouldSetCookies = true + config.httpAdditionalHeaders = ["Content-Type": thriftContentType, + "Accept": thriftContentType, + "User-Agent": "Thrift/Swift (Session)"] + + + } + + public init(session: URLSession, url: URL) { + self.session = session + self.url = url + } + + public func newTransport() -> THTTPSessionTransport { + return THTTPSessionTransport(factory: self) + } + + func validateResponse(_ response: HTTPURLResponse?, data: Data?) throws { + try responseValidate?(response, data) + } + + func taskWithRequest(_ request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> ()) throws -> URLSessionTask { + + let newTask: URLSessionTask? = session.dataTask(with: request, completionHandler: completionHandler) + if let newTask = newTask { + return newTask + } else { + throw TTransportError(error: .unknown, message: "Failed to create session data task") + } + } + } + + var factory: Factory + var requestData = Data() + var responseData = Data() + var responseDataOffset: Int = 0 + + init(factory: Factory) { + self.factory = factory + } + + public func readAll(size: Int) throws -> Data { + let read = try self.read(size: size) + if read.count != size { + throw TTransportError(error: .endOfFile) + } + return read + } + + public func read(size: Int) throws -> Data { + let avail = responseData.count - responseDataOffset + let (start, stop) = (responseDataOffset, responseDataOffset + min(size, avail)) + let read = responseData.subdata(in: start.. Void) { + var error: Error? + var task: URLSessionTask? + + var request = URLRequest(url: factory.url) + request.httpMethod = "POST" + request.httpBody = requestData + + requestData = Data() + + do { + task = try factory.taskWithRequest(request, completionHandler: { (data, response, taskError) in + + // Check if there was an error with the network + if taskError != nil { + error = TTransportError(error: .timedOut) + completed(self, error) + return + } + + // Check response type + if taskError == nil && !(response is HTTPURLResponse) { + error = THTTPTransportError(error: .invalidResponse) + completed(self, error) + return + } + + // Check status code + if let httpResponse = response as? HTTPURLResponse { + if taskError == nil && httpResponse.statusCode != 200 { + if httpResponse.statusCode == 401 { + error = THTTPTransportError(error: .authentication) + } else { + error = THTTPTransportError(error: .invalidStatus(statusCode: httpResponse.statusCode)) + } + } + + // Allow factory to check + if error != nil { + do { + try self.factory.validateResponse(httpResponse, data: data) + } catch let validateError { + error = validateError + } + } + + self.responseDataOffset = 0 + if error != nil { + self.responseData = Data() + } else { + self.responseData = data ?? Data() + } + completed(self, error) + } + }) + + } catch let taskError { + error = taskError + } + + if let error = error, task == nil { + completed(self, error) + } + task?.resume() + } + + public func flush() throws { + let completed = DispatchSemaphore(value: 0) + var internalError: Error? + + flush() { _, error in + internalError = error + completed.signal() + } + + _ = completed.wait(timeout: DispatchTime.distantFuture) + + if let error = internalError { + throw error + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TList.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TList.swift new file mode 100644 index 0000000..c239d10 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TList.swift @@ -0,0 +1,138 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +public struct TList : RandomAccessCollection, MutableCollection, ExpressibleByArrayLiteral, TSerializable, Hashable { + public typealias Storage = Array + public typealias Indices = Storage.Indices + + internal var storage = Storage() + public init() { } + public init(arrayLiteral elements: Element...) { + self.storage = Storage(elements) + } + public init(_ sequence: Source) where Source.Iterator.Element == Element { + storage = Storage(sequence) + } + + /// Mark: Hashable + public var hashValue : Int { + let prime = 31 + var result = 1 + for element in storage { + result = prime &* result &+ element.hashValue + } + return result + } + + /// Mark: TSerializable + public static var thriftType : TType { return .list } + + public static func read(from proto: TProtocol) throws -> TList { + let (elementType, size) = try proto.readListBegin() + if elementType != Element.thriftType { + throw TProtocolError(error: .invalidData, + extendedError: .unexpectedType(type: elementType)) + } + var list = TList() + for _ in 0.. Element { + get { + return storage[position] + } + set { + storage[position] = newValue + } + } + + public subscript(range: Range) -> SubSequence { + get { + return storage[range] + } + set { + storage[range] = newValue + } + } + + public var startIndex: Index { + return storage.startIndex + } + public var endIndex: Index { + return storage.endIndex + } + + public func formIndex(after i: inout Index) { + storage.formIndex(after: &i) + } + + public func formIndex(before i: inout Int) { + storage.formIndex(before: &i) + } + + public func index(after i: Index) -> Index { + return storage.index(after: i) + } + + public func index(before i: Int) -> Int { + return storage.index(before: i) + } + +} + +extension TList : RangeReplaceableCollection { + public mutating func replaceSubrange(_ subrange: Range, with newElements: C) + where C.Iterator.Element == Element { + storage.replaceSubrange(subrange, with: newElements) + } +} + +extension TList : CustomStringConvertible, CustomDebugStringConvertible { + + public var description : String { + return storage.description + } + + public var debugDescription : String { + return storage.debugDescription + } + +} + +public func ==(lhs: TList, rhs: TList) -> Bool { + return lhs.storage.elementsEqual(rhs.storage) { $0 == $1 } +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TMap.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TMap.swift new file mode 100644 index 0000000..8980377 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TMap.swift @@ -0,0 +1,194 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +public struct TMap: Collection, ExpressibleByDictionaryLiteral, Hashable, TSerializable { + public typealias Storage = Dictionary + public typealias Element = Storage.Element + public typealias Index = Storage.Index + public typealias IndexDistance = Storage.IndexDistance + public typealias Indices = Storage.Indices + public typealias SubSequence = Storage.SubSequence + internal var storage = Storage() + + /// Mark: Be Like Dictionary + + public func indexForKey(_ key: Key) -> Index? { + return storage.index(forKey: key) + } + + public mutating func updateValue(_ value: Value, forKey key: Key) -> Value? { + return updateValue(value, forKey: key) + } + + public mutating func removeAtIndex(_ index: DictionaryIndex) -> (Key, Value) { + return removeAtIndex(index) + } + + public mutating func removeValueForKey(_ key: Key) -> Value? { + return storage.removeValue(forKey: key) + } + + public init(minimumCapacity: Int) { + storage = Storage(minimumCapacity: minimumCapacity) + } + + /// init from Dictionary + public init(_ dict: [Key: Value]) { + storage = dict + } + + /// read only access to storage if needed as Dictionary + public var dictionary: [Key: Value] { + return storage + } + + public subscript (key: Key) -> Value? { + get { + return storage[key] + } + set { + storage[key] = newValue + } + } + + /// Mark: Collection + + public var indices: Indices { + return storage.indices + } + + public func distance(from start: Index, to end: Index) -> IndexDistance { + return storage.distance(from: start, to: end) + } + + public func index(_ i: Index, offsetBy n: IndexDistance) -> Index { + return storage.index(i, offsetBy: n) + } + + public func index(_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index) -> Index? { + return storage.index(i, offsetBy: n, limitedBy: limit) + } + + public subscript(position: Index) -> Element { + return storage[position] + } + + /// Mark: IndexableBase + + public var startIndex: Index { return storage.startIndex } + public var endIndex: Index { return storage.endIndex } + public func index(after i: Index) -> Index { + return storage.index(after: i) + } + + public func formIndex(after i: inout Index) { + storage.formIndex(after: &i) + } + + public subscript(bounds: Range) -> SubSequence { + return storage[bounds] + } + + /// Mark: DictionaryLiteralConvertible + + public init(dictionaryLiteral elements: (Key, Value)...) { + storage = Storage() + for (key, value) in elements { + storage[key] = value + } + } + + /// Mark: Hashable + + public var hashValue: Int { + let prime = 31 + var result = 1 + for (key, value) in storage { + result = prime &* result &+ key.hashValue + result = prime &* result &+ value.hashValue + } + return result + } + + /// Mark: TSerializable + + public static var thriftType : TType { return .map } + public init() { + storage = Storage() + } + + public static func read(from proto: TProtocol) throws -> TMap { + + let (keyType, valueType, size) = try proto.readMapBegin() + if size > 0 { + if keyType != Key.thriftType { + throw TProtocolError(error: .invalidData, + message: "Unexpected TMap Key Type", + extendedError: .unexpectedType(type: keyType)) + } + if valueType != Value.thriftType { + throw TProtocolError(error: .invalidData, + message: "Unexpected TMap Value Type", + extendedError: .unexpectedType(type: valueType)) + } + } + + var map = TMap() + for _ in 0..(lhs: TMap, rhs: TMap) -> Bool { + if lhs.count != rhs.count { + return false + } + return lhs.storage.elementsEqual(rhs.storage) { $0.key == $1.key && $0.value == $1.value } +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TMemoryBufferTransport.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TMemoryBufferTransport.swift new file mode 100644 index 0000000..bd58b6e --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TMemoryBufferTransport.swift @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +import Foundation + +public class TMemoryBufferTransport : TTransport { + public private(set) var readBuffer = Data() + public private(set) var writeBuffer = Data() + + public private(set) var position = 0 + + public var bytesRemainingInBuffer: Int { + return readBuffer.count - position + } + + public func consumeBuffer(size: Int) { + position += size + } + public func clear() { + readBuffer = Data() + writeBuffer = Data() + } + + + private var flushHandler: ((TMemoryBufferTransport, Data) -> ())? + + public init(flushHandler: ((TMemoryBufferTransport, Data) -> ())? = nil) { + self.flushHandler = flushHandler + } + + public convenience init(readBuffer: Data, flushHandler: ((TMemoryBufferTransport, Data) -> ())? = nil) { + self.init() + self.readBuffer = readBuffer + } + + public func reset(readBuffer: Data = Data(), writeBuffer: Data = Data()) { + self.readBuffer = readBuffer + self.writeBuffer = writeBuffer + } + + public func read(size: Int) throws -> Data { + let amountToRead = min(bytesRemainingInBuffer, size) + if amountToRead > 0 { + let ret = readBuffer.subdata(in: Range(uncheckedBounds: (lower: position, upper: position + amountToRead))) + position += ret.count + return ret + } + return Data() + } + + public func write(data: Data) throws { + writeBuffer.append(data) + } + + public func flush() throws { + flushHandler?(self, writeBuffer) + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TMultiplexedProtocol.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TMultiplexedProtocol.swift new file mode 100644 index 0000000..73a8d51 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TMultiplexedProtocol.swift @@ -0,0 +1,47 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you 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. +*/ + +public class TMultiplexedProtocol: TWrappedProtocol { + public let separator = ":" + + public var serviceName = "" + + public convenience init(on transport: TTransport, serviceName: String) { + self.init(on: transport) + self.serviceName = serviceName + } + + override public func writeMessageBegin(name: String, + type messageType: TMessageType, + sequenceID: Int32) throws { + switch messageType { + case .call, .oneway: + var serviceFunction = serviceName + serviceFunction += serviceName == "" ? "" : separator + serviceFunction += name + return try super.writeMessageBegin(name: serviceFunction, + type: messageType, + sequenceID: sequenceID) + default: + return try super.writeMessageBegin(name: name, + type: messageType, + sequenceID: sequenceID) + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TProcessor.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TProcessor.swift new file mode 100644 index 0000000..7ff222e --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TProcessor.swift @@ -0,0 +1,29 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you 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. +*/ + + +public typealias TProcessorMessageHandler = (Int, TProtocol, TProtocol, T) -> Void + +public protocol TProcessor { + associatedtype Service + var service: Service { get set } + func process(on inProtocol: TProtocol, outProtocol: TProtocol) throws + init(service: Service) +} + diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TProtocol.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TProtocol.swift new file mode 100644 index 0000000..a4e4a20 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TProtocol.swift @@ -0,0 +1,182 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you 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. +*/ + +import Foundation +// + +public enum TMessageType: Int32 { + case call = 1 + case reply = 2 + case exception = 3 + case oneway = 4 +} + +public enum TType: Int32 { + case stop = 0 + case void = 1 + case bool = 2 + case i8 = 3 + case double = 4 + case i16 = 6 + case i32 = 8 + case i64 = 10 + case string = 11 + case `struct` = 12 + case map = 13 + case set = 14 + case list = 15 + case utf8 = 16 + case utf16 = 17 +} + +public protocol TProtocol { + var transport: TTransport { get set } + init(on transport: TTransport) + // Reading Methods + + func readMessageBegin() throws -> (String, TMessageType, Int32) + func readMessageEnd() throws + func readStructBegin() throws -> String + func readStructEnd() throws + func readFieldBegin() throws -> (String, TType, Int32) + func readFieldEnd() throws + func readMapBegin() throws -> (TType, TType, Int32) + func readMapEnd() throws + func readSetBegin() throws -> (TType, Int32) + func readSetEnd() throws + func readListBegin() throws -> (TType, Int32) + func readListEnd() throws + + func read() throws -> String + func read() throws -> Bool + func read() throws -> UInt8 + func read() throws -> Int16 + func read() throws -> Int32 + func read() throws -> Int64 + func read() throws -> Double + func read() throws -> Data + + // Writing methods + + func writeMessageBegin(name: String, type messageType: TMessageType, sequenceID: Int32) throws + func writeMessageEnd() throws + func writeStructBegin(name: String) throws + func writeStructEnd() throws + func writeFieldBegin(name: String, type fieldType: TType, fieldID: Int32) throws + func writeFieldStop() throws + func writeFieldEnd() throws + func writeMapBegin(keyType: TType, valueType: TType, size: Int32) throws + func writeMapEnd() throws + func writeSetBegin(elementType: TType, size: Int32) throws + func writeSetEnd() throws + func writeListBegin(elementType: TType, size: Int32) throws + func writeListEnd() throws + + func write(_ value: String) throws + func write(_ value: Bool) throws + func write(_ value: UInt8) throws + func write(_ value: Int16) throws + func write(_ value: Int32) throws + func write(_ value: Int64) throws + func write(_ value: Double) throws + func write(_ value: Data) throws +} + +public extension TProtocol { + public func writeFieldValue(_ value: TSerializable, name: String, type: TType, id: Int32) throws { + try writeFieldBegin(name: name, type: type, fieldID: id) + try value.write(to: self) + try writeFieldEnd() + } + + public func validateValue(_ value: Any?, named name: String) throws { + if value == nil { + throw TProtocolError(error: .unknown, message: "Missing required value for field: \(name)") + } + } + + public func readResultMessageBegin() throws { + let (_, type, _) = try readMessageBegin(); + if type == .exception { + let x = try readException() + throw x + } + return + } + + public func readException() throws -> TApplicationError { + return try TApplicationError.read(from: self) + } + + public func writeException(messageName name: String, sequenceID: Int32, ex: TApplicationError) throws { + try writeMessageBegin(name: name, type: .exception, sequenceID: sequenceID) + try ex.write(to: self) + try writeMessageEnd() + } + + public func skip(type: TType) throws { + switch type { + case .bool: _ = try read() as Bool + case .i8: _ = try read() as UInt8 + case .i16: _ = try read() as Int16 + case .i32: _ = try read() as Int32 + case .i64: _ = try read() as Int64 + case .double: _ = try read() as Double + case .string: _ = try read() as String + + case .struct: + _ = try readStructBegin() + while true { + let (_, fieldType, _) = try readFieldBegin() + if fieldType == .stop { + break + } + try skip(type: fieldType) + try readFieldEnd() + } + try readStructEnd() + + + case .map: + let (keyType, valueType, size) = try readMapBegin() + for _ in 0.. ()) throws { + // Need mutable copy + var error = error + do { + try block() + } catch let err as TError { + var message = error.message ?? "" + message += "\nFile: \(sourceFile)\n" + message += "Line: \(sourceLine)\n" + message += "Method: \(sourceMethod)" + message += "\nOriginal Error:\n" + err.description + error.message = message + throw error + } +} + + diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TSSLSocketTransport.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TSSLSocketTransport.swift new file mode 100644 index 0000000..c2b5902 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TSSLSocketTransport.swift @@ -0,0 +1,229 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you 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. +*/ + +import Foundation +import CoreFoundation + +#if os(Linux) +public class TSSLSocketTransport { + init(hostname: String, port: UInt16) { + // FIXME! + assert(false, "Security not available in Linux, TSSLSocketTransport Unavilable for now") + } +} +#else +let isLittleEndian = Int(OSHostByteOrder()) == OSLittleEndian +let htons = isLittleEndian ? _OSSwapInt16 : { $0 } +let htonl = isLittleEndian ? _OSSwapInt32 : { $0 } + +public class TSSLSocketTransport: TStreamTransport { + var sslHostname: String + var sd: Int32 = 0 + + public init(hostname: String, port: UInt16) throws { + sslHostname = hostname + var readStream: Unmanaged? + var writeStream: Unmanaged? + + /* create a socket structure */ + var pin: sockaddr_in = sockaddr_in() + var hp: UnsafeMutablePointer? = nil + for i in 0..<10 { + + hp = gethostbyname(hostname.cString(using: String.Encoding.utf8)!) + if hp == nil { + print("failed to resolve hostname \(hostname)") + herror("resolv") + if i == 9 { + super.init(inputStream: nil, outputStream: nil) // have to init before throwing + throw TSSLSocketTransportError(error: .hostanameResolution(hostname: hostname)) + } + Thread.sleep(forTimeInterval: 0.2) + } else { + break + } + } + pin.sin_family = UInt8(AF_INET) + pin.sin_addr = in_addr(s_addr: UInt32((hp?.pointee.h_addr_list.pointee?.pointee)!)) // Is there a better way to get this??? + pin.sin_port = htons(port) + + /* create the socket */ + sd = socket(Int32(AF_INET), Int32(SOCK_STREAM), Int32(IPPROTO_TCP)) + if sd == -1 { + super.init(inputStream: nil, outputStream: nil) // have to init before throwing + throw TSSLSocketTransportError(error: .socketCreate(port: Int(port))) + } + + /* open a connection */ + // need a non-self ref to sd, otherwise the j complains + let sd_local = sd + let connectResult = withUnsafePointer(to: &pin) { + connect(sd_local, UnsafePointer(OpaquePointer($0)), socklen_t(MemoryLayout.size)) + } + if connectResult == -1 { + super.init(inputStream: nil, outputStream: nil) // have to init before throwing + throw TSSLSocketTransportError(error: .connect) + } + + CFStreamCreatePairWithSocket(kCFAllocatorDefault, sd, &readStream, &writeStream) + + CFReadStreamSetProperty(readStream?.takeRetainedValue(), .socketNativeHandle, kCFBooleanTrue) + CFWriteStreamSetProperty(writeStream?.takeRetainedValue(), .socketNativeHandle, kCFBooleanTrue) + + var inputStream: InputStream? = nil + var outputStream: OutputStream? = nil + if readStream != nil && writeStream != nil { + + CFReadStreamSetProperty(readStream?.takeRetainedValue(), + .socketSecurityLevel, + kCFStreamSocketSecurityLevelTLSv1) + + let settings: [String: Bool] = [kCFStreamSSLValidatesCertificateChain as String: true] + + CFReadStreamSetProperty(readStream?.takeRetainedValue(), + .SSLSettings, + settings as CFTypeRef!) + + CFWriteStreamSetProperty(writeStream?.takeRetainedValue(), + .SSLSettings, + settings as CFTypeRef!) + + inputStream = readStream!.takeRetainedValue() + inputStream?.schedule(in: .current, forMode: .defaultRunLoopMode) + inputStream?.open() + + outputStream = writeStream!.takeRetainedValue() + outputStream?.schedule(in: .current, forMode: .defaultRunLoopMode) + outputStream?.open() + + readStream?.release() + writeStream?.release() + } + + + super.init(inputStream: inputStream, outputStream: outputStream) + self.input?.delegate = self + self.output?.delegate = self + } + + func recoverFromTrustFailure(_ myTrust: SecTrust, lastTrustResult: SecTrustResultType) -> Bool { + let trustTime = SecTrustGetVerifyTime(myTrust) + let currentTime = CFAbsoluteTimeGetCurrent() + + let timeIncrement = 31536000 // from TSSLSocketTransport.m + let newTime = currentTime - Double(timeIncrement) + + if trustTime - newTime != 0 { + let newDate = CFDateCreate(nil, newTime) + SecTrustSetVerifyDate(myTrust, newDate!) + + var tr = lastTrustResult + let success = withUnsafeMutablePointer(to: &tr) { trPtr -> Bool in + if SecTrustEvaluate(myTrust, trPtr) != errSecSuccess { + return false + } + return true + } + if !success { return false } + } + if lastTrustResult == .proceed || lastTrustResult == .unspecified { + return false + } + + print("TSSLSocketTransport: Unable to recover certificate trust failure") + return true + } + + public func isOpen() -> Bool { + return sd > 0 + } +} + +extension TSSLSocketTransport: StreamDelegate { + public func stream(_ aStream: Stream, handle eventCode: Stream.Event) { + + switch eventCode { + case Stream.Event(): break + case Stream.Event.hasBytesAvailable: break + case Stream.Event.openCompleted: break + case Stream.Event.hasSpaceAvailable: + var proceed = false + var trustResult: SecTrustResultType = .invalid + + var newPolicies: CFMutableArray? + + repeat { + let trust: SecTrust = aStream.property(forKey: .SSLPeerTrust) as! SecTrust + + // Add new policy to current list of policies + let policy = SecPolicyCreateSSL(false, sslHostname as CFString?) + var ppolicy = policy // mutable for pointer + let policies: UnsafeMutablePointer? = nil + if SecTrustCopyPolicies(trust, policies!) != errSecSuccess { + break + } + withUnsafeMutablePointer(to: &ppolicy) { ptr in + newPolicies = CFArrayCreateMutableCopy(nil, 0, policies?.pointee) + CFArrayAppendValue(newPolicies, ptr) + } + + // update trust policies + if SecTrustSetPolicies(trust, newPolicies!) != errSecSuccess { + break + } + + // Evaluate the trust chain + let success = withUnsafeMutablePointer(to: &trustResult) { trustPtr -> Bool in + if SecTrustEvaluate(trust, trustPtr) != errSecSuccess { + return false + } + return true + } + + if !success { + break + } + + + switch trustResult { + case .proceed: proceed = true + case .unspecified: proceed = true + case .recoverableTrustFailure: + proceed = self.recoverFromTrustFailure(trust, lastTrustResult: trustResult) + + case .deny: break + case .fatalTrustFailure: break + case .otherError: break + case .invalid: break + default: break + } + } while false + + if !proceed { + print("TSSLSocketTransport: Cannot trust certificate. Result: \(trustResult)") + aStream.close() + } + + case Stream.Event.errorOccurred: break + case Stream.Event.endEncountered: break + default: break + } + } +} +#endif diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TSSLSocketTransportError.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TSSLSocketTransportError.swift new file mode 100644 index 0000000..fda162b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TSSLSocketTransportError.swift @@ -0,0 +1,48 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you 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. +*/ + +public struct TSSLSocketTransportError: TError { + public enum ErrorCode: TErrorCode { + case hostanameResolution(hostname: String) + case socketCreate(port: Int) + case connect + + public var thriftErrorCode: Int { + switch self { + case .hostanameResolution: return -10000 + case .socketCreate: return -10001 + case .connect: return -10002 + } + } + + public var description: String { + switch self { + case .hostanameResolution(let hostname): return "Failed to resolve hostname: \(hostname)" + case .socketCreate(let port): return "Could not create socket on port: \(port)" + case .connect: return "Connect error" + } + } + + } + public var error: ErrorCode = .connect + public var message: String? + public static var defaultCase: ErrorCode { return .connect } + + public init() { } +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TSerializable.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TSerializable.swift new file mode 100644 index 0000000..b45096b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TSerializable.swift @@ -0,0 +1,136 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +import Foundation + + +public protocol TSerializable { + var hashValue: Int { get } + + /// TType for instance + static var thriftType: TType { get } + + /// Read TSerializable instance from Protocol + static func read(from proto: TProtocol) throws -> Self + + /// Write TSerializable instance to Protocol + func write(to proto: TProtocol) throws + +} + +extension TSerializable { + public static func write(_ value: Self, to proto: TProtocol) throws { + try value.write(to: proto) + } + + /// convenience for member access + public var thriftType: TType { return Self.thriftType } +} + +public func ==(lhs: T, rhs: T) -> Bool where T : TSerializable { + return lhs.hashValue == rhs.hashValue +} + +/// Default read/write for primitave Thrift types: +/// Bool, Int8 (byte), Int16, Int32, Int64, Double, String + +extension Bool : TSerializable { + public static var thriftType: TType { return .bool } + + public static func read(from proto: TProtocol) throws -> Bool { + return try proto.read() + } + + public func write(to proto: TProtocol) throws { + try proto.write(self) + } +} + +extension Int8 : TSerializable { + public static var thriftType: TType { return .i8 } + + public static func read(from proto: TProtocol) throws -> Int8 { + return Int8(try proto.read() as UInt8) + } + + public func write(to proto: TProtocol) throws { + try proto.write(UInt8(self)) + } +} + +extension Int16 : TSerializable { + public static var thriftType: TType { return .i16 } + + public static func read(from proto: TProtocol) throws -> Int16 { + return try proto.read() + } + + public func write(to proto: TProtocol) throws { + try proto.write(self) + } +} + +extension Int32 : TSerializable { + public static var thriftType: TType { return .i32 } + + public static func read(from proto: TProtocol) throws -> Int32 { + return try proto.read() + } + + public func write(to proto: TProtocol) throws { + try proto.write(self) + } +} + + +extension Int64 : TSerializable { + public static var thriftType: TType { return .i64 } + + public static func read(from proto: TProtocol) throws -> Int64 { + return try proto.read() + } + + public func write(to proto: TProtocol) throws { + try proto.write(self) + } +} + +extension Double : TSerializable { + public static var thriftType: TType { return .double } + + public static func read(from proto: TProtocol) throws -> Double { + return try proto.read() + } + + public func write(to proto: TProtocol) throws { + try proto.write(self) + } +} + +extension String : TSerializable { + public static var thriftType: TType { return .string } + + public static func read(from proto: TProtocol) throws -> String { + return try proto.read() + } + + public func write(to proto: TProtocol) throws { + try proto.write(self) + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TSet.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TSet.swift new file mode 100644 index 0000000..1ecd170 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TSet.swift @@ -0,0 +1,189 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +import Foundation + +public struct TSet : SetAlgebra, Hashable, Collection, ExpressibleByArrayLiteral, TSerializable { + /// Typealias for Storage type + public typealias Storage = Set + + + /// Internal Storage used for TSet (Set\) + internal var storage : Storage + + + /// Mark: Collection + + public typealias Indices = Storage.Indices + public typealias Index = Storage.Index + public typealias IndexDistance = Storage.IndexDistance + public typealias SubSequence = Storage.SubSequence + + + public var indices: Indices { return storage.indices } + + // Must implement isEmpty even though both SetAlgebra and Collection provide it due to their conflciting default implementations + public var isEmpty: Bool { return storage.isEmpty } + + public func distance(from start: Index, to end: Index) -> IndexDistance { + return storage.distance(from: start, to: end) + } + + public func index(_ i: Index, offsetBy n: IndexDistance) -> Index { + return storage.index(i, offsetBy: n) + } + + public func index(_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index) -> Index? { + return storage.index(i, offsetBy: n, limitedBy: limit) + } + + #if swift(>=3.2) + public subscript (position: Storage.Index) -> Element { + return storage[position] + } + #else + public subscript (position: Storage.Index) -> Element? { + return storage[position] + } + #endif + + /// Mark: SetAlgebra + internal init(storage: Set) { + self.storage = storage + } + + public func contains(_ member: Element) -> Bool { + return storage.contains(member) + } + + public mutating func insert(_ newMember: Element) -> (inserted: Bool, memberAfterInsert: Element) { + return storage.insert(newMember) + } + + public mutating func remove(_ member: Element) -> Element? { + return storage.remove(member) + } + + public func union(_ other: TSet) -> TSet { + return TSet(storage: storage.union(other.storage)) + } + + public mutating func formIntersection(_ other: TSet) { + return storage.formIntersection(other.storage) + } + + public mutating func formSymmetricDifference(_ other: TSet) { + return storage.formSymmetricDifference(other.storage) + } + + public mutating func formUnion(_ other: TSet) { + return storage.formUnion(other.storage) + } + + public func intersection(_ other: TSet) -> TSet { + return TSet(storage: storage.intersection(other.storage)) + } + + public func symmetricDifference(_ other: TSet) -> TSet { + return TSet(storage: storage.symmetricDifference(other.storage)) + } + + public mutating func update(with newMember: Element) -> Element? { + return storage.update(with: newMember) + } + + /// Mark: IndexableBase + + public var startIndex: Index { return storage.startIndex } + public var endIndex: Index { return storage.endIndex } + public func index(after i: Index) -> Index { + return storage.index(after: i) + } + + public func formIndex(after i: inout Storage.Index) { + storage.formIndex(after: &i) + } + + public subscript(bounds: Range) -> SubSequence { + return storage[bounds] + } + + + /// Mark: Hashable + public var hashValue : Int { + let prime = 31 + var result = 1 + for element in storage { + result = prime &* result &+ element.hashValue + } + return result + } + + /// Mark: TSerializable + public static var thriftType : TType { return .set } + + public init() { + storage = Storage() + } + + public init(arrayLiteral elements: Element...) { + self.storage = Storage(elements) + } + + public init(_ sequence: Source) where Source.Iterator.Element == Element { + storage = Storage(sequence) + } + + public static func read(from proto: TProtocol) throws -> TSet { + let (elementType, size) = try proto.readSetBegin() + if elementType != Element.thriftType { + throw TProtocolError(error: .invalidData, + extendedError: .unexpectedType(type: elementType)) + } + var set = TSet() + for _ in 0..(lhs: TSet, rhs: TSet) -> Bool { + return lhs.storage == rhs.storage +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TSocketServer.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TSocketServer.swift new file mode 100644 index 0000000..0224e67 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TSocketServer.swift @@ -0,0 +1,149 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you 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. +*/ + +#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) + import Darwin +#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) + import Glibc + import Dispatch +#endif + +import Foundation +import CoreFoundation + +public let TSocketServerClientConnectionFinished = "TSocketServerClientConnectionFinished" +public let TSocketServerProcessorKey = "TSocketServerProcessor" +public let TSocketServerTransportKey = "TSocketServerTransport" + +class TSocketServer where Processor.Service == Service { + var socketFileHandle: FileHandle + var processingQueue = DispatchQueue(label: "TSocketServer.processing", + qos: .background, + attributes: .concurrent) + var serviceHandler: Service + + public init(port: Int, + service: Service, + inProtocol: InProtocol.Type, + outProtocol: OutProtocol.Type, + processor: Processor.Type) throws { + // set service handler + self.serviceHandler = service + + // create a socket + var fd: Int32 = -1 + #if os(Linux) + let sock = CFSocketCreate(kCFAllocatorDefault, PF_INET, Int32(SOCK_STREAM.rawValue), Int32(IPPROTO_TCP), 0, nil, nil) + #else + let sock = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, 0, nil, nil) + #endif + if sock != nil { + CFSocketSetSocketFlags(sock, CFSocketGetSocketFlags(sock) & ~kCFSocketCloseOnInvalidate) + + fd = CFSocketGetNative(sock) + var yes = 1 + setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, UInt32(MemoryLayout.size)) + + #if os(Linux) + var addr = sockaddr_in(sin_family: sa_family_t(AF_INET), + sin_port: in_port_t(port.bigEndian), + sin_addr: in_addr(s_addr: in_addr_t(0)), + sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) + #else + var addr = sockaddr_in(sin_len: UInt8(MemoryLayout.size), + sin_family: sa_family_t(AF_INET), + sin_port: in_port_t(port.bigEndian), + sin_addr: in_addr(s_addr: in_addr_t(0)), + sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) + #endif + + let ptr = withUnsafePointer(to: &addr) { + return UnsafePointer(OpaquePointer($0)) + } + + let address = Data(bytes: ptr, count: MemoryLayout.size) + + let cfaddr = address.withUnsafeBytes { + CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, $0, address.count, nil) + } + if CFSocketSetAddress(sock, cfaddr) != CFSocketError.success { //kCFSocketSuccess { + CFSocketInvalidate(sock) + print("TSocketServer: Could not bind to address") + throw TTransportError(error: .notOpen, message: "Could not bind to address") + } + + } else { + print("TSocketServer: No server socket") + throw TTransportError(error: .notOpen, message: "Could not create socket") + } + + // wrap it in a file handle so we can get messages from it + socketFileHandle = FileHandle(fileDescriptor: fd, closeOnDealloc: true) + + // throw away our socket + CFSocketInvalidate(sock) + + // register for notifications of accepted incoming connections + _ = NotificationCenter.default.addObserver(forName: .NSFileHandleConnectionAccepted, + object: nil, queue: nil) { + [weak self] notification in + guard let strongSelf = self else { return } + strongSelf.connectionAccepted(strongSelf.socketFileHandle) + + } + + // tell socket to listen + socketFileHandle.acceptConnectionInBackgroundAndNotify() + + print("TSocketServer: Listening on TCP port \(port)") + } + + deinit { + NotificationCenter.default.removeObserver(self) + } + + func connectionAccepted(_ socket: FileHandle) { + // Now that we have a client connected, handle the request on queue + processingQueue.async { + self.handleClientConnection(socket) + } + } + + func handleClientConnection(_ clientSocket: FileHandle) { + + let transport = TFileHandleTransport(fileHandle: clientSocket) + let processor = Processor(service: serviceHandler) + + let inProtocol = InProtocol(on: transport) + let outProtocol = OutProtocol(on: transport) + + do { + try processor.process(on: inProtocol, outProtocol: outProtocol) + } catch let error { + print("Error processign request: \(error)") + } + DispatchQueue.main.async { + NotificationCenter.default + .post(name: Notification.Name(rawValue: TSocketServerClientConnectionFinished), + object: self, + userInfo: [TSocketServerProcessorKey: processor, + TSocketServerTransportKey: transport]) + } + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TSocketTransport.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TSocketTransport.swift new file mode 100644 index 0000000..0316e37 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TSocketTransport.swift @@ -0,0 +1,210 @@ + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + + +#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) + import Darwin +#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) + import Glibc + import Dispatch +#endif + +import Foundation +import CoreFoundation + +private struct Sys { + #if os(Linux) + static let read = Glibc.read + static let write = Glibc.write + static let close = Glibc.close + #else + static let read = Darwin.read + static let write = Darwin.write + static let close = Darwin.close + #endif +} + +extension in_addr { + public init?(hostent: hostent?) { + guard let host = hostent, host.h_addr_list != nil, host.h_addr_list.pointee != nil else { + return nil + } + self.init() + memcpy(&self, host.h_addr_list.pointee!, Int(host.h_length)) + + } +} + + +#if os(Linux) + /// TCFSocketTransport currently unavailable + /// remove comments and build to see why/fix + /// currently CF[Read|Write]Stream's can't cast to [Input|Output]Streams which breaks thigns +#else +extension Stream.PropertyKey { + static let SSLPeerTrust = Stream.PropertyKey(kCFStreamPropertySSLPeerTrust as String) +} + +/// TCFSocketTransport, uses CFSockets and (NS)Stream's +public class TCFSocketTransport: TStreamTransport { + public init?(hostname: String, port: Int, secure: Bool = false) { + + var inputStream: InputStream + var outputStream: OutputStream + + var readStream: Unmanaged? + var writeStream: Unmanaged? + CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, + hostname as CFString!, + UInt32(port), + &readStream, + &writeStream) + + if let readStream = readStream?.takeRetainedValue(), + let writeStream = writeStream?.takeRetainedValue() { + CFReadStreamSetProperty(readStream, .shouldCloseNativeSocket, kCFBooleanTrue) + CFWriteStreamSetProperty(writeStream, .shouldCloseNativeSocket, kCFBooleanTrue) + + if secure { + CFReadStreamSetProperty(readStream, .socketSecurityLevel, StreamSocketSecurityLevel.negotiatedSSL.rawValue as CFString) + CFWriteStreamSetProperty(writeStream, .socketSecurityLevel, StreamSocketSecurityLevel.negotiatedSSL.rawValue as CFString) + } + + inputStream = readStream as InputStream + inputStream.schedule(in: .current, forMode: .defaultRunLoopMode) + inputStream.open() + + outputStream = writeStream as OutputStream + outputStream.schedule(in: .current, forMode: .defaultRunLoopMode) + outputStream.open() + + } else { + + if readStream != nil { + readStream?.release() + } + if writeStream != nil { + writeStream?.release() + } + super.init(inputStream: nil, outputStream: nil) + return nil + } + + super.init(inputStream: inputStream, outputStream: outputStream) + + self.input?.delegate = self + self.output?.delegate = self + } +} + +extension TCFSocketTransport: StreamDelegate { } +#endif + + +/// TSocketTransport, posix sockets. Supports IPv4 only for now +public class TSocketTransport : TTransport { + public var socketDescriptor: Int32 + + + + /// Initialize from an already set up socketDescriptor. + /// Expects socket thats already bound/connected (i.e. from listening) + /// + /// - parameter socketDescriptor: posix socket descriptor (Int32) + public init(socketDescriptor: Int32) { + self.socketDescriptor = socketDescriptor + } + + + public convenience init(hostname: String, port: Int) throws { + guard let hp = gethostbyname(hostname.cString(using: .utf8)!)?.pointee, + let hostAddr = in_addr(hostent: hp) else { + throw TTransportError(error: .unknown, message: "Invalid address: \(hostname)") + } + + + + #if os(Linux) + let sock = socket(AF_INET, Int32(SOCK_STREAM.rawValue), 0) + var addr = sockaddr_in(sin_family: sa_family_t(AF_INET), + sin_port: in_port_t(htons(UInt16(port))), + sin_addr: hostAddr, + sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) + #else + let sock = socket(AF_INET, SOCK_STREAM, 0) + + var addr = sockaddr_in(sin_len: UInt8(MemoryLayout.size), + sin_family: sa_family_t(AF_INET), + sin_port: in_port_t(htons(UInt16(port))), + sin_addr: in_addr(s_addr: in_addr_t(0)), + sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) + + #endif + + let addrPtr = withUnsafePointer(to: &addr){ UnsafePointer(OpaquePointer($0)) } + + let connected = connect(sock, addrPtr, UInt32(MemoryLayout.size)) + if connected != 0 { + throw TTransportError(error: .notOpen, message: "Error binding to host: \(hostname) \(port)") + } + + self.init(socketDescriptor: sock) + } + + deinit { + close() + } + + public func readAll(size: Int) throws -> Data { + var out = Data() + while out.count < size { + out.append(try self.read(size: size)) + } + return out + } + + public func read(size: Int) throws -> Data { + var buff = Array.init(repeating: 0, count: size) + let readBytes = Sys.read(socketDescriptor, &buff, size) + + return Data(bytes: buff[0.. 0 { + let written = writeBuffer.withUnsafeBytes { + Sys.write(socketDescriptor, $0, writeBuffer.count) + } + writeBuffer = writeBuffer.subdata(in: written ..< writeBuffer.count) + bytesToWrite -= written + } + } + + public func flush() throws { + // nothing to do + } + + public func close() { + shutdown(socketDescriptor, Int32(SHUT_RDWR)) + _ = Sys.close(socketDescriptor) + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TStreamTransport.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TStreamTransport.swift new file mode 100644 index 0000000..26bc1b8 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TStreamTransport.swift @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +import Foundation +import CoreFoundation + +#if os(Linux) + /// Currently unavailable in Linux + /// Remove comments and build to fix + /// Currently kConstants for CFSockets don't exist in linux and not all have been moved + /// to property structs yet +#else + // Must inherit NSObject for NSStreamDelegate conformance + public class TStreamTransport : NSObject, TTransport { + public var input: InputStream? = nil + public var output: OutputStream? = nil + + public init(inputStream: InputStream?, outputStream: OutputStream?) { + input = inputStream + output = outputStream + } + + public convenience init(inputStream: InputStream?) { + self.init(inputStream: inputStream, outputStream: nil) + } + + public convenience init(outputStream: OutputStream?) { + self.init(inputStream: nil, outputStream: outputStream) + } + + deinit { + close() + } + + public func readAll(size: Int) throws -> Data { + guard let input = input else { + throw TTransportError(error: .unknown) + } + + var read = Data() + while read.count < size { + var buffer = Array(repeating: 0, count: size - read.count) + + let bytesRead = buffer.withUnsafeMutableBufferPointer { bufferPtr in + return input.read(bufferPtr.baseAddress!, maxLength: size - read.count) + } + + if bytesRead <= 0 { + throw TTransportError(error: .notOpen) + } + read.append(Data(bytes: buffer)) + } + return read + } + + public func read(size: Int) throws -> Data { + guard let input = input else { + throw TTransportError(error: .unknown) + } + + var read = Data() + while read.count < size { + var buffer = Array(repeating: 0, count: size - read.count) + let bytesRead = buffer.withUnsafeMutableBufferPointer { + input.read($0.baseAddress!, maxLength: size - read.count) + } + + if bytesRead <= 0 { + break + } + + read.append(Data(bytes: buffer)) + } + return read + } + + public func write(data: Data) throws { + guard let output = output else { + throw TTransportError(error: .unknown) + } + + var bytesWritten = 0 + while bytesWritten < data.count { + bytesWritten = data.withUnsafeBytes { + return output.write($0, maxLength: data.count) + } + + if bytesWritten == -1 { + throw TTransportError(error: .notOpen) + } else if bytesWritten == 0 { + throw TTransportError(error: .endOfFile) + } + } + } + + + public func flush() throws { + return + } + + public func close() { + + if input != nil { + // Close and reset inputstream + if let cf: CFReadStream = input { + CFReadStreamSetProperty(cf, .shouldCloseNativeSocket, kCFBooleanTrue) + } + + input?.delegate = nil + input?.close() + input?.remove(from: .current, forMode: .defaultRunLoopMode) + input = nil + } + + if output != nil { + // Close and reset output stream + if let cf: CFWriteStream = output { + CFWriteStreamSetProperty(cf, .shouldCloseNativeSocket, kCFBooleanTrue) + } + output?.delegate = nil + output?.close() + output?.remove(from: .current, forMode: .defaultRunLoopMode) + output = nil + } + } + } +#endif diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TStruct.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TStruct.swift new file mode 100644 index 0000000..f172a32 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TStruct.swift @@ -0,0 +1,100 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + + +/// Protocol for Generated Structs to conform to +/// Dictionary maps field names to internal IDs and uses Reflection +/// to iterate through all fields. +/// `writeFieldValue(_:name:type:id:)` calls `TSerializable.write(to:)` internally +/// giving a nice recursive behavior for nested TStructs, TLists, TMaps, and TSets +public protocol TStruct : TSerializable { + static var fieldIds: [String: Int32] { get } + static var structName: String { get } +} + +public extension TStruct { + public static var fieldIds: [String: (id: Int32, type: TType)] { return [:] } + public static var thriftType: TType { return .struct } + + public func write(to proto: TProtocol) throws { + // Write struct name first + try proto.writeStructBegin(name: Self.structName) + + try self.forEach { name, value, id in + // Write to protocol + try proto.writeFieldValue(value, name: name, + type: value.thriftType, id: id) + } + try proto.writeFieldStop() + try proto.writeStructEnd() + } + + public var hashValue: Int { + let prime = 31 + var result = 1 + self.forEach { _, value, _ in + result = prime &* result &+ (value.hashValue) + } + return result + } + + /// Provides a block for handling each (available) thrift property using reflection + /// Caveat: Skips over optional values + + + /// Provides a block for handling each (available) thrift property using reflection + /// + /// - parameter block: block for handling property + /// + /// - throws: rethrows any Error thrown in block + private func forEach(_ block: (_ name: String, _ value: TSerializable, _ id: Int32) throws -> Void) rethrows { + // Mirror the object, getting (name: String?, value: Any) for every property + let mirror = Mirror(reflecting: self) + + // Iterate through all children, ignore empty property names + for (propName, propValue) in mirror.children { + guard let propName = propName else { continue } + + if let tval = unwrap(any: propValue) as? TSerializable, let id = Self.fieldIds[propName] { + try block(propName, tval, id) + } + } + } + + + /// Any can mysteriously be an Optional at the same time, + /// this checks and always returns Optional without double wrapping + /// we then try to bind value as TSerializable to ignore any extension properties + /// and the like and verify the property exists and grab the Thrift + /// property ID at the same time + /// + /// - parameter any: Any instance to attempt to unwrap + /// + /// - returns: Unwrapped Any as Optional + private func unwrap(any: Any) -> Any? { + let mi = Mirror(reflecting: any) + + if mi.displayStyle != .optional { return any } + if mi.children.count == 0 { return nil } + + let (_, some) = mi.children.first! + return some + } +} + diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TTransport.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TTransport.swift new file mode 100644 index 0000000..e82bbe1 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TTransport.swift @@ -0,0 +1,64 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you 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. +*/ + +import Foundation + +public protocol TTransport { + + // Required + func read(size: Int) throws -> Data + func write(data: Data) throws + func flush() throws + + // Optional (default provided) + func readAll(size: Int) throws -> Data + func isOpen() throws -> Bool + func open() throws + func close() throws +} + +public extension TTransport { + func isOpen() throws -> Bool { return true } + func open() throws { } + func close() throws { } + + func readAll(size: Int) throws -> Data { + var buff = Data() + var have = 0 + while have < size { + let chunk = try self.read(size: size - have) + have += chunk.count + buff.append(chunk) + if chunk.count == 0 { + throw TTransportError(error: .endOfFile) + } + } + return buff + } +} + +public protocol TAsyncTransport : TTransport { + // Factory + func flush(_ completion: @escaping (TAsyncTransport, Error?) ->()) +} + +public protocol TAsyncTransportFactory { + associatedtype Transport : TAsyncTransport + func newTransport() -> Transport +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TTransportError.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TTransportError.swift new file mode 100644 index 0000000..3fd0059 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TTransportError.swift @@ -0,0 +1,86 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you 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. +*/ + +public struct TTransportError: TError { + public enum ErrorCode: TErrorCode { + case unknown + case notOpen + case alreadyOpen + case timedOut + case endOfFile + case negativeSize + case sizeLimit(limit: Int, got: Int) + + public var thriftErrorCode: Int { + switch self { + case .unknown: return 0 + case .notOpen: return 1 + case .alreadyOpen: return 2 + case .timedOut: return 3 + case .endOfFile: return 4 + case .negativeSize: return 5 + case .sizeLimit: return 6 + } + } + public var description: String { + switch self { + case .unknown: return "Unknown TTransportError" + case .notOpen: return "Not Open" + case .alreadyOpen: return "Already Open" + case .timedOut: return "Timed Out" + case .endOfFile: return "End Of File" + case .negativeSize: return "Negative Size" + case .sizeLimit(let limit, let got): + return "Message exceeds size limit of \(limit) (received: \(got)" + } + } + } + public var error: ErrorCode = .unknown + public var message: String? = nil + public static var defaultCase: ErrorCode { return .unknown } + + public init() { } + +} + +/// THTTPTransportError +/// +/// Error's thrown on HTTP Transport +public struct THTTPTransportError: TError { + public enum ErrorCode: TErrorCode { + case invalidResponse + case invalidStatus(statusCode: Int) + case authentication + + public var description: String { + switch self { + case .invalidResponse: return "Invalid HTTP Response" + case .invalidStatus(let statusCode): return "Invalid HTTP Status Code (\(statusCode))" + case .authentication: return "Authentication Error" + } + } + public var thriftErrorCode: Int { return 0 } + } + public var error: ErrorCode = .invalidResponse + public var message: String? = nil + public static var defaultCase: ErrorCode { return .invalidResponse } + + public init() { } +} + diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/TWrappedProtocol.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TWrappedProtocol.swift new file mode 100644 index 0000000..8e8577b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/TWrappedProtocol.swift @@ -0,0 +1,208 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you 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. +*/ + +import Foundation // For (NS)Data + + +/// Generic protocol, implementes TProtocol and wraps a concrete protocol. +/// Useful for generically subclassing protocols to override specific methods +/// (i.e. TMultiplexedProtocol) +open class TWrappedProtocol : TProtocol { + var concreteProtocol: Protocol + + public var transport: TTransport { + get { + return concreteProtocol.transport + } + set { + concreteProtocol.transport = newValue + } + } + + public required init(on transport: TTransport) { + self.concreteProtocol = Protocol(on: transport) + } + + // Read methods + + public func readMessageBegin() throws -> (String, TMessageType, Int32) { + return try concreteProtocol.readMessageBegin() + } + + public func readMessageEnd() throws { + try concreteProtocol.readMessageEnd() + } + + public func readStructBegin() throws -> String { + return try concreteProtocol.readStructBegin() + } + + public func readStructEnd() throws { + try concreteProtocol.readStructEnd() + } + + public func readFieldBegin() throws -> (String, TType, Int32) { + return try concreteProtocol.readFieldBegin() + } + + public func readFieldEnd() throws { + try concreteProtocol.readFieldEnd() + } + + public func readMapBegin() throws -> (TType, TType, Int32) { + return try concreteProtocol.readMapBegin() + } + + public func readMapEnd() throws { + try concreteProtocol.readMapEnd() + } + + public func readSetBegin() throws -> (TType, Int32) { + return try concreteProtocol.readSetBegin() + } + + public func readSetEnd() throws { + try concreteProtocol.readSetEnd() + } + + public func readListBegin() throws -> (TType, Int32) { + return try concreteProtocol.readListBegin() + } + + public func readListEnd() throws { + try concreteProtocol.readListEnd() + } + + public func read() throws -> String { + return try concreteProtocol.read() + } + + public func read() throws -> Bool { + return try concreteProtocol.read() + } + + public func read() throws -> UInt8 { + return try concreteProtocol.read() + } + + public func read() throws -> Int16 { + return try concreteProtocol.read() + } + + public func read() throws -> Int32 { + return try concreteProtocol.read() + } + + public func read() throws -> Int64 { + return try concreteProtocol.read() + } + + public func read() throws -> Double { + return try concreteProtocol.read() + } + + public func read() throws -> Data { + return try concreteProtocol.read() + } + + // Write methods + + public func writeMessageBegin(name: String, type messageType: TMessageType, sequenceID: Int32) throws { + return try concreteProtocol.writeMessageBegin(name: name, type: messageType, sequenceID: sequenceID) + } + + public func writeMessageEnd() throws { + try concreteProtocol.writeMessageEnd() + } + + public func writeStructBegin(name: String) throws { + try concreteProtocol.writeStructBegin(name: name) + } + + public func writeStructEnd() throws { + try concreteProtocol.writeStructEnd() + } + + public func writeFieldBegin(name: String, type fieldType: TType, fieldID: Int32) throws { + try concreteProtocol.writeFieldBegin(name: name, type: fieldType, fieldID: fieldID) + } + + public func writeFieldStop() throws { + try concreteProtocol.writeFieldStop() + } + + public func writeFieldEnd() throws { + try concreteProtocol.writeFieldEnd() + } + + public func writeMapBegin(keyType: TType, valueType: TType, size: Int32) throws { + try concreteProtocol.writeMapBegin(keyType: keyType, valueType: valueType, size: size) + } + + public func writeMapEnd() throws { + try concreteProtocol.writeMapEnd() + } + + public func writeSetBegin(elementType: TType, size: Int32) throws { + try concreteProtocol.writeSetBegin(elementType: elementType, size: size) + } + + public func writeSetEnd() throws { + try concreteProtocol.writeSetEnd() + } + + public func writeListBegin(elementType: TType, size: Int32) throws { + try concreteProtocol.writeListBegin(elementType: elementType, size: size) + } + + public func writeListEnd() throws { + try concreteProtocol.writeListEnd() + } + public func write(_ value: String) throws { + try concreteProtocol.write(value) + } + + public func write(_ value: Bool) throws { + try concreteProtocol.write(value) + } + + public func write(_ value: UInt8) throws { + try concreteProtocol.write(value) + } + + public func write(_ value: Int16) throws { + try concreteProtocol.write(value) + } + + public func write(_ value: Int32) throws { + try concreteProtocol.write(value) + } + + public func write(_ value: Int64) throws { + try concreteProtocol.write(value) + } + + public func write(_ value: Double) throws { + try concreteProtocol.write(value) + } + + public func write(_ data: Data) throws { + try concreteProtocol.write(data) + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Sources/Thrift.swift b/vendor/git.apache.org/thrift.git/lib/swift/Sources/Thrift.swift new file mode 100644 index 0000000..5bd1758 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Sources/Thrift.swift @@ -0,0 +1,3 @@ +class Thrift { + let version = "1.1.0" +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Tests/LinuxMain.swift b/vendor/git.apache.org/thrift.git/lib/swift/Tests/LinuxMain.swift new file mode 100644 index 0000000..288fec9 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Tests/LinuxMain.swift @@ -0,0 +1,8 @@ +import XCTest +@testable import ThriftTests + +XCTMain([ + testCase(ThriftTests.allTests), + testCase(TBinaryProtocolTests.allTests), + testCase(TCompactProtocolTests.allTests), +]) diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Tests/ThriftTests/TBinaryProtocolTests.swift b/vendor/git.apache.org/thrift.git/lib/swift/Tests/ThriftTests/TBinaryProtocolTests.swift new file mode 100644 index 0000000..56a5572 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Tests/ThriftTests/TBinaryProtocolTests.swift @@ -0,0 +1,168 @@ +// +// TBinaryProtocolTests.swift +// Thrift +// +// Created by Christopher Simpson on 8/18/16. +// +// + +import XCTest +import Foundation +@testable import Thrift + + +/// Testing Binary protocol read/write against itself +/// Uses separate read/write transport/protocols +class TBinaryProtocolTests: XCTestCase { + var transport: TMemoryBufferTransport = TMemoryBufferTransport(flushHandler: { + $0.reset(readBuffer: $1) + }) + + var proto: TBinaryProtocol! + + override func setUp() { + super.setUp() + proto = TBinaryProtocol(on: transport) + transport.reset() + } + + override func tearDown() { + super.tearDown() + transport.reset() + } + + func testInt8WriteRead() { + let writeVal: UInt8 = 250 + try? proto.write(writeVal) + try? transport.flush() + + let readVal: UInt8 = (try? proto.read()) ?? 0 + XCTAssertEqual(writeVal, readVal, "Error with UInt8, wrote \(writeVal) but read \(readVal)") + } + + func testInt16WriteRead() { + + let writeVal: Int16 = 12312 + try? proto.write(writeVal) + try? transport.flush() + let readVal: Int16 = (try? proto.read()) ?? 0 + XCTAssertEqual(writeVal, readVal, "Error with Int16, wrote \(writeVal) but read \(readVal)") + } + + func testInt32WriteRead() { + let writeVal: Int32 = 2029234 + try? proto.write(writeVal) + try? transport.flush() + + let readVal: Int32 = (try? proto.read()) ?? 0 + XCTAssertEqual(writeVal, readVal, "Error with Int32, wrote \(writeVal) but read \(readVal)") + } + + func testInt64WriteRead() { + let writeVal: Int64 = 234234981374134 + try? proto.write(writeVal) + try? transport.flush() + + let readVal: Int64 = (try? proto.read()) ?? 0 + XCTAssertEqual(writeVal, readVal, "Error with Int64, wrote \(writeVal) but read \(readVal)") + } + + func testDoubleWriteRead() { + let writeVal: Double = 3.1415926 + try? proto.write(writeVal) + try? transport.flush() + + let readVal: Double = (try? proto.read()) ?? 0.0 + XCTAssertEqual(writeVal, readVal, "Error with Double, wrote \(writeVal) but read \(readVal)") + } + + func testBoolWriteRead() { + let writeVal: Bool = true + try? proto.write(writeVal) + try? transport.flush() + + let readVal: Bool = (try? proto.read()) ?? false + XCTAssertEqual(writeVal, readVal, "Error with Bool, wrote \(writeVal) but read \(readVal)") + } + + func testStringWriteRead() { + let writeVal: String = "Hello World" + try? proto.write(writeVal) + try? transport.flush() + + let readVal: String! + do { + readVal = try proto.read() + } catch let error { + XCTAssertFalse(true, "Error reading \(error)") + return + } + + XCTAssertEqual(writeVal, readVal, "Error with String, wrote \(writeVal) but read \(readVal)") + } + + func testDataWriteRead() { + let writeVal: Data = "Data World".data(using: .utf8)! + try? proto.write(writeVal) + try? transport.flush() + + let readVal: Data = (try? proto.read()) ?? "Goodbye World".data(using: .utf8)! + XCTAssertEqual(writeVal, readVal, "Error with Data, wrote \(writeVal) but read \(readVal)") + } + + func testStructWriteRead() { + let msg = "Test Protocol Error" + let writeVal = TApplicationError(error: .protocolError, message: msg) + do { + try writeVal.write(to: proto) + try? transport.flush() + + } catch let error { + XCTAssertFalse(true, "Caught Error attempting to write \(error)") + } + + do { + let readVal = try TApplicationError.read(from: proto) + XCTAssertEqual(readVal.error.thriftErrorCode, writeVal.error.thriftErrorCode, "Error case mismatch, expected \(readVal.error) got \(writeVal.error)") + XCTAssertEqual(readVal.message, writeVal.message, "Error message mismatch, expected \(readVal.message) got \(writeVal.message)") + } catch let error { + XCTAssertFalse(true, "Caught Error attempting to read \(error)") + } + } + func testUnsafeBitcastUpdate() { + let value: Double = 3.14159 + let val: Int64 = 31415926 + let uval: UInt64 = 31415926 + + let i64 = Int64(bitPattern: value.bitPattern) + let ubc = unsafeBitCast(value, to: Int64.self) + + XCTAssertEqual(i64, ubc, "Bitcast Double-> i64 Values don't match") + + let dbl = Double(bitPattern: UInt64(val)) + let ubdb = unsafeBitCast(val, to: Double.self) + + XCTAssertEqual(dbl, ubdb, "Bitcast i64 -> Double Values don't match") + + let db2 = Double(bitPattern: uval) + let usbc2 = unsafeBitCast(uval, to: Double.self) + + XCTAssertEqual(db2, usbc2, "Bitcast u64 -> Double Values don't match") + + + } + + static var allTests : [(String, (TBinaryProtocolTests) -> () throws -> Void)] { + return [ + ("testInt8WriteRead", testInt8WriteRead), + ("testInt16WriteRead", testInt16WriteRead), + ("testInt32WriteRead", testInt32WriteRead), + ("testInt64WriteRead", testInt64WriteRead), + ("testDoubleWriteRead", testDoubleWriteRead), + ("testBoolWriteRead", testBoolWriteRead), + ("testStringWriteRead", testStringWriteRead), + ("testDataWriteRead", testDataWriteRead), + ("testStructWriteRead", testStructWriteRead) + ] + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Tests/ThriftTests/TCompactProtocolTests.swift b/vendor/git.apache.org/thrift.git/lib/swift/Tests/ThriftTests/TCompactProtocolTests.swift new file mode 100644 index 0000000..882c260 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Tests/ThriftTests/TCompactProtocolTests.swift @@ -0,0 +1,210 @@ +// +// TCompactProtocolTests.swift +// Thrift +// +// Created by Christopher Simpson on 8/19/16. +// +// + +import XCTest +import Foundation +@testable import Thrift + + +/// Testing Binary protocol read/write against itself +/// Uses separate read/write transport/protocols +class TCompactProtocolTests: XCTestCase { + var transport: TMemoryBufferTransport = TMemoryBufferTransport(flushHandler: { + $0.reset(readBuffer: $1) + }) + var proto: TCompactProtocol! + + override func setUp() { + super.setUp() + proto = TCompactProtocol(on: transport) + transport.reset() + } + + override func tearDown() { + super.tearDown() + transport.reset() + } + + func testInt8WriteRead() { + let writeVal: UInt8 = 250 + try? proto.write(writeVal) + try? transport.flush() + let readVal: UInt8 = (try? proto.read()) ?? 0 + XCTAssertEqual(writeVal, readVal, "Error with UInt8, wrote \(writeVal) but read \(readVal)") + } + + func testInt16WriteRead() { + let writeVal: Int16 = 12312 + try? proto.write(writeVal) + try? transport.flush() + + let readVal: Int16 = (try? proto.read()) ?? 0 + XCTAssertEqual(writeVal, readVal, "Error with Int16, wrote \(writeVal) but read \(readVal)") + } + + func testInt32WriteRead() { + let writeVal: Int32 = 2029234 + try? proto.write(writeVal) + try? transport.flush() + + let readVal: Int32 = (try? proto.read()) ?? 0 + XCTAssertEqual(writeVal, readVal, "Error with Int32, wrote \(writeVal) but read \(readVal)") + } + + func testInt64WriteRead() { + let writeVal: Int64 = 234234981374134 + try? proto.write(writeVal) + try? transport.flush() + + let readVal: Int64 = (try? proto.read()) ?? 0 + XCTAssertEqual(writeVal, readVal, "Error with Int64, wrote \(writeVal) but read \(readVal)") + } + + func testDoubleWriteRead() { + let writeVal: Double = 3.1415926 + try? proto.write(writeVal) + try? transport.flush() + + let readVal: Double = (try? proto.read()) ?? 0.0 + XCTAssertEqual(writeVal, readVal, "Error with Double, wrote \(writeVal) but read \(readVal)") + } + + func testBoolWriteRead() { + let writeVal: Bool = true + try? proto.write(writeVal) + try? transport.flush() + + let readVal: Bool = (try? proto.read()) ?? false + XCTAssertEqual(writeVal, readVal, "Error with Bool, wrote \(writeVal) but read \(readVal)") + } + + func testStringWriteRead() { + let writeVal: String = "Hello World" + try? proto.write(writeVal) + try? transport.flush() + + let readVal: String! + do { + readVal = try proto.read() + } catch let error { + XCTAssertFalse(true, "Error reading \(error)") + return + } + + XCTAssertEqual(writeVal, readVal, "Error with String, wrote \(writeVal) but read \(readVal)") + } + + func testDataWriteRead() { + let writeVal: Data = "Data World".data(using: .utf8)! + try? proto.write(writeVal) + try? transport.flush() + + let readVal: Data = (try? proto.read()) ?? "Goodbye World".data(using: .utf8)! + XCTAssertEqual(writeVal, readVal, "Error with Data, wrote \(writeVal) but read \(readVal)") + } + + func testStructWriteRead() { + let msg = "Test Protocol Error" + let writeVal = TApplicationError(error: .protocolError, message: msg) + do { + try writeVal.write(to: proto) + try transport.flush() + + } catch let error { + XCTAssertFalse(true, "Caught Error attempting to write \(error)") + } + + do { + let readVal = try TApplicationError.read(from: proto) + XCTAssertEqual(readVal.error.thriftErrorCode, writeVal.error.thriftErrorCode, "Error case mismatch, expected \(readVal.error) got \(writeVal.error)") + XCTAssertEqual(readVal.message, writeVal.message, "Error message mismatch, expected \(readVal.message) got \(writeVal.message)") + } catch let error { + XCTAssertFalse(true, "Caught Error attempting to read \(error)") + } + } + + func testInt32ZigZag() { + let zero: Int32 = 0 + let one: Int32 = 1 + let nOne: Int32 = -1 + let two: Int32 = 2 + let nTwo: Int32 = -2 + let max = Int32.max + let min = Int32.min + + XCTAssertEqual(proto.i32ToZigZag(zero), UInt32(0), "Error 32bit zigzag on \(zero)") + XCTAssertEqual(proto.zigZagToi32(0), zero, "Error 32bit zigzag on \(zero)") + + XCTAssertEqual(proto.i32ToZigZag(nOne), UInt32(1), "Error 32bit zigzag on \(nOne)") + XCTAssertEqual(proto.zigZagToi32(1), nOne, "Error 32bit zigzag on \(nOne)") + + XCTAssertEqual(proto.i32ToZigZag(one), UInt32(2), "Error 32bit zigzag on \(one)") + XCTAssertEqual(proto.zigZagToi32(2), one, "Error 32bit zigzag on \(one)") + + XCTAssertEqual(proto.i32ToZigZag(nTwo), UInt32(3), "Error 32bit zigzag on \(nTwo)") + XCTAssertEqual(proto.zigZagToi32(3), nTwo, "Error 32bit zigzag on \(nTwo)") + + XCTAssertEqual(proto.i32ToZigZag(two), UInt32(4), "Error 32bit zigzag on \(two)") + XCTAssertEqual(proto.zigZagToi32(4), two, "Error 32bit zigzag on \(two)") + + let uMaxMinusOne: UInt32 = UInt32.max - 1 + XCTAssertEqual(proto.i32ToZigZag(max), uMaxMinusOne, "Error 32bit zigzag on \(max)") + XCTAssertEqual(proto.zigZagToi32(uMaxMinusOne), max, "Error 32bit zigzag on \(max)") + + XCTAssertEqual(proto.i32ToZigZag(min), UInt32.max, "Error 32bit zigzag on \(min)") + XCTAssertEqual(proto.zigZagToi32(UInt32.max), min, "Error 32bit zigzag on \(min)") + } + + func testInt64ZigZag() { + let zero: Int64 = 0 + let one: Int64 = 1 + let nOne: Int64 = -1 + let two: Int64 = 2 + let nTwo: Int64 = -2 + let max = Int64.max + let min = Int64.min + + XCTAssertEqual(proto.i64ToZigZag(zero), UInt64(0), "Error 64bit zigzag on \(zero)") + XCTAssertEqual(proto.zigZagToi64(0), zero, "Error 64bit zigzag on \(zero)") + + XCTAssertEqual(proto.i64ToZigZag(nOne), UInt64(1), "Error 64bit zigzag on \(nOne)") + XCTAssertEqual(proto.zigZagToi64(1), nOne, "Error 64bit zigzag on \(nOne)") + + XCTAssertEqual(proto.i64ToZigZag(one), UInt64(2), "Error 64bit zigzag on \(one)") + XCTAssertEqual(proto.zigZagToi64(2), one, "Error 64bit zigzag on \(one)") + + XCTAssertEqual(proto.i64ToZigZag(nTwo), UInt64(3), "Error 64bit zigzag on \(nTwo)") + XCTAssertEqual(proto.zigZagToi64(3), nTwo, "Error 64bit zigzag on \(nTwo)") + + XCTAssertEqual(proto.i64ToZigZag(two), UInt64(4), "Error 64bit zigzag on \(two)") + XCTAssertEqual(proto.zigZagToi64(4), two, "Error 64bit zigzag on \(two)") + + let uMaxMinusOne: UInt64 = UInt64.max - 1 + XCTAssertEqual(proto.i64ToZigZag(max), uMaxMinusOne, "Error 64bit zigzag on \(max)") + XCTAssertEqual(proto.zigZagToi64(uMaxMinusOne), max, "Error 64bit zigzag on \(max)") + + XCTAssertEqual(proto.i64ToZigZag(min), UInt64.max, "Error 64bit zigzag on \(min)") + XCTAssertEqual(proto.zigZagToi64(UInt64.max), min, "Error 64bit zigzag on \(min)") + } + + static var allTests : [(String, (TCompactProtocolTests) -> () throws -> Void)] { + return [ + ("testInt8WriteRead", testInt8WriteRead), + ("testInt16WriteRead", testInt16WriteRead), + ("testInt32WriteRead", testInt32WriteRead), + ("testInt64WriteRead", testInt64WriteRead), + ("testDoubleWriteRead", testDoubleWriteRead), + ("testBoolWriteRead", testBoolWriteRead), + ("testStringWriteRead", testStringWriteRead), + ("testDataWriteRead", testDataWriteRead), + ("testStructWriteRead", testStructWriteRead), + ("testInt32ZigZag", testInt32ZigZag), + ("testInt64ZigZag", testInt64ZigZag) + ] + } +} diff --git a/vendor/git.apache.org/thrift.git/lib/swift/Tests/ThriftTests/ThriftTests.swift b/vendor/git.apache.org/thrift.git/lib/swift/Tests/ThriftTests/ThriftTests.swift new file mode 100644 index 0000000..9316100 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/lib/swift/Tests/ThriftTests/ThriftTests.swift @@ -0,0 +1,18 @@ +import XCTest +@testable import Thrift + +class ThriftTests: XCTestCase { + func testVersion() { + XCTAssertEqual(Thrift().version, "1.1.0") + } + + func test_in_addr_extension() { + + } + + static var allTests : [(String, (ThriftTests) -> () throws -> Void)] { + return [ + ("testVersion", testVersion), + ] + } +} diff --git a/vendor/git.apache.org/thrift.git/package-lock.json b/vendor/git.apache.org/thrift.git/package-lock.json new file mode 100644 index 0000000..0342c15 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/package-lock.json @@ -0,0 +1,2183 @@ +{ + "name": "thrift", + "version": "0.12.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@babel/code-frame": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0.tgz", + "integrity": "sha512-OfC2uemaknXr87bdLUkWog7nYuliM9Ij5HUcajsVcMCpQrcLmtxRbVFTIqmcSkSeYRBFBRxs2FiUqFJDLdiebA==", + "dev": true, + "requires": { + "@babel/highlight": "^7.0.0" + } + }, + "@babel/highlight": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.0.0.tgz", + "integrity": "sha512-UFMC4ZeFC48Tpvj7C8UgLvtkaUuovQX+5xNWrsIoMG8o2z+XFKjKaN9iVmS84dPwVN00W4wPmqvYoZF3EGAsfw==", + "dev": true, + "requires": { + "chalk": "^2.0.0", + "esutils": "^2.0.2", + "js-tokens": "^4.0.0" + } + }, + "@types/node": { + "version": "10.12.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-10.12.6.tgz", + "integrity": "sha512-+ZWB5Ec1iki99xQFzBlivlKxSZQ+fuUKBott8StBOnLN4dWbRHlgdg1XknpW6g0tweniN5DcOqA64CJyOUPSAw==", + "dev": true + }, + "@types/q": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@types/q/-/q-1.5.1.tgz", + "integrity": "sha512-eqz8c/0kwNi/OEHQfvIuJVLTst3in0e7uTKeuY+WL/zfKn0xVujOTp42bS/vUUokhK5P2BppLd9JXMOMHcgbjA==", + "dev": true + }, + "abbrev": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.9.tgz", + "integrity": "sha1-kbR5JYinc4wl813W9jdSovh3YTU=", + "dev": true + }, + "acorn": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-6.0.2.tgz", + "integrity": "sha512-GXmKIvbrN3TV7aVqAzVFaMW8F8wzVX7voEBRO3bDA64+EX37YSayggRJP5Xig6HYHBkWKpFg9W5gg6orklubhg==", + "dev": true + }, + "acorn-jsx": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.0.0.tgz", + "integrity": "sha512-XkB50fn0MURDyww9+UYL3c1yLbOBz0ZFvrdYlGB8l+Ije1oSC75qAqrzSPjYQbdnQUzhlUGNKuesryAv0gxZOg==", + "dev": true + }, + "ajv": { + "version": "6.5.4", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.5.4.tgz", + "integrity": "sha512-4Wyjt8+t6YszqaXnLDfMmG/8AlO5Zbcsy3ATHncCzjW/NoPzAId8AK6749Ybjmdt+kUY1gP60fCu46oDxPv/mg==", + "dev": true, + "requires": { + "fast-deep-equal": "^2.0.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + } + }, + "amdefine": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/amdefine/-/amdefine-1.0.1.tgz", + "integrity": "sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU=", + "dev": true, + "optional": true + }, + "ansi-escapes": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", + "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==", + "dev": true + }, + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", + "dev": true + }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "aproba": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/aproba/-/aproba-1.2.0.tgz", + "integrity": "sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw==", + "dev": true + }, + "are-we-there-yet": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-1.1.5.tgz", + "integrity": "sha512-5hYdAkZlcG8tOLujVDTgCT+uPX0VnpAH28gWsLfzpXYm7wP6mp5Q/gYyR7YQ0cKVJcXJnl3j2kpBan13PtQf6w==", + "dev": true, + "requires": { + "delegates": "^1.0.0", + "readable-stream": "^2.0.6" + } + }, + "argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "requires": { + "sprintf-js": "~1.0.2" + } + }, + "array-union": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-1.0.2.tgz", + "integrity": "sha1-mjRBDk9OPaI96jdb5b5w8kd47Dk=", + "dev": true, + "requires": { + "array-uniq": "^1.0.1" + } + }, + "array-uniq": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", + "integrity": "sha1-r2rId6Jcx/dOBYiUdThY39sk/bY=", + "dev": true + }, + "arrify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", + "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=", + "dev": true + }, + "async": { + "version": "1.5.2", + "resolved": "http://registry.npmjs.org/async/-/async-1.5.2.tgz", + "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=", + "dev": true + }, + "async-limiter": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz", + "integrity": "sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg==" + }, + "babylon": { + "version": "7.0.0-beta.19", + "resolved": "https://registry.npmjs.org/babylon/-/babylon-7.0.0-beta.19.tgz", + "integrity": "sha512-Vg0C9s/REX6/WIXN37UKpv5ZhRi6A4pjHlpkE34+8/a6c2W1Q692n3hmc+SZG5lKRnaExLUbxtJ1SVT+KaCQ/A==", + "dev": true + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "bindings": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.3.0.tgz", + "integrity": "sha512-DpLh5EzMR2kzvX1KIlVC0VkC3iZtHKTgdtZ0a3pglBZdaQFjt5S9g9xd1lE+YvXyfd6mtCeRnrUfOLYiTMlNSw==", + "dev": true + }, + "bl": { + "version": "1.2.2", + "resolved": "http://registry.npmjs.org/bl/-/bl-1.2.2.tgz", + "integrity": "sha512-e8tQYnZodmebYDWGH7KMRvtzKXaJHx3BbilrgZCfvyLUYdKpK1t5PSPmpkny/SgiTSCnjfLW7v5rlONXVFkQEA==", + "dev": true, + "requires": { + "readable-stream": "^2.3.5", + "safe-buffer": "^5.1.1" + } + }, + "bluebird": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.2.tgz", + "integrity": "sha512-dhHTWMI7kMx5whMQntl7Vr9C6BvV10lFXDAasnqnrMYhXVCzzk6IO9Fo2L75jXHT07WrOngL1WDXOp+yYS91Yg==", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "buffer-alloc": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/buffer-alloc/-/buffer-alloc-1.2.0.tgz", + "integrity": "sha512-CFsHQgjtW1UChdXgbyJGtnm+O/uLQeZdtbDo8mfUgYXCHSM1wgrVxXm6bSyrUuErEb+4sYVGCzASBRot7zyrow==", + "dev": true, + "requires": { + "buffer-alloc-unsafe": "^1.1.0", + "buffer-fill": "^1.0.0" + } + }, + "buffer-alloc-unsafe": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/buffer-alloc-unsafe/-/buffer-alloc-unsafe-1.1.0.tgz", + "integrity": "sha512-TEM2iMIEQdJ2yjPJoSIsldnleVaAk1oW3DBVUykyOLsEsFmEc9kn+SFFPz+gl54KQNxlDnAwCXosOS9Okx2xAg==", + "dev": true + }, + "buffer-equals": { + "version": "1.0.4", + "resolved": "http://registry.npmjs.org/buffer-equals/-/buffer-equals-1.0.4.tgz", + "integrity": "sha1-A1O1T9B/2VZBcGca5vZrnPENJ/U=", + "dev": true + }, + "buffer-fill": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/buffer-fill/-/buffer-fill-1.0.0.tgz", + "integrity": "sha1-+PeLdniYiO858gXNY39o5wISKyw=", + "dev": true + }, + "caller-path": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/caller-path/-/caller-path-0.1.0.tgz", + "integrity": "sha1-lAhe9jWB7NPaqSREqP6U6CV3dR8=", + "dev": true, + "requires": { + "callsites": "^0.2.0" + } + }, + "callsites": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-0.2.0.tgz", + "integrity": "sha1-r6uWJikQp/M8GaV3WCXGnzTjUMo=", + "dev": true + }, + "catharsis": { + "version": "0.8.9", + "resolved": "https://registry.npmjs.org/catharsis/-/catharsis-0.8.9.tgz", + "integrity": "sha1-mMyJDKZS3S7w5ws3klMQ/56Q/Is=", + "dev": true, + "requires": { + "underscore-contrib": "~0.3.0" + } + }, + "chalk": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", + "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "chardet": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", + "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", + "dev": true + }, + "chownr": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.1.tgz", + "integrity": "sha512-j38EvO5+LHX84jlo6h4UzmOwi0UgW61WRyPtJz4qaadK5eY3BTS5TY/S1Stc3Uk2lIM6TPevAlULiEJwie860g==", + "dev": true + }, + "circular-json": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/circular-json/-/circular-json-0.3.3.tgz", + "integrity": "sha512-UZK3NBx2Mca+b5LsG7bY183pHWt5Y1xts4P3Pz7ENTwGVnJOUWbRb3ocjvX7hx9tq/yTAdclXm9sZ38gNuem4A==", + "dev": true + }, + "cli-cursor": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-2.1.0.tgz", + "integrity": "sha1-s12sN2R5+sw+lHR9QdDQ9SOP/LU=", + "dev": true, + "requires": { + "restore-cursor": "^2.0.0" + } + }, + "cli-width": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-2.2.0.tgz", + "integrity": "sha1-/xnt6Kml5XkyQUewwR8PvLq+1jk=", + "dev": true + }, + "code-point-at": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz", + "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=", + "dev": true + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", + "dev": true + }, + "commander": { + "version": "2.19.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", + "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==", + "dev": true + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "connect": { + "version": "3.6.6", + "resolved": "https://registry.npmjs.org/connect/-/connect-3.6.6.tgz", + "integrity": "sha1-Ce/2xVr3I24TcTWnJXSFi2eG9SQ=", + "dev": true, + "requires": { + "debug": "2.6.9", + "finalhandler": "1.1.0", + "parseurl": "~1.3.2", + "utils-merge": "1.0.1" + } + }, + "console-control-strings": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", + "integrity": "sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=", + "dev": true + }, + "core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", + "dev": true + }, + "cross-spawn": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", + "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", + "dev": true, + "requires": { + "nice-try": "^1.0.4", + "path-key": "^2.0.1", + "semver": "^5.5.0", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + } + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "decompress-response": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-3.3.0.tgz", + "integrity": "sha1-gKTdMjdIOEv6JICDYirt7Jgq3/M=", + "dev": true, + "requires": { + "mimic-response": "^1.0.0" + } + }, + "deep-equal": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.0.1.tgz", + "integrity": "sha1-9dJgKStmDghO/0zbyfCK0yR0SLU=", + "dev": true + }, + "deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "dev": true + }, + "deep-is": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", + "dev": true + }, + "define-properties": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", + "integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", + "dev": true, + "requires": { + "object-keys": "^1.0.12" + } + }, + "defined": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/defined/-/defined-1.0.0.tgz", + "integrity": "sha1-yY2bzvdWdBiOEQlpFRGZ45sfppM=", + "dev": true + }, + "del": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/del/-/del-2.2.2.tgz", + "integrity": "sha1-wSyYHQZ4RshLyvhiz/kw2Qf/0ag=", + "dev": true, + "requires": { + "globby": "^5.0.0", + "is-path-cwd": "^1.0.0", + "is-path-in-cwd": "^1.0.0", + "object-assign": "^4.0.1", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0", + "rimraf": "^2.2.8" + } + }, + "delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=", + "dev": true + }, + "detect-libc": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-1.0.3.tgz", + "integrity": "sha1-+hN8S9aY7fVc1c0CrFWfkaTEups=", + "dev": true + }, + "doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "requires": { + "esutils": "^2.0.2" + } + }, + "ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=", + "dev": true + }, + "encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=", + "dev": true + }, + "end-of-stream": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.1.tgz", + "integrity": "sha512-1MkrZNvWTKCaigbn+W15elq2BB/L22nqrSY5DKlo3X6+vclJm8Bb5djXJBmEX6fS3+zCh/F4VBK5Z2KxJt4s2Q==", + "dev": true, + "requires": { + "once": "^1.4.0" + } + }, + "es-abstract": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.12.0.tgz", + "integrity": "sha512-C8Fx/0jFmV5IPoMOFPA9P9G5NtqW+4cOPit3MIuvR2t7Ag2K15EJTpxnHAYTzL+aYQJIESYeXZmDBfOBE1HcpA==", + "dev": true, + "requires": { + "es-to-primitive": "^1.1.1", + "function-bind": "^1.1.1", + "has": "^1.0.1", + "is-callable": "^1.1.3", + "is-regex": "^1.0.4" + } + }, + "es-to-primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.0.tgz", + "integrity": "sha512-qZryBOJjV//LaxLTV6UC//WewneB3LcXOL9NP++ozKVXsIIIpm/2c13UDiD9Jp2eThsecw9m3jPqDwTyobcdbg==", + "dev": true, + "requires": { + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" + } + }, + "escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=", + "dev": true + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "escodegen": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.8.1.tgz", + "integrity": "sha1-WltTr0aTEQvrsIZ6o0MN07cKEBg=", + "dev": true, + "requires": { + "esprima": "^2.7.1", + "estraverse": "^1.9.1", + "esutils": "^2.0.2", + "optionator": "^0.8.1", + "source-map": "~0.2.0" + }, + "dependencies": { + "esprima": { + "version": "2.7.3", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-2.7.3.tgz", + "integrity": "sha1-luO3DVd59q1JzQMmc9HDEnZ7pYE=", + "dev": true + }, + "estraverse": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-1.9.3.tgz", + "integrity": "sha1-r2fy3JIlgkFZUJJgkaQAXSnJu0Q=", + "dev": true + } + } + }, + "eslint": { + "version": "5.7.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-5.7.0.tgz", + "integrity": "sha512-zYCeFQahsxffGl87U2aJ7DPyH8CbWgxBC213Y8+TCanhUTf2gEvfq3EKpHmEcozTLyPmGe9LZdMAwC/CpJBM5A==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.0.0", + "ajv": "^6.5.3", + "chalk": "^2.1.0", + "cross-spawn": "^6.0.5", + "debug": "^4.0.1", + "doctrine": "^2.1.0", + "eslint-scope": "^4.0.0", + "eslint-utils": "^1.3.1", + "eslint-visitor-keys": "^1.0.0", + "espree": "^4.0.0", + "esquery": "^1.0.1", + "esutils": "^2.0.2", + "file-entry-cache": "^2.0.0", + "functional-red-black-tree": "^1.0.1", + "glob": "^7.1.2", + "globals": "^11.7.0", + "ignore": "^4.0.6", + "imurmurhash": "^0.1.4", + "inquirer": "^6.1.0", + "is-resolvable": "^1.1.0", + "js-yaml": "^3.12.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "levn": "^0.3.0", + "lodash": "^4.17.5", + "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", + "natural-compare": "^1.4.0", + "optionator": "^0.8.2", + "path-is-inside": "^1.0.2", + "pluralize": "^7.0.0", + "progress": "^2.0.0", + "regexpp": "^2.0.1", + "require-uncached": "^1.0.3", + "semver": "^5.5.1", + "strip-ansi": "^4.0.0", + "strip-json-comments": "^2.0.1", + "table": "^5.0.2", + "text-table": "^0.2.0" + }, + "dependencies": { + "debug": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.0.tgz", + "integrity": "sha512-heNPJUJIqC+xB6ayLAMHaIrmN9HKa7aQO8MGqKpvCA+uJYVcvR6l5kgdrhRuwPFHU7P5/A1w0BjByPHwpfTDKg==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", + "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", + "dev": true + } + } + }, + "eslint-config-prettier": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-3.1.0.tgz", + "integrity": "sha512-QYGfmzuc4q4J6XIhlp8vRKdI/fI0tQfQPy1dME3UOLprE+v4ssH/3W9LM2Q7h5qBcy5m0ehCrBDU2YF8q6OY8w==", + "dev": true, + "requires": { + "get-stdin": "^6.0.0" + } + }, + "eslint-plugin-prettier": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-3.0.0.tgz", + "integrity": "sha512-4g11opzhqq/8+AMmo5Vc2Gn7z9alZ4JqrbZ+D4i8KlSyxeQhZHlmIrY8U9Akf514MoEhogPa87Jgkq87aZ2Ohw==", + "dev": true, + "requires": { + "prettier-linter-helpers": "^1.0.0" + } + }, + "eslint-scope": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-4.0.0.tgz", + "integrity": "sha512-1G6UTDi7Jc1ELFwnR58HV4fK9OQK4S6N985f166xqXxpjU6plxFISJa2Ba9KCQuFa8RCnj/lSFJbHo7UFDBnUA==", + "dev": true, + "requires": { + "esrecurse": "^4.1.0", + "estraverse": "^4.1.1" + } + }, + "eslint-utils": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-1.3.1.tgz", + "integrity": "sha512-Z7YjnIldX+2XMcjr7ZkgEsOj/bREONV60qYeB/bjMAqqqZ4zxKyWX+BOUkdmRmA9riiIPVvo5x86m5elviOk0Q==", + "dev": true + }, + "eslint-visitor-keys": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz", + "integrity": "sha512-qzm/XxIbxm/FHyH341ZrbnMUpe+5Bocte9xkmFMzPMjRaZMcXww+MpBptFvtU+79L362nqiLhekCxCxDPaUMBQ==", + "dev": true + }, + "espree": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-4.1.0.tgz", + "integrity": "sha512-I5BycZW6FCVIub93TeVY1s7vjhP9CY6cXCznIRfiig7nRviKZYdRnj/sHEWC6A7WE9RDWOFq9+7OsWSYz8qv2w==", + "dev": true, + "requires": { + "acorn": "^6.0.2", + "acorn-jsx": "^5.0.0", + "eslint-visitor-keys": "^1.0.0" + } + }, + "esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true + }, + "esquery": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.0.1.tgz", + "integrity": "sha512-SmiyZ5zIWH9VM+SRUReLS5Q8a7GxtRdxEBVZpm98rJM7Sb+A9DVCndXfkeFUd3byderg+EbDkfnevfCwynWaNA==", + "dev": true, + "requires": { + "estraverse": "^4.0.0" + } + }, + "esrecurse": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.1.tgz", + "integrity": "sha512-64RBB++fIOAXPw3P9cy89qfMlvZEXZkqqJkjqqXIvzP5ezRZjW+lPWjw35UX/3EhUPFYbg5ER4JYgDw4007/DQ==", + "dev": true, + "requires": { + "estraverse": "^4.1.0" + } + }, + "estraverse": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", + "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=", + "dev": true + }, + "esutils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", + "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", + "dev": true + }, + "expand-template": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-1.1.1.tgz", + "integrity": "sha512-cebqLtV8KOZfw0UI8TEFWxtczxxC1jvyUvx6H4fyp1K1FN7A4Q+uggVUlOsI1K8AGU0rwOGqP8nCapdrw8CYQg==", + "dev": true + }, + "external-editor": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.0.3.tgz", + "integrity": "sha512-bn71H9+qWoOQKyZDo25mOMVpSmXROAsTJVVVYzrrtol3d4y+AsKjf4Iwl2Q+IuT0kFSQ1qo166UuIwqYq7mGnA==", + "dev": true, + "requires": { + "chardet": "^0.7.0", + "iconv-lite": "^0.4.24", + "tmp": "^0.0.33" + } + }, + "fast-deep-equal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", + "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=", + "dev": true + }, + "fast-diff": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.2.0.tgz", + "integrity": "sha512-xJuoT5+L99XlZ8twedaRf6Ax2TgQVxvgZOYoPKqZufmJib0tL2tegPBOZb1pVNgIhlqDlA0eO0c3wBvQcmzx4w==", + "dev": true + }, + "fast-json-stable-stringify": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz", + "integrity": "sha1-1RQsDK7msRifh9OnYREGT4bIu/I=", + "dev": true + }, + "fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", + "dev": true + }, + "figures": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", + "integrity": "sha1-OrGi0qYsi/tDGgyUy3l6L84nyWI=", + "dev": true, + "requires": { + "escape-string-regexp": "^1.0.5" + } + }, + "file-entry-cache": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-2.0.0.tgz", + "integrity": "sha1-w5KZDD5oR4PYOLjISkXYoEhFg2E=", + "dev": true, + "requires": { + "flat-cache": "^1.2.1", + "object-assign": "^4.0.1" + } + }, + "finalhandler": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.0.tgz", + "integrity": "sha1-zgtoVbRYU+eRsvzGgARtiCU91/U=", + "dev": true, + "requires": { + "debug": "2.6.9", + "encodeurl": "~1.0.1", + "escape-html": "~1.0.3", + "on-finished": "~2.3.0", + "parseurl": "~1.3.2", + "statuses": "~1.3.1", + "unpipe": "~1.0.0" + } + }, + "flat-cache": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-1.3.0.tgz", + "integrity": "sha1-0wMLMrOBVPTjt+nHCfSQ9++XxIE=", + "dev": true, + "requires": { + "circular-json": "^0.3.1", + "del": "^2.0.2", + "graceful-fs": "^4.1.2", + "write": "^0.2.1" + } + }, + "for-each": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz", + "integrity": "sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==", + "dev": true, + "requires": { + "is-callable": "^1.1.3" + } + }, + "fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "dev": true + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "dev": true + }, + "functional-red-black-tree": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", + "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=", + "dev": true + }, + "gauge": { + "version": "2.7.4", + "resolved": "https://registry.npmjs.org/gauge/-/gauge-2.7.4.tgz", + "integrity": "sha1-LANAXHU4w51+s3sxcCLjJfsBi/c=", + "dev": true, + "requires": { + "aproba": "^1.0.3", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.0", + "object-assign": "^4.1.0", + "signal-exit": "^3.0.0", + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wide-align": "^1.1.0" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", + "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", + "dev": true, + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "string-width": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", + "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", + "dev": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + } + } + }, + "get-stdin": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-6.0.0.tgz", + "integrity": "sha512-jp4tHawyV7+fkkSKyvjuLZswblUtz+SQKzSWnBbii16BuZksJlU1wuBYXY75r+duh/llF1ur6oNwi+2ZzjKZ7g==", + "dev": true + }, + "github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha1-l/tdlr/eiXMxPyDoKI75oWf6ZM4=", + "dev": true + }, + "glob": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.3.tgz", + "integrity": "sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "globals": { + "version": "11.8.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.8.0.tgz", + "integrity": "sha512-io6LkyPVuzCHBSQV9fmOwxZkUk6nIaGmxheLDgmuFv89j0fm2aqDbIXKAGfzCMHqz3HLF2Zf8WSG6VqMh2qFmA==", + "dev": true + }, + "globby": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-5.0.0.tgz", + "integrity": "sha1-69hGZ8oNuzMLmbz8aOrCvFQ3Dg0=", + "dev": true, + "requires": { + "array-union": "^1.0.1", + "arrify": "^1.0.0", + "glob": "^7.0.3", + "object-assign": "^4.0.1", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0" + } + }, + "graceful-fs": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", + "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", + "dev": true + }, + "handlebars": { + "version": "4.0.12", + "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.0.12.tgz", + "integrity": "sha512-RhmTekP+FZL+XNhwS1Wf+bTTZpdLougwt5pcgA1tuz6Jcx0fpH/7z0qd71RKnZHBCxIRBHfBOnio4gViPemNzA==", + "dev": true, + "requires": { + "async": "^2.5.0", + "optimist": "^0.6.1", + "source-map": "^0.6.1", + "uglify-js": "^3.1.4" + }, + "dependencies": { + "async": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.1.tgz", + "integrity": "sha512-fNEiL2+AZt6AlAw/29Cr0UDe4sRAHCpEHh54WMz+Bb7QfNcFw4h3loofyJpLeQs4Yx7yuqu/2dLgM5hKOs6HlQ==", + "dev": true, + "requires": { + "lodash": "^4.17.10" + } + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1" + } + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "dev": true + }, + "has-symbols": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.0.tgz", + "integrity": "sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q=", + "dev": true + }, + "has-unicode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", + "integrity": "sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk=", + "dev": true + }, + "iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dev": true, + "requires": { + "safer-buffer": ">= 2.1.2 < 3" + } + }, + "ignore": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", + "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", + "dev": true + }, + "imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "ini": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.5.tgz", + "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==", + "dev": true + }, + "inquirer": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.0.tgz", + "integrity": "sha512-QIEQG4YyQ2UYZGDC4srMZ7BjHOmNk1lR2JQj5UknBapklm6WHA+VVH7N+sUdX3A7NeCfGF8o4X1S3Ao7nAcIeg==", + "dev": true, + "requires": { + "ansi-escapes": "^3.0.0", + "chalk": "^2.0.0", + "cli-cursor": "^2.1.0", + "cli-width": "^2.0.0", + "external-editor": "^3.0.0", + "figures": "^2.0.0", + "lodash": "^4.17.10", + "mute-stream": "0.0.7", + "run-async": "^2.2.0", + "rxjs": "^6.1.0", + "string-width": "^2.1.0", + "strip-ansi": "^4.0.0", + "through": "^2.3.6" + } + }, + "is-callable": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.4.tgz", + "integrity": "sha512-r5p9sxJjYnArLjObpjA4xu5EKI3CuKHkJXMhT7kwbpUyIFD1n5PMAsoPvWnvtZiNz7LjkYDRZhd7FlI0eMijEA==", + "dev": true + }, + "is-date-object": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.1.tgz", + "integrity": "sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY=", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", + "dev": true + }, + "is-path-cwd": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-path-cwd/-/is-path-cwd-1.0.0.tgz", + "integrity": "sha1-0iXsIxMuie3Tj9p2dHLmLmXxEG0=", + "dev": true + }, + "is-path-in-cwd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-path-in-cwd/-/is-path-in-cwd-1.0.1.tgz", + "integrity": "sha512-FjV1RTW48E7CWM7eE/J2NJvAEEVektecDBVBE5Hh3nM1Jd0kvhHtX68Pr3xsDf857xt3Y4AkwVULK1Vku62aaQ==", + "dev": true, + "requires": { + "is-path-inside": "^1.0.0" + } + }, + "is-path-inside": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-1.0.1.tgz", + "integrity": "sha1-jvW33lBDej/cprToZe96pVy0gDY=", + "dev": true, + "requires": { + "path-is-inside": "^1.0.1" + } + }, + "is-promise": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz", + "integrity": "sha1-eaKp7OfwlugPNtKy87wWwf9L8/o=", + "dev": true + }, + "is-regex": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.4.tgz", + "integrity": "sha1-VRdIm1RwkbCTDglWVM7SXul+lJE=", + "dev": true, + "requires": { + "has": "^1.0.1" + } + }, + "is-resolvable": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-resolvable/-/is-resolvable-1.1.0.tgz", + "integrity": "sha512-qgDYXFSR5WvEfuS5dMj6oTMEbrrSaM0CrFk2Yiq/gXnBvD9pMa2jGXxyhGLfvhZpuMZe18CJpFxAt3CRs42NMg==", + "dev": true + }, + "is-symbol": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.2.tgz", + "integrity": "sha512-HS8bZ9ox60yCJLH9snBpIwv9pYUAkcuLhSA1oero1UB5y9aiQpRA8y2ex945AOtCZL1lJDeIk3G5LthswI46Lw==", + "dev": true, + "requires": { + "has-symbols": "^1.0.0" + } + }, + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", + "dev": true + }, + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", + "dev": true + }, + "istanbul": { + "version": "0.4.5", + "resolved": "https://registry.npmjs.org/istanbul/-/istanbul-0.4.5.tgz", + "integrity": "sha1-ZcfXPUxNqE1POsMQuRj7C4Azczs=", + "dev": true, + "requires": { + "abbrev": "1.0.x", + "async": "1.x", + "escodegen": "1.8.x", + "esprima": "2.7.x", + "glob": "^5.0.15", + "handlebars": "^4.0.1", + "js-yaml": "3.x", + "mkdirp": "0.5.x", + "nopt": "3.x", + "once": "1.x", + "resolve": "1.1.x", + "supports-color": "^3.1.0", + "which": "^1.1.1", + "wordwrap": "^1.0.0" + }, + "dependencies": { + "esprima": { + "version": "2.7.3", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-2.7.3.tgz", + "integrity": "sha1-luO3DVd59q1JzQMmc9HDEnZ7pYE=", + "dev": true + }, + "glob": { + "version": "5.0.15", + "resolved": "https://registry.npmjs.org/glob/-/glob-5.0.15.tgz", + "integrity": "sha1-G8k2ueAvSmA/zCIuz3Yz0wuLk7E=", + "dev": true, + "requires": { + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "2 || 3", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=", + "dev": true + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "dev": true, + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true + }, + "js-yaml": { + "version": "3.12.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", + "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "dev": true, + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + } + }, + "js2xmlparser": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/js2xmlparser/-/js2xmlparser-3.0.0.tgz", + "integrity": "sha1-P7YOqgicVED5MZ9RdgzNB+JJlzM=", + "dev": true, + "requires": { + "xmlcreate": "^1.0.1" + } + }, + "jsdoc": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/jsdoc/-/jsdoc-3.5.5.tgz", + "integrity": "sha512-6PxB65TAU4WO0Wzyr/4/YhlGovXl0EVYfpKbpSroSj0qBxT4/xod/l40Opkm38dRHRdQgdeY836M0uVnJQG7kg==", + "dev": true, + "requires": { + "babylon": "7.0.0-beta.19", + "bluebird": "~3.5.0", + "catharsis": "~0.8.9", + "escape-string-regexp": "~1.0.5", + "js2xmlparser": "~3.0.0", + "klaw": "~2.0.0", + "marked": "~0.3.6", + "mkdirp": "~0.5.1", + "requizzle": "~0.2.1", + "strip-json-comments": "~2.0.1", + "taffydb": "2.6.2", + "underscore": "~1.8.3" + } + }, + "json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true + }, + "json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=", + "dev": true + }, + "klaw": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/klaw/-/klaw-2.0.0.tgz", + "integrity": "sha1-WcEo4Nxc5BAgEVEZTuucv4WGUPY=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.9" + } + }, + "levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "dev": true, + "requires": { + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2" + } + }, + "lodash": { + "version": "4.17.11", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", + "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==", + "dev": true + }, + "marked": { + "version": "0.3.19", + "resolved": "http://registry.npmjs.org/marked/-/marked-0.3.19.tgz", + "integrity": "sha512-ea2eGWOqNxPcXv8dyERdSr/6FmzvWwzjMxpfGB/sbMccXoct+xY+YukPD+QTUZwyvK7BZwcr4m21WBOW41pAkg==", + "dev": true + }, + "mimic-fn": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz", + "integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==", + "dev": true + }, + "mimic-response": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz", + "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==", + "dev": true + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "0.0.8", + "resolved": "http://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "dev": true + }, + "mkdirp": { + "version": "0.5.1", + "resolved": "http://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "dev": true, + "requires": { + "minimist": "0.0.8" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "mute-stream": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.7.tgz", + "integrity": "sha1-MHXOk7whuPq0PhvE2n6BFe0ee6s=", + "dev": true + }, + "nan": { + "version": "2.10.0", + "resolved": "http://registry.npmjs.org/nan/-/nan-2.10.0.tgz", + "integrity": "sha512-bAdJv7fBLhWC+/Bls0Oza+mvTaNQtP+1RyhhhvD95pgUJz6XM5IzgmxOkItJ9tkoCiplvAnXI1tNmmUD/eScyA==", + "dev": true + }, + "natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", + "dev": true + }, + "nice-try": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", + "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==", + "dev": true + }, + "node-abi": { + "version": "2.4.5", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-2.4.5.tgz", + "integrity": "sha512-aa/UC6Nr3+tqhHGRsAuw/edz7/q9nnetBrKWxj6rpTtm+0X9T1qU7lIEHMS3yN9JwAbRiKUbRRFy1PLz/y3aaA==", + "dev": true, + "requires": { + "semver": "^5.4.1" + } + }, + "node-int64": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", + "integrity": "sha1-h6kGXNs1XTGC2PlM4RGIuCXGijs=" + }, + "noop-logger": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/noop-logger/-/noop-logger-0.1.1.tgz", + "integrity": "sha1-lKKxYzxPExdVMAfYlm/Q6EG2pMI=", + "dev": true + }, + "nopt": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-3.0.6.tgz", + "integrity": "sha1-xkZdvwirzU2zWTF/eaxopkayj/k=", + "dev": true, + "requires": { + "abbrev": "1" + } + }, + "npmlog": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-4.1.2.tgz", + "integrity": "sha512-2uUqazuKlTaSI/dC8AzicUck7+IrEaOnN/e0jd3Xtt1KcGpwx30v50mL7oPyr/h9bL3E4aZccVwpwP+5W9Vjkg==", + "dev": true, + "requires": { + "are-we-there-yet": "~1.1.2", + "console-control-strings": "~1.1.0", + "gauge": "~2.7.3", + "set-blocking": "~2.0.0" + } + }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", + "dev": true + }, + "object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", + "dev": true + }, + "object-inspect": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.6.0.tgz", + "integrity": "sha512-GJzfBZ6DgDAmnuaM3104jR4s1Myxr3Y3zfIyN4z3UdqN69oSRacNK8UhnobDdC+7J2AHCjGwxQubNJfE70SXXQ==", + "dev": true + }, + "object-keys": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.0.12.tgz", + "integrity": "sha512-FTMyFUm2wBcGHnH2eXmz7tC6IwlqQZ6mVZ+6dm6vZ4IQIHjs6FdNsQBuKGPuUUUY6NfJw2PshC08Tn6LzLDOag==", + "dev": true + }, + "on-finished": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", + "dev": true, + "requires": { + "ee-first": "1.1.1" + } + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "onetime": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-2.0.1.tgz", + "integrity": "sha1-BnQoIw/WdEOyeUsiu6UotoZ5YtQ=", + "dev": true, + "requires": { + "mimic-fn": "^1.0.0" + } + }, + "optimist": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/optimist/-/optimist-0.6.1.tgz", + "integrity": "sha1-2j6nRob6IaGaERwybpDrFaAZZoY=", + "dev": true, + "requires": { + "minimist": "~0.0.1", + "wordwrap": "~0.0.2" + }, + "dependencies": { + "wordwrap": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.3.tgz", + "integrity": "sha1-o9XabNXAvAAI03I0u68b7WMFkQc=", + "dev": true + } + } + }, + "optionator": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz", + "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", + "dev": true, + "requires": { + "deep-is": "~0.1.3", + "fast-levenshtein": "~2.0.4", + "levn": "~0.3.0", + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2", + "wordwrap": "~1.0.0" + } + }, + "os-homedir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", + "integrity": "sha1-/7xJiDNuDoM94MFox+8VISGqf7M=", + "dev": true + }, + "os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", + "dev": true + }, + "parseurl": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.2.tgz", + "integrity": "sha1-/CidTtiZMRlGDBViUyYs3I3mW/M=", + "dev": true + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "path-is-inside": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/path-is-inside/-/path-is-inside-1.0.2.tgz", + "integrity": "sha1-NlQX3t5EQw0cEa9hAn+s8HS9/FM=", + "dev": true + }, + "path-key": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", + "dev": true + }, + "path-parse": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", + "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==", + "dev": true + }, + "pify": { + "version": "2.3.0", + "resolved": "http://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", + "dev": true + }, + "pinkie": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", + "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=", + "dev": true + }, + "pinkie-promise": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", + "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", + "dev": true, + "requires": { + "pinkie": "^2.0.0" + } + }, + "pluralize": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-7.0.0.tgz", + "integrity": "sha512-ARhBOdzS3e41FbkW/XWrTEtukqqLoK5+Z/4UeDaLuSW+39JPeFgs4gCGqsrJHVZX0fUrx//4OF0K1CUGwlIFow==", + "dev": true + }, + "prebuild-install": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-4.0.0.tgz", + "integrity": "sha512-7tayxeYboJX0RbVzdnKyGl2vhQRWr6qfClEXDhOkXjuaOKCw2q8aiuFhONRYVsG/czia7KhpykIlI2S2VaPunA==", + "dev": true, + "requires": { + "detect-libc": "^1.0.3", + "expand-template": "^1.0.2", + "github-from-package": "0.0.0", + "minimist": "^1.2.0", + "mkdirp": "^0.5.1", + "node-abi": "^2.2.0", + "noop-logger": "^0.1.1", + "npmlog": "^4.0.1", + "os-homedir": "^1.0.1", + "pump": "^2.0.1", + "rc": "^1.1.6", + "simple-get": "^2.7.0", + "tar-fs": "^1.13.0", + "tunnel-agent": "^0.6.0", + "which-pm-runs": "^1.0.0" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "resolved": "http://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", + "dev": true + } + } + }, + "prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", + "dev": true + }, + "prettier": { + "version": "1.14.3", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.14.3.tgz", + "integrity": "sha512-qZDVnCrnpsRJJq5nSsiHCE3BYMED2OtsI+cmzIzF1QIfqm5ALf8tEJcO27zV1gKNKRPdhjO0dNWnrzssDQ1tFg==", + "dev": true + }, + "prettier-linter-helpers": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz", + "integrity": "sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w==", + "dev": true, + "requires": { + "fast-diff": "^1.1.2" + } + }, + "process-nextick-args": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.0.tgz", + "integrity": "sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==", + "dev": true + }, + "progress": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.1.tgz", + "integrity": "sha512-OE+a6vzqazc+K6LxJrX5UPyKFvGnL5CYmq2jFGNIBWHpc4QyE49/YOumcrpQFJpfejmvRtbJzgO1zPmMCqlbBg==", + "dev": true + }, + "pump": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pump/-/pump-2.0.1.tgz", + "integrity": "sha512-ruPMNRkN3MHP1cWJc9OWr+T/xDP0jhXYCLfJcBuX54hhfIBnaQmAUMfDcG4DM5UMWByBbJY69QSphm3jtDKIkA==", + "dev": true, + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "dev": true + }, + "q": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/q/-/q-1.5.1.tgz", + "integrity": "sha1-fjL3W0E4EpHQRhHxvxQQmsAGUdc=" + }, + "rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "dev": true, + "requires": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "resolved": "http://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", + "dev": true + } + } + }, + "readable-stream": { + "version": "2.3.6", + "resolved": "http://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", + "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "regexpp": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-2.0.1.tgz", + "integrity": "sha512-lv0M6+TkDVniA3aD1Eg0DVpfU/booSu7Eev3TDO/mZKHBfVjgCGTV4t4buppESEYDtkArYFOxTJWv6S5C+iaNw==", + "dev": true + }, + "require-uncached": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/require-uncached/-/require-uncached-1.0.3.tgz", + "integrity": "sha1-Tg1W1slmL9MeQwEcS5WqSZVUIdM=", + "dev": true, + "requires": { + "caller-path": "^0.1.0", + "resolve-from": "^1.0.0" + } + }, + "requizzle": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/requizzle/-/requizzle-0.2.1.tgz", + "integrity": "sha1-aUPDUwxNmn5G8c3dUcFY/GcM294=", + "dev": true, + "requires": { + "underscore": "~1.6.0" + }, + "dependencies": { + "underscore": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.6.0.tgz", + "integrity": "sha1-izixDKze9jM3uLJOT/htRa6lKag=", + "dev": true + } + } + }, + "resolve": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.1.7.tgz", + "integrity": "sha1-IDEU2CrSxe2ejgQRs5ModeiJ6Xs=", + "dev": true + }, + "resolve-from": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-1.0.1.tgz", + "integrity": "sha1-Jsv+k10a7uq7Kbw/5a6wHpPUQiY=", + "dev": true + }, + "restore-cursor": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-2.0.0.tgz", + "integrity": "sha1-n37ih/gv0ybU/RYpI9YhKe7g368=", + "dev": true, + "requires": { + "onetime": "^2.0.0", + "signal-exit": "^3.0.2" + } + }, + "resumer": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/resumer/-/resumer-0.0.0.tgz", + "integrity": "sha1-8ej0YeQGS6Oegq883CqMiT0HZ1k=", + "dev": true, + "requires": { + "through": "~2.3.4" + } + }, + "rimraf": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.2.tgz", + "integrity": "sha512-lreewLK/BlghmxtfH36YYVg1i8IAce4TI7oao75I1g245+6BctqTVQiBP3YUJ9C6DQOXJmkYR9X9fCLtCOJc5w==", + "dev": true, + "requires": { + "glob": "^7.0.5" + } + }, + "run-async": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.3.0.tgz", + "integrity": "sha1-A3GrSuC91yDUFm19/aZP96RFpsA=", + "dev": true, + "requires": { + "is-promise": "^2.1.0" + } + }, + "rxjs": { + "version": "6.3.3", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", + "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", + "dev": true, + "requires": { + "tslib": "^1.9.0" + } + }, + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true + }, + "safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true + }, + "semver": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.6.0.tgz", + "integrity": "sha512-RS9R6R35NYgQn++fkDWaOmqGoj4Ek9gGs+DPxNUZKuwE183xjJroKvyo1IzVFeXvUrvmALy6FWD5xrdJT25gMg==", + "dev": true + }, + "set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", + "dev": true + }, + "shebang-command": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", + "dev": true, + "requires": { + "shebang-regex": "^1.0.0" + } + }, + "shebang-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", + "dev": true + }, + "signal-exit": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", + "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=", + "dev": true + }, + "simple-concat": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.0.tgz", + "integrity": "sha1-c0TLuLbib7J9ZrL8hvn21Zl1IcY=", + "dev": true + }, + "simple-get": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-2.8.1.tgz", + "integrity": "sha512-lSSHRSw3mQNUGPAYRqo7xy9dhKmxFXIjLjp4KHpf99GEH2VH7C3AM+Qfx6du6jhfUi6Vm7XnbEVEf7Wb6N8jRw==", + "dev": true, + "requires": { + "decompress-response": "^3.3.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "slice-ansi": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-1.0.0.tgz", + "integrity": "sha512-POqxBK6Lb3q6s047D/XsDVNPnF9Dl8JSaqe9h9lURl0OdNqy/ujDrOiIHtsqXMGbWWTIomRzAMaTyawAU//Reg==", + "dev": true, + "requires": { + "is-fullwidth-code-point": "^2.0.0" + } + }, + "source-map": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.2.0.tgz", + "integrity": "sha1-2rc/vPwrqBm03gO9b26qSBZLP50=", + "dev": true, + "optional": true, + "requires": { + "amdefine": ">=0.0.4" + } + }, + "sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", + "dev": true + }, + "statuses": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.3.1.tgz", + "integrity": "sha1-+vUbnrdKrvOzrPStX2Gr8ky3uT4=", + "dev": true + }, + "string-width": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", + "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", + "dev": true, + "requires": { + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^4.0.0" + } + }, + "string.prototype.trim": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.1.2.tgz", + "integrity": "sha1-0E3iyJ4Tf019IG8Ia17S+ua+jOo=", + "dev": true, + "requires": { + "define-properties": "^1.1.2", + "es-abstract": "^1.5.0", + "function-bind": "^1.0.2" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } + }, + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "dev": true, + "requires": { + "ansi-regex": "^3.0.0" + } + }, + "strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=", + "dev": true + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + }, + "table": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/table/-/table-5.1.0.tgz", + "integrity": "sha512-e542in22ZLhD/fOIuXs/8yDZ9W61ltF8daM88rkRNtgTIct+vI2fTnAyu/Db2TCfEcI8i7mjZz6meLq0nW7TYg==", + "dev": true, + "requires": { + "ajv": "^6.5.3", + "lodash": "^4.17.10", + "slice-ansi": "1.0.0", + "string-width": "^2.1.1" + } + }, + "taffydb": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/taffydb/-/taffydb-2.6.2.tgz", + "integrity": "sha1-fLy2S1oUG2ou/CxdLGe04VCyomg=", + "dev": true + }, + "tape": { + "version": "4.9.1", + "resolved": "https://registry.npmjs.org/tape/-/tape-4.9.1.tgz", + "integrity": "sha512-6fKIXknLpoe/Jp4rzHKFPpJUHDHDqn8jus99IfPnHIjyz78HYlefTGD3b5EkbQzuLfaEvmfPK3IolLgq2xT3kw==", + "dev": true, + "requires": { + "deep-equal": "~1.0.1", + "defined": "~1.0.0", + "for-each": "~0.3.3", + "function-bind": "~1.1.1", + "glob": "~7.1.2", + "has": "~1.0.3", + "inherits": "~2.0.3", + "minimist": "~1.2.0", + "object-inspect": "~1.6.0", + "resolve": "~1.7.1", + "resumer": "~0.0.0", + "string.prototype.trim": "~1.1.2", + "through": "~2.3.8" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "resolved": "http://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", + "dev": true + }, + "resolve": { + "version": "1.7.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.7.1.tgz", + "integrity": "sha512-c7rwLofp8g1U+h1KNyHL/jicrKg1Ek4q+Lr33AL65uZTinUZHe30D5HlyN5V9NW0JX1D5dXQ4jqW5l7Sy/kGfw==", + "dev": true, + "requires": { + "path-parse": "^1.0.5" + } + } + } + }, + "tar-fs": { + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-1.16.3.tgz", + "integrity": "sha512-NvCeXpYx7OsmOh8zIOP/ebG55zZmxLE0etfWRbWok+q2Qo8x/vOR/IJT1taADXPe+jsiu9axDb3X4B+iIgNlKw==", + "dev": true, + "requires": { + "chownr": "^1.0.1", + "mkdirp": "^0.5.1", + "pump": "^1.0.0", + "tar-stream": "^1.1.2" + }, + "dependencies": { + "pump": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/pump/-/pump-1.0.3.tgz", + "integrity": "sha512-8k0JupWme55+9tCVE+FS5ULT3K6AbgqrGa58lTT49RpyfwwcGedHqaC5LlQNdEAumn/wFsu6aPwkuPMioy8kqw==", + "dev": true, + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + } + } + }, + "tar-stream": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-1.6.2.tgz", + "integrity": "sha512-rzS0heiNf8Xn7/mpdSVVSMAWAoy9bfb1WOTYC78Z0UQKeKa/CWS8FOq0lKGNa8DWKAn9gxjCvMLYc5PGXYlK2A==", + "dev": true, + "requires": { + "bl": "^1.0.0", + "buffer-alloc": "^1.2.0", + "end-of-stream": "^1.0.0", + "fs-constants": "^1.0.0", + "readable-stream": "^2.3.0", + "to-buffer": "^1.1.1", + "xtend": "^4.0.0" + } + }, + "text-table": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", + "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", + "dev": true + }, + "through": { + "version": "2.3.8", + "resolved": "http://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=", + "dev": true + }, + "tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "dev": true, + "requires": { + "os-tmpdir": "~1.0.2" + } + }, + "to-buffer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/to-buffer/-/to-buffer-1.1.1.tgz", + "integrity": "sha512-lx9B5iv7msuFYE3dytT+KE5tap+rNYw+K4jVkb9R/asAb+pbBSM17jtunHplhBe6RRJdZx3Pn2Jph24O32mOVg==", + "dev": true + }, + "tslib": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.9.3.tgz", + "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==", + "dev": true + }, + "tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", + "dev": true, + "requires": { + "safe-buffer": "^5.0.1" + } + }, + "type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "dev": true, + "requires": { + "prelude-ls": "~1.1.2" + } + }, + "typescript": { + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.1.6.tgz", + "integrity": "sha512-tDMYfVtvpb96msS1lDX9MEdHrW4yOuZ4Kdc4Him9oU796XldPYF/t2+uKoX0BBa0hXXwDlqYQbXY5Rzjzc5hBA==", + "dev": true + }, + "uglify-js": { + "version": "3.4.9", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.4.9.tgz", + "integrity": "sha512-8CJsbKOtEbnJsTyv6LE6m6ZKniqMiFWmm9sRbopbkGs3gMPPfd3Fh8iIA4Ykv5MgaTbqHr4BaoGLJLZNhsrW1Q==", + "dev": true, + "optional": true, + "requires": { + "commander": "~2.17.1", + "source-map": "~0.6.1" + }, + "dependencies": { + "commander": { + "version": "2.17.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.17.1.tgz", + "integrity": "sha512-wPMUt6FnH2yzG95SA6mzjQOEKUU3aLaDEmzs1ti+1E9h+CsrZghRlqEM/EJ4KscsQVG8uNN4uVreUeT8+drlgg==", + "dev": true, + "optional": true + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "optional": true + } + } + }, + "underscore": { + "version": "1.8.3", + "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.8.3.tgz", + "integrity": "sha1-Tz+1OxBuYJf8+ctBCfKl6b36UCI=", + "dev": true + }, + "underscore-contrib": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/underscore-contrib/-/underscore-contrib-0.3.0.tgz", + "integrity": "sha1-ZltmwkeD+PorGMn4y7Dix9SMJsc=", + "dev": true, + "requires": { + "underscore": "1.6.0" + }, + "dependencies": { + "underscore": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.6.0.tgz", + "integrity": "sha1-izixDKze9jM3uLJOT/htRa6lKag=", + "dev": true + } + } + }, + "unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=", + "dev": true + }, + "uri-js": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.2.2.tgz", + "integrity": "sha512-KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ==", + "dev": true, + "requires": { + "punycode": "^2.1.0" + } + }, + "utf-8-validate": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-4.0.2.tgz", + "integrity": "sha512-CS63Ssp6zynBQ4IxVzgjP5Abdo6LuJ87HFIcgIiVUeY96+MTHkqKtrUhphbwQ6jX8aSGZv8zX6l1DCPpfcAnxA==", + "dev": true, + "requires": { + "bindings": "~1.3.0", + "nan": "~2.10.0", + "prebuild-install": "~4.0.0" + } + }, + "util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", + "dev": true + }, + "utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=", + "dev": true + }, + "which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + }, + "which-pm-runs": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/which-pm-runs/-/which-pm-runs-1.0.0.tgz", + "integrity": "sha1-Zws6+8VS4LVd9rd4DKdGFfI60cs=", + "dev": true + }, + "wide-align": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.3.tgz", + "integrity": "sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA==", + "dev": true, + "requires": { + "string-width": "^1.0.2 || 2" + } + }, + "wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", + "dev": true + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + }, + "write": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/write/-/write-0.2.1.tgz", + "integrity": "sha1-X8A4KOJkzqP+kUVUdvejxWbLB1c=", + "dev": true, + "requires": { + "mkdirp": "^0.5.1" + } + }, + "ws": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-5.2.2.tgz", + "integrity": "sha512-jaHFD6PFv6UgoIVda6qZllptQsMlDEJkTQcybzzXDYM1XO9Y8em691FGMPmM46WGyLU4z9KMgQN+qrux/nhlHA==", + "requires": { + "async-limiter": "~1.0.0" + } + }, + "xmlcreate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/xmlcreate/-/xmlcreate-1.0.2.tgz", + "integrity": "sha1-+mv3YqYKQT+z3Y9LA8WyaSONMI8=", + "dev": true + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + } + } +} diff --git a/vendor/git.apache.org/thrift.git/package.json b/vendor/git.apache.org/thrift.git/package.json index edfc355..722ae7d 100644 --- a/vendor/git.apache.org/thrift.git/package.json +++ b/vendor/git.apache.org/thrift.git/package.json @@ -6,7 +6,7 @@ "type": "git", "url": "https://git-wip-us.apache.org/repos/asf/thrift.git" }, - "version": "0.10.0", + "version": "0.12.0", "author": { "name": "Apache Thrift Developers", "email": "dev@thrift.apache.org", @@ -32,23 +32,35 @@ }, "main": "./lib/nodejs/lib/thrift", "engines": { - "node": ">= 0.2.4" + "node": ">= 4.1.0" }, "dependencies": { - "node-int64": "~0.3.0", - "q": "1.0.x", - "ws": "~0.4.32" + "node-int64": "^0.4.0", + "q": "^1.5.0", + "ws": "^5.0.0" }, "devDependencies": { - "buffer-equals": "^1.0.3", - "commander": "2.1.x", - "connect": "2.7.x", - "istanbul": "^0.3.5", - "run-browser": "^2.0.1", - "tape": "~3.5.0" + "buffer-equals": "^1.0.4", + "commander": "^2.14.1", + "connect": "^3.6.6", + "eslint": "^5.7.0", + "eslint-config-prettier": "^3.1.0", + "eslint-plugin-prettier": "^3.0.0", + "istanbul": "^0.4.5", + "jsdoc": "^3.5.5", + "prettier": "^1.14.3", + "tape": "^4.9.0", + "utf-8-validate": "^4.0.0", + "typescript": "^3.1.6", + "@types/node": "^10.12.6", + "@types/q": "^1.5.1" }, "scripts": { "cover": "lib/nodejs/test/testAll.sh COVER", - "test": "lib/nodejs/test/testAll.sh" + "test": "lib/nodejs/test/testAll.sh", + "test-ts": "lib/nodets/test/testAll.sh", + "prettier": "prettier --write '**/*.js'", + "lint": "eslint lib/nodejs/. --ext .js", + "lint-tests": "eslint lib/nodejs/test/. --ext .js" } } diff --git a/vendor/git.apache.org/thrift.git/phpcs.xml.dist b/vendor/git.apache.org/thrift.git/phpcs.xml.dist new file mode 100644 index 0000000..180388a --- /dev/null +++ b/vendor/git.apache.org/thrift.git/phpcs.xml.dist @@ -0,0 +1,25 @@ + + + The coding standard for thrift. + + lib/php/lib + lib/php/test + lib/php/test/packages/* + + + + + + + + + + + + lib/php/test/* + + + lib/php/test/* + + + diff --git a/vendor/git.apache.org/thrift.git/pull_request_template.md b/vendor/git.apache.org/thrift.git/pull_request_template.md new file mode 100644 index 0000000..0b6965b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/pull_request_template.md @@ -0,0 +1,19 @@ +Some helpful tips for a successful Apache Thrift PR: + +* Did you test your changes locally or using CI in your fork? +* Is the Apache Jira THRIFT ticket identifier in the PR title? +* Is the Apache Jira THRIFT ticket identifier in the commit message? +* Did you squash your changes to a single commit? +* Are these changes backwards compatible? (please say so in PR description) +* Do you need to update the language-specific README? + +Example ideal pull request title: + + THRIFT-9999: an example pull request title + +Example ideal commit message: + + THRIFT-9999: [summary of fix, one line if possible] + Client: [language(s) affected, comma separated, use lib/ directory names please] + +For more information about committing, see CONTRIBUTING.md diff --git a/vendor/git.apache.org/thrift.git/sonar-project.properties b/vendor/git.apache.org/thrift.git/sonar-project.properties index 6e6c5db..ef11517 100755 --- a/vendor/git.apache.org/thrift.git/sonar-project.properties +++ b/vendor/git.apache.org/thrift.git/sonar-project.properties @@ -16,7 +16,7 @@ development, combines a software stack with a code generation engine to build services that work efficiently and seamlessly between all major languages. # Apache Thrift Version -sonar.projectVersion=0.10.0 +sonar.projectVersion=0.12.0 # use this to set another version string # $ sonar-runner -D sonar.projectVersion=`git rev-parse HEAD` # set projectDate in combination with projectVersion for imports of old releases @@ -54,15 +54,15 @@ module1.sonar.projectName=Apache Thrift - Java Library module1.sonar.projectBaseDir=lib/java module1.sonar.sources=src module1.sonar.tests=test -module1.sonar.binaries=build/libthrift-0.10.0.jar -module1.sonar.libraries=build/lib/*.jar +module1.sonar.binaries=build/libs/libthrift-0.12.0.jar +module1.sonar.libraries=build/deps/*.jar module1.sonar.language=java module2.sonar.projectName=Apache Thrift - Java Tutorial module2.sonar.projectBaseDir=. module2.sonar.sources=tutorial/java/src, tutorial/java/gen-java module2.sonar.binaries=tutorial/java/tutorial.jar -module2.sonar.libraries=lib/java/build/lib/*.jar,lib/java/build/libthrift-1.0.0.jar +module2.sonar.libraries=lib/java/build/deps/*.jar,lib/java/build/libs/libthrift-0.12.0.jar module2.sonar.language=java module3.sonar.projectName=Apache Thrift - JavaScript Library diff --git a/vendor/git.apache.org/thrift.git/test/AnnotationTest.thrift b/vendor/git.apache.org/thrift.git/test/AnnotationTest.thrift index 191995a..7e24e1c 100644 --- a/vendor/git.apache.org/thrift.git/test/AnnotationTest.thrift +++ b/vendor/git.apache.org/thrift.git/test/AnnotationTest.thrift @@ -57,6 +57,15 @@ senum seasons { "Winter" } ( foo = "bar" ) +struct ostr_default { + 1: i32 bar; +} + +struct ostr_custom { + 1: i32 bar; +} (cpp.customostream) + + service foo_service { void foo() ( foo = "bar" ) } (a.b="c") diff --git a/vendor/git.apache.org/thrift.git/test/ConstantsDemo.thrift b/vendor/git.apache.org/thrift.git/test/ConstantsDemo.thrift index b99bdb2..a54534d 100644 --- a/vendor/git.apache.org/thrift.git/test/ConstantsDemo.thrift +++ b/vendor/git.apache.org/thrift.git/test/ConstantsDemo.thrift @@ -18,6 +18,7 @@ */ namespace cpp yozone +namespace erl consts_ struct thing { 1: i32 hello, diff --git a/vendor/git.apache.org/thrift.git/test/DoubleConstantsTest.thrift b/vendor/git.apache.org/thrift.git/test/DoubleConstantsTest.thrift new file mode 100644 index 0000000..c9212ab --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/DoubleConstantsTest.thrift @@ -0,0 +1,17 @@ +namespace java thrift.test +namespace cpp thrift.test + +// more tests on double constants (precision and type checks) +const double DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST = 1 +const double DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST = -100 +const double DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST = 9223372036854775807 +const double DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST = -9223372036854775807 +const double DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST = 3.14159265359 +const double DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST = 1000000.1 +const double DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST = -1000000.1 +const double DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST = 1.7e+308 +const double DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST = 9223372036854775816.43 +const double DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST = -1.7e+308 +const double DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST = -9223372036854775816.43 + +const list DOUBLE_LIST_TEST = [1,-100,100,9223372036854775807,-9223372036854775807,3.14159265359,1000000.1,-1000000.1,1.7e+308,-1.7e+308,9223372036854775816.43,-9223372036854775816.43] diff --git a/vendor/git.apache.org/thrift.git/test/EnumContainersTest.thrift b/vendor/git.apache.org/thrift.git/test/EnumContainersTest.thrift new file mode 100644 index 0000000..3b6408f --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/EnumContainersTest.thrift @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +namespace java thrift.test.enumcontainers + +enum GreekGodGoddess { + ARES, + APHRODITE, + ZEUS, + POSEIDON, + HERA, +} + +typedef GreekGodGoddess GreekGodGoddessType +typedef i32 Power + +struct GodBean { + 1: optional map power, + 2: optional set goddess, + 3: optional map byAlias, + 4: optional set images, +} + +const map ATTRIBUTES = +{ + GreekGodGoddess.ZEUS: "lightning bolt", + GreekGodGoddess.POSEIDON: "trident", +} + +const set BEAUTY = [ GreekGodGoddess.APHRODITE, GreekGodGoddess.HERA ] diff --git a/vendor/git.apache.org/thrift.git/test/EnumTest.thrift b/vendor/git.apache.org/thrift.git/test/EnumTest.thrift index f38cec3..7961f38 100644 --- a/vendor/git.apache.org/thrift.git/test/EnumTest.thrift +++ b/vendor/git.apache.org/thrift.git/test/EnumTest.thrift @@ -71,6 +71,11 @@ enum MyEnum5 { e2 = 42 // fails with 0.9.3 and earlier } +enum MyEnumWithCustomOstream { + custom1 = 1, + CustoM2 +} (cpp.customostream) + struct MyStruct { 1: MyEnum2 me2_2 = MyEnum1.ME2_2 2: MyEnum3 me3_n2 = MyEnum3.ME3_N2 diff --git a/vendor/git.apache.org/thrift.git/test/JavaDeepCopyTest.thrift b/vendor/git.apache.org/thrift.git/test/JavaDeepCopyTest.thrift new file mode 100644 index 0000000..fc974ae --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/JavaDeepCopyTest.thrift @@ -0,0 +1,19 @@ +include "JavaTypes.thrift" + +namespace java thrift.test + +struct DeepCopyFoo { + 1: optional list l, + 2: optional set s, + 3: optional map m, + 4: optional list li, + 5: optional set si, + 6: optional map mi, + 7: optional DeepCopyBar bar, +} + +struct DeepCopyBar { + 1: optional string a, + 2: optional i32 b, + 3: optional bool c, +} diff --git a/vendor/git.apache.org/thrift.git/test/JavaTypes.thrift b/vendor/git.apache.org/thrift.git/test/JavaTypes.thrift index fcb0ab2..8c733ad 100644 --- a/vendor/git.apache.org/thrift.git/test/JavaTypes.thrift +++ b/vendor/git.apache.org/thrift.git/test/JavaTypes.thrift @@ -96,3 +96,8 @@ service AsyncNonblockingService { 7: Map somemap, ) throws (1:Exception ex); } + +struct SafeBytes { + 1: binary bytes; +} + diff --git a/vendor/git.apache.org/thrift.git/test/Makefile.am b/vendor/git.apache.org/thrift.git/test/Makefile.am index ff780c3..68f1986 100755 --- a/vendor/git.apache.org/thrift.git/test/Makefile.am +++ b/vendor/git.apache.org/thrift.git/test/Makefile.am @@ -25,6 +25,11 @@ SUBDIRS += c_glib PRECROSS_TARGET += precross-c_glib endif +if WITH_CL +SUBDIRS += cl +PRECROSS_TARGET += precross-cl +endif + if WITH_MONO SUBDIRS += csharp PRECROSS_TARGET += precross-csharp @@ -72,6 +77,10 @@ if WITH_HAXE SUBDIRS += haxe endif +if WITH_DOTNETCORE +SUBDIRS += netcore +endif + if WITH_GO SUBDIRS += go PRECROSS_TARGET += precross-go @@ -87,6 +96,11 @@ SUBDIRS += lua PRECROSS_TARGET += precross-lua endif +if WITH_RS +SUBDIRS += rs +PRECROSS_TARGET += precross-rs +endif + # # generate html for ThriftTest.thrift # @@ -101,6 +115,7 @@ EXTRA_DIST = \ crossrunner \ keys \ c_glib \ + cl \ cpp \ dart \ erl \ @@ -113,17 +128,20 @@ EXTRA_DIST = \ py.twisted \ py.tornado \ rb \ + rs \ threads \ AnnotationTest.thrift \ BrokenConstants.thrift \ ConstantsDemo.thrift \ DebugProtoTest.thrift \ + DoubleConstantsTest.thrift \ DenseLinkingTest.thrift \ DocTest.thrift \ EnumTest.thrift \ FullCamelTest.thrift \ Include.thrift \ JavaBeansTest.thrift \ + JavaDeepCopyTest.thrift \ JavaTypes.thrift \ JsDeepConstructorTest.thrift \ ManyOptionals.thrift \ @@ -132,10 +150,12 @@ EXTRA_DIST = \ OptionalRequiredTest.thrift \ Recursive.thrift \ ReuseObjects.thrift \ + EnumContainersTest.thrift \ SmallTest.thrift \ StressTest.thrift \ ThriftTest.thrift \ TypedefTest.thrift \ + UnsafeTypes.thrift \ known_failures_Linux.json \ test.py \ tests.json \ diff --git a/vendor/git.apache.org/thrift.git/test/ThriftTest.thrift b/vendor/git.apache.org/thrift.git/test/ThriftTest.thrift index ca70873..3499ab5 100644 --- a/vendor/git.apache.org/thrift.git/test/ThriftTest.thrift +++ b/vendor/git.apache.org/thrift.git/test/ThriftTest.thrift @@ -37,6 +37,7 @@ namespace delphi Thrift.Test namespace cocoa ThriftTest namespace lua ThriftTest namespace xsd test (uri = 'http://thrift.apache.org/ns/ThriftTest') +namespace netcore ThriftTest // Presence of namespaces and sub-namespaces for which there is // no generator should compile with warnings only @@ -195,7 +196,7 @@ service ThriftTest * @return binary - returns the binary 'thing' */ binary testBinary(1: binary thing), - + /** * Prints 'testStruct("{%s}")' where thing has been formatted into a string of comma separated values * @param Xtruct thing - the Xtruct to print @@ -320,13 +321,12 @@ service ThriftTest service SecondService { - void blahBlah() /** * Prints 'testString("%s")' with thing as '%s' * @param string thing - the string to print * @return string - returns the string 'thing' */ - string secondtestString(1: string thing), + string secondtestString(1: string thing) } struct VersioningTestV1 { diff --git a/vendor/git.apache.org/thrift.git/test/UnsafeTypes.thrift b/vendor/git.apache.org/thrift.git/test/UnsafeTypes.thrift new file mode 100644 index 0000000..b38c905 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/UnsafeTypes.thrift @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +namespace java thrift.test + +struct UnsafeBytes { + 1: binary bytes; +} diff --git a/vendor/git.apache.org/thrift.git/test/c_glib/Makefile.am b/vendor/git.apache.org/thrift.git/test/c_glib/Makefile.am index 4f9a119..4a03d29 100755 --- a/vendor/git.apache.org/thrift.git/test/c_glib/Makefile.am +++ b/vendor/git.apache.org/thrift.git/test/c_glib/Makefile.am @@ -45,6 +45,8 @@ test_client_LDADD = \ test_server_SOURCES = \ src/thrift_test_handler.c \ src/thrift_test_handler.h \ + src/thrift_second_service_handler.c \ + src/thrift_second_service_handler.h \ src/test_server.c test_server_LDADD = \ @@ -54,8 +56,6 @@ test_server_LDADD = \ # # Common thrift code generation rules # -THRIFT = $(top_builddir)/compiler/cpp/thrift - gen-c_glib/t_test_second_service.c gen-c_glib/t_test_second_service.h gen-c_glib/t_test_thrift_test.c gen-c_glib/t_test_thrift_test.h gen-c_glib/t_test_thrift_test_types.c gen-c_glib/t_test_thrift_test_types.h: $(top_srcdir)/test/ThriftTest.thrift $(THRIFT) $(THRIFT) --gen c_glib -r $< diff --git a/vendor/git.apache.org/thrift.git/test/c_glib/src/test_client.c b/vendor/git.apache.org/thrift.git/test/c_glib/src/test_client.c index 3ae9325..ef24ab7 100644 --- a/vendor/git.apache.org/thrift.git/test/c_glib/src/test_client.c +++ b/vendor/git.apache.org/thrift.git/test/c_glib/src/test_client.c @@ -28,11 +28,14 @@ #include #include #include +#include #include #include +#include #include #include +#include "../gen-c_glib/t_test_second_service.h" #include "../gen-c_glib/t_test_thrift_test.h" /* Handle SIGPIPE signals (indicating the server has closed the @@ -72,42 +75,82 @@ gint32_compare (gconstpointer a, gconstpointer b) return result; } +/** + * It gets a multiplexed protocol which uses a concrete protocol underneath + * @param protocol_name the fully qualified protocol path (e.g. "binary:multi") + * @param transport the underlying transport + * @param service_name the single supported service name + * @todo need to allow multiple services to fully test multiplexed + * @return a multiplexed protocol wrapping the correct underlying protocol + */ +ThriftProtocol * +get_multiplexed_protocol(gchar *protocol_name, ThriftTransport *transport, gchar *service_name) +{ + ThriftProtocol * multiplexed_protocol = NULL; + + if ( strncmp(protocol_name, "binary:", 7) == 0) { + multiplexed_protocol = g_object_new (THRIFT_TYPE_BINARY_PROTOCOL, + "transport", transport, + NULL); + } else if ( strncmp(protocol_name, "compact:", 8) == 0) { + multiplexed_protocol = g_object_new (THRIFT_TYPE_COMPACT_PROTOCOL, + "transport", transport, + NULL); + } else { + fprintf(stderr, "Unknown multiplex protocol name: %s\n", protocol_name); + return NULL; + } + + return g_object_new (THRIFT_TYPE_MULTIPLEXED_PROTOCOL, + "transport", transport, + "protocol", multiplexed_protocol, + "service-name", service_name, + NULL); +} + int main (int argc, char **argv) { - static gchar *host = NULL; - static gint port = 9090; - static gchar *transport_option = NULL; - static gchar *protocol_option = NULL; - static gint num_tests = 1; + static gchar * host = NULL; + static gint port = 9090; + static gboolean ssl = FALSE; + static gchar * transport_option = NULL; + static gchar * protocol_option = NULL; + static gint num_tests = 1; static GOptionEntry option_entries[] ={ - { "host", 0, 0, G_OPTION_ARG_STRING, &host, + { "host", 'h', 0, G_OPTION_ARG_STRING, &host, "Host to connect (=localhost)", NULL }, - { "port", 0, 0, G_OPTION_ARG_INT, &port, + { "port", 'p', 0, G_OPTION_ARG_INT, &port, "Port number to connect (=9090)", NULL }, - { "transport", 0, 0, G_OPTION_ARG_STRING, &transport_option, + { "ssl", 's', 0, G_OPTION_ARG_NONE, &ssl, + "Enable SSL", NULL }, + { "transport", 't', 0, G_OPTION_ARG_STRING, &transport_option, "Transport: buffered, framed (=buffered)", NULL }, - { "protocol", 0, 0, G_OPTION_ARG_STRING, &protocol_option, - "Protocol: binary, compact (=binary)", NULL }, - { "testloops", 'n', 0, G_OPTION_ARG_INT, &num_tests, + { "protocol", 'r', 0, G_OPTION_ARG_STRING, &protocol_option, + "Protocol: binary, compact, multi, multic (=binary)", NULL }, + { "testloops", 'n', 0, G_OPTION_ARG_INT, &num_tests, "Number of tests (=1)", NULL }, { NULL } }; struct sigaction sigpipe_action; + GType socket_type = THRIFT_TYPE_SOCKET; + gchar *socket_name = "ip"; GType transport_type = THRIFT_TYPE_BUFFERED_TRANSPORT; gchar *transport_name = "buffered"; GType protocol_type = THRIFT_TYPE_BINARY_PROTOCOL; gchar *protocol_name = "binary"; - ThriftSocket *socket; - ThriftTransport *transport; - ThriftProtocol *protocol; + ThriftSocket *socket = NULL; + ThriftTransport *transport = NULL; + ThriftProtocol *protocol = NULL; + ThriftProtocol *protocol2 = NULL; // for multiplexed tests - TTestThriftTestIf *test_client; + TTestThriftTestIf *test_client = NULL; + TTestSecondServiceIf *second_service = NULL; // for multiplexed tests struct timeval time_start, time_stop, time_elapsed; guint64 time_elapsed_usec, time_total_usec = 0; @@ -147,7 +190,18 @@ main (int argc, char **argv) protocol_type = THRIFT_TYPE_COMPACT_PROTOCOL; protocol_name = "compact"; } - else if (strncmp (protocol_option, "binary", 7) != 0) { + else if (strncmp (protocol_option, "multi", 6) == 0) { + protocol_type = THRIFT_TYPE_MULTIPLEXED_PROTOCOL; + protocol_name = "binary:multi"; + } + else if (strncmp (protocol_option, "multic", 7) == 0) { + protocol_type = THRIFT_TYPE_MULTIPLEXED_PROTOCOL; + protocol_name = "compact:multic"; + } + else if (strncmp (protocol_option, "binary", 7) == 0) { + printf("We are going with default protocol\n"); + } + else { fprintf (stderr, "Unknown protocol type %s\n", protocol_option); options_valid = FALSE; } @@ -164,12 +218,19 @@ main (int argc, char **argv) } } + if (ssl) { + socket_type = THRIFT_TYPE_SSL_SOCKET; + socket_name = "ip-ssl"; + printf("Type name %s\n", g_type_name (socket_type)); + } + if (!options_valid) return 254; - printf ("Connecting (%s/%s) to: %s:%d\n", + printf ("Connecting (%s/%s) to: %s/%s:%d\n", transport_name, protocol_name, + socket_name, host, port); @@ -181,17 +242,50 @@ main (int argc, char **argv) sigpipe_action.sa_flags = SA_RESETHAND; sigaction (SIGPIPE, &sigpipe_action, NULL); + if (ssl) { + thrift_ssl_socket_initialize_openssl(); + } + /* Establish all our connection objects */ - socket = g_object_new (THRIFT_TYPE_SOCKET, + socket = g_object_new (socket_type, "hostname", host, "port", port, NULL); + + if (ssl && !thrift_ssl_load_cert_from_file(THRIFT_SSL_SOCKET(socket), "../keys/CA.pem")) { + fprintf(stderr, "Unable to load validation certificate ../keys/CA.pem - did you run in the test/c_glib directory?\n"); + g_clear_object (&socket); + return 253; + } + transport = g_object_new (transport_type, "transport", socket, NULL); - protocol = g_object_new (protocol_type, - "transport", transport, - NULL); + + if(protocol_type==THRIFT_TYPE_MULTIPLEXED_PROTOCOL) { + // TODO: A multiplexed test should also test "Second" (see Java TestServer) + // The context comes from the name of the thrift file. If multiple thrift + // schemas are used we have to redo the way this is done. + protocol = get_multiplexed_protocol(protocol_name, transport, "ThriftTest"); + if (NULL == protocol) { + g_clear_object (&transport); + g_clear_object (&socket); + return 252; + } + + // Make a second protocol and client running on the same multiplexed transport + protocol2 = get_multiplexed_protocol(protocol_name, transport, "SecondService"); + second_service = g_object_new (T_TEST_TYPE_SECOND_SERVICE_CLIENT, + "input_protocol", protocol2, + "output_protocol", protocol2, + NULL); + + }else{ + protocol = g_object_new (protocol_type, + "transport", transport, + NULL); + } + test_client = g_object_new (T_TEST_TYPE_THRIFT_TEST_CLIENT, "input_protocol", protocol, "output_protocol", protocol, @@ -277,10 +371,11 @@ main (int argc, char **argv) printf (" = void\n"); } else { - printf ("%s\n", error->message); - g_error_free (error); - error = NULL; - + if(error!=NULL){ + printf ("%s\n", error->message); + g_error_free (error); + error = NULL; + } fail_count++; } @@ -307,6 +402,31 @@ main (int argc, char **argv) fail_count++; } + /** + * Multiplexed Test - do this right in the middle of the normal Test Client run + */ + if (second_service) { + printf ("testSecondServiceMultiplexSecondTestString(\"2nd\")"); + if (t_test_second_service_if_secondtest_string (second_service, + &string, + "2nd", + &error)) { + printf (" = \"%s\"\n", string); + if (strcmp (string, "testString(\"2nd\")") != 0) { + ++fail_count; + } + + g_free (string); + string = NULL; + } else { + printf ("%s\n", error->message); + g_error_free (error); + error = NULL; + + ++fail_count; + } + } + /** * BOOL TEST */ @@ -439,8 +559,105 @@ main (int argc, char **argv) fail_count++; } - // TODO: add testBinary() - + /** + * BINARY TEST + */ + printf ("testBinary(empty)"); + GByteArray *emptyArray = g_byte_array_new(); + GByteArray *result = NULL; + if (t_test_thrift_test_if_test_binary (test_client, + &result, + emptyArray, + &error)) { + GBytes *response = g_byte_array_free_to_bytes(result); // frees result + result = NULL; + gsize siz = g_bytes_get_size(response); + if (siz == 0) { + printf(" = empty\n"); + } else { + printf(" = not empty (%ld bytes)\n", (long)siz); + ++fail_count; + } + g_bytes_unref(response); + } else { + printf ("%s\n", error->message); + g_error_free (error); + error = NULL; + + fail_count++; + } + g_byte_array_unref(emptyArray); + emptyArray = NULL; + + // TODO: add testBinary() with data + printf ("testBinary([-128..127]) = {"); + const signed char bin_data[256] + = {-128, -127, -126, -125, -124, -123, -122, -121, -120, -119, -118, -117, -116, -115, -114, + -113, -112, -111, -110, -109, -108, -107, -106, -105, -104, -103, -102, -101, -100, -99, + -98, -97, -96, -95, -94, -93, -92, -91, -90, -89, -88, -87, -86, -85, -84, + -83, -82, -81, -80, -79, -78, -77, -76, -75, -74, -73, -72, -71, -70, -69, + -68, -67, -66, -65, -64, -63, -62, -61, -60, -59, -58, -57, -56, -55, -54, + -53, -52, -51, -50, -49, -48, -47, -46, -45, -44, -43, -42, -41, -40, -39, + -38, -37, -36, -35, -34, -33, -32, -31, -30, -29, -28, -27, -26, -25, -24, + -23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, + -8, -7, -6, -5, -4, -3, -2, -1, 0, 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}; + GByteArray *fullArray = g_byte_array_new(); + g_byte_array_append(fullArray, (guint8 *)(&bin_data[0]), 256); + if (t_test_thrift_test_if_test_binary (test_client, + &result, + fullArray, + &error)) { + GBytes *response = g_byte_array_free_to_bytes(result); // frees result + result = NULL; + gsize siz = g_bytes_get_size(response); + gconstpointer ptr = g_bytes_get_data(response, &siz); + if (siz == 256) { + gboolean first = 1; + gboolean failed = 0; + int i; + + for (i = 0; i < 256; ++i) { + if (!first) + printf(","); + else + first = 0; + int val = ((signed char *)ptr)[i]; + printf("%d", val); + if (!failed && val != i - 128) { + failed = 1; + } + } + printf("} "); + if (failed) { + printf("FAIL (bad content) size %ld OK\n", (long)siz); + ++fail_count; + } else { + printf("OK size %ld OK\n", (long)siz); + } + } else { + printf(" = bad size %ld\n", (long)siz); + ++fail_count; + } + g_bytes_unref(response); + } else { + printf ("%s\n", error->message); + g_error_free (error); + error = NULL; + + fail_count++; + } + g_byte_array_unref(fullArray); + fullArray = NULL; + /** * STRUCT TEST */ @@ -474,6 +691,11 @@ main (int argc, char **argv) i32_thing != -3 || i64_thing != (gint64)-5) fail_count++; + + if (string) { + g_free (string); + string = NULL; + } } else { printf ("%s\n", error->message); @@ -482,7 +704,8 @@ main (int argc, char **argv) fail_count++; } - g_object_unref (xtruct_in); + // g_clear_object(&xtruct_out); used below + g_clear_object(&xtruct_in); /** * NESTED STRUCT TEST @@ -525,6 +748,11 @@ main (int argc, char **argv) inner_i64_thing != (gint64)-5 || i32_thing != 5) fail_count++; + + if (string) { + g_free(string); + string = NULL; + } } else { printf ("%s\n", error->message); @@ -534,10 +762,10 @@ main (int argc, char **argv) fail_count++; } - g_object_unref (xtruct_in); - g_object_unref (xtruct2_in); - g_object_unref (xtruct2_out); - g_object_unref (xtruct_out); + g_clear_object(&xtruct_in); + g_clear_object(&xtruct2_in); + g_clear_object(&xtruct2_out); + g_clear_object(&xtruct_out); /** * MAP TEST @@ -1280,7 +1508,7 @@ main (int argc, char **argv) } g_hash_table_unref (map_in); - g_object_unref (insanity_out); + g_clear_object (&insanity_out); /* test exception */ printf ("testClient.testException(\"Xception\") =>"); @@ -1296,8 +1524,7 @@ main (int argc, char **argv) printf (" {%u, \"%s\"}\n", int32, string); g_free (string); - g_object_unref (xception); - xception = NULL; + g_clear_object (&xception); g_error_free (error); error = NULL; @@ -1333,10 +1560,7 @@ main (int argc, char **argv) printf (" void\nFAILURE\n"); fail_count++; - if (xception != NULL) { - g_object_unref (xception); - xception = NULL; - } + g_clear_object (&xception); if (error != NULL) { g_error_free (error); @@ -1354,10 +1578,7 @@ main (int argc, char **argv) printf (" void\nFAILURE\n"); fail_count++; - if (xception != NULL) { - g_object_unref (xception); - xception = NULL; - } + g_clear_object (&xception); g_error_free (error); error = NULL; @@ -1394,15 +1615,8 @@ main (int argc, char **argv) printf (" result\nFAILURE\n"); fail_count++; - if (xception != NULL) { - g_object_unref (xception); - xception = NULL; - } - - if (xception2 != NULL) { - g_object_unref (xception2); - xception = NULL; - } + g_clear_object (&xception); + g_clear_object (&xception2); if (error != NULL) { g_error_free (error); @@ -1432,11 +1646,8 @@ main (int argc, char **argv) printf (" {%u, {\"%s\"}}\n", int32, string); g_free (string); - g_object_unref (inner_xtruct_in); - inner_xtruct_in = NULL; - - g_object_unref (xception2); - xception2 = NULL; + g_clear_object (&inner_xtruct_in); + g_clear_object (&xception2); g_error_free (error); error = NULL; @@ -1445,22 +1656,15 @@ main (int argc, char **argv) printf (" result\nFAILURE\n"); fail_count++; - if (xception != NULL) { - g_object_unref (xception); - xception = NULL; - } - - if (xception2 != NULL) { - g_object_unref (xception2); - xception = NULL; - } + g_clear_object (&xception); + g_clear_object (&xception2); if (error != NULL) { g_error_free (error); error = NULL; } } - g_object_unref (xtruct_in); + g_clear_object (&xtruct_in); printf ("testClient.testMultiException(\"success\", \"test 3\") =>"); xtruct_in = g_object_new (T_TEST_TYPE_XTRUCT, NULL); @@ -1483,22 +1687,15 @@ main (int argc, char **argv) printf (" result\nFAILURE\n"); fail_count++; - if (xception != NULL) { - g_object_unref (xception); - xception = NULL; - } - - if (xception2 != NULL) { - g_object_unref (xception2); - xception = NULL; - } + g_clear_object (&xception); + g_clear_object (&xception2); if (error != NULL) { g_error_free (error); error = NULL; } } - g_object_unref (xtruct_in); + g_clear_object (&xtruct_in); /* test oneway void */ printf ("testClient.testOneway(1) =>"); @@ -1584,6 +1781,7 @@ main (int argc, char **argv) /* All done---output statistics */ puts ("\nAll tests done."); + printf("Number of failures: %d\n", fail_count); time_avg_usec = time_total_usec / num_tests; @@ -1591,10 +1789,16 @@ main (int argc, char **argv) printf ("Max time: %" PRIu64 " us\n", time_max_usec); printf ("Avg time: %" PRIu64 " us\n", time_avg_usec); - g_object_unref (test_client); - g_object_unref (protocol); - g_object_unref (transport); - g_free (host); + g_clear_object(&second_service); + g_clear_object(&protocol2); + g_clear_object(&test_client); + g_clear_object(&protocol); + g_clear_object(&transport); + g_clear_object(&socket); + + if (ssl) { + thrift_ssl_socket_finalize_openssl(); + } return fail_count; } diff --git a/vendor/git.apache.org/thrift.git/test/c_glib/src/test_server.c b/vendor/git.apache.org/thrift.git/test/c_glib/src/test_server.c index 7f41d3f..2d716ec 100644 --- a/vendor/git.apache.org/thrift.git/test/c_glib/src/test_server.c +++ b/vendor/git.apache.org/thrift.git/test/c_glib/src/test_server.c @@ -23,6 +23,7 @@ #include #include +#include #include #include #include @@ -37,8 +38,10 @@ #include #include "../gen-c_glib/t_test_thrift_test.h" +#include "../gen-c_glib/t_test_second_service.h" #include "thrift_test_handler.h" +#include "thrift_second_service_handler.h" /* Our server object, declared globally so it is accessible within the SIGINT signal handler */ @@ -96,7 +99,10 @@ main (int argc, char **argv) GType protocol_factory_type = THRIFT_TYPE_BINARY_PROTOCOL_FACTORY; TTestThriftTestHandler *handler; + TTestThriftTestHandler *handler_second_service = NULL; ThriftProcessor *processor; + ThriftProcessor *processor_test = NULL; + ThriftProcessor *processor_second_service = NULL; ThriftServerTransport *server_transport; ThriftTransportFactory *transport_factory; ThriftProtocolFactory *protocol_factory; @@ -138,6 +144,13 @@ main (int argc, char **argv) protocol_factory_type = THRIFT_TYPE_COMPACT_PROTOCOL_FACTORY; protocol_name = "compact"; } + else if (strncmp (protocol_option, "multi", 6) == 0) { + protocol_name = "binary:multi"; + } + else if (strncmp (protocol_option, "multic", 7) == 0) { + protocol_factory_type = THRIFT_TYPE_COMPACT_PROTOCOL_FACTORY; + protocol_name = "compact:multic"; + } else if (strncmp (protocol_option, "binary", 7) != 0) { fprintf (stderr, "Unknown protocol type %s\n", protocol_option); options_valid = FALSE; @@ -161,16 +174,57 @@ main (int argc, char **argv) /* Establish all our connection objects */ handler = g_object_new (TYPE_THRIFT_TEST_HANDLER, NULL); - processor = g_object_new (T_TEST_TYPE_THRIFT_TEST_PROCESSOR, - "handler", handler, - NULL); + + + + if(strstr(protocol_name, ":multi")){ + /* When a multiplexed processor is involved the handler is not + registered as usual. We create the processor and the real + processor is registered. Multiple processors can be registered + at once. This is why we don't have a constructor property */ + processor = g_object_new (THRIFT_TYPE_MULTIPLEXED_PROCESSOR, + NULL); + + handler_second_service = g_object_new (TYPE_SECOND_SERVICE_HANDLER, + NULL); + + processor_test = g_object_new (T_TEST_TYPE_THRIFT_TEST_PROCESSOR, + "handler", handler, + NULL); + processor_second_service = g_object_new (T_TEST_TYPE_SECOND_SERVICE_PROCESSOR, + "handler", handler_second_service, + NULL); + + /* We register a test processor with Multiplexed name ThriftTest */ + if(!thrift_multiplexed_processor_register_processor(processor, + "ThriftTest", processor_test, + &error)){ + g_message ("thrift_server_serve: %s", + error != NULL ? error->message : "(null)"); + g_clear_error (&error); + } + /* We register a second test processor with Multiplexed name SecondService + * we are responsible of freeing the processor when it's not used anymore */ + if(!thrift_multiplexed_processor_register_processor(processor, + "SecondService", processor_second_service, + &error)){ + g_message ("thrift_server_serve: %s", + error != NULL ? error->message : "(null)"); + g_clear_error (&error); + } + + }else{ + processor = g_object_new (T_TEST_TYPE_THRIFT_TEST_PROCESSOR, + "handler", handler, + NULL); + } server_transport = g_object_new (THRIFT_TYPE_SERVER_SOCKET, "port", port, NULL); transport_factory = g_object_new (transport_factory_type, NULL); - if (strncmp (protocol_name, "compact", 8) == 0) { + if (strstr (protocol_name, "compact") != NULL) { protocol_factory = g_object_new (protocol_factory_type, "string_limit", string_limit, "container_limit", container_limit, @@ -222,6 +276,15 @@ main (int argc, char **argv) g_object_unref (server_transport); g_object_unref (processor); g_object_unref (handler); + if(handler_second_service){ + g_object_unref (handler_second_service); + } + if(processor_test){ + g_object_unref (processor_test); + } + if(processor_second_service){ + g_object_unref (processor_second_service); + } return 0; } diff --git a/vendor/git.apache.org/thrift.git/test/c_glib/src/thrift_second_service_handler.c b/vendor/git.apache.org/thrift.git/test/c_glib/src/thrift_second_service_handler.c new file mode 100644 index 0000000..66ac7bc --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/c_glib/src/thrift_second_service_handler.c @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +#include +#include +#include + +#include +#include + +#include "thrift_second_service_handler.h" + +/* A handler that implements the TTestSecondServiceIf interface */ + +G_DEFINE_TYPE (SecondServiceHandler, + second_service_handler, + T_TEST_TYPE_SECOND_SERVICE_HANDLER); + + +gboolean +second_service_handler_secondtest_string (TTestSecondServiceIf *iface, + gchar **_return, + const gchar *thing, + GError **error) +{ + THRIFT_UNUSED_VAR (iface); + THRIFT_UNUSED_VAR (error); + gchar buffer[256]; + + printf ("testSecondServiceMultiplexSecondTestString(\"%s\")\n", thing); + snprintf(buffer, 255, "testString(\"%s\")", thing); + *_return = g_strdup (buffer); + + return TRUE; +} + +static void +second_service_handler_init (SecondServiceHandler *self) +{ + THRIFT_UNUSED_VAR (self); +} + +static void +second_service_handler_class_init (SecondServiceHandlerClass *klass) +{ + TTestSecondServiceHandlerClass *base_class = + T_TEST_SECOND_SERVICE_HANDLER_CLASS (klass); + + + base_class->secondtest_string = + second_service_handler_secondtest_string; + +} diff --git a/vendor/git.apache.org/thrift.git/test/c_glib/src/thrift_second_service_handler.h b/vendor/git.apache.org/thrift.git/test/c_glib/src/thrift_second_service_handler.h new file mode 100644 index 0000000..bbe048c --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/c_glib/src/thrift_second_service_handler.h @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +#ifndef _SECOND_SERVICE_HANDLER_H +#define _SECOND_SERVICE_HANDLER_H + +#include +#include + +#include "../gen-c_glib/t_test_second_service.h" + +G_BEGIN_DECLS + +/* A handler that implements the TTestSecondServiceIf interface */ + +#define TYPE_SECOND_SERVICE_HANDLER (second_service_handler_get_type ()) + +#define SECOND_SERVICE_HANDLER(obj) \ + (G_TYPE_CHECK_INSTANCE_CAST ((obj), \ + TYPE_SECOND_SERVICE_HANDLER, \ + SecondServiceHandler)) +#define IS_SECOND_SERVICE_HANDLER(obj) \ + (G_TYPE_CHECK_INSTANCE_TYPE ((obj), \ + TYPE_SECOND_SERVICE_HANDLER)) +#define SECOND_SERVICE_HANDLER_CLASS(c) \ + (G_TYPE_CHECK_CLASS_CAST ((c), \ + TYPE_SECOND_SERVICE_HANDLER, \ + SecondServiceHandlerClass)) +#define IS_SECOND_SERVICE_HANDLER_CLASS(c) \ + (G_TYPE_CHECK_CLASS_TYPE ((c), \ + TYPE_SECOND_SERVICE_HANDLER)) +#define SECOND_SERVICE_HANDLER_GET_CLASS(obj) \ + (G_TYPE_INSTANCE_GET_CLASS ((obj), \ + TYPE_SECOND_SERVICE_HANDLER, \ + SecondServiceHandlerClass)) + +typedef struct _SecondServiceHandler SecondServiceHandler; +typedef struct _SecondServiceHandlerClass SecondServiceHandlerClass; + +struct _SecondServiceHandler { + TTestSecondServiceHandler parent; +}; + +struct _SecondServiceHandlerClass { + TTestSecondServiceHandlerClass parent; + +}; + +/* Used by SECOND_SERVICE_HANDLER_GET_TYPE */ +GType second_service_handler_get_type (void); + +gboolean second_service_handler_blah_blah (TTestSecondServiceIf *iface, GError **error); +gboolean second_service_handler_secondtest_string (TTestSecondServiceIf *iface, gchar ** _return, const gchar * thing, GError **error); + +G_END_DECLS + +#endif /* _SECOND_SERVICE_HANDLER_H */ diff --git a/vendor/git.apache.org/thrift.git/test/cl/Makefile.am b/vendor/git.apache.org/thrift.git/test/cl/Makefile.am new file mode 100755 index 0000000..b5e72bc --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/cl/Makefile.am @@ -0,0 +1,42 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +THRIFT = $(top_builddir)/compiler/cpp/thrift + +stubs: ../ThriftTest.thrift + $(THRIFT) --gen cl ../ThriftTest.thrift + +TestServer: make-test-server.lisp + $(SBCL) --script make-test-server.lisp + +TestClient: make-test-client.lisp + $(SBCL) --script make-test-client.lisp + +precross: stubs TestServer TestClient + +clean-local: + $(RM) -r gen-cl + $(RM) TestServer + $(RM) TestClient + +EXTRA_DIST = \ + implementation.lisp \ + make-test-client.lisp \ + make-test-server.lisp \ + tests.lisp diff --git a/vendor/git.apache.org/thrift.git/test/cl/implementation.lisp b/vendor/git.apache.org/thrift.git/test/cl/implementation.lisp new file mode 100644 index 0000000..0caf7be --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/cl/implementation.lisp @@ -0,0 +1,136 @@ +(in-package #:thrift.test-implementation) + +;;;; 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. + +(defun thrift.test.thrift-test-implementation:test-void () + (format t "testVoid()~%")) + +(defun thrift.test.thrift-test-implementation:test-string (thing) + (format t "testString(~a)~%" thing) + thing) + +(defun thrift.test.thrift-test-implementation:test-bool (thing) + (format t "testBool(~a)~%" (if thing "true" "false")) + thing) + +(defun thrift.test.thrift-test-implementation:test-byte (thing) + (format t "testByte(~a)~%" thing) + thing) + +(defun thrift.test.thrift-test-implementation:test-i32 (thing) + (format t "testI32(~a)~%" thing) + thing) + +(defun thrift.test.thrift-test-implementation:test-i64 (thing) + (format t "testI64(~a)~%" thing) + thing) + +(defun thrift.test.thrift-test-implementation:test-double (thing) + (format t "testDouble(~a)~%" thing) + thing) + +(defun thrift.test.thrift-test-implementation:test-binary (thing) + (format t "testBinary(~a)~%" thing) + thing) + +(defun thrift.test.thrift-test-implementation:test-struct (thing) + (format t "testStruct(~a)~%" thing) + thing) + +(defun thrift.test.thrift-test-implementation:test-nest (thing) + (format t "testNest(~a)~%" thing) + thing) + +(defun thrift.test.thrift-test-implementation:test-map (thing) + (format t "testMap(~a)~%" thing) + thing) + +(defun thrift.test.thrift-test-implementation:test-string-map (thing) + (format t "testStringMap(~a)~%" thing) + thing) + +(defun thrift.test.thrift-test-implementation:test-set (thing) + (format t "testSet(~a)~%" thing) + thing) + +(defun thrift.test.thrift-test-implementation:test-list (thing) + (format t "testList(~a)~%" thing) + thing) + +(defun thrift.test.thrift-test-implementation:test-enum (thing) + (format t "testEnum(~a)~%" thing) + thing) + +(defun thrift.test.thrift-test-implementation:test-typedef (thing) + (format t "testTypedef(~a)~%" thing) + thing) + +(defun thrift.test.thrift-test-implementation:test-map-map (hello) + (format t "testMapMap(~a)~%" hello) + '((-4 . ((-4 . -4) (-3 . -3) (-2 . -2) (-1 . -1))) (4 . ((1 . 1) (2 . 2) (3 . 3) (4 . 4))))) + +(defun thrift.test.thrift-test-implementation:test-insanity (argument) + (let ((result `((1 . ((2 . ,argument) (3 . ,argument))) + (2 . ((6 . ,(thrift.test::make-insanity :user-map nil :xtructs nil))))))) + (format t "~a~%" result) + result)) + +(defun thrift.test.thrift-test-implementation:test-multi (arg0 arg1 arg2 arg3 arg4 arg5) + (declare (ignorable arg3 arg4 arg5)) + (format t "testMulti()~%") + (thrift.test:make-xtruct :string-thing "Hello2" + :byte-thing arg0 + :i32-thing arg1 + :i64-thing arg2)) + +(defun thrift.test.thrift-test-implementation:test-exception (arg) + (format t "testException(~a)~%" arg) + (cond + ((string= arg "Xception") (error 'thrift.test:xception + :error-code 1001 + :message arg)) + ((string= arg "TException") (error 'thrift.test:xception + :error-code 0 + :message "Stuff!")))) + +(defun thrift.test.thrift-test-implementation:test-multi-exception (arg0 arg1) + (format t "testMultiException(~a, ~a)~%" arg0 arg1) + (cond + ((string= arg0 "Xception") (error 'thrift.test:xception + :error-code 1001 + :message "This is an Xception")) + ((string= arg0 "Xception2") (error 'thrift.test:xception2 + :error-code 2002 + :struct-thing (thrift.test:make-xtruct :string-thing "This is an Xception2" + :byte-thing 0 + :i32-thing 0 + :i64-thing 0)))) + (thrift.test:make-xtruct :string-thing arg1 + :byte-thing 0 + :i32-thing 0 + :i64-thing 0)) + +(defun thrift.test.thrift-test-implementation:test-oneway (seconds) + (format t "testOneway(~a): Sleeping...~%" seconds) + (sleep seconds) + (format t "testOneway(~a): done sleeping!~%" seconds)) + +;;; Removed from the IDL definition. +#+(or) +(defun thrift.test.second-service-implementation:blah-blah () + (format t "blahBlah()~%")) + +(defun thrift.test.second-service-implementation:secondtest-string (thing) + (format t "secondtestString(~a)~%" thing) + (concatenate 'string "testString(\"" thing "\")")) + diff --git a/vendor/git.apache.org/thrift.git/test/cl/make-test-client.lisp b/vendor/git.apache.org/thrift.git/test/cl/make-test-client.lisp new file mode 100644 index 0000000..509669d --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/cl/make-test-client.lisp @@ -0,0 +1,93 @@ +(in-package #:cl-user) + +;;;; 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. + +#+(or) (when (not (boundp 'sb-impl::default-external-format) + (setf sb-impl::default-external-format :UTF-8))) + +(require "asdf") +(load (merge-pathnames "../../lib/cl/load-locally.lisp" *load-truename*)) +(asdf:load-system :net.didierverna.clon) +(asdf:load-system :fiasco) +(asdf:load-asd (merge-pathnames "gen-cl/ThriftTest/thrift-gen-ThriftTest.asd" *load-truename*)) +(asdf:load-system :thrift-gen-thrifttest) + +(net.didierverna.clon:nickname-package) + +(defpackage #:thrift-cross + (:use #:common-lisp #:fiasco) + (:export #:cross-test)) + +(in-package #:thrift-cross) + +(defparameter *prot* nil) + +(load (merge-pathnames "tests.lisp" *load-truename*) :external-format :UTF-8) + +(clon:defsynopsis () + (text :contents "The Common Lisp client for Thrift's cross-language test suite.") + (group (:header "Allowed options:") + (flag :short-name "h" :long-name "help" + :description "Print this help and exit.") + (stropt :long-name "host" + :description "The host to connect to." + :default-value "localhost" + :argument-name "ARG") + (stropt :long-name "port" + :description "Number of the port to listen for connections on." + :default-value "9090" + :argument-name "ARG" + :argument-type :optional) + (stropt :long-name "transport" + :description "Transport: transport to use (\"buffered\", \"framed\")" + :default-value "buffered" + :argument-name "ARG") + (stropt :long-name "protocol" + :description "Protocol: protocol to use (\"binary\", \"multi\")" + :default-value "binary" + :argument-name "ARG"))) + +(defun main () + "Entry point for our standalone application." + (clon:make-context) + (when (clon:getopt :short-name "h") + (clon:help) + (clon:exit)) + (let ((port "9090") + (host "localhost") + (framed nil) + (multiplexed nil)) + (clon:do-cmdline-options (option name value source) + (print (list option name value source)) + (if (string= name "host") + (setf host value)) + (if (string= name "port") + (setf port value)) + (if (string= name "transport") + (cond ((string= value "buffered") (setf framed nil)) + ((string= value "framed") (setf framed t)) + (t (error "Unsupported transport.")))) + (if (string= name "protocol") + (cond ((string= value "binary") (setf multiplexed nil)) + ((string= value "multi") (setf multiplexed t)) + (t (error "Unsupported protocol."))))) + (terpri) + (setf *prot* (thrift.implementation::client (puri:parse-uri + (concatenate 'string "thrift://" host ":" port)) + :framed framed + :multiplexed multiplexed)) + (let ((result (cross-test :multiplexed multiplexed))) + (thrift.implementation::close *prot*) + (clon:exit result)))) + +(clon:dump "TestClient" main) diff --git a/vendor/git.apache.org/thrift.git/test/cl/make-test-server.lisp b/vendor/git.apache.org/thrift.git/test/cl/make-test-server.lisp new file mode 100644 index 0000000..293c879 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/cl/make-test-server.lisp @@ -0,0 +1,80 @@ +(in-package #:cl-user) + +;;;; 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. + +(require "asdf") +(load (merge-pathnames "../../lib/cl/load-locally.lisp" *load-truename*)) +(asdf:load-system :net.didierverna.clon) +(asdf:load-asd (merge-pathnames "gen-cl/ThriftTest/thrift-gen-ThriftTest.asd" *load-truename*)) +(asdf:load-system :thrift-gen-thrifttest) +(load (merge-pathnames "implementation.lisp" *load-truename*)) + +(net.didierverna.clon:nickname-package) + +(clon:defsynopsis () + (text :contents "The Common Lisp server for Thrift's cross-language test suite.") + (group (:header "Allowed options:") + (flag :short-name "h" :long-name "help" + :description "Print this help and exit.") + (stropt :long-name "port" + :description "Number of the port to listen for connections on." + :default-value "9090" + :argument-name "ARG" + :argument-type :optional) + (stropt :long-name "server-type" + :description "The type of server, currently only \"simple\" is available." + :default-value "simple" + :argument-name "ARG") + (stropt :long-name "transport" + :description "Transport: transport to use (\"buffered\" or \"framed\")" + :default-value "buffered" + :argument-name "ARG") + (stropt :long-name "protocol" + :description "Protocol: protocol to use (\"binary\" or \"multi\")" + :default-value "binary" + :argument-name "ARG"))) + +(defun main () + "Entry point for our standalone application." + (clon:make-context) + (when (clon:getopt :short-name "h") + (clon:help) + (clon:exit)) + (let ((port "9090") + (framed nil) + (multiplexed nil)) + (clon:do-cmdline-options (option name value source) + (print (list option name value source)) + (if (string= name "port") + (setf port value)) + (if (string= name "transport") + (cond ((string= value "buffered") (setf framed nil)) + ((string= value "framed") (setf framed t)) + (t (error "Unsupported transport.")))) + (if (string= name "protocol") + (cond ((string= value "binary") (setf multiplexed nil)) + ((string= value "multi") (setf multiplexed t)) + (t (error "Unsupported protocol."))))) + (terpri) + (let ((services (if multiplexed + (list thrift.test:thrift-test thrift.test:second-service) + thrift.test:thrift-test))) + (thrift:serve (puri:parse-uri (concatenate 'string + "thrift://127.0.0.1:" + port)) + services + :framed framed + :multiplexed multiplexed))) + (clon:exit)) + +(clon:dump "TestServer" main) diff --git a/vendor/git.apache.org/thrift.git/test/cl/tests.lisp b/vendor/git.apache.org/thrift.git/test/cl/tests.lisp new file mode 100644 index 0000000..c5035fd --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/cl/tests.lisp @@ -0,0 +1,240 @@ +(in-package #:thrift-cross) + +;;;; 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. + +;;;; The tests here only make sense in the context of a TestServer +;;;; running and the dynamic variable thrift-cross::*prot* +;;;; being set with a client connection to the TestServer. Normally, +;;;; this is handled in make-test-client.lisp. + + +;;; Standard Thrift cross-test error codes +(defparameter *test_basetypes* 1) +(defparameter *test_structs* 2) +(defparameter *test_containers* 4) +(defparameter *test_exceptions* 8) +(defparameter *test_unknown* 64) +(defparameter *test_timeout* 128) + +(defun cross-test (&key (multiplexed nil)) + "The main cross-test runner." + (let ((result nil)) + (handler-case + (progn + (unless (run-package-tests :package :base-types) + (pushnew *test_basetypes* result)) + (unless (run-package-tests :package :structs) + (pushnew *test_structs* result)) + (unless (run-package-tests :package :containers) + (pushnew *test_containers* result)) + (unless (run-package-tests :package :exceptions) + (pushnew *test_exceptions* result)) + (unless (run-package-tests :package :misc) + (pushnew *test_unknown* result)) + + ;; It doesn't seem like anyone actually uses + ;; the second test service when testing multiplexing, + ;; so this would fail against servers in other + ;; languages. For now, anyway. + #+(or) + (when multiplexed + (unless (run-package-tests :package :multiplex) + (pushnew *test_unknown* result)))) + (error (e) (pushnew *test_unknown* result))) + (apply #'+ result))) + +(fiasco:define-test-package #:base-types) + +(in-package #:base-types) + +(defconstant *lang-string* "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, Asturianu, Aymar aru, AzÉ™rbaycan, Башҡорт, Boarisch, ŽemaitÄ—Å¡ka, БеларуÑкаÑ, БеларуÑÐºÐ°Ñ (тарашкевіца), БългарÑки, Bamanankan, বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Ðохчийн, Cebuano, á£áŽ³áŽ©, ÄŒesky, СловѣÌньÑкъ / ⰔⰎⰑⰂⰡâ°â° â°”â°â°Ÿ, Чӑвашла, Cymraeg, Dansk, Zazaki, Þ‹Þ¨ÞˆÞ¬Þ€Þ¨Þ„Þ¦ÞÞ°, Ελληνικά, Emiliàn e rumagnòl, English, Esperanto, Español, Eesti, Euskara, ÙØ§Ø±Ø³ÛŒ, Suomi, Võro, Føroyskt, Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, Avañe'ẽ, ગà«àªœàª°àª¾àª¤à«€, Gaelg, עברית, हिनà¥à¤¦à¥€, Fiji Hindi, Hrvatski, Kreyòl ayisyen, Magyar, Õ€Õ¡ÕµÕ¥Ö€Õ¥Õ¶, Interlingua, Bahasa Indonesia, Ilokano, Ido, Ãslenska, Italiano, 日本語, Lojban, Basa Jawa, ქáƒáƒ áƒ—ული, Kongo, Kalaallisut, ಕನà³à²¨à²¡, 한국어, Къарачай-Малкъар, Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, LatvieÅ¡u, Basa Banyumasan, Malagasy, МакедонÑки, മലയാളം, मराठी, Ù…Ø§Ø²ÙØ±ÙˆÙ†ÛŒ, Bahasa Melayu, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, ‪Norsk (nynorsk)‬, ‪Norsk (bokmÃ¥l)‬, Nouormand, Diné bizaad, Occitan, Иронау, Papiamentu, Deitsch, Polski, پنجابی, پښتو, Norfuk / Pitkern, Português, Runa Simi, Rumantsch, Romani, Română, РуÑÑкий, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple English, SlovenÄina, SlovenÅ¡Äina, СрпÑки / Srpski, Seeltersk, Svenska, Kiswahili, தமிழà¯, తెలà±à°—à±, Тоҷикӣ, ไทย, Türkmençe, Tagalog, Türkçe, Татарча/Tatarça, УкраїнÑька, اردو, Tiếng Việt, Volapük, Walon, Winaray, å´è¯­, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, Bân-lâm-gú, 粵語") + +(defparameter *trick-string* (format nil "quote: \" backslash: \\ newline: ~% backspace: ~C ~ + tab: ~T junk: !@#$%&()(&%$#{}{}<><><" #\backspace)) + +(defconstant *binary-sequence* #(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 0 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)) + +(deftest void-test () + (is (null (thrift.test.thrift-test:test-void thrift-cross::*prot*)))) + +(deftest boolean-test () + (is (thrift.test.thrift-test:test-bool thrift-cross::*prot* t)) + (is (not (thrift.test.thrift-test:test-bool thrift-cross::*prot* nil)))) + +(deftest integer-test () + (is (= (thrift.test.thrift-test:test-byte thrift-cross::*prot* 127) 127)) + (is (= (thrift.test.thrift-test:test-byte thrift-cross::*prot* -128) -128)) + (is (= (thrift.test.thrift-test:test-byte thrift-cross::*prot* 42) 42)) + (is (= (thrift.test.thrift-test:test-byte thrift-cross::*prot* 0) 0)) + (is (= (thrift.test.thrift-test:test-i32 thrift-cross::*prot* 0) 0)) + (is (= (thrift.test.thrift-test:test-i32 thrift-cross::*prot* 2147483647) 2147483647)) + (is (= (thrift.test.thrift-test:test-i32 thrift-cross::*prot* -2147483648) -2147483648)) + (is (= (thrift.test.thrift-test:test-i64 thrift-cross::*prot* 0) 0)) + (is (= (thrift.test.thrift-test:test-i64 thrift-cross::*prot* 9223372036854775807) 9223372036854775807)) + (is (= (thrift.test.thrift-test:test-i64 thrift-cross::*prot* -9223372036854775808) -9223372036854775808))) + +(deftest double-test () + (is (= (thrift.test.thrift-test:test-double thrift-cross::*prot* 0.0) 0)) + (is (= (thrift.test.thrift-test:test-double thrift-cross::*prot* 42.0) 42)) + (is (= (thrift.test.thrift-test:test-double thrift-cross::*prot* -555.0) -555)) + (is (= (thrift.test.thrift-test:test-double thrift-cross::*prot* -52.3678) -52.3678))) + +(deftest string-test () + (is (string= (thrift.test.thrift-test:test-string thrift-cross::*prot* "") "")) + (is (string= (thrift.test.thrift-test:test-string thrift-cross::*prot* "(defun botsbuildbots () (botsbuilsbots))") + "(defun botsbuildbots () (botsbuilsbots))")) + (is (string= (thrift.test.thrift-test:test-string thrift-cross::*prot* *lang-string*) *lang-string*)) + (is (string= (thrift.test.thrift-test:test-string thrift-cross::*prot* *trick-string*) *trick-string*))) + +(deftest binary-test () + (is (equalp (thrift.test.thrift-test:test-binary thrift-cross::*prot* #()) #())) + (is (equalp (thrift.test.thrift-test:test-binary thrift-cross::*prot* *binary-sequence*) *binary-sequence*))) + +(deftest enum-test () + (is (= (thrift.test.thrift-test:test-enum thrift-cross::*prot* thrift.test:numberz.five) thrift.test:numberz.five)) + (is (= (thrift.test.thrift-test:test-enum thrift-cross::*prot* thrift.test:numberz.eight) thrift.test:numberz.eight)) + (is (= (thrift.test.thrift-test:test-enum thrift-cross::*prot* thrift.test:numberz.one) thrift.test:numberz.one))) + +(deftest typedef-test () + (is (= (thrift.test.thrift-test:test-typedef thrift-cross::*prot* 309858235082523) 309858235082523))) + +(fiasco:define-test-package #:structs) + +(in-package #:structs) + +(defparameter *test-struct* (thrift.test:make-xtruct :string-thing "Hell is empty." + :byte-thing -2 + :i32-thing 42 + :i64-thing 42424242)) + +(defparameter *test-nest* (thrift.test:make-xtruct2 :byte-thing 42 + :struct-thing *test-struct* + :i32-thing -42)) + +(deftest struct-test () + (let ((rec-struct (thrift.test.thrift-test:test-struct thrift-cross::*prot* *test-struct*))) + (is (string= (thrift.test:xtruct-string-thing *test-struct*) + (thrift.test:xtruct-string-thing rec-struct))) + (is (= (thrift.test:xtruct-byte-thing *test-struct*) + (thrift.test:xtruct-byte-thing rec-struct))) + (is (= (thrift.test:xtruct-i32-thing *test-struct*) + (thrift.test:xtruct-i32-thing rec-struct))) + (is (= (thrift.test:xtruct-i64-thing *test-struct*) + (thrift.test:xtruct-i64-thing rec-struct))))) + +(deftest nest-test () + (let* ((rec-nest (thrift.test.thrift-test:test-nest thrift-cross::*prot* *test-nest*)) + (rec-struct (thrift.test:xtruct2-struct-thing rec-nest))) + (is (string= (thrift.test:xtruct-string-thing *test-struct*) + (thrift.test:xtruct-string-thing rec-struct))) + (is (= (thrift.test:xtruct-byte-thing *test-struct*) + (thrift.test:xtruct-byte-thing rec-struct))) + (is (= (thrift.test:xtruct-i32-thing *test-struct*) + (thrift.test:xtruct-i32-thing rec-struct))) + (is (= (thrift.test:xtruct-i64-thing *test-struct*) + (thrift.test:xtruct-i64-thing rec-struct))) + (is (= (thrift.test:xtruct2-byte-thing *test-nest*) + (thrift.test:xtruct2-byte-thing rec-nest))) + (is (= (thrift.test:xtruct2-i32-thing *test-nest*) + (thrift.test:xtruct2-i32-thing rec-nest))))) + +(fiasco:define-test-package #:containers) + +(in-package #:containers) + +(deftest list-test () + (is (null (thrift.test.thrift-test:test-list thrift-cross::*prot* nil))) + (is (equal (thrift.test.thrift-test:test-list thrift-cross::*prot* '(42 -42 0 5)) '(42 -42 0 5)))) + +(deftest set-test () + (is (null (thrift.test.thrift-test:test-set thrift-cross::*prot* nil))) + (is (equal (sort (thrift.test.thrift-test:test-set thrift-cross::*prot* (list 42 -42 0 5)) #'<) + '(-42 0 5 42)))) + +(defun map= (map1 map2 &key (car-predicate #'equal) (cdr-predicate #'equal)) + "Compare two assoc maps according to the predicates given." + (not (set-exclusive-or map1 map2 :test (lambda (el1 el2) + (and (funcall car-predicate + (car el1) + (car el2)) + (funcall cdr-predicate + (cdr el1) + (cdr el2))))))) + +(deftest map-test () + (is (null (thrift.test.thrift-test:test-map thrift-cross::*prot* nil))) + (is (map= (thrift.test.thrift-test:test-map thrift-cross::*prot* '((0 . 1) (42 . -42) (5 . 5))) + '((0 . 1) (42 . -42) (5 . 5)))) + (is (map= (thrift.test.thrift-test:test-map-map thrift-cross::*prot* 42) + '((-4 . ((-4 . -4) (-3 . -3) (-2 . -2) (-1 . -1))) + (4 . ((1 . 1) (2 . 2) (3 . 3) (4 . 4)))) + :cdr-predicate #'map=))) + +(fiasco:define-test-package #:exceptions) + +(in-package #:exceptions) + +(defun test-xception (expected-code expected-message function &rest args) + "A helper function to test whether xception is signalled, and whether its fields have the expected values." + (handler-case (progn (apply function args) + nil) + (thrift.test:xception (ex) (and (= (thrift.test::xception-error-code ex) expected-code) + (string= (thrift.test::xception-message ex) expected-message))))) + +(defun test-xception2 (expected-code expected-message function &rest args) + "A helper function to test whether xception2 is signalled, and whether its fields have the expected values." + (handler-case (progn (apply function args) + nil) + (thrift.test:xception2 (ex) (and (= (thrift.test::xception2-error-code ex) expected-code) + (string= (thrift.test::xtruct-string-thing + (thrift.test::xception2-struct-thing ex)) + expected-message))))) + +(deftest exception-test () + (is (test-xception 1001 "Xception" #'thrift.test.thrift-test:test-exception thrift-cross::*prot* "Xception")) + (signals thrift:application-error (thrift.test.thrift-test:test-exception thrift-cross::*prot* "TException")) + (finishes (thrift.test.thrift-test:test-exception thrift-cross::*prot* "success"))) + +(deftest multi-exception-test () + (is (test-xception 1001 + "This is an Xception" + #'thrift.test.thrift-test:test-multi-exception + thrift-cross::*prot* + "Xception" + "meaningless")) + (is (test-xception2 2002 + "This is an Xception2" + #'thrift.test.thrift-test:test-multi-exception + thrift-cross::*prot* + "Xception2" + "meaningless too!")) + (is (string= "foobar" (thrift.test:xtruct-string-thing + (thrift.test.thrift-test:test-multi-exception thrift-cross::*prot* + "success!" + "foobar"))))) + +(fiasco:define-test-package #:misc) + +(in-package #:misc) + +(deftest oneway-test () + (is (null (thrift.test.thrift-test:test-oneway thrift-cross::*prot* 1)))) + +(fiasco:define-test-package #:multiplex) + +(in-package #:multiplex) + +(deftest multiplex-test () + ;; Removed from the IDL definition. + ;; (finishes (thrift.test.second-service:blah-blah thrift-cross::*prot*)) + (is (string= "asd" (thrift.test.second-service:secondtest-string thrift-cross::*prot* "asd")))) diff --git a/vendor/git.apache.org/thrift.git/test/cpp/CMakeLists.txt b/vendor/git.apache.org/thrift.git/test/cpp/CMakeLists.txt index 09850a8..95d2991 100755 --- a/vendor/git.apache.org/thrift.git/test/cpp/CMakeLists.txt +++ b/vendor/git.apache.org/thrift.git/test/cpp/CMakeLists.txt @@ -28,13 +28,16 @@ include_directories(SYSTEM "${OPENSSL_INCLUDE_DIR}") find_package(Libevent REQUIRED) # Libevent comes with CMake support from upstream include_directories(SYSTEM ${LIBEVENT_INCLUDE_DIRS}) +find_package(ZLIB REQUIRED) +include_directories(SYSTEM ${ZLIB_INCLUDE_DIRS}) + #Make sure gen-cpp files can be included include_directories("${CMAKE_CURRENT_BINARY_DIR}") include_directories("${CMAKE_CURRENT_BINARY_DIR}/gen-cpp") include_directories("${PROJECT_SOURCE_DIR}/lib/cpp/src") - set(crosstestgencpp_SOURCES + gen-cpp/SecondService.cpp gen-cpp/ThriftTest.cpp gen-cpp/ThriftTest_types.cpp gen-cpp/ThriftTest_constants.cpp @@ -45,7 +48,7 @@ LINK_AGAINST_THRIFT_LIBRARY(crosstestgencpp thrift) set(crossstressgencpp_SOURCES gen-cpp/Service.cpp - #gen-cpp/StressTest_types.cpp #basically empty, so omitting + gen-cpp/StressTest_types.cpp gen-cpp/StressTest_constants.cpp ) add_library(crossstressgencpp STATIC ${crossstressgencpp_SOURCES}) @@ -80,7 +83,7 @@ add_test(NAME StressTestNonBlocking COMMAND StressTestNonBlocking) # Common thrift code generation rules # -add_custom_command(OUTPUT gen-cpp/ThriftTest.cpp gen-cpp/ThriftTest_types.cpp gen-cpp/ThriftTest_constants.cpp +add_custom_command(OUTPUT gen-cpp/SecondService.cpp gen-cpp/SecondService.h gen-cpp/ThriftTest.cpp gen-cpp/ThriftTest.h gen-cpp/ThriftTest_types.cpp gen-cpp/ThriftTest_constants.cpp COMMAND ${THRIFT_COMPILER} --gen cpp:templates,cob_style -r ${PROJECT_SOURCE_DIR}/test/ThriftTest.thrift ) diff --git a/vendor/git.apache.org/thrift.git/test/cpp/Makefile.am b/vendor/git.apache.org/thrift.git/test/cpp/Makefile.am index 9c4ac07..e8be80a 100755 --- a/vendor/git.apache.org/thrift.git/test/cpp/Makefile.am +++ b/vendor/git.apache.org/thrift.git/test/cpp/Makefile.am @@ -21,12 +21,16 @@ AUTOMAKE_OPTIONS = subdir-objects serial-tests BUILT_SOURCES = gen-cpp/ThriftTest.cpp \ gen-cpp/ThriftTest_types.cpp \ gen-cpp/ThriftTest_constants.cpp \ + gen-cpp/SecondService.cpp \ gen-cpp/StressTest_types.cpp \ gen-cpp/StressTest_constants.cpp \ gen-cpp/Service.cpp noinst_LTLIBRARIES = libtestgencpp.la libstresstestgencpp.la nodist_libtestgencpp_la_SOURCES = \ + gen-cpp/SecondService.cpp \ + gen-cpp/SecondService.h \ + gen-cpp/SecondService.tcc \ gen-cpp/ThriftTest_constants.cpp \ gen-cpp/ThriftTest_constants.h \ gen-cpp/ThriftTest_types.cpp \ @@ -98,16 +102,14 @@ StressTestNonBlocking_LDADD = \ # # Common thrift code generation rules # -THRIFT = $(top_builddir)/compiler/cpp/thrift - -gen-cpp/ThriftTest.cpp gen-cpp/ThriftTest_types.cpp gen-cpp/ThriftTest_constants.cpp: $(top_srcdir)/test/ThriftTest.thrift $(THRIFT) +gen-cpp/ThriftTest.cpp gen-cpp/ThriftTest_types.cpp gen-cpp/ThriftTest_constants.cpp gen-cpp/SecondService.cpp gen-cpp/SecondService.h gen-cpp/SecondService.tcc: $(top_srcdir)/test/ThriftTest.thrift $(THRIFT) $(THRIFT) --gen cpp:templates,cob_style -r $< gen-cpp/StressTest_types.cpp gen-cpp/StressTest_constants.cpp gen-cpp/Service.cpp: $(top_srcdir)/test/StressTest.thrift $(THRIFT) $(THRIFT) --gen cpp $< AM_CPPFLAGS = $(BOOST_CPPFLAGS) $(LIBEVENT_CPPFLAGS) -I$(top_srcdir)/lib/cpp/src -Igen-cpp -AM_CXXFLAGS = -Wall -Wextra -pedantic +AM_CXXFLAGS = -Wall -Wextra -pedantic -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS AM_LDFLAGS = $(BOOST_LDFLAGS) $(LIBEVENT_LDFLAGS) $(ZLIB_LIBS) clean-local: @@ -120,6 +122,4 @@ EXTRA_DIST = \ src/TestClient.cpp \ src/TestServer.cpp \ src/StressTest.cpp \ - src/StressTestNonBlocking.cpp \ - realloc/realloc_test.c \ - realloc/Makefile + src/StressTestNonBlocking.cpp diff --git a/vendor/git.apache.org/thrift.git/test/cpp/realloc/realloc_test.c b/vendor/git.apache.org/thrift.git/test/cpp/realloc/realloc_test.c deleted file mode 100644 index f9763ad..0000000 --- a/vendor/git.apache.org/thrift.git/test/cpp/realloc/realloc_test.c +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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. - */ - -#define _GNU_SOURCE -#include -#include -#include -#include - -int copies; -int non_copies; - -void *realloc(void *ptr, size_t size) { - static void *(*real_realloc)(void*, size_t) = NULL; - if (real_realloc == NULL) { - real_realloc = (void* (*) (void*, size_t)) dlsym(RTLD_NEXT, "realloc"); - } - - void *ret_ptr = (*real_realloc)(ptr, size); - - if (ret_ptr == ptr) { - non_copies++; - } else { - copies++; - } - - return ret_ptr; -} - - -struct TMemoryBuffer { - void* ptr; - int size; -}; - -int main(int argc, char *argv[]) { - int num_buffers; - int init_size; - int max_size; - int doublings; - int iterations; - - if (argc < 6 || - argc > 7 || - (num_buffers = atoi(argv[1])) == 0 || - (init_size = atoi(argv[2])) == 0 || - (max_size = atoi(argv[3])) == 0 || - init_size > max_size || - (iterations = atoi(argv[4])) == 0 || - (doublings = atoi(argv[5])) == 0 || - (argc == 7 && atoi(argv[6]) == 0)) { - fprintf(stderr, "usage: realloc_test [seed]\n"); - exit(EXIT_FAILURE); - } - - for ( int i = 0 ; i < argc ; i++ ) { - printf("%s ", argv[i]); - } - printf("\n"); - - if (argc == 7) { - srand(atoi(argv[6])); - } else { - srand(time(NULL)); - } - - struct TMemoryBuffer* buffers = calloc(num_buffers, sizeof(*buffers)); - if (buffers == NULL) abort(); - - for ( int i = 0 ; i < num_buffers ; i++ ) { - buffers[i].size = max_size; - } - - while (iterations --> 0) { - for ( int i = 0 ; i < doublings * num_buffers ; i++ ) { - struct TMemoryBuffer* buf = &buffers[rand() % num_buffers]; - buf->size *= 2; - if (buf->size <= max_size) { - buf->ptr = realloc(buf->ptr, buf->size); - } else { - free(buf->ptr); - buf->size = init_size; - buf->ptr = malloc(buf->size); - } - if (buf->ptr == NULL) abort(); - } - } - - printf("Non-copied %d/%d (%.2f%%)\n", non_copies, copies + non_copies, 100.0 * non_copies / (copies + non_copies)); - return 0; -} diff --git a/vendor/git.apache.org/thrift.git/test/cpp/src/StressTest.cpp b/vendor/git.apache.org/thrift.git/test/cpp/src/StressTest.cpp index 9371bce..5ff5e44 100644 --- a/vendor/git.apache.org/thrift.git/test/cpp/src/StressTest.cpp +++ b/vendor/git.apache.org/thrift.git/test/cpp/src/StressTest.cpp @@ -31,6 +31,7 @@ #include #include #include +#include #include "Service.h" #include @@ -107,8 +108,8 @@ enum TransportOpenCloseBehavior { }; class ClientThread : public Runnable { public: - ClientThread(boost::shared_ptr transport, - boost::shared_ptr client, + ClientThread(stdcxx::shared_ptr transport, + stdcxx::shared_ptr client, Monitor& monitor, size_t& workerCount, size_t loopCount, @@ -224,8 +225,8 @@ public: } } - boost::shared_ptr _transport; - boost::shared_ptr _client; + stdcxx::shared_ptr _transport; + stdcxx::shared_ptr _client; Monitor& _monitor; size_t& _workerCount; size_t _loopCount; @@ -285,14 +286,14 @@ int main(int argc, char** argv) { "server only. Default is " << clientCount << endl << "\thelp Prints this help text." << endl << "\tcall Service method to call. Default is " << callName << endl - << "\tloop The number of remote thrift calls each client makes. Default is " << loopCount << endl + << "\tloop The number of remote thrift calls each client makes. Default is " << loopCount << endl << "\tport The port the server and clients should bind to " "for thrift network connections. Default is " << port << endl - << "\tserver Run the Thrift server in this process. Default is " << runServer << endl + << "\tserver Run the Thrift server in this process. Default is " << runServer << endl << "\tserver-type Type of server, \"simple\" or \"thread-pool\". Default is " << serverType << endl << "\tprotocol-type Type of protocol, \"binary\", \"ascii\", or \"xml\". Default is " << protocolType << endl - << "\tlog-request Log all request to ./requestlog.tlog. Default is " << logRequests << endl - << "\treplay-request Replay requests from log file (./requestlog.tlog) Default is " << replayRequests << endl + << "\tlog-request Log all request to ./requestlog.tlog. Default is " << logRequests << endl + << "\treplay-request Replay requests from log file (./requestlog.tlog) Default is " << replayRequests << endl << "\tworkers Number of thread pools workers. Only valid " "for thread-pool server type. Default is " << workerCount << endl << "\tclient-type Type of client, \"regular\" or \"concurrent\". Default is " << clientType << endl @@ -390,24 +391,24 @@ int main(int argc, char** argv) { cerr << usage.str(); } - boost::shared_ptr threadFactory - = boost::shared_ptr(new PlatformThreadFactory()); + stdcxx::shared_ptr threadFactory + = stdcxx::shared_ptr(new PlatformThreadFactory()); // Dispatcher - boost::shared_ptr serviceHandler(new Server()); + stdcxx::shared_ptr serviceHandler(new Server()); if (replayRequests) { - boost::shared_ptr serviceHandler(new Server()); - boost::shared_ptr serviceProcessor(new ServiceProcessor(serviceHandler)); + stdcxx::shared_ptr serviceHandler(new Server()); + stdcxx::shared_ptr serviceProcessor(new ServiceProcessor(serviceHandler)); // Transports - boost::shared_ptr fileTransport(new TFileTransport(requestLogPath)); + stdcxx::shared_ptr fileTransport(new TFileTransport(requestLogPath)); fileTransport->setChunkSize(2 * 1024 * 1024); fileTransport->setMaxEventSize(1024 * 16); fileTransport->seekToEnd(); // Protocol Factory - boost::shared_ptr protocolFactory(new TBinaryProtocolFactory()); + stdcxx::shared_ptr protocolFactory(new TBinaryProtocolFactory()); TFileProcessor fileProcessor(serviceProcessor, protocolFactory, fileTransport); @@ -417,28 +418,28 @@ int main(int argc, char** argv) { if (runServer) { - boost::shared_ptr serviceProcessor(new ServiceProcessor(serviceHandler)); + stdcxx::shared_ptr serviceProcessor(new ServiceProcessor(serviceHandler)); // Transport - boost::shared_ptr serverSocket(new TServerSocket(port)); + stdcxx::shared_ptr serverSocket(new TServerSocket(port)); // Transport Factory - boost::shared_ptr transportFactory(new TBufferedTransportFactory()); + stdcxx::shared_ptr transportFactory(new TBufferedTransportFactory()); // Protocol Factory - boost::shared_ptr protocolFactory(new TBinaryProtocolFactory()); + stdcxx::shared_ptr protocolFactory(new TBinaryProtocolFactory()); if (logRequests) { // initialize the log file - boost::shared_ptr fileTransport(new TFileTransport(requestLogPath)); + stdcxx::shared_ptr fileTransport(new TFileTransport(requestLogPath)); fileTransport->setChunkSize(2 * 1024 * 1024); fileTransport->setMaxEventSize(1024 * 16); transportFactory - = boost::shared_ptr(new TPipedTransportFactory(fileTransport)); + = stdcxx::shared_ptr(new TPipedTransportFactory(fileTransport)); } - boost::shared_ptr server; + stdcxx::shared_ptr server; if (serverType == "simple") { @@ -452,7 +453,7 @@ int main(int argc, char** argv) { } else if (serverType == "thread-pool") { - boost::shared_ptr threadManager + stdcxx::shared_ptr threadManager = ThreadManager::newSimpleThreadManager(workerCount); threadManager->threadFactory(threadFactory); @@ -464,9 +465,9 @@ int main(int argc, char** argv) { threadManager)); } - boost::shared_ptr observer(new TStartObserver); + stdcxx::shared_ptr observer(new TStartObserver); server->setServerEventHandler(observer); - boost::shared_ptr serverThread = threadFactory->newThread(server); + stdcxx::shared_ptr serverThread = threadFactory->newThread(server); cerr << "Starting the server on port " << port << endl; @@ -485,7 +486,7 @@ int main(int argc, char** argv) { size_t threadCount = 0; - set > clientThreads; + set > clientThreads; if (callName == "echoVoid") { loopType = T_VOID; @@ -504,28 +505,28 @@ int main(int argc, char** argv) { if(clientType == "regular") { for (size_t ix = 0; ix < clientCount; ix++) { - boost::shared_ptr socket(new TSocket("127.0.0.1", port)); - boost::shared_ptr bufferedSocket(new TBufferedTransport(socket, 2048)); - boost::shared_ptr protocol(new TBinaryProtocol(bufferedSocket)); - boost::shared_ptr serviceClient(new ServiceClient(protocol)); + stdcxx::shared_ptr socket(new TSocket("127.0.0.1", port)); + stdcxx::shared_ptr bufferedSocket(new TBufferedTransport(socket, 2048)); + stdcxx::shared_ptr protocol(new TBinaryProtocol(bufferedSocket)); + stdcxx::shared_ptr serviceClient(new ServiceClient(protocol)); - clientThreads.insert(threadFactory->newThread(boost::shared_ptr( + clientThreads.insert(threadFactory->newThread(stdcxx::shared_ptr( new ClientThread(socket, serviceClient, monitor, threadCount, loopCount, loopType, OpenAndCloseTransportInThread)))); } } else if(clientType == "concurrent") { - boost::shared_ptr socket(new TSocket("127.0.0.1", port)); - boost::shared_ptr bufferedSocket(new TBufferedTransport(socket, 2048)); - boost::shared_ptr protocol(new TBinaryProtocol(bufferedSocket)); - //boost::shared_ptr serviceClient(new ServiceClient(protocol)); - boost::shared_ptr serviceClient(new ServiceConcurrentClient(protocol)); + stdcxx::shared_ptr socket(new TSocket("127.0.0.1", port)); + stdcxx::shared_ptr bufferedSocket(new TBufferedTransport(socket, 2048)); + stdcxx::shared_ptr protocol(new TBinaryProtocol(bufferedSocket)); + //stdcxx::shared_ptr serviceClient(new ServiceClient(protocol)); + stdcxx::shared_ptr serviceClient(new ServiceConcurrentClient(protocol)); socket->open(); for (size_t ix = 0; ix < clientCount; ix++) { - clientThreads.insert(threadFactory->newThread(boost::shared_ptr( + clientThreads.insert(threadFactory->newThread(stdcxx::shared_ptr( new ClientThread(socket, serviceClient, monitor, threadCount, loopCount, loopType, DontOpenAndCloseTransportInThread)))); } } - for (std::set >::const_iterator thread = clientThreads.begin(); + for (std::set >::const_iterator thread = clientThreads.begin(); thread != clientThreads.end(); thread++) { (*thread)->start(); @@ -558,12 +559,12 @@ int main(int argc, char** argv) { int64_t minTime = 9223372036854775807LL; int64_t maxTime = 0; - for (set >::iterator ix = clientThreads.begin(); + for (set >::iterator ix = clientThreads.begin(); ix != clientThreads.end(); ix++) { - boost::shared_ptr client - = boost::dynamic_pointer_cast((*ix)->runnable()); + stdcxx::shared_ptr client + = stdcxx::dynamic_pointer_cast((*ix)->runnable()); int64_t delta = client->_endTime - client->_startTime; diff --git a/vendor/git.apache.org/thrift.git/test/cpp/src/StressTestNonBlocking.cpp b/vendor/git.apache.org/thrift.git/test/cpp/src/StressTestNonBlocking.cpp index 8f161c0..e68988f 100644 --- a/vendor/git.apache.org/thrift.git/test/cpp/src/StressTestNonBlocking.cpp +++ b/vendor/git.apache.org/thrift.git/test/cpp/src/StressTestNonBlocking.cpp @@ -29,14 +29,14 @@ #include #include #include +#include #include #include #include +#include #include "Service.h" -#include - #include #include #include @@ -109,8 +109,8 @@ private: class ClientThread : public Runnable { public: - ClientThread(boost::shared_ptr transport, - boost::shared_ptr client, + ClientThread(stdcxx::shared_ptr transport, + stdcxx::shared_ptr client, Monitor& monitor, size_t& workerCount, size_t loopCount, @@ -221,8 +221,8 @@ public: } } - boost::shared_ptr _transport; - boost::shared_ptr _client; + stdcxx::shared_ptr _transport; + stdcxx::shared_ptr _client; Monitor& _monitor; size_t& _workerCount; size_t _loopCount; @@ -344,24 +344,24 @@ int main(int argc, char** argv) { cerr << usage.str(); } - boost::shared_ptr threadFactory - = boost::shared_ptr(new PlatformThreadFactory()); + stdcxx::shared_ptr threadFactory + = stdcxx::shared_ptr(new PlatformThreadFactory()); // Dispatcher - boost::shared_ptr serviceHandler(new Server()); + stdcxx::shared_ptr serviceHandler(new Server()); if (replayRequests) { - boost::shared_ptr serviceHandler(new Server()); - boost::shared_ptr serviceProcessor(new ServiceProcessor(serviceHandler)); + stdcxx::shared_ptr serviceHandler(new Server()); + stdcxx::shared_ptr serviceProcessor(new ServiceProcessor(serviceHandler)); // Transports - boost::shared_ptr fileTransport(new TFileTransport(requestLogPath)); + stdcxx::shared_ptr fileTransport(new TFileTransport(requestLogPath)); fileTransport->setChunkSize(2 * 1024 * 1024); fileTransport->setMaxEventSize(1024 * 16); fileTransport->seekToEnd(); // Protocol Factory - boost::shared_ptr protocolFactory(new TBinaryProtocolFactory()); + stdcxx::shared_ptr protocolFactory(new TBinaryProtocolFactory()); TFileProcessor fileProcessor(serviceProcessor, protocolFactory, fileTransport); @@ -371,45 +371,51 @@ int main(int argc, char** argv) { if (runServer) { - boost::shared_ptr serviceProcessor(new ServiceProcessor(serviceHandler)); + stdcxx::shared_ptr serviceProcessor(new ServiceProcessor(serviceHandler)); // Protocol Factory - boost::shared_ptr protocolFactory(new TBinaryProtocolFactory()); + stdcxx::shared_ptr protocolFactory(new TBinaryProtocolFactory()); // Transport Factory - boost::shared_ptr transportFactory; + stdcxx::shared_ptr transportFactory; if (logRequests) { // initialize the log file - boost::shared_ptr fileTransport(new TFileTransport(requestLogPath)); + stdcxx::shared_ptr fileTransport(new TFileTransport(requestLogPath)); fileTransport->setChunkSize(2 * 1024 * 1024); fileTransport->setMaxEventSize(1024 * 16); transportFactory - = boost::shared_ptr(new TPipedTransportFactory(fileTransport)); + = stdcxx::shared_ptr(new TPipedTransportFactory(fileTransport)); } - boost::shared_ptr serverThread; - boost::shared_ptr serverThread2; + stdcxx::shared_ptr serverThread; + stdcxx::shared_ptr serverThread2; + stdcxx::shared_ptr nbSocket1; + stdcxx::shared_ptr nbSocket2; if (serverType == "simple") { - serverThread = threadFactory->newThread(boost::shared_ptr( - new TNonblockingServer(serviceProcessor, protocolFactory, port))); - serverThread2 = threadFactory->newThread(boost::shared_ptr( - new TNonblockingServer(serviceProcessor, protocolFactory, port + 1))); + nbSocket1.reset(new transport::TNonblockingServerSocket(port)); + serverThread = threadFactory->newThread(stdcxx::shared_ptr( + new TNonblockingServer(serviceProcessor, protocolFactory, nbSocket1))); + nbSocket2.reset(new transport::TNonblockingServerSocket(port + 1)); + serverThread2 = threadFactory->newThread(stdcxx::shared_ptr( + new TNonblockingServer(serviceProcessor, protocolFactory, nbSocket2))); } else if (serverType == "thread-pool") { - boost::shared_ptr threadManager + stdcxx::shared_ptr threadManager = ThreadManager::newSimpleThreadManager(workerCount); threadManager->threadFactory(threadFactory); threadManager->start(); - serverThread = threadFactory->newThread(boost::shared_ptr( - new TNonblockingServer(serviceProcessor, protocolFactory, port, threadManager))); - serverThread2 = threadFactory->newThread(boost::shared_ptr( - new TNonblockingServer(serviceProcessor, protocolFactory, port + 1, threadManager))); + nbSocket1.reset(new transport::TNonblockingServerSocket(port)); + serverThread = threadFactory->newThread(stdcxx::shared_ptr( + new TNonblockingServer(serviceProcessor, protocolFactory, nbSocket1, threadManager))); + nbSocket2.reset(new transport::TNonblockingServerSocket(port + 1)); + serverThread2 = threadFactory->newThread(stdcxx::shared_ptr( + new TNonblockingServer(serviceProcessor, protocolFactory, nbSocket2, threadManager))); } cerr << "Starting the server on port " << port << " and " << (port + 1) << endl; @@ -431,7 +437,7 @@ int main(int argc, char** argv) { size_t threadCount = 0; - set > clientThreads; + set > clientThreads; if (callName == "echoVoid") { loopType = T_VOID; @@ -449,16 +455,16 @@ int main(int argc, char** argv) { for (uint32_t ix = 0; ix < clientCount; ix++) { - boost::shared_ptr socket(new TSocket("127.0.0.1", port + (ix % 2))); - boost::shared_ptr framedSocket(new TFramedTransport(socket)); - boost::shared_ptr protocol(new TBinaryProtocol(framedSocket)); - boost::shared_ptr serviceClient(new ServiceClient(protocol)); + stdcxx::shared_ptr socket(new TSocket("127.0.0.1", port + (ix % 2))); + stdcxx::shared_ptr framedSocket(new TFramedTransport(socket)); + stdcxx::shared_ptr protocol(new TBinaryProtocol(framedSocket)); + stdcxx::shared_ptr serviceClient(new ServiceClient(protocol)); - clientThreads.insert(threadFactory->newThread(boost::shared_ptr( + clientThreads.insert(threadFactory->newThread(stdcxx::shared_ptr( new ClientThread(socket, serviceClient, monitor, threadCount, loopCount, loopType)))); } - for (std::set >::const_iterator thread = clientThreads.begin(); + for (std::set >::const_iterator thread = clientThreads.begin(); thread != clientThreads.end(); thread++) { (*thread)->start(); @@ -491,12 +497,12 @@ int main(int argc, char** argv) { int64_t minTime = 9223372036854775807LL; int64_t maxTime = 0; - for (set >::iterator ix = clientThreads.begin(); + for (set >::iterator ix = clientThreads.begin(); ix != clientThreads.end(); ix++) { - boost::shared_ptr client - = boost::dynamic_pointer_cast((*ix)->runnable()); + stdcxx::shared_ptr client + = stdcxx::dynamic_pointer_cast((*ix)->runnable()); int64_t delta = client->_endTime - client->_startTime; diff --git a/vendor/git.apache.org/thrift.git/test/cpp/src/TestClient.cpp b/vendor/git.apache.org/thrift.git/test/cpp/src/TestClient.cpp index c16d045..ca21326 100644 --- a/vendor/git.apache.org/thrift.git/test/cpp/src/TestClient.cpp +++ b/vendor/git.apache.org/thrift.git/test/cpp/src/TestClient.cpp @@ -1,4 +1,4 @@ -/* +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -17,8 +17,6 @@ * under the License. */ -#define __STDC_FORMAT_MACROS -#include #include #include #include @@ -28,29 +26,40 @@ #include #include #include +#include #include #include #include #include +#include #include #include // -#include -#include +#ifdef HAVE_STDINT_H +#include +#endif +#ifdef HAVE_INTTYPES_H +#include +#endif + +#include #include -#include +#include +#include +#include #if _WIN32 #include #endif +#include "SecondService.h" #include "ThriftTest.h" using namespace std; using namespace apache::thrift; +using namespace apache::thrift::async; using namespace apache::thrift::protocol; using namespace apache::thrift::transport; using namespace thrift::test; -using namespace apache::thrift::async; // Current time, microseconds since the epoch uint64_t now() { @@ -89,10 +98,10 @@ static void testVoid_clientReturn(event_base* base, ThriftTestCobClient* client) for (int testNr = 0; testNr < 10; ++testNr) { std::ostringstream os; os << "test" << testNr; - client->testString(tcxx::bind(testString_clientReturn, + client->testString(stdcxx::bind(testString_clientReturn, base, testNr, - tcxx::placeholders::_1), + stdcxx::placeholders::_1), os.str()); } } catch (TException& exn) { @@ -123,16 +132,22 @@ bool print_eq(T expected, T actual) { return_code |= ERR_BASETYPES; \ } +int binary_test(ThriftTestClient& testClient, string::size_type siz); + +BOOST_CONSTEXPR_OR_CONST int ERR_BASETYPES = 1; +BOOST_CONSTEXPR_OR_CONST int ERR_STRUCTS = 2; +BOOST_CONSTEXPR_OR_CONST int ERR_CONTAINERS = 4; +BOOST_CONSTEXPR_OR_CONST int ERR_EXCEPTIONS = 8; +BOOST_CONSTEXPR_OR_CONST int ERR_UNKNOWN = 64; + int main(int argc, char** argv) { cout.precision(19); - int ERR_BASETYPES = 1; - int ERR_STRUCTS = 2; - int ERR_CONTAINERS = 4; - int ERR_EXCEPTIONS = 8; - int ERR_UNKNOWN = 64; - string testDir = boost::filesystem::system_complete(argv[0]).parent_path().parent_path().parent_path().string(); - string pemPath = testDir + "/keys/CA.pem"; + string testDir = boost::filesystem::system_complete(argv[0]).parent_path().parent_path().parent_path().string(); + string caPath = testDir + "/keys/CA.pem"; + string certPath = testDir + "/keys/client.crt"; + string keyPath = testDir + "/keys/client.key"; + #if _WIN32 transport::TWinsockSingleton::create(); #endif @@ -140,6 +155,7 @@ int main(int argc, char** argv) { int port = 9090; int numTests = 1; bool ssl = false; + bool zlib = false; string transport_type = "buffered"; string protocol_type = "binary"; string domain_socket = ""; @@ -149,28 +165,35 @@ int main(int argc, char** argv) { int return_code = 0; boost::program_options::options_description desc("Allowed options"); - desc.add_options()("help,h", - "produce help message")("host", - boost::program_options::value(&host) - ->default_value(host), - "Host to connect")("port", - boost::program_options::value( - &port)->default_value(port), - "Port number to connect")( - "domain-socket", - boost::program_options::value(&domain_socket)->default_value(domain_socket), - "Domain Socket (e.g. /tmp/ThriftTest.thrift), instead of host and port")( - "abstract-namespace", - "Look for the domain socket in the Abstract Namespace (no connection with filesystem pathnames)")( - "transport", - boost::program_options::value(&transport_type)->default_value(transport_type), - "Transport: buffered, framed, http, evhttp")( - "protocol", - boost::program_options::value(&protocol_type)->default_value(protocol_type), - "Protocol: binary, header, compact, json")("ssl", "Encrypted Transport using SSL")( - "testloops,n", - boost::program_options::value(&numTests)->default_value(numTests), - "Number of Tests")("noinsane", "Do not run insanity test"); + desc.add_options() + ("help,h", "produce help message") + ("host", + boost::program_options::value(&host)->default_value(host), + "Host to connect") + ("port", + boost::program_options::value(&port)->default_value(port), + "Port number to connect") + ("domain-socket", + boost::program_options::value(&domain_socket)->default_value(domain_socket), + "Domain Socket (e.g. /tmp/ThriftTest.thrift), instead of host and port") + ("abstract-namespace", + "Look for the domain socket in the Abstract Namespace" + " (no connection with filesystem pathnames)") + ("transport", + boost::program_options::value(&transport_type)->default_value(transport_type), + "Transport: buffered, framed, http, evhttp, zlib") + ("protocol", + boost::program_options::value(&protocol_type)->default_value(protocol_type), + "Protocol: binary, compact, header, json, multi, multic, multih, multij") + ("ssl", + "Encrypted Transport using SSL") + ("zlib", + "Wrap Transport with Zlib") + ("testloops,n", + boost::program_options::value(&numTests)->default_value(numTests), + "Number of Tests") + ("noinsane", + "Do not run insanity test"); boost::program_options::variables_map vm; boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm); @@ -187,6 +210,10 @@ int main(int argc, char** argv) { } else if (protocol_type == "compact") { } else if (protocol_type == "header") { } else if (protocol_type == "json") { + } else if (protocol_type == "multi") { + } else if (protocol_type == "multic") { + } else if (protocol_type == "multih") { + } else if (protocol_type == "multij") { } else { throw invalid_argument("Unknown protocol type " + protocol_type); } @@ -197,6 +224,8 @@ int main(int argc, char** argv) { } else if (transport_type == "framed") { } else if (transport_type == "http") { } else if (transport_type == "evhttp") { + } else if (transport_type == "zlib") { + // crosstest will pass zlib as a transport and as a flag right now.. } else { throw invalid_argument("Unknown transport type " + transport_type); } @@ -212,6 +241,10 @@ int main(int argc, char** argv) { ssl = true; } + if (vm.count("zlib")) { + zlib = true; + } + if (vm.count("abstract-namespace")) { abstract_namespace = true; } @@ -220,16 +253,23 @@ int main(int argc, char** argv) { noinsane = true; } - boost::shared_ptr transport; - boost::shared_ptr protocol; - - boost::shared_ptr socket; - boost::shared_ptr factory; + // THRIFT-4164: The factory MUST outlive any sockets it creates for correct behavior! + stdcxx::shared_ptr factory; + stdcxx::shared_ptr socket; + stdcxx::shared_ptr transport; + stdcxx::shared_ptr protocol; + stdcxx::shared_ptr protocol2; // SecondService for multiplexed if (ssl) { - factory = boost::shared_ptr(new TSSLSocketFactory()); + cout << "Client Certificate File: " << certPath << endl; + cout << "Client Key File: " << keyPath << endl; + cout << "CA File: " << caPath << endl; + + factory = stdcxx::shared_ptr(new TSSLSocketFactory()); factory->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); - factory->loadTrustedCertificates(pemPath.c_str()); + factory->loadTrustedCertificates(caPath.c_str()); + factory->loadCertificate(certPath.c_str()); + factory->loadPrivateKey(keyPath.c_str()); factory->authenticate(true); socket = factory->createSocket(host, port); } else { @@ -237,39 +277,42 @@ int main(int argc, char** argv) { if (abstract_namespace) { std::string abstract_socket("\0", 1); abstract_socket += domain_socket; - socket = boost::shared_ptr(new TSocket(abstract_socket)); + socket = stdcxx::shared_ptr(new TSocket(abstract_socket)); } else { - socket = boost::shared_ptr(new TSocket(domain_socket)); + socket = stdcxx::shared_ptr(new TSocket(domain_socket)); } port = 0; } else { - socket = boost::shared_ptr(new TSocket(host, port)); + socket = stdcxx::shared_ptr(new TSocket(host, port)); } } if (transport_type.compare("http") == 0) { - boost::shared_ptr httpSocket(new THttpClient(socket, host, "/service")); - transport = httpSocket; + transport = stdcxx::make_shared(socket, host, "/service"); } else if (transport_type.compare("framed") == 0) { - boost::shared_ptr framedSocket(new TFramedTransport(socket)); - transport = framedSocket; + transport = stdcxx::make_shared(socket); } else { - boost::shared_ptr bufferedSocket(new TBufferedTransport(socket)); - transport = bufferedSocket; + transport = stdcxx::make_shared(socket); } - if (protocol_type.compare("json") == 0) { - boost::shared_ptr jsonProtocol(new TJSONProtocol(transport)); - protocol = jsonProtocol; - } else if (protocol_type.compare("compact") == 0) { - boost::shared_ptr compactProtocol(new TCompactProtocol(transport)); - protocol = compactProtocol; - } else if (protocol_type == "header") { - boost::shared_ptr headerProtocol(new THeaderProtocol(transport)); - protocol = headerProtocol; + if (zlib) { + transport = stdcxx::make_shared(transport); + } + + if (protocol_type == "json" || protocol_type == "multij") { + protocol = stdcxx::make_shared(transport); + } else if (protocol_type == "compact" || protocol_type == "multic") { + protocol = stdcxx::make_shared(transport); + } else if (protocol_type == "header" || protocol_type == "multih") { + protocol = stdcxx::make_shared(transport); } else { - boost::shared_ptr binaryProtocol(new TBinaryProtocol(transport)); - protocol = binaryProtocol; + protocol = stdcxx::make_shared(transport); + } + + if (boost::starts_with(protocol_type, "multi")) { + protocol2 = stdcxx::make_shared(protocol, "SecondService"); + // we don't need access to the original protocol any more, so... + protocol = stdcxx::make_shared(protocol, "ThriftTest"); } // Connection info @@ -291,14 +334,14 @@ int main(int argc, char** argv) { cout << "Libevent Features: 0x" << hex << event_base_get_features(base) << endl; #endif - boost::shared_ptr protocolFactory(new TBinaryProtocolFactory()); + stdcxx::shared_ptr protocolFactory(new TBinaryProtocolFactory()); - boost::shared_ptr channel( + stdcxx::shared_ptr channel( new TEvhttpClientChannel(host.c_str(), "/", host.c_str(), port, base)); ThriftTestCobClient* client = new ThriftTestCobClient(channel, protocolFactory.get()); - client->testVoid(tcxx::bind(testVoid_clientReturn, + client->testVoid(stdcxx::bind(testVoid_clientReturn, base, - tcxx::placeholders::_1)); + stdcxx::placeholders::_1)); event_base_loop(base, 0); return 0; @@ -354,7 +397,30 @@ int main(int argc, char** argv) { return_code |= ERR_BASETYPES; } + // + // Multiplexed protocol - call another service method + // in the middle of the ThriftTest + // + if (boost::starts_with(protocol_type, "multi")) { + SecondServiceClient ssc(protocol2); + // transport is already open... + + try { + cout << "secondService.secondTestString(\"foo\") => " << flush; + std::string result; + ssc.secondtestString(result, "foo"); + cout << "{" << result << "}" << endl; + } catch (std::exception& e) { + cout << " *** FAILED *** " << e.what() << endl; + return_code |= ERR_EXCEPTIONS; + } + } + try { +#ifdef _MSC_VER +#pragma warning( push ) +#pragma warning( disable : 4566 ) +#endif string str( "}{Afrikaans, Alemannisch, Aragonés, العربية, مصرى, " "Asturianu, Aymar aru, AzÉ™rbaycan, Башҡорт, Boarisch, ŽemaitÄ—Å¡ka, " @@ -381,6 +447,9 @@ int main(int argc, char** argv) { "Türkçe, Татарча/Tatarça, УкраїнÑька, اردو, Tiếng Việt, Volapük, " "Walon, Winaray, å´è¯­, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, " "Bân-lâm-gú, 粵語"); +#ifdef _MSC_VER +#pragma warning( pop ) +#endif cout << "testString(" << str << ") = " << flush; testClient.testString(s, str); cout << s << endl; @@ -447,8 +516,8 @@ int main(int argc, char** argv) { BASETYPE_IDENTITY_TEST(testI32, -1); BASETYPE_IDENTITY_TEST(testI32, 190000013); BASETYPE_IDENTITY_TEST(testI32, -190000013); - BASETYPE_IDENTITY_TEST(testI32, numeric_limits::max()); - BASETYPE_IDENTITY_TEST(testI32, numeric_limits::min()); + BASETYPE_IDENTITY_TEST(testI32, (numeric_limits::max)()); + BASETYPE_IDENTITY_TEST(testI32, (numeric_limits::min)()); /** * I64 TEST @@ -457,12 +526,12 @@ int main(int argc, char** argv) { BASETYPE_IDENTITY_TEST(testI64, (int64_t)-1); BASETYPE_IDENTITY_TEST(testI64, (int64_t)7000000000000000123LL); BASETYPE_IDENTITY_TEST(testI64, (int64_t)-7000000000000000123LL); - BASETYPE_IDENTITY_TEST(testI64, (int64_t)pow(2LL, 32)); - BASETYPE_IDENTITY_TEST(testI64, (int64_t)-pow(2LL, 32)); - BASETYPE_IDENTITY_TEST(testI64, (int64_t)pow(2LL, 32) + 1); - BASETYPE_IDENTITY_TEST(testI64, (int64_t)-pow(2LL, 32) - 1); - BASETYPE_IDENTITY_TEST(testI64, numeric_limits::max()); - BASETYPE_IDENTITY_TEST(testI64, numeric_limits::min()); + BASETYPE_IDENTITY_TEST(testI64, (int64_t)pow(static_cast(2LL), 32)); + BASETYPE_IDENTITY_TEST(testI64, (int64_t)-pow(static_cast(2LL), 32)); + BASETYPE_IDENTITY_TEST(testI64, (int64_t)pow(static_cast(2LL), 32) + 1); + BASETYPE_IDENTITY_TEST(testI64, (int64_t)-pow(static_cast(2LL), 32) - 1); + BASETYPE_IDENTITY_TEST(testI64, (numeric_limits::max)()); + BASETYPE_IDENTITY_TEST(testI64, (numeric_limits::min)()); /** * DOUBLE TEST @@ -472,19 +541,19 @@ int main(int argc, char** argv) { BASETYPE_IDENTITY_TEST(testDouble, -1.0); BASETYPE_IDENTITY_TEST(testDouble, -5.2098523); BASETYPE_IDENTITY_TEST(testDouble, -0.000341012439638598279); - BASETYPE_IDENTITY_TEST(testDouble, pow(2, 32)); - BASETYPE_IDENTITY_TEST(testDouble, pow(2, 32) + 1); - BASETYPE_IDENTITY_TEST(testDouble, pow(2, 53) - 1); - BASETYPE_IDENTITY_TEST(testDouble, -pow(2, 32)); - BASETYPE_IDENTITY_TEST(testDouble, -pow(2, 32) - 1); - BASETYPE_IDENTITY_TEST(testDouble, -pow(2, 53) + 1); + BASETYPE_IDENTITY_TEST(testDouble, pow(static_cast(2), 32)); + BASETYPE_IDENTITY_TEST(testDouble, pow(static_cast(2), 32) + 1); + BASETYPE_IDENTITY_TEST(testDouble, pow(static_cast(2), 53) - 1); + BASETYPE_IDENTITY_TEST(testDouble, -pow(static_cast(2), 32)); + BASETYPE_IDENTITY_TEST(testDouble, -pow(static_cast(2), 32) - 1); + BASETYPE_IDENTITY_TEST(testDouble, -pow(static_cast(2), 53) + 1); try { - double expected = pow(10, 307); + double expected = pow(static_cast(10), 307); cout << "testDouble(" << expected << ") = " << flush; double actual = testClient.testDouble(expected); cout << "(" << actual << ")" << endl; - if (expected - actual > pow(10, 292)) { + if (expected - actual > pow(static_cast(10), 292)) { cout << "*** FAILED ***" << endl << "Expected: " << expected << " but got: " << actual << endl; } @@ -496,11 +565,11 @@ int main(int argc, char** argv) { } try { - double expected = pow(10, -292); + double expected = pow(static_cast(10), -292); cout << "testDouble(" << expected << ") = " << flush; double actual = testClient.testDouble(expected); cout << "(" << actual << ")" << endl; - if (expected - actual > pow(10, -307)) { + if (expected - actual > pow(static_cast(10), -307)) { cout << "*** FAILED ***" << endl << "Expected: " << expected << " but got: " << actual << endl; } @@ -514,72 +583,9 @@ int main(int argc, char** argv) { /** * BINARY TEST */ - cout << "testBinary(empty)" << endl; - try { - string bin_result; - testClient.testBinary(bin_result, string()); - if (!bin_result.empty()) { - cout << endl << "*** FAILED ***" << endl; - cout << "invalid length: " << bin_result.size() << endl; - return_code |= ERR_BASETYPES; - } - } catch (TTransportException&) { - throw; - } catch (exception& ex) { - cout << "*** FAILED ***" << endl << ex.what() << endl; - return_code |= ERR_BASETYPES; - } - cout << "testBinary([-128..127]) = {" << flush; - const signed char bin_data[256] - = {-128, -127, -126, -125, -124, -123, -122, -121, -120, -119, -118, -117, -116, -115, -114, - -113, -112, -111, -110, -109, -108, -107, -106, -105, -104, -103, -102, -101, -100, -99, - -98, -97, -96, -95, -94, -93, -92, -91, -90, -89, -88, -87, -86, -85, -84, - -83, -82, -81, -80, -79, -78, -77, -76, -75, -74, -73, -72, -71, -70, -69, - -68, -67, -66, -65, -64, -63, -62, -61, -60, -59, -58, -57, -56, -55, -54, - -53, -52, -51, -50, -49, -48, -47, -46, -45, -44, -43, -42, -41, -40, -39, - -38, -37, -36, -35, -34, -33, -32, -31, -30, -29, -28, -27, -26, -25, -24, - -23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, - -8, -7, -6, -5, -4, -3, -2, -1, 0, 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}; - try { - string bin_result; - testClient.testBinary(bin_result, string(reinterpret_cast(bin_data), 256)); - if (bin_result.size() != 256) { - cout << endl << "*** FAILED ***" << endl; - cout << "invalid length: " << bin_result.size() << endl; - return_code |= ERR_BASETYPES; - } else { - bool first = true; - bool failed = false; - for (int i = 0; i < 256; ++i) { - if (!first) - cout << ","; - else - first = false; - cout << static_cast(bin_result[i]); - if (!failed && bin_result[i] != i - 128) { - failed = true; - } - } - cout << "}" << endl; - if (failed) { - cout << "*** FAILED ***" << endl; - return_code |= ERR_BASETYPES; - } - } - } catch (TTransportException&) { - throw; - } catch (exception& ex) { - cout << "*** FAILED ***" << endl << ex.what() << endl; - return_code |= ERR_BASETYPES; + for (string::size_type i = 0; i < 131073 && !return_code; ) { + return_code |= binary_test(testClient, i); + if (i > 0) { i *= 2; } else { ++i; } } @@ -951,7 +957,7 @@ int main(int argc, char** argv) { failed = true; } else { map::const_iterator it26 = it2->second.find(Numberz::SIX); - if (it26 == it1->second.end() || it26->second != Insanity()) { + if (it26 == it2->second.end() || it26->second != Insanity()) { failed = true; } } @@ -1076,12 +1082,14 @@ int main(int argc, char** argv) { /** * I32 TEST */ - cout << "re-test testI32(-1)"; + cout << "re-test testI32(-1)" << flush; int i32 = testClient.testI32(-1); cout << " = " << i32 << endl; if (i32 != -1) return_code |= ERR_BASETYPES; + cout << endl << "All tests done." << endl << flush; + uint64_t stop = now(); uint64_t tot = stop - start; @@ -1095,10 +1103,10 @@ int main(int argc, char** argv) { time_max = tot; } + cout << flush; transport->close(); } - cout << endl << "All tests done." << endl; uint64_t time_avg = time_tot / numTests; @@ -1108,3 +1116,66 @@ int main(int argc, char** argv) { return return_code; } + +void binary_fill(std::string& str, string::size_type siz) +{ + static const signed char bin_data[256] + = {-128, -127, -126, -125, -124, -123, -122, -121, -120, -119, -118, -117, -116, -115, -114, + -113, -112, -111, -110, -109, -108, -107, -106, -105, -104, -103, -102, -101, -100, -99, + -98, -97, -96, -95, -94, -93, -92, -91, -90, -89, -88, -87, -86, -85, -84, + -83, -82, -81, -80, -79, -78, -77, -76, -75, -74, -73, -72, -71, -70, -69, + -68, -67, -66, -65, -64, -63, -62, -61, -60, -59, -58, -57, -56, -55, -54, + -53, -52, -51, -50, -49, -48, -47, -46, -45, -44, -43, -42, -41, -40, -39, + -38, -37, -36, -35, -34, -33, -32, -31, -30, -29, -28, -27, -26, -25, -24, + -23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, + -8, -7, -6, -5, -4, -3, -2, -1, 0, 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}; + + str.resize(siz); + char *ptr = &str[0]; + string::size_type pos = 0; + for (string::size_type i = 0; i < siz; ++i) + { + if (pos == 255) { pos = 0; } else { ++pos; } + *ptr++ = bin_data[pos]; + } +} + +int binary_test(ThriftTestClient& testClient, string::size_type siz) +{ + string bin_request; + string bin_result; + + cout << "testBinary(siz = " << siz << ")" << endl; + binary_fill(bin_request, siz); + try { + testClient.testBinary(bin_result, bin_request); + + if (bin_request.size() != bin_result.size()) { + cout << "*** FAILED: request size " << bin_request.size() << "; result size " << bin_result.size() << endl; + return ERR_BASETYPES; + } + + for (string::size_type i = 0; i < siz; ++i) { + if (bin_request.at(i) != bin_result.at(i)) { + cout << "*** FAILED: at position " << i << " request[i] is h" << hex << bin_request.at(i) << " result[i] is h" << hex << bin_result.at(i) << endl; + return ERR_BASETYPES; + } + } + } catch (TTransportException&) { + throw; + } catch (exception& ex) { + cout << "*** FAILED ***" << endl << ex.what() << endl; + return ERR_BASETYPES; + } + + return 0; +} diff --git a/vendor/git.apache.org/thrift.git/test/cpp/src/TestServer.cpp b/vendor/git.apache.org/thrift.git/test/cpp/src/TestServer.cpp index b437860..323f873 100644 --- a/vendor/git.apache.org/thrift.git/test/cpp/src/TestServer.cpp +++ b/vendor/git.apache.org/thrift.git/test/cpp/src/TestServer.cpp @@ -17,39 +17,52 @@ * under the License. */ -#define __STDC_FORMAT_MACROS -#include - -#include +#include +#include +#include #include +#include +#include #include #include #include #include -#include -#include -#include -#include -#include -#include #include -#include -#include -#include +#include +#include +#include #include #include +#include +#include +#include +#include +#include #include +#include + +#include "SecondService.h" #include "ThriftTest.h" +#ifdef HAVE_STDINT_H +#include +#endif +#ifdef HAVE_INTTYPES_H +#include +#endif +#ifdef HAVE_SIGNAL_H +#include +#endif + #include #include #include +#include #include #include -#include +#include -#include #if _WIN32 #include #endif @@ -57,14 +70,25 @@ using namespace std; using namespace apache::thrift; +using namespace apache::thrift::async; using namespace apache::thrift::concurrency; using namespace apache::thrift::protocol; using namespace apache::thrift::transport; using namespace apache::thrift::server; -using namespace apache::thrift::async; using namespace thrift::test; +// to handle a controlled shutdown, signal handling is mandatory +#ifdef HAVE_SIGNAL_H +apache::thrift::concurrency::Monitor gMonitor; +void signal_handler(int signum) +{ + if (signum == SIGINT) { + gMonitor.notifyAll(); + } +} +#endif + class TestHandler : public ThriftTestIf { public: TestHandler() {} @@ -104,7 +128,7 @@ public: void testBinary(std::string& _return, const std::string& thing) { std::ostringstream hexstr; hexstr << std::hex << thing; - printf("testBinary(%s)\n", hexstr.str().c_str()); + printf("testBinary(%lu: %s)\n", safe_numeric_cast(thing.size()), hexstr.str().c_str()); _return = thing; } @@ -326,13 +350,18 @@ public: } } - void testOneway(const int32_t sleepFor) { - printf("testOneway(%d): Sleeping...\n", sleepFor); - THRIFT_SLEEP_SEC(sleepFor); - printf("testOneway(%d): done sleeping!\n", sleepFor); + void testOneway(const int32_t aNum) { + printf("testOneway(%d): call received\n", aNum); } }; +class SecondHandler : public SecondServiceIf +{ + public: + void secondtestString(std::string& result, const std::string& thing) + { result = "testString(\"" + thing + "\")"; } +}; + class TestProcessorEventHandler : public TProcessorEventHandler { virtual void* getContext(const char* fn_name, void* serverContext) { (void)serverContext; @@ -366,66 +395,66 @@ class TestProcessorEventHandler : public TProcessorEventHandler { class TestHandlerAsync : public ThriftTestCobSvIf { public: - TestHandlerAsync(boost::shared_ptr& handler) : _delegate(handler) {} + TestHandlerAsync(stdcxx::shared_ptr& handler) : _delegate(handler) {} virtual ~TestHandlerAsync() {} - virtual void testVoid(tcxx::function cob) { + virtual void testVoid(stdcxx::function cob) { _delegate->testVoid(); cob(); } - virtual void testString(tcxx::function cob, + virtual void testString(stdcxx::function cob, const std::string& thing) { std::string res; _delegate->testString(res, thing); cob(res); } - virtual void testBool(tcxx::function cob, const bool thing) { + virtual void testBool(stdcxx::function cob, const bool thing) { bool res = _delegate->testBool(thing); cob(res); } - virtual void testByte(tcxx::function cob, const int8_t thing) { + virtual void testByte(stdcxx::function cob, const int8_t thing) { int8_t res = _delegate->testByte(thing); cob(res); } - virtual void testI32(tcxx::function cob, const int32_t thing) { + virtual void testI32(stdcxx::function cob, const int32_t thing) { int32_t res = _delegate->testI32(thing); cob(res); } - virtual void testI64(tcxx::function cob, const int64_t thing) { + virtual void testI64(stdcxx::function cob, const int64_t thing) { int64_t res = _delegate->testI64(thing); cob(res); } - virtual void testDouble(tcxx::function cob, const double thing) { + virtual void testDouble(stdcxx::function cob, const double thing) { double res = _delegate->testDouble(thing); cob(res); } - virtual void testBinary(tcxx::function cob, + virtual void testBinary(stdcxx::function cob, const std::string& thing) { std::string res; _delegate->testBinary(res, thing); cob(res); } - virtual void testStruct(tcxx::function cob, const Xtruct& thing) { + virtual void testStruct(stdcxx::function cob, const Xtruct& thing) { Xtruct res; _delegate->testStruct(res, thing); cob(res); } - virtual void testNest(tcxx::function cob, const Xtruct2& thing) { + virtual void testNest(stdcxx::function cob, const Xtruct2& thing) { Xtruct2 res; _delegate->testNest(res, thing); cob(res); } - virtual void testMap(tcxx::function const& _return)> cob, + virtual void testMap(stdcxx::function const& _return)> cob, const std::map& thing) { std::map res; _delegate->testMap(res, thing); @@ -433,40 +462,40 @@ public: } virtual void testStringMap( - tcxx::function const& _return)> cob, + stdcxx::function const& _return)> cob, const std::map& thing) { std::map res; _delegate->testStringMap(res, thing); cob(res); } - virtual void testSet(tcxx::function const& _return)> cob, + virtual void testSet(stdcxx::function const& _return)> cob, const std::set& thing) { std::set res; _delegate->testSet(res, thing); cob(res); } - virtual void testList(tcxx::function const& _return)> cob, + virtual void testList(stdcxx::function const& _return)> cob, const std::vector& thing) { std::vector res; _delegate->testList(res, thing); cob(res); } - virtual void testEnum(tcxx::function cob, + virtual void testEnum(stdcxx::function cob, const Numberz::type thing) { Numberz::type res = _delegate->testEnum(thing); cob(res); } - virtual void testTypedef(tcxx::function cob, const UserId thing) { + virtual void testTypedef(stdcxx::function cob, const UserId thing) { UserId res = _delegate->testTypedef(thing); cob(res); } virtual void testMapMap( - tcxx::function > const& _return)> cob, + stdcxx::function > const& _return)> cob, const int32_t hello) { std::map > res; _delegate->testMapMap(res, hello); @@ -474,14 +503,14 @@ public: } virtual void testInsanity( - tcxx::function > const& _return)> cob, + stdcxx::function > const& _return)> cob, const Insanity& argument) { std::map > res; _delegate->testInsanity(res, argument); cob(res); } - virtual void testMulti(tcxx::function cob, + virtual void testMulti(stdcxx::function cob, const int8_t arg0, const int32_t arg1, const int64_t arg2, @@ -494,8 +523,8 @@ public: } virtual void testException( - tcxx::function cob, - tcxx::function exn_cob, + stdcxx::function cob, + stdcxx::function exn_cob, const std::string& arg) { try { _delegate->testException(arg); @@ -507,8 +536,8 @@ public: } virtual void testMultiException( - tcxx::function cob, - tcxx::function exn_cob, + stdcxx::function cob, + stdcxx::function exn_cob, const std::string& arg0, const std::string& arg1) { Xtruct res; @@ -521,13 +550,13 @@ public: cob(res); } - virtual void testOneway(tcxx::function cob, const int32_t secondsToSleep) { + virtual void testOneway(stdcxx::function cob, const int32_t secondsToSleep) { _delegate->testOneway(secondsToSleep); cob(); } protected: - boost::shared_ptr _delegate; + stdcxx::shared_ptr _delegate; }; namespace po = boost::program_options; @@ -543,6 +572,7 @@ int main(int argc, char** argv) { #endif int port = 9090; bool ssl = false; + bool zlib = false; string transport_type = "buffered"; string protocol_type = "binary"; string server_type = "simple"; @@ -559,9 +589,10 @@ int main(int argc, char** argv) { ("domain-socket", po::value(&domain_socket) ->default_value(domain_socket), "Unix Domain Socket (e.g. /tmp/ThriftTest.thrift)") ("abstract-namespace", "Create the domain socket in the Abstract Namespace (no connection with filesystem pathnames)") ("server-type", po::value(&server_type)->default_value(server_type), "type of server, \"simple\", \"thread-pool\", \"threaded\", or \"nonblocking\"") - ("transport", po::value(&transport_type)->default_value(transport_type), "transport: buffered, framed, http") - ("protocol", po::value(&protocol_type)->default_value(protocol_type), "protocol: binary, compact, header, json") + ("transport", po::value(&transport_type)->default_value(transport_type), "transport: buffered, framed, http, zlib") + ("protocol", po::value(&protocol_type)->default_value(protocol_type), "protocol: binary, compact, header, json, multi, multic, multih, multij") ("ssl", "Encrypted Transport using SSL") + ("zlib", "Wrapped Transport using Zlib") ("processor-events", "processor-events") ("workers,n", po::value(&workers)->default_value(workers), "Number of thread pools workers. Only valid for thread-pool server type") ("string-limit", po::value(&string_limit)) @@ -592,6 +623,10 @@ int main(int argc, char** argv) { } else if (protocol_type == "compact") { } else if (protocol_type == "json") { } else if (protocol_type == "header") { + } else if (protocol_type == "multi") { // multiplexed binary + } else if (protocol_type == "multic") { // multiplexed compact + } else if (protocol_type == "multih") { // multiplexed header + } else if (protocol_type == "multij") { // multiplexed json } else { throw invalid_argument("Unknown protocol type " + protocol_type); } @@ -601,6 +636,8 @@ int main(int argc, char** argv) { if (transport_type == "buffered") { } else if (transport_type == "framed") { } else if (transport_type == "http") { + } else if (transport_type == "zlib") { + // crosstester will pass zlib as a flag and a transport right now... } else { throw invalid_argument("Unknown transport type " + transport_type); } @@ -616,22 +653,32 @@ int main(int argc, char** argv) { ssl = true; } + if (vm.count("zlib")) { + zlib = true; + } + +#if defined(HAVE_SIGNAL_H) && defined(SIGPIPE) + if (ssl) { + signal(SIGPIPE, SIG_IGN); // for OpenSSL, otherwise we end abruptly + } +#endif + if (vm.count("abstract-namespace")) { abstract_namespace = true; } // Dispatcher - boost::shared_ptr protocolFactory; - if (protocol_type == "json") { - boost::shared_ptr jsonProtocolFactory(new TJSONProtocolFactory()); + stdcxx::shared_ptr protocolFactory; + if (protocol_type == "json" || protocol_type == "multij") { + stdcxx::shared_ptr jsonProtocolFactory(new TJSONProtocolFactory()); protocolFactory = jsonProtocolFactory; - } else if (protocol_type == "compact") { + } else if (protocol_type == "compact" || protocol_type == "multic") { TCompactProtocolFactoryT *compactProtocolFactory = new TCompactProtocolFactoryT(); compactProtocolFactory->setContainerSizeLimit(container_limit); compactProtocolFactory->setStringSizeLimit(string_limit); protocolFactory.reset(compactProtocolFactory); - } else if (protocol_type == "header") { - boost::shared_ptr headerProtocolFactory(new THeaderProtocolFactory()); + } else if (protocol_type == "header" || protocol_type == "multih") { + stdcxx::shared_ptr headerProtocolFactory(new THeaderProtocolFactory()); protocolFactory = headerProtocolFactory; } else { TBinaryProtocolFactoryT* binaryProtocolFactory = new TBinaryProtocolFactoryT(); @@ -640,53 +687,57 @@ int main(int argc, char** argv) { protocolFactory.reset(binaryProtocolFactory); } - // Processor - boost::shared_ptr testHandler(new TestHandler()); - boost::shared_ptr testProcessor(new ThriftTestProcessor(testHandler)); + // Processors + stdcxx::shared_ptr testHandler(new TestHandler()); + stdcxx::shared_ptr testProcessor(new ThriftTestProcessor(testHandler)); if (vm.count("processor-events")) { testProcessor->setEventHandler( - boost::shared_ptr(new TestProcessorEventHandler())); + stdcxx::shared_ptr(new TestProcessorEventHandler())); } // Transport - boost::shared_ptr sslSocketFactory; - boost::shared_ptr serverSocket; + stdcxx::shared_ptr sslSocketFactory; + stdcxx::shared_ptr serverSocket; if (ssl) { - sslSocketFactory = boost::shared_ptr(new TSSLSocketFactory()); + sslSocketFactory = stdcxx::shared_ptr(new TSSLSocketFactory()); sslSocketFactory->loadCertificate(certPath.c_str()); sslSocketFactory->loadPrivateKey(keyPath.c_str()); sslSocketFactory->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); - serverSocket = boost::shared_ptr(new TSSLServerSocket(port, sslSocketFactory)); + if (server_type != "nonblocking") { + serverSocket = stdcxx::shared_ptr(new TSSLServerSocket(port, sslSocketFactory)); + } } else { if (domain_socket != "") { if (abstract_namespace) { std::string abstract_socket("\0", 1); abstract_socket += domain_socket; - serverSocket = boost::shared_ptr(new TServerSocket(abstract_socket)); + serverSocket = stdcxx::shared_ptr(new TServerSocket(abstract_socket)); } else { unlink(domain_socket.c_str()); - serverSocket = boost::shared_ptr(new TServerSocket(domain_socket)); + serverSocket = stdcxx::shared_ptr(new TServerSocket(domain_socket)); } port = 0; } else { - serverSocket = boost::shared_ptr(new TServerSocket(port)); + serverSocket = stdcxx::shared_ptr(new TServerSocket(port)); } } // Factory - boost::shared_ptr transportFactory; + stdcxx::shared_ptr transportFactory; if (transport_type == "http" && server_type != "nonblocking") { - boost::shared_ptr httpTransportFactory(new THttpServerTransportFactory()); - transportFactory = httpTransportFactory; + transportFactory = stdcxx::make_shared(); } else if (transport_type == "framed") { - boost::shared_ptr framedTransportFactory(new TFramedTransportFactory()); - transportFactory = framedTransportFactory; + transportFactory = stdcxx::make_shared(); } else { - boost::shared_ptr bufferedTransportFactory(new TBufferedTransportFactory()); - transportFactory = bufferedTransportFactory; + transportFactory = stdcxx::make_shared(); + } + + if (zlib) { + // hmm.. doesn't seem to be a way to make it wrap the others... + transportFactory = stdcxx::make_shared(); } // Server Info @@ -701,20 +752,30 @@ int main(int argc, char** argv) { } cout << endl; + // Multiplexed Processor if needed + if (boost::starts_with(protocol_type, "multi")) { + stdcxx::shared_ptr secondHandler(new SecondHandler()); + stdcxx::shared_ptr secondProcessor(new SecondServiceProcessor(secondHandler)); + + stdcxx::shared_ptr multiplexedProcessor(new TMultiplexedProcessor()); + multiplexedProcessor->registerDefault(testProcessor); // non-multi clients go to the default processor (multi:binary, multic:compact, ...) + multiplexedProcessor->registerProcessor("ThriftTest", testProcessor); + multiplexedProcessor->registerProcessor("SecondService", secondProcessor); + testProcessor = stdcxx::dynamic_pointer_cast(multiplexedProcessor); + } + // Server - boost::shared_ptr server; + stdcxx::shared_ptr server; if (server_type == "simple") { server.reset(new TSimpleServer(testProcessor, serverSocket, transportFactory, protocolFactory)); } else if (server_type == "thread-pool") { - boost::shared_ptr threadManager = ThreadManager::newSimpleThreadManager(workers); - - boost::shared_ptr threadFactory - = boost::shared_ptr(new PlatformThreadFactory()); + stdcxx::shared_ptr threadFactory + = stdcxx::shared_ptr(new PlatformThreadFactory()); + stdcxx::shared_ptr threadManager = ThreadManager::newSimpleThreadManager(workers); threadManager->threadFactory(threadFactory); - threadManager->start(); server.reset(new TThreadPoolServer(testProcessor, @@ -723,15 +784,14 @@ int main(int argc, char** argv) { protocolFactory, threadManager)); } else if (server_type == "threaded") { - server.reset( new TThreadedServer(testProcessor, serverSocket, transportFactory, protocolFactory)); } else if (server_type == "nonblocking") { if (transport_type == "http") { - boost::shared_ptr testHandlerAsync(new TestHandlerAsync(testHandler)); - boost::shared_ptr testProcessorAsync( + stdcxx::shared_ptr testHandlerAsync(new TestHandlerAsync(testHandler)); + stdcxx::shared_ptr testProcessorAsync( new ThriftTestAsyncProcessor(testHandlerAsync)); - boost::shared_ptr testBufferProcessor( + stdcxx::shared_ptr testBufferProcessor( new TAsyncProtocolProcessor(testProcessorAsync, protocolFactory)); // not loading nonblockingServer into "server" because @@ -739,8 +799,15 @@ int main(int argc, char** argv) { // provide a stop method. TEvhttpServer nonblockingServer(testBufferProcessor, port); nonblockingServer.serve(); + } else if (transport_type == "framed") { + stdcxx::shared_ptr nbSocket; + nbSocket.reset( + ssl ? new transport::TNonblockingSSLServerSocket(port, sslSocketFactory) + : new transport::TNonblockingServerSocket(port)); + server.reset(new TNonblockingServer(testProcessor, protocolFactory, nbSocket)); } else { - server.reset(new TNonblockingServer(testProcessor, protocolFactory, port)); + cerr << "server-type nonblocking requires transport of http or framed" << endl; + exit(1); } } @@ -748,22 +815,25 @@ int main(int argc, char** argv) { if (protocol_type == "header") { // Tell the server to use the same protocol for input / output // if using header - server->setOutputProtocolFactory(boost::shared_ptr()); + server->setOutputProtocolFactory(stdcxx::shared_ptr()); } + apache::thrift::concurrency::PlatformThreadFactory factory; factory.setDetached(false); - boost::shared_ptr serverThreadRunner(server); - boost::shared_ptr thread + stdcxx::shared_ptr serverThreadRunner(server); + stdcxx::shared_ptr thread = factory.newThread(serverThreadRunner); - thread->start(); - // HACK: cross language test suite is unable to handle cin properly - // that's why we stay in a endless loop here - while (1) { - } - // FIXME: find another way to stop the server (e.g. a signal) - // cout<<"Press enter to stop the server."<start(); + gMonitor.waitForever(); // wait for a shutdown signal + +#ifdef HAVE_SIGNAL_H + signal(SIGINT, SIG_DFL); +#endif server->stop(); thread->join(); @@ -773,3 +843,4 @@ int main(int argc, char** argv) { cout << "done." << endl; return 0; } + diff --git a/vendor/git.apache.org/thrift.git/test/crossrunner/collect.py b/vendor/git.apache.org/thrift.git/test/crossrunner/collect.py index 03b0c36..e2d8978 100644 --- a/vendor/git.apache.org/thrift.git/test/crossrunner/collect.py +++ b/vendor/git.apache.org/thrift.git/test/crossrunner/collect.py @@ -51,6 +51,7 @@ VALID_JSON_KEYS = [ ] DEFAULT_MAX_DELAY = 5 +DEFAULT_SIGNAL = 1 DEFAULT_TIMEOUT = 5 @@ -112,7 +113,7 @@ def _do_collect_tests(servers, clients): yield name, impl1, impl2 def maybe_max(key, o1, o2, default): - """maximum of two if present, otherwise defult value""" + """maximum of two if present, otherwise default value""" v1 = o1.get(key) v2 = o2.get(key) return max(v1, v2) if v1 and v2 else v1 or v2 or default @@ -138,6 +139,7 @@ def _do_collect_tests(servers, clients): 'server': merge_metadata(sv, **{'protocol': proto1, 'transport': trans1}), 'client': merge_metadata(cl, **{'protocol': proto2, 'transport': trans2}), 'delay': maybe_max('delay', sv, cl, DEFAULT_MAX_DELAY), + 'stop_signal': maybe_max('stop_signal', sv, cl, DEFAULT_SIGNAL), 'timeout': maybe_max('timeout', sv, cl, DEFAULT_TIMEOUT), 'protocol': proto, 'transport': trans, diff --git a/vendor/git.apache.org/thrift.git/test/crossrunner/report.py b/vendor/git.apache.org/thrift.git/test/crossrunner/report.py index cc5f26f..5baf161 100644 --- a/vendor/git.apache.org/thrift.git/test/crossrunner/report.py +++ b/vendor/git.apache.org/thrift.git/test/crossrunner/report.py @@ -104,7 +104,7 @@ class TestReporter(object): def _print_bar(self, out=None): print( - '==========================================================================', + '===============================================================================', file=(out or self.out)) def _print_exec_time(self): @@ -157,9 +157,14 @@ class ExecReporter(TestReporter): ])), 'client': list(map(re.compile, [ '[Cc]onnection refused', - 'Could not connect to localhost', + 'Could not connect to', + 'Could not open UNIX ', # domain socket (rb) 'ECONNREFUSED', + 'econnrefused', # erl + 'CONNECTION-REFUSED-ERROR', # cl + 'connect ENOENT', # nodejs domain socket 'No such file or directory', # domain socket + 'Sockets.TcpClient.Connect', # csharp ])), } @@ -174,6 +179,7 @@ class ExecReporter(TestReporter): def match(line): for expr in exprs: if expr.search(line): + self._log.info("maybe false positive: %s" % line) return True with logfile_open(self.logpath, 'r') as fp: @@ -204,7 +210,7 @@ class ExecReporter(TestReporter): def _print_footer(self, returncode=None): self._print_bar() if returncode is not None: - print('Return code: %d' % returncode, file=self.out) + print('Return code: %d (negative values indicate kill by signal)' % returncode, file=self.out) else: print('Process is killed.', file=self.out) self._print_exec_time() @@ -259,14 +265,15 @@ class SummaryReporter(TestReporter): name = '%s-%s' % (test.server.name, test.client.name) trans = '%s-%s' % (test.transport, test.socket) if not with_result: - return '{:24s}{:13s}{:25s}'.format(name[:23], test.protocol[:12], trans[:24]) + return '{:24s}{:18s}{:25s}'.format(name[:23], test.protocol[:17], trans[:24]) else: - return '{:24s}{:13s}{:25s}{:s}\n'.format(name[:23], test.protocol[:12], trans[:24], self._result_string(test)) + return '{:24s}{:18s}{:25s}{:s}\n'.format(name[:23], test.protocol[:17], + trans[:24], self._result_string(test)) def _print_test_header(self): self._print_bar() print( - '{:24s}{:13s}{:25s}{:s}'.format('server-client:', 'protocol:', 'transport:', 'result:'), + '{:24s}{:18s}{:25s}{:s}'.format('server-client:', 'protocol:', 'transport:', 'result:'), file=self.out) def _print_header(self): @@ -332,8 +339,8 @@ class SummaryReporter(TestReporter): '# then browse:\n', '# \thttp://localhost:%d/%s/\n' % (8001, self._testdir_rel), 'Full log for each test is here:\n', - '\ttest/log/client_server_protocol_transport_client.log\n', - '\ttest/log/client_server_protocol_transport_server.log\n', + '\ttest/log/server_client_protocol_transport_client.log\n', + '\ttest/log/server_client_protocol_transport_server.log\n', '%d failed of %d tests in total.\n' % (fail_count, len(self._tests)), ]) self._print_exec_time() diff --git a/vendor/git.apache.org/thrift.git/test/crossrunner/run.py b/vendor/git.apache.org/thrift.git/test/crossrunner/run.py index f522bb1..ef8fb60 100644 --- a/vendor/git.apache.org/thrift.git/test/crossrunner/run.py +++ b/vendor/git.apache.org/thrift.git/test/crossrunner/run.py @@ -23,19 +23,20 @@ import multiprocessing.managers import os import platform import random -import signal import socket import subprocess import sys -import threading import time from .compat import str_join -from .test import TestEntry, domain_socket_path from .report import ExecReporter, SummaryReporter +from .test import TestEntry +from .util import domain_socket_path -RESULT_TIMEOUT = 128 RESULT_ERROR = 64 +RESULT_TIMEOUT = 128 +SIGNONE = 0 +SIGKILL = 15 # globals ports = None @@ -43,35 +44,18 @@ stop = None class ExecutionContext(object): - def __init__(self, cmd, cwd, env, report): + def __init__(self, cmd, cwd, env, stop_signal, is_server, report): self._log = multiprocessing.get_logger() - self.report = report self.cmd = cmd self.cwd = cwd self.env = env - self.timer = None + self.stop_signal = stop_signal + self.is_server = is_server + self.report = report self.expired = False self.killed = False self.proc = None - def _expire(self): - self._log.info('Timeout') - self.expired = True - self.kill() - - def kill(self): - self._log.debug('Killing process : %d' % self.proc.pid) - self.killed = True - if platform.system() != 'Windows': - try: - os.killpg(self.proc.pid, signal.SIGKILL) - except Exception: - self._log.info('Failed to kill process group', exc_info=sys.exc_info()) - try: - self.proc.kill() - except Exception: - self._log.info('Failed to kill process', exc_info=sys.exc_info()) - def _popen_args(self): args = { 'cwd': self.cwd, @@ -87,75 +71,125 @@ class ExecutionContext(object): args.update(preexec_fn=os.setsid) return args - def start(self, timeout=0): + def start(self): joined = str_join(' ', self.cmd) self._log.debug('COMMAND: %s', joined) self._log.debug('WORKDIR: %s', self.cwd) self._log.debug('LOGFILE: %s', self.report.logpath) self.report.begin() self.proc = subprocess.Popen(self.cmd, **self._popen_args()) - if timeout > 0: - self.timer = threading.Timer(timeout, self._expire) - self.timer.start() + self._log.debug(' PID: %d', self.proc.pid) + self._log.debug(' PGID: %d', os.getpgid(self.proc.pid)) return self._scoped() @contextlib.contextmanager def _scoped(self): yield self - self._log.debug('Killing scoped process') - if self.proc.poll() is None: - self.kill() - self.report.killed() + if self.is_server: + # the server is supposed to run until we stop it + if self.returncode is not None: + self.report.died() + else: + if self.stop_signal != SIGNONE: + if self.sigwait(self.stop_signal): + self.report.end(self.returncode) + else: + self.report.killed() + else: + self.sigwait(SIGKILL) else: - self._log.debug('Process died unexpectedly') - self.report.died() + # the client is supposed to exit normally + if self.returncode is not None: + self.report.end(self.returncode) + else: + self.sigwait(SIGKILL) + self.report.killed() + self._log.debug('[{0}] exited with return code {1}'.format(self.proc.pid, self.returncode)) - def wait(self): - self.proc.communicate() - if self.timer: - self.timer.cancel() - self.report.end(self.returncode) + # Send a signal to the process and then wait for it to end + # If the signal requested is SIGNONE, no signal is sent, and + # instead we just wait for the process to end; further if it + # does not end normally with SIGNONE, we mark it as expired. + # If the process fails to end and the signal is not SIGKILL, + # it re-runs with SIGKILL so that a real process kill occurs + # returns True if the process ended, False if it may not have + def sigwait(self, sig=SIGKILL, timeout=2): + try: + if sig != SIGNONE: + self._log.debug('[{0}] send signal {1}'.format(self.proc.pid, sig)) + if sig == SIGKILL: + self.killed = True + try: + if platform.system() != 'Windows': + os.killpg(os.getpgid(self.proc.pid), sig) + else: + self.proc.send_signal(sig) + except Exception: + self._log.info('[{0}] Failed to kill process'.format(self.proc.pid), exc_info=sys.exc_info()) + self._log.debug('[{0}] wait begin, timeout {1} sec(s)'.format(self.proc.pid, timeout)) + self.proc.communicate(timeout=timeout) + self._log.debug('[{0}] process ended with return code {1}'.format(self.proc.pid, self.returncode)) + self.report.end(self.returncode) + return True + except subprocess.TimeoutExpired: + self._log.info('[{0}] timeout waiting for process to end'.format(self.proc.pid)) + if sig == SIGNONE: + self.expired = True + return False if sig == SIGKILL else self.sigwait(SIGKILL, 1) + + # called on the client process to wait for it to end naturally + def wait(self, timeout): + self.sigwait(SIGNONE, timeout) @property def returncode(self): return self.proc.returncode if self.proc else None -def exec_context(port, logdir, test, prog): +def exec_context(port, logdir, test, prog, is_server): report = ExecReporter(logdir, test, prog) prog.build_command(port) - return ExecutionContext(prog.command, prog.workdir, prog.env, report) + return ExecutionContext(prog.command, prog.workdir, prog.env, prog.stop_signal, is_server, report) -def run_test(testdir, logdir, test_dict, max_retry, async=True): +def run_test(testdir, logdir, test_dict, max_retry, async_mode=True): logger = multiprocessing.get_logger() - def ensure_socket_open(proc, port, max_delay): - sleeped = 0.1 - time.sleep(sleeped) - sleep_step = 0.2 + def ensure_socket_open(sv, port, test): + slept = 0.1 + time.sleep(slept) + sleep_step = 0.1 while True: - # Create sockets every iteration because refused sockets cannot be - # reused on some systems. - sock4 = socket.socket() - sock6 = socket.socket(family=socket.AF_INET6) - try: - if sock4.connect_ex(('127.0.0.1', port)) == 0 \ - or sock6.connect_ex(('::1', port)) == 0: - return True - if proc.poll() is not None: - logger.warn('server process is exited') - return False - if sleeped > max_delay: - logger.warn('sleeped for %f seconds but server port is not open' % sleeped) - return False - time.sleep(sleep_step) - sleeped += sleep_step - finally: - sock4.close() - sock6.close() - logger.debug('waited %f sec for server port open' % sleeped) - return True + if slept > test.delay: + logger.warn('[{0}] slept for {1} seconds but server is not open'.format(sv.proc.pid, slept)) + return False + if test.socket == 'domain': + if not os.path.exists(domain_socket_path(port)): + logger.debug('[{0}] domain(unix) socket not available yet. slept for {1} seconds so far'.format(sv.proc.pid, slept)) + time.sleep(sleep_step) + slept += sleep_step + elif test.socket == 'abstract': + return True + else: + # Create sockets every iteration because refused sockets cannot be + # reused on some systems. + sock4 = socket.socket() + sock6 = socket.socket(family=socket.AF_INET6) + try: + if sock4.connect_ex(('127.0.0.1', port)) == 0 \ + or sock6.connect_ex(('::1', port)) == 0: + return True + if sv.proc.poll() is not None: + logger.warn('[{0}] server process is exited'.format(sv.proc.pid)) + return False + logger.debug('[{0}] socket not available yet. slept for {1} seconds so far'.format(sv.proc.pid, slept)) + time.sleep(sleep_step) + slept += sleep_step + finally: + sock4.close() + sock6.close() + logger.debug('[{0}] server ready - waited for {1} seconds'.format(sv.proc.pid, slept)) + return True try: max_bind_retry = 3 @@ -169,31 +203,27 @@ def run_test(testdir, logdir, test_dict, max_retry, async=True): logger.debug('Start') with PortAllocator.alloc_port_scoped(ports, test.socket) as port: logger.debug('Start with port %d' % port) - sv = exec_context(port, logdir, test, test.server) - cl = exec_context(port, logdir, test, test.client) + sv = exec_context(port, logdir, test, test.server, True) + cl = exec_context(port, logdir, test, test.client, False) logger.debug('Starting server') with sv.start(): - if test.socket in ('domain', 'abstract'): - time.sleep(0.1) - port_ok = True - else: - port_ok = ensure_socket_open(sv.proc, port, test.delay) + port_ok = ensure_socket_open(sv, port, test) if port_ok: connect_retry_count = 0 - max_connect_retry = 3 - connect_retry_wait = 0.5 + max_connect_retry = 12 + connect_retry_wait = 0.25 while True: if sv.proc.poll() is not None: logger.info('not starting client because server process is absent') break logger.debug('Starting client') - cl.start(test.timeout) - logger.debug('Waiting client') - cl.wait() + cl.start() + logger.debug('Waiting client (up to %d secs)' % test.timeout) + cl.wait(test.timeout) if not cl.report.maybe_false_positive() or connect_retry_count >= max_connect_retry: if connect_retry_count > 0 and connect_retry_count < max_connect_retry: - logger.warn('[%s]: Connected after %d retry (%.2f sec each)' % (test.server.name, connect_retry_count, connect_retry_wait)) + logger.info('[%s]: Connected after %d retry (%.2f sec each)' % (test.server.name, connect_retry_count, connect_retry_wait)) # Wait for 50ms to see if server does not die at the end. time.sleep(0.05) break @@ -205,12 +235,18 @@ def run_test(testdir, logdir, test_dict, max_retry, async=True): logger.warn('[%s]: Detected socket bind failure, retrying...', test.server.name) bind_retry_count += 1 else: - if cl.expired: - result = RESULT_TIMEOUT + result = RESULT_TIMEOUT if cl.expired else cl.returncode if (cl.proc and cl.proc.poll()) is not None else RESULT_ERROR + + # For servers that handle a controlled shutdown by signal + # if they are killed, or return an error code, that is a + # problem. For servers that are not signal-aware, we simply + # kill them off; if we didn't kill them off, something else + # happened (crashed?) + if test.server.stop_signal != 0: + if sv.killed or sv.returncode > 0: + result |= RESULT_ERROR else: - result = cl.proc.returncode if cl.proc else RESULT_ERROR if not sv.killed: - # Server died without being killed. result |= RESULT_ERROR if result == 0 or retry_count >= max_retry: @@ -219,13 +255,13 @@ def run_test(testdir, logdir, test_dict, max_retry, async=True): logger.info('[%s-%s]: test failed, retrying...', test.server.name, test.client.name) retry_count += 1 except Exception: - if not async: + if not async_mode: raise logger.warn('Error executing [%s]', test.name, exc_info=True) return (retry_count, RESULT_ERROR) except: logger.info('Interrupted execution', exc_info=True) - if not async: + if not async_mode: raise stop.set() return (retry_count, RESULT_ERROR) @@ -349,7 +385,7 @@ class TestDispatcher(object): ports = m.ports() def _dispatch_sync(self, test, cont, max_retry): - r = run_test(self.testdir, self.logdir, test, max_retry, False) + r = run_test(self.testdir, self.logdir, test, max_retry, async_mode=False) cont(r) return NonAsyncResult(r) diff --git a/vendor/git.apache.org/thrift.git/test/crossrunner/test.py b/vendor/git.apache.org/thrift.git/test/crossrunner/test.py index 74fd916..0e91284 100644 --- a/vendor/git.apache.org/thrift.git/test/crossrunner/test.py +++ b/vendor/git.apache.org/thrift.git/test/crossrunner/test.py @@ -22,22 +22,20 @@ import multiprocessing import os import sys from .compat import path_join -from .util import merge_dict - - -def domain_socket_path(port): - return '/tmp/ThriftTest.thrift.%d' % port +from .util import merge_dict, domain_socket_path class TestProgram(object): - def __init__(self, kind, name, protocol, transport, socket, workdir, command, env=None, + def __init__(self, kind, name, protocol, transport, socket, workdir, stop_signal, command, env=None, extra_args=[], extra_args2=[], join_args=False, **kwargs): + self.kind = kind self.name = name self.protocol = protocol self.transport = transport self.socket = socket self.workdir = workdir + self.stop_signal = stop_signal self.command = None self._base_command = self._fix_cmd_path(command) if env: @@ -68,11 +66,19 @@ class TestProgram(object): 'abstract': ['--abstract-namespace', '--domain-socket=%s' % domain_socket_path(port)], }.get(socket, None) + def _transport_args(self, transport): + return { + 'zlib': ['--zlib'], + }.get(transport, None) + def build_command(self, port): cmd = copy.copy(self._base_command) args = copy.copy(self._extra_args2) args.append('--protocol=' + self.protocol) args.append('--transport=' + self.transport) + transport_args = self._transport_args(self.transport) + if transport_args: + args += transport_args socket_args = self._socket_args(self.socket, port) if socket_args: args += socket_args diff --git a/vendor/git.apache.org/thrift.git/test/crossrunner/util.py b/vendor/git.apache.org/thrift.git/test/crossrunner/util.py index e2d195a..c214df8 100644 --- a/vendor/git.apache.org/thrift.git/test/crossrunner/util.py +++ b/vendor/git.apache.org/thrift.git/test/crossrunner/util.py @@ -20,6 +20,10 @@ import copy +def domain_socket_path(port): + return '/tmp/ThriftTest.thrift.%d' % port + + def merge_dict(base, update): """Update dict concatenating list values""" res = copy.deepcopy(base) diff --git a/vendor/git.apache.org/thrift.git/test/csharp/Makefile.am b/vendor/git.apache.org/thrift.git/test/csharp/Makefile.am index 7aa332c..ad166e3 100644 --- a/vendor/git.apache.org/thrift.git/test/csharp/Makefile.am +++ b/vendor/git.apache.org/thrift.git/test/csharp/Makefile.am @@ -85,3 +85,11 @@ check-local: TestClientServer.exe MONO_PATH=$(LIBDIR) timeout 10 mono TestClientServer.exe server --port=$(TESTPORT) & sleep 1 MONO_PATH=$(LIBDIR) mono TestClientServer.exe client --port=$(TESTPORT) + +EXTRA_DIST = \ + Properties/AssemblyInfo.cs \ + ThriftTest.csproj \ + ThriftTest.sln \ + Program.cs \ + TestServer.cs \ + TestClient.cs diff --git a/vendor/git.apache.org/thrift.git/test/csharp/Properties/AssemblyInfo.cs b/vendor/git.apache.org/thrift.git/test/csharp/Properties/AssemblyInfo.cs index 504ca8d..d7e04b5 100644 --- a/vendor/git.apache.org/thrift.git/test/csharp/Properties/AssemblyInfo.cs +++ b/vendor/git.apache.org/thrift.git/test/csharp/Properties/AssemblyInfo.cs @@ -27,9 +27,9 @@ using System.Runtime.InteropServices; [assembly: AssemblyTitle("ThriftTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ThriftTest")] -[assembly: AssemblyCopyright("Copyright © 2009 The Apache Software Foundation")] +[assembly: AssemblyCompany("The Apache Software Foundation")] +[assembly: AssemblyProduct("Thrift")] +[assembly: AssemblyCopyright("The Apache Software Foundation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] @@ -51,5 +51,5 @@ using System.Runtime.InteropServices; // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyVersion("0.12.0.0")] +[assembly: AssemblyFileVersion("0.12.0.0")] diff --git a/vendor/git.apache.org/thrift.git/test/csharp/TestClient.cs b/vendor/git.apache.org/thrift.git/test/csharp/TestClient.cs index 67673ec..949c06e 100644 --- a/vendor/git.apache.org/thrift.git/test/csharp/TestClient.cs +++ b/vendor/git.apache.org/thrift.git/test/csharp/TestClient.cs @@ -33,7 +33,7 @@ namespace Test { public class TestClient { - private class TestParams + public class TestParams { public int numIterations = 1; public string host = "localhost"; @@ -44,6 +44,7 @@ namespace Test public bool framed; public string protocol; public bool encrypted = false; + public bool multiplexed = false; protected bool _isFirstTransport = true; @@ -61,7 +62,9 @@ namespace Test { string certPath = "../keys/client.p12"; X509Certificate cert = new X509Certificate2(certPath, "thrift"); - trans = new TTLSSocket(host, port, 0, cert, (o, c, chain, errors) => true, null, SslProtocols.Tls); + trans = new TTLSSocket(host, port, 0, cert, + (o, c, chain, errors) => true, + null, SslProtocols.Tls); } else { @@ -105,21 +108,30 @@ namespace Test private const int ErrorStructs = 2; private const int ErrorContainers = 4; private const int ErrorExceptions = 8; + private const int ErrorProtocol = 16; private const int ErrorUnknown = 64; private class ClientTest { + private readonly TestParams param; private readonly TTransport transport; + private readonly SecondService.Client second; private readonly ThriftTest.Client client; private readonly int numIterations; private bool done; public int ReturnCode { get; set; } - public ClientTest(TestParams param) + public ClientTest(TestParams paramin) { + param = paramin; transport = param.CreateTransport(); - client = new ThriftTest.Client(param.CreateProtocol(transport)); + TProtocol protocol = param.CreateProtocol(transport); + if (param.multiplexed) + { + second = new SecondService.Client(new TMultiplexedProtocol(protocol, "SecondService")); + } + client = new ThriftTest.Client(protocol); numIterations = param.numIterations; } public void Execute() @@ -148,7 +160,7 @@ namespace Test try { - ReturnCode |= ExecuteClientTest(client); + ReturnCode |= ExecuteClientTest(client, second, param); } catch (Exception ex) { @@ -215,12 +227,12 @@ namespace Test { numThreads = Convert.ToInt32(args[++i]); } - else if (args[i] == "--compact" || args[i] == "--protocol=compact") + else if (args[i] == "--compact" || args[i] == "--protocol=compact" || args[i] == "--protocol=multic") { param.protocol = "compact"; Console.WriteLine("Using compact protocol"); } - else if (args[i] == "--json" || args[i] == "--protocol=json") + else if (args[i] == "--json" || args[i] == "--protocol=json" || args[i] == "--protocol=multij") { param.protocol = "json"; Console.WriteLine("Using JSON protocol"); @@ -230,6 +242,11 @@ namespace Test param.encrypted = true; Console.WriteLine("Using encrypted transport"); } + + if (args[i].StartsWith("--protocol=multi")) + { + param.multiplexed = true; + } } } catch (Exception ex) @@ -265,10 +282,11 @@ namespace Test return BitConverter.ToString(data).Replace("-", string.Empty); } - public static byte[] PrepareTestData(bool randomDist) + public static byte[] PrepareTestData(bool randomDist, bool huge) { - byte[] retval = new byte[0x100]; - int initLen = Math.Min(0x100,retval.Length); + // huge = true tests for THRIFT-4372 + byte[] retval = new byte[huge ? 0x12345 : 0x100]; + int initLen = retval.Length; // linear distribution, unless random is requested if (!randomDist) { @@ -295,7 +313,7 @@ namespace Test return retval; } - public static int ExecuteClientTest(ThriftTest.Client client) + public static int ExecuteClientTest(ThriftTest.Client client, SecondService.Client second, TestParams param) { int returnCode = 0; @@ -312,6 +330,18 @@ namespace Test returnCode |= ErrorBaseTypes; } + if (param.multiplexed) + { + Console.WriteLine("secondTestString(\"Test2\")"); + s = second.secondtestString("Test2"); + Console.WriteLine(" = \"" + s + "\""); + if ("testString(\"Test2\")" != s) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorProtocol; + } + } + Console.Write("testBool(true)"); bool t = client.testBool((bool)true); Console.WriteLine(" = " + t); @@ -374,29 +404,33 @@ namespace Test returnCode |= ErrorBaseTypes; } - byte[] binOut = PrepareTestData(true); - Console.Write("testBinary(" + BytesToHex(binOut) + ")"); - try + for (i32 = 0; i32 < 2; ++i32) { - byte[] binIn = client.testBinary(binOut); - Console.WriteLine(" = " + BytesToHex(binIn)); - if (binIn.Length != binOut.Length) + var huge = (i32 > 0); + byte[] binOut = PrepareTestData(false,huge); + Console.Write("testBinary(" + BytesToHex(binOut) + ")"); + try { - Console.WriteLine("*** FAILED ***"); - returnCode |= ErrorBaseTypes; - } - for (int ofs = 0; ofs < Math.Min(binIn.Length, binOut.Length); ++ofs) - if (binIn[ofs] != binOut[ofs]) + byte[] binIn = client.testBinary(binOut); + Console.WriteLine(" = " + BytesToHex(binIn)); + if (binIn.Length != binOut.Length) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } - } - catch (Thrift.TApplicationException ex) - { - Console.WriteLine("*** FAILED ***"); - returnCode |= ErrorBaseTypes; - Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); + for (int ofs = 0; ofs < Math.Min(binIn.Length, binOut.Length); ++ofs) + if (binIn[ofs] != binOut[ofs]) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorBaseTypes; + } + } + catch (Thrift.TApplicationException ex) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorBaseTypes; + Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); + } } // binary equals? only with hashcode option enabled ... diff --git a/vendor/git.apache.org/thrift.git/test/csharp/TestServer.cs b/vendor/git.apache.org/thrift.git/test/csharp/TestServer.cs index a9af715..bf645c2 100644 --- a/vendor/git.apache.org/thrift.git/test/csharp/TestServer.cs +++ b/vendor/git.apache.org/thrift.git/test/csharp/TestServer.cs @@ -41,27 +41,28 @@ namespace Test public static int _clientID = -1; public delegate void TestLogDelegate(string msg, params object[] values); - public class TradeServerEventHandler : TServerEventHandler - { - public int callCount = 0; - public void preServe() - { - callCount++; - } - public Object createContext(Thrift.Protocol.TProtocol input, Thrift.Protocol.TProtocol output) - { - callCount++; - return null; - } - public void deleteContext(Object serverContext, Thrift.Protocol.TProtocol input, Thrift.Protocol.TProtocol output) - { - callCount++; - } - public void processContext(Object serverContext, Thrift.Transport.TTransport transport) - { - callCount++; - } - }; + public class TradeServerEventHandler : TServerEventHandler + { + public int callCount = 0; + public void preServe() + { + callCount++; + } + public Object createContext(Thrift.Protocol.TProtocol input, Thrift.Protocol.TProtocol output) + { + callCount++; + return null; + } + public void deleteContext(Object serverContext, Thrift.Protocol.TProtocol input, Thrift.Protocol.TProtocol output) + { + callCount++; + } + public void processContext(Object serverContext, Thrift.Transport.TTransport transport) + { + callCount++; + } + }; + public class TestHandler : ThriftTest.Iface, Thrift.TControllingHandler { @@ -273,39 +274,24 @@ namespace Test return mapmap; } + // Insanity + // returns: + // { 1 => { 2 => argument, + // 3 => argument, + // }, + // 2 => { 6 => , }, + // } public Dictionary> testInsanity(Insanity argument) { testLogDelegate.Invoke("testInsanity()"); - Xtruct hello = new Xtruct(); - hello.String_thing = "Hello2"; - hello.Byte_thing = 2; - hello.I32_thing = 2; - hello.I64_thing = 2; - - Xtruct goodbye = new Xtruct(); - goodbye.String_thing = "Goodbye4"; - goodbye.Byte_thing = (sbyte)4; - goodbye.I32_thing = 4; - goodbye.I64_thing = (long)4; - - Insanity crazy = new Insanity(); - crazy.UserMap = new Dictionary(); - crazy.UserMap[Numberz.EIGHT] = (long)8; - crazy.Xtructs = new List(); - crazy.Xtructs.Add(goodbye); - - Insanity looney = new Insanity(); - crazy.UserMap[Numberz.FIVE] = (long)5; - crazy.Xtructs.Add(hello); - Dictionary first_map = new Dictionary(); Dictionary second_map = new Dictionary(); ; - first_map[Numberz.TWO] = crazy; - first_map[Numberz.THREE] = crazy; + first_map[Numberz.TWO] = argument; + first_map[Numberz.THREE] = argument; - second_map[Numberz.SIX] = looney; + second_map[Numberz.SIX] = new Insanity(); Dictionary> insane = new Dictionary>(); @@ -469,7 +455,9 @@ namespace Test if (useEncryption) { string certPath = "../keys/server.p12"; - trans = new TTLSServerSocket(port, 0, useBufferedSockets, new X509Certificate2(certPath, "thrift"), null, null, SslProtocols.Tls); + trans = new TTLSServerSocket(port, 0, useBufferedSockets, new X509Certificate2(certPath, "thrift"), + null, + null, SslProtocols.Tls); } else { diff --git a/vendor/git.apache.org/thrift.git/test/csharp/ThriftTest.csproj b/vendor/git.apache.org/thrift.git/test/csharp/ThriftTest.csproj index 65c0daf..363627f 100644 --- a/vendor/git.apache.org/thrift.git/test/csharp/ThriftTest.csproj +++ b/vendor/git.apache.org/thrift.git/test/csharp/ThriftTest.csproj @@ -46,7 +46,7 @@ false true 0 - 1.0.0.%2a + 0.12.0.%2a false true @@ -138,4 +138,4 @@ for %25%25I in ("%25THRIFT_FILE%25") do set THRIFT_SHORT=%25%25~fsI "$(ProjectDir)\..\..\compiler\cpp\thrift.exe" --gen csharp -o %25SHORT_DIR%25 %25THRIFT_SHORT%25 $(MSBuildToolsPath)\Csc.exe /t:library /out:"$(ProjectDir)ThriftImpl.dll" /recurse:"$(ProjectDir)gen-csharp"\* /reference:"$(ProjectDir)..\..\lib\csharp\bin\Debug\Thrift.dll" - \ No newline at end of file + diff --git a/vendor/git.apache.org/thrift.git/test/dart/Makefile.am b/vendor/git.apache.org/thrift.git/test/dart/Makefile.am index 6f97de9..9750ec2 100644 --- a/vendor/git.apache.org/thrift.git/test/dart/Makefile.am +++ b/vendor/git.apache.org/thrift.git/test/dart/Makefile.am @@ -17,8 +17,6 @@ # under the License. # -THRIFT = $(top_builddir)/compiler/cpp/thrift - gen-dart/thrift_test/lib/thrift_test.dart: ../ThriftTest.thrift $(THRIFT) --gen dart ../ThriftTest.thrift @@ -38,6 +36,7 @@ clean-local: $(RM) -r gen-dart test_client/.pub find . -type d -name "packages" | xargs $(RM) -r find . -type f -name ".packages" | xargs $(RM) + find . -type f -name "pubspec.lock" | xargs $(RM) client: stubs ${DART} test_client/bin/main.dart diff --git a/vendor/git.apache.org/thrift.git/test/dart/test_client/pubspec.yaml b/vendor/git.apache.org/thrift.git/test/dart/test_client/pubspec.yaml index 0b6bda2..63428b7 100644 --- a/vendor/git.apache.org/thrift.git/test/dart/test_client/pubspec.yaml +++ b/vendor/git.apache.org/thrift.git/test/dart/test_client/pubspec.yaml @@ -16,7 +16,7 @@ # under the License. name: thrift_test_client -version: 0.10.0 +version: 0.12.0 description: A client integration test for the Dart Thrift library author: Apache Thrift Developers homepage: http://thrift.apache.org diff --git a/vendor/git.apache.org/thrift.git/test/erl/Makefile.am b/vendor/git.apache.org/thrift.git/test/erl/Makefile.am index be8b4f5..ff25e89 100644 --- a/vendor/git.apache.org/thrift.git/test/erl/Makefile.am +++ b/vendor/git.apache.org/thrift.git/test/erl/Makefile.am @@ -17,8 +17,6 @@ # under the License. # -THRIFT = $(top_builddir)/compiler/cpp/thrift - THRIFT_FILES = $(wildcard ../*.thrift) if ERLANG_OTP16 diff --git a/vendor/git.apache.org/thrift.git/test/erl/src/test_client.erl b/vendor/git.apache.org/thrift.git/test/erl/src/test_client.erl index 50ffc64..9bad592 100644 --- a/vendor/git.apache.org/thrift.git/test/erl/src/test_client.erl +++ b/vendor/git.apache.org/thrift.git/test/erl/src/test_client.erl @@ -51,8 +51,9 @@ parse_args([Head | Rest], Opts) -> ssl:start(), SslOptions = {ssloptions, [ - {certfile, "../keys/client.crt"} - ,{keyfile, "../keys/server.key"} + {cacertfile, "../keys/CA.pem"}, + {certfile, "../keys/client.pem"}, + {keyfile, "../keys/client.key"} ]}, Opts#options{client_opts = [{ssltransport, true} | [SslOptions | Opts#options.client_opts]]}; "--protocol=" ++ Proto -> @@ -159,12 +160,11 @@ start(Args) -> ClientS4 end, - %% Use deprecated erlang:now until we start requiring OTP18 %% Started = erlang:monotonic_time(milli_seconds), - {_, StartSec, StartUSec} = erlang:now(), + {_, StartSec, StartUSec} = erlang:timestamp(), error_logger:info_msg("testOneway"), {Client20, {ok, ok}} = thrift_client:call(Client19, testOneway, [1]), - {_, EndSec, EndUSec} = erlang:now(), + {_, EndSec, EndUSec} = erlang:timestamp(), Elapsed = (EndSec - StartSec) * 1000 + (EndUSec - StartUSec) / 1000, if Elapsed > 1000 -> exit(1); diff --git a/vendor/git.apache.org/thrift.git/test/erl/src/test_thrift_server.erl b/vendor/git.apache.org/thrift.git/test/erl/src/test_thrift_server.erl index f3ed2f7..dad8dec 100644 --- a/vendor/git.apache.org/thrift.git/test/erl/src/test_thrift_server.erl +++ b/vendor/git.apache.org/thrift.git/test/erl/src/test_thrift_server.erl @@ -51,7 +51,7 @@ parse_args([Head | Rest], Opts) -> ssl:start(), SslOptions = {ssloptions, [ - {certfile, "../keys/server.crt"} + {certfile, "../keys/server.pem"} ,{keyfile, "../keys/server.key"} ]}, Opts#options{server_opts = [{ssltransport, true} | [SslOptions | Opts#options.server_opts]]}; diff --git a/vendor/git.apache.org/thrift.git/test/erl/src/thrift_test.app.src b/vendor/git.apache.org/thrift.git/test/erl/src/thrift_test.app.src index 6653639..f166cc4 100644 --- a/vendor/git.apache.org/thrift.git/test/erl/src/thrift_test.app.src +++ b/vendor/git.apache.org/thrift.git/test/erl/src/thrift_test.app.src @@ -22,7 +22,7 @@ {description, "Thrift cross language test"}, % The version of the applicaton - {vsn, "0.10.0"}, + {vsn, "0.12.0"}, % All modules used by the application. {modules, [ diff --git a/vendor/git.apache.org/thrift.git/test/features/Makefile.am b/vendor/git.apache.org/thrift.git/test/features/Makefile.am index f8d6538..337d789 100644 --- a/vendor/git.apache.org/thrift.git/test/features/Makefile.am +++ b/vendor/git.apache.org/thrift.git/test/features/Makefile.am @@ -21,8 +21,10 @@ EXTRA_DIST = \ index.html \ known_failures_Linux.json \ Makefile.am \ + nosslv3.sh \ string_limit.py \ tests.json \ theader_binary.py \ setup.cfg \ + tls.sh \ util.py diff --git a/vendor/git.apache.org/thrift.git/test/features/container_limit.py b/vendor/git.apache.org/thrift.git/test/features/container_limit.py index a16e364..88f8487 100644 --- a/vendor/git.apache.org/thrift.git/test/features/container_limit.py +++ b/vendor/git.apache.org/thrift.git/test/features/container_limit.py @@ -61,7 +61,7 @@ def main(argv): print('[OK]: just limit') try: test_list(proto, list(range(args.limit + 1))) - except: + except Exception: print('[OK]: limit + 1') else: print('[ERROR]: limit + 1') diff --git a/vendor/git.apache.org/thrift.git/test/features/known_failures_Linux.json b/vendor/git.apache.org/thrift.git/test/features/known_failures_Linux.json index 257095d..8376968 100644 --- a/vendor/git.apache.org/thrift.git/test/features/known_failures_Linux.json +++ b/vendor/git.apache.org/thrift.git/test/features/known_failures_Linux.json @@ -1,36 +1,50 @@ [ - "c_glib-limit_container_length_binary_buffered-ip", - "c_glib-limit_string_length_binary_buffered-ip", - "csharp-limit_container_length_binary_buffered-ip", - "csharp-limit_container_length_compact_buffered-ip", - "csharp-limit_string_length_binary_buffered-ip", - "csharp-limit_string_length_compact_buffered-ip", - "d-limit_container_length_binary_buffered-ip", - "d-limit_container_length_compact_buffered-ip", - "d-limit_string_length_binary_buffered-ip", - "d-limit_string_length_compact_buffered-ip", - "erl-limit_container_length_binary_buffered-ip", - "erl-limit_container_length_compact_buffered-ip", - "erl-limit_string_length_binary_buffered-ip", - "erl-limit_string_length_compact_buffered-ip", - "go-limit_container_length_binary_buffered-ip", - "go-limit_container_length_compact_buffered-ip", - "go-limit_string_length_binary_buffered-ip", - "go-limit_string_length_compact_buffered-ip", - "hs-limit_container_length_binary_buffered-ip", - "hs-limit_container_length_compact_buffered-ip", - "hs-limit_string_length_binary_buffered-ip", - "hs-limit_string_length_compact_buffered-ip", - "nodejs-limit_container_length_binary_buffered-ip", - "nodejs-limit_container_length_compact_buffered-ip", - "nodejs-limit_string_length_binary_buffered-ip", - "nodejs-limit_string_length_compact_buffered-ip", - "perl-limit_container_length_binary_buffered-ip", - "perl-limit_string_length_binary_buffered-ip", - "rb-limit_container_length_accel-binary_buffered-ip", - "rb-limit_container_length_binary_buffered-ip", - "rb-limit_container_length_compact_buffered-ip", - "rb-limit_string_length_accel-binary_buffered-ip", - "rb-limit_string_length_binary_buffered-ip", - "rb-limit_string_length_compact_buffered-ip" -] \ No newline at end of file + "c_glib-limit_container_length_binary_buffered-ip", + "c_glib-limit_string_length_binary_buffered-ip", + "cl-limit_string_length_binary_buffered-ip", + "cl-limit_container_length_binary_buffered-ip", + "cpp-theader_framed_binary_multih-header_buffered-ip", + "cpp-theader_framed_compact_multih-header_buffered-ip", + "cpp-theader_unframed_binary_multih-header_buffered-ip", + "cpp-theader_unframed_compact_multih-header_buffered-ip", + "csharp-limit_container_length_binary_buffered-ip", + "csharp-limit_container_length_compact_buffered-ip", + "csharp-limit_string_length_binary_buffered-ip", + "csharp-limit_string_length_compact_buffered-ip", + "d-limit_container_length_binary_buffered-ip", + "d-limit_container_length_compact_buffered-ip", + "d-limit_string_length_binary_buffered-ip", + "d-limit_string_length_compact_buffered-ip", + "erl-limit_container_length_binary_buffered-ip", + "erl-limit_container_length_compact_buffered-ip", + "erl-limit_string_length_binary_buffered-ip", + "erl-limit_string_length_compact_buffered-ip", + "go-limit_container_length_binary_buffered-ip", + "go-limit_container_length_compact_buffered-ip", + "go-limit_string_length_binary_buffered-ip", + "go-limit_string_length_compact_buffered-ip", + "hs-limit_container_length_binary_buffered-ip", + "hs-limit_container_length_compact_buffered-ip", + "hs-limit_string_length_binary_buffered-ip", + "hs-limit_string_length_compact_buffered-ip", + "nodejs-limit_container_length_binary_buffered-ip", + "nodejs-limit_container_length_compact_buffered-ip", + "nodejs-limit_string_length_binary_buffered-ip", + "nodejs-limit_string_length_compact_buffered-ip", + "perl-limit_container_length_binary_buffered-ip", + "perl-limit_string_length_binary_buffered-ip", + "rb-limit_container_length_accel-binary_buffered-ip", + "rb-limit_container_length_binary_buffered-ip", + "rb-limit_container_length_compact_buffered-ip", + "rb-limit_string_length_accel-binary_buffered-ip", + "rb-limit_string_length_binary_buffered-ip", + "rb-limit_string_length_compact_buffered-ip", + "rs-limit_container_length_binary_buffered-ip", + "rs-limit_container_length_compact_buffered-ip", + "rs-limit_container_length_multic-compact_buffered-ip", + "rs-limit_string_length_binary_buffered-ip", + "rs-limit_string_length_compact_buffered-ip", + "rs-limit_string_length_multic-compact_buffered-ip", + "netcore-limit_string_length_compact_buffered-ip", + "netcore-limit_container_length_compact_buffered-ip" +] diff --git a/vendor/git.apache.org/thrift.git/test/features/nosslv3.sh b/vendor/git.apache.org/thrift.git/test/features/nosslv3.sh new file mode 100755 index 0000000..38cca07 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/features/nosslv3.sh @@ -0,0 +1,59 @@ +#!/bin/bash + +# +# Checks to make sure SSLv3 is not allowed by a server. +# + +THRIFTHOST=localhost +THRIFTPORT=9090 + +while [[ $# -ge 1 ]]; do + arg="$1" + argIN=(${arg//=/ }) + + case ${argIN[0]} in + -h|--host) + THRIFTHOST=${argIN[1]} + shift # past argument + ;; + -p|--port) + THRIFTPORT=${argIN[1]} + shift # past argument + ;; + *) + # unknown option ignored + ;; + esac + + shift # past argument or value +done + +function nosslv3 +{ + local nego + local negodenied + local opensslv + + opensslv=$(openssl version | cut -d' ' -f2) + if [[ $opensslv > "1.0" ]]; then + echo "[pass] OpenSSL 1.1 or later - no need to check ssl3" + return 0 + fi + + # echo "openssl s_client -connect $THRIFTHOST:$THRIFTPORT -CAfile ../keys/CA.pem -ssl3 2>&1 < /dev/null" + nego=$(openssl s_client -connect $THRIFTHOST:$THRIFTPORT -CAfile ../keys/CA.pem -ssl3 2>&1 < /dev/null) + negodenied=$? + + if [[ $negodenied -ne 0 ]]; then + echo "[pass] SSLv3 negotiation disabled" + echo $nego + return 0 + fi + + echo "[fail] SSLv3 negotiation enabled! stdout:" + echo $nego + return 1 +} + +nosslv3 +exit $? diff --git a/vendor/git.apache.org/thrift.git/test/features/string_limit.py b/vendor/git.apache.org/thrift.git/test/features/string_limit.py index 695d965..b8991d6 100644 --- a/vendor/git.apache.org/thrift.git/test/features/string_limit.py +++ b/vendor/git.apache.org/thrift.git/test/features/string_limit.py @@ -51,11 +51,12 @@ def main(argv): print('[OK]: just limit') try: test_string(proto, 'a' * (args.limit + 1)) - except: + except Exception: print('[OK]: limit + 1') else: print('[ERROR]: limit + 1') assert False + if __name__ == '__main__': main(sys.argv[1:]) diff --git a/vendor/git.apache.org/thrift.git/test/features/tests.json b/vendor/git.apache.org/thrift.git/test/features/tests.json index cfcb4b6..41e07d7 100644 --- a/vendor/git.apache.org/thrift.git/test/features/tests.json +++ b/vendor/git.apache.org/thrift.git/test/features/tests.json @@ -66,7 +66,6 @@ "--string-limit=50" ], "protocols": [ - "binary", "compact" ], "transports": ["buffered"], @@ -84,11 +83,32 @@ "--container-limit=50" ], "protocols": [ - "binary", "compact" ], "transports": ["buffered"], "sockets": ["ip"], "workdir": "features" + }, + { + "name": "nosslv3", + "comment": "check to make sure SSLv3 is not supported", + "command": [ + "nosslv3.sh" + ], + "protocols": ["binary"], + "transports": ["buffered"], + "sockets": ["ip-ssl"], + "workdir": "features" + }, + { + "name": "tls", + "comment": "check to make sure TLSv1.0 or later is supported", + "command": [ + "tls.sh" + ], + "protocols": ["binary"], + "transports": ["buffered"], + "sockets": ["ip-ssl"], + "workdir": "features" } ] diff --git a/vendor/git.apache.org/thrift.git/test/features/tls.sh b/vendor/git.apache.org/thrift.git/test/features/tls.sh new file mode 100755 index 0000000..dada6ab --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/features/tls.sh @@ -0,0 +1,71 @@ +#!/bin/bash + +# +# Checks to make sure TLSv1.0 or later is allowed by a server. +# + +THRIFTHOST=localhost +THRIFTPORT=9090 + +while [[ $# -ge 1 ]]; do + arg="$1" + argIN=(${arg//=/ }) + + case ${argIN[0]} in + -h|--host) + THRIFTHOST=${argIN[1]} + shift # past argument + ;; + -p|--port) + THRIFTPORT=${argIN[1]} + shift # past argument + ;; + *) + # unknown option ignored + ;; + esac + + shift # past argument or value +done + +declare -A EXPECT_NEGOTIATE +EXPECT_NEGOTIATE[tls1]=1 +EXPECT_NEGOTIATE[tls1_1]=1 +EXPECT_NEGOTIATE[tls1_2]=1 + +failures=0 + +function tls +{ + for PROTO in "${!EXPECT_NEGOTIATE[@]}"; do + + local nego + local negodenied + local res + + echo "openssl s_client -connect $THRIFTHOST:$THRIFTPORT -CAfile ../keys/CA.pem -$PROTO 2>&1 < /dev/null" + nego=$(openssl s_client -connect $THRIFTHOST:$THRIFTPORT -CAfile ../keys/CA.pem -$PROTO 2>&1 < /dev/null) + negodenied=$? + echo "result of command: $negodenied" + + res="enabled"; if [[ ${EXPECT_NEGOTIATE[$PROTO]} -eq 0 ]]; then res="disabled"; fi + + if [[ $negodenied -ne ${EXPECT_NEGOTIATE[$PROTO]} ]]; then + echo "$PROTO negotiation allowed" + else + echo "[warn] $PROTO negotiation did not work" + echo $nego + ((failures++)) + fi + done +} + +tls + +if [[ $failures -eq 3 ]]; then + echo "[fail] At least one of TLSv1.0, TLSv1.1, or TLSv1.2 needs to work, but does not" + exit $failures +fi + +echo "[pass] At least one of TLSv1.0, TLSv1.1, or TLSv1.2 worked" +exit 0 diff --git a/vendor/git.apache.org/thrift.git/test/go/Makefile.am b/vendor/git.apache.org/thrift.git/test/go/Makefile.am index 2b2dbce..6da8339 100644 --- a/vendor/git.apache.org/thrift.git/test/go/Makefile.am +++ b/vendor/git.apache.org/thrift.git/test/go/Makefile.am @@ -19,8 +19,7 @@ BUILT_SOURCES = gopath -THRIFT = $(top_builddir)/compiler/cpp/thrift -THRIFTCMD = $(THRIFT) -out src/gen --gen go:thrift_import=thrift +THRIFTCMD = $(THRIFT) -out src/gen --gen go:thrift_import=thrift$(COMPILER_EXTRAFLAG) THRIFTTEST = $(top_srcdir)/test/ThriftTest.thrift precross: bin/testclient bin/testserver @@ -28,13 +27,17 @@ precross: bin/testclient bin/testserver ThriftTest.thrift: $(THRIFTTEST) grep -v list.*map.*list.*map $(THRIFTTEST) > ThriftTest.thrift +.PHONY: gopath + # Thrift for GO has problems with complex map keys: THRIFT-2063 gopath: $(THRIFT) ThriftTest.thrift mkdir -p src/gen $(THRIFTCMD) ThriftTest.thrift $(THRIFTCMD) ../StressTest.thrift - ln -nfs ../../../lib/go/thrift src/thrift + GOPATH=`pwd` $(GO) get github.com/golang/mock/gomock || true + sed -i 's/\"context\"/\"golang.org\/x\/net\/context\"/g' src/github.com/golang/mock/gomock/controller.go || true GOPATH=`pwd` $(GO) get github.com/golang/mock/gomock + ln -nfs ../../../lib/go/thrift src/thrift touch gopath bin/testclient: gopath @@ -51,7 +54,7 @@ clean-local: check_PROGRAMS: bin/testclient bin/testserver bin/stress -check: gopath +check: gopath genmock GOPATH=`pwd` $(GO) test -v common/... genmock: gopath diff --git a/vendor/git.apache.org/thrift.git/test/go/src/bin/stress/main.go b/vendor/git.apache.org/thrift.git/test/go/src/bin/stress/main.go index 1f713bb..f2e0f20 100644 --- a/vendor/git.apache.org/thrift.git/test/go/src/bin/stress/main.go +++ b/vendor/git.apache.org/thrift.git/test/go/src/bin/stress/main.go @@ -20,6 +20,7 @@ package main import ( + "context" "flag" "fmt" "gen/stress" @@ -219,35 +220,35 @@ func client(protocolFactory thrift.TProtocolFactory) { type handler struct{} -func (h *handler) EchoVoid() (err error) { +func (h *handler) EchoVoid(ctx context.Context) (err error) { atomic.AddInt64(&counter, 1) return nil } -func (h *handler) EchoByte(arg int8) (r int8, err error) { +func (h *handler) EchoByte(ctx context.Context, arg int8) (r int8, err error) { atomic.AddInt64(&counter, 1) return arg, nil } -func (h *handler) EchoI32(arg int32) (r int32, err error) { +func (h *handler) EchoI32(ctx context.Context, arg int32) (r int32, err error) { atomic.AddInt64(&counter, 1) return arg, nil } -func (h *handler) EchoI64(arg int64) (r int64, err error) { +func (h *handler) EchoI64(ctx context.Context, arg int64) (r int64, err error) { atomic.AddInt64(&counter, 1) return arg, nil } -func (h *handler) EchoString(arg string) (r string, err error) { +func (h *handler) EchoString(ctx context.Context, arg string) (r string, err error) { atomic.AddInt64(&counter, 1) return arg, nil } -func (h *handler) EchoList(arg []int8) (r []int8, err error) { +func (h *handler) EchoList(ctx context.Context, arg []int8) (r []int8, err error) { atomic.AddInt64(&counter, 1) return arg, nil } -func (h *handler) EchoSet(arg map[int8]struct{}) (r map[int8]struct{}, err error) { +func (h *handler) EchoSet(ctx context.Context, arg map[int8]struct{}) (r map[int8]struct{}, err error) { atomic.AddInt64(&counter, 1) return arg, nil } -func (h *handler) EchoMap(arg map[int8]int8) (r map[int8]int8, err error) { +func (h *handler) EchoMap(ctx context.Context, arg map[int8]int8) (r map[int8]int8, err error) { atomic.AddInt64(&counter, 1) return arg, nil } diff --git a/vendor/git.apache.org/thrift.git/test/go/src/bin/testclient/main.go b/vendor/git.apache.org/thrift.git/test/go/src/bin/testclient/main.go index f4a19dd..4357ee8 100644 --- a/vendor/git.apache.org/thrift.git/test/go/src/bin/testclient/main.go +++ b/vendor/git.apache.org/thrift.git/test/go/src/bin/testclient/main.go @@ -21,6 +21,7 @@ package main import ( "common" + "context" "flag" "gen/thrifttest" t "log" @@ -34,11 +35,12 @@ var domain_socket = flag.String("domain-socket", "", "Domain Socket (e.g. /tmp/t var transport = flag.String("transport", "buffered", "Transport: buffered, framed, http, zlib") var protocol = flag.String("protocol", "binary", "Protocol: binary, compact, json") var ssl = flag.Bool("ssl", false, "Encrypted Transport using SSL") +var zlib = flag.Bool("zlib", false, "Wrapped Transport using Zlib") var testloops = flag.Int("testloops", 1, "Number of Tests") func main() { flag.Parse() - client, err := common.StartClient(*host, *port, *domain_socket, *transport, *protocol, *ssl) + client, _, err := common.StartClient(*host, *port, *domain_socket, *transport, *protocol, *ssl) if err != nil { t.Fatalf("Unable to start client: ", err) } @@ -60,14 +62,15 @@ var xxs = &thrifttest.Xtruct{ } var xcept = &thrifttest.Xception{ErrorCode: 1001, Message: "Xception"} +var defaultCtx = context.Background() func callEverything(client *thrifttest.ThriftTestClient) { var err error - if err = client.TestVoid(); err != nil { + if err = client.TestVoid(defaultCtx); err != nil { t.Fatalf("Unexpected error in TestVoid() call: ", err) } - thing, err := client.TestString("thing") + thing, err := client.TestString(defaultCtx, "thing") if err != nil { t.Fatalf("Unexpected error in TestString() call: ", err) } @@ -75,14 +78,14 @@ func callEverything(client *thrifttest.ThriftTestClient) { t.Fatalf("Unexpected TestString() result, expected 'thing' got '%s' ", thing) } - bl, err := client.TestBool(true) + bl, err := client.TestBool(defaultCtx, true) if err != nil { t.Fatalf("Unexpected error in TestBool() call: ", err) } if !bl { t.Fatalf("Unexpected TestBool() result expected true, got %f ", bl) } - bl, err = client.TestBool(false) + bl, err = client.TestBool(defaultCtx, false) if err != nil { t.Fatalf("Unexpected error in TestBool() call: ", err) } @@ -90,7 +93,7 @@ func callEverything(client *thrifttest.ThriftTestClient) { t.Fatalf("Unexpected TestBool() result expected false, got %f ", bl) } - b, err := client.TestByte(42) + b, err := client.TestByte(defaultCtx, 42) if err != nil { t.Fatalf("Unexpected error in TestByte() call: ", err) } @@ -98,7 +101,7 @@ func callEverything(client *thrifttest.ThriftTestClient) { t.Fatalf("Unexpected TestByte() result expected 42, got %d ", b) } - i32, err := client.TestI32(4242) + i32, err := client.TestI32(defaultCtx, 4242) if err != nil { t.Fatalf("Unexpected error in TestI32() call: ", err) } @@ -106,7 +109,7 @@ func callEverything(client *thrifttest.ThriftTestClient) { t.Fatalf("Unexpected TestI32() result expected 4242, got %d ", i32) } - i64, err := client.TestI64(424242) + i64, err := client.TestI64(defaultCtx, 424242) if err != nil { t.Fatalf("Unexpected error in TestI64() call: ", err) } @@ -114,7 +117,7 @@ func callEverything(client *thrifttest.ThriftTestClient) { t.Fatalf("Unexpected TestI64() result expected 424242, got %d ", i64) } - d, err := client.TestDouble(42.42) + d, err := client.TestDouble(defaultCtx, 42.42) if err != nil { t.Fatalf("Unexpected error in TestDouble() call: ", err) } @@ -126,19 +129,19 @@ func callEverything(client *thrifttest.ThriftTestClient) { for i := 0; i < 256; i++ { binout[i] = byte(i) } - bin, err := client.TestBinary(binout) + bin, err := client.TestBinary(defaultCtx, binout) for i := 0; i < 256; i++ { - if (binout[i] != bin[i]) { + if binout[i] != bin[i] { t.Fatalf("Unexpected TestBinary() result expected %d, got %d ", binout[i], bin[i]) } } - + xs := thrifttest.NewXtruct() xs.StringThing = "thing" xs.ByteThing = 42 xs.I32Thing = 4242 xs.I64Thing = 424242 - xsret, err := client.TestStruct(xs) + xsret, err := client.TestStruct(defaultCtx, xs) if err != nil { t.Fatalf("Unexpected error in TestStruct() call: ", err) } @@ -148,7 +151,7 @@ func callEverything(client *thrifttest.ThriftTestClient) { x2 := thrifttest.NewXtruct2() x2.StructThing = xs - x2ret, err := client.TestNest(x2) + x2ret, err := client.TestNest(defaultCtx, x2) if err != nil { t.Fatalf("Unexpected error in TestNest() call: ", err) } @@ -157,7 +160,7 @@ func callEverything(client *thrifttest.ThriftTestClient) { } m := map[int32]int32{1: 2, 3: 4, 5: 42} - mret, err := client.TestMap(m) + mret, err := client.TestMap(defaultCtx, m) if err != nil { t.Fatalf("Unexpected error in TestMap() call: ", err) } @@ -166,7 +169,7 @@ func callEverything(client *thrifttest.ThriftTestClient) { } sm := map[string]string{"a": "2", "b": "blah", "some": "thing"} - smret, err := client.TestStringMap(sm) + smret, err := client.TestStringMap(defaultCtx, sm) if err != nil { t.Fatalf("Unexpected error in TestStringMap() call: ", err) } @@ -174,25 +177,32 @@ func callEverything(client *thrifttest.ThriftTestClient) { t.Fatalf("Unexpected TestStringMap() result expected %#v, got %#v ", sm, smret) } - s := map[int32]struct{}{1: struct{}{}, 2: struct{}{}, 42: struct{}{}} - sret, err := client.TestSet(s) + s := []int32{1, 2, 42} + sret, err := client.TestSet(defaultCtx, s) if err != nil { t.Fatalf("Unexpected error in TestSet() call: ", err) } - if !reflect.DeepEqual(s, sret) { - t.Fatalf("Unexpected TestSet() result expected %#v, got %#v ", s, sret) + // Sets can be in any order, but Go slices are ordered, so reflect.DeepEqual won't work. + stemp := map[int32]struct{}{} + for _, val := range s { + stemp[val] = struct{}{} + } + for _, val := range sret { + if _, ok := stemp[val]; !ok { + t.Fatalf("Unexpected TestSet() result expected %#v, got %#v ", s, sret) + } } l := []int32{1, 2, 42} - lret, err := client.TestList(l) + lret, err := client.TestList(defaultCtx, l) if err != nil { t.Fatalf("Unexpected error in TestList() call: ", err) } if !reflect.DeepEqual(l, lret) { - t.Fatalf("Unexpected TestSet() result expected %#v, got %#v ", l, lret) + t.Fatalf("Unexpected TestList() result expected %#v, got %#v ", l, lret) } - eret, err := client.TestEnum(thrifttest.Numberz_TWO) + eret, err := client.TestEnum(defaultCtx, thrifttest.Numberz_TWO) if err != nil { t.Fatalf("Unexpected error in TestEnum() call: ", err) } @@ -200,7 +210,7 @@ func callEverything(client *thrifttest.ThriftTestClient) { t.Fatalf("Unexpected TestEnum() result expected %#v, got %#v ", thrifttest.Numberz_TWO, eret) } - tret, err := client.TestTypedef(thrifttest.UserId(42)) + tret, err := client.TestTypedef(defaultCtx, thrifttest.UserId(42)) if err != nil { t.Fatalf("Unexpected error in TestTypedef() call: ", err) } @@ -208,7 +218,7 @@ func callEverything(client *thrifttest.ThriftTestClient) { t.Fatalf("Unexpected TestTypedef() result expected %#v, got %#v ", thrifttest.UserId(42), tret) } - mapmap, err := client.TestMapMap(42) + mapmap, err := client.TestMapMap(defaultCtx, 42) if err != nil { t.Fatalf("Unexpected error in TestMapMap() call: ", err) } @@ -217,44 +227,44 @@ func callEverything(client *thrifttest.ThriftTestClient) { } crazy := thrifttest.NewInsanity() - crazy.UserMap = map[thrifttest.Numberz]thrifttest.UserId { - thrifttest.Numberz_FIVE: 5, + crazy.UserMap = map[thrifttest.Numberz]thrifttest.UserId{ + thrifttest.Numberz_FIVE: 5, thrifttest.Numberz_EIGHT: 8, } truck1 := thrifttest.NewXtruct() truck1.StringThing = "Goodbye4" - truck1.ByteThing = 4; - truck1.I32Thing = 4; - truck1.I64Thing = 4; + truck1.ByteThing = 4 + truck1.I32Thing = 4 + truck1.I64Thing = 4 truck2 := thrifttest.NewXtruct() truck2.StringThing = "Hello2" - truck2.ByteThing = 2; - truck2.I32Thing = 2; - truck2.I64Thing = 2; - crazy.Xtructs = []*thrifttest.Xtruct { + truck2.ByteThing = 2 + truck2.I32Thing = 2 + truck2.I64Thing = 2 + crazy.Xtructs = []*thrifttest.Xtruct{ truck1, truck2, } - insanity, err := client.TestInsanity(crazy) + insanity, err := client.TestInsanity(defaultCtx, crazy) if err != nil { t.Fatalf("Unexpected error in TestInsanity() call: ", err) } if !reflect.DeepEqual(crazy, insanity[1][2]) { t.Fatalf("Unexpected TestInsanity() first result expected %#v, got %#v ", - crazy, - insanity[1][2]) + crazy, + insanity[1][2]) } if !reflect.DeepEqual(crazy, insanity[1][3]) { t.Fatalf("Unexpected TestInsanity() second result expected %#v, got %#v ", - crazy, - insanity[1][3]) + crazy, + insanity[1][3]) } if len(insanity[2][6].UserMap) > 0 || len(insanity[2][6].Xtructs) > 0 { t.Fatalf("Unexpected TestInsanity() non-empty result got %#v ", - insanity[2][6]) + insanity[2][6]) } - xxsret, err := client.TestMulti(42, 4242, 424242, map[int16]string{1: "blah", 2: "thing"}, thrifttest.Numberz_EIGHT, thrifttest.UserId(24)) + xxsret, err := client.TestMulti(defaultCtx, 42, 4242, 424242, map[int16]string{1: "blah", 2: "thing"}, thrifttest.Numberz_EIGHT, thrifttest.UserId(24)) if err != nil { t.Fatalf("Unexpected error in TestMulti() call: ", err) } @@ -262,7 +272,7 @@ func callEverything(client *thrifttest.ThriftTestClient) { t.Fatalf("Unexpected TestMulti() result expected %#v, got %#v ", xxs, xxsret) } - err = client.TestException("Xception") + err = client.TestException(defaultCtx, "Xception") if err == nil { t.Fatalf("Expecting exception in TestException() call") } @@ -270,13 +280,13 @@ func callEverything(client *thrifttest.ThriftTestClient) { t.Fatalf("Unexpected TestException() result expected %#v, got %#v ", xcept, err) } - err = client.TestException("TException") + err = client.TestException(defaultCtx, "TException") _, ok := err.(thrift.TApplicationException) if err == nil || !ok { t.Fatalf("Unexpected TestException() result expected ApplicationError, got %#v ", err) } - ign, err := client.TestMultiException("Xception", "ignoreme") + ign, err := client.TestMultiException(defaultCtx, "Xception", "ignoreme") if ign != nil || err == nil { t.Fatalf("Expecting exception in TestMultiException() call") } @@ -284,7 +294,7 @@ func callEverything(client *thrifttest.ThriftTestClient) { t.Fatalf("Unexpected TestMultiException() %#v ", err) } - ign, err = client.TestMultiException("Xception2", "ignoreme") + ign, err = client.TestMultiException(defaultCtx, "Xception2", "ignoreme") if ign != nil || err == nil { t.Fatalf("Expecting exception in TestMultiException() call") } @@ -294,13 +304,13 @@ func callEverything(client *thrifttest.ThriftTestClient) { t.Fatalf("Unexpected TestMultiException() %#v ", err) } - err = client.TestOneway(2) + err = client.TestOneway(defaultCtx, 2) if err != nil { t.Fatalf("Unexpected error in TestOneway() call: ", err) } //Make sure the connection still alive - if err = client.TestVoid(); err != nil { + if err = client.TestVoid(defaultCtx); err != nil { t.Fatalf("Unexpected error in TestVoid() call: ", err) } } diff --git a/vendor/git.apache.org/thrift.git/test/go/src/bin/testserver/main.go b/vendor/git.apache.org/thrift.git/test/go/src/bin/testserver/main.go index 0bf833d..ca2d967 100644 --- a/vendor/git.apache.org/thrift.git/test/go/src/bin/testserver/main.go +++ b/vendor/git.apache.org/thrift.git/test/go/src/bin/testserver/main.go @@ -34,6 +34,7 @@ var domain_socket = flag.String("domain-socket", "", "Domain Socket (e.g. /tmp/T var transport = flag.String("transport", "buffered", "Transport: buffered, framed, http, zlib") var protocol = flag.String("protocol", "binary", "Protocol: binary, compact, json") var ssl = flag.Bool("ssl", false, "Encrypted Transport using SSL") +var zlib = flag.Bool("zlib", false, "Wrapped Transport using Zlib") var certPath = flag.String("certPath", "keys", "Directory that contains SSL certificates") func main() { diff --git a/vendor/git.apache.org/thrift.git/test/go/src/common/client.go b/vendor/git.apache.org/thrift.git/test/go/src/common/client.go index 4251d91..236ce43 100644 --- a/vendor/git.apache.org/thrift.git/test/go/src/common/client.go +++ b/vendor/git.apache.org/thrift.git/test/go/src/common/client.go @@ -41,7 +41,7 @@ func StartClient( domain_socket string, transport string, protocol string, - ssl bool) (client *thrifttest.ThriftTestClient, err error) { + ssl bool) (client *thrifttest.ThriftTestClient, trans thrift.TTransport, err error) { hostPort := fmt.Sprintf("%s:%d", host, port) @@ -56,12 +56,11 @@ func StartClient( case "binary": protocolFactory = thrift.NewTBinaryProtocolFactoryDefault() default: - return nil, fmt.Errorf("Invalid protocol specified %s", protocol) + return nil, nil, fmt.Errorf("Invalid protocol specified %s", protocol) } if debugClientProtocol { protocolFactory = thrift.NewTDebugProtocolFactory(protocolFactory, "client:") } - var trans thrift.TTransport if ssl { trans, err = thrift.NewTSSLSocket(hostPort, &tls.Config{InsecureSkipVerify: true}) } else { @@ -72,7 +71,7 @@ func StartClient( } } if err != nil { - return nil, err + return nil, nil, err } switch transport { case "http": @@ -86,29 +85,25 @@ func StartClient( } else { trans, err = thrift.NewTHttpPostClient(fmt.Sprintf("http://%s/", hostPort)) } - - if err != nil { - return nil, err - } - case "framed": trans = thrift.NewTFramedTransport(trans) case "buffered": trans = thrift.NewTBufferedTransport(trans, 8192) case "zlib": trans, err = thrift.NewTZlibTransport(trans, zlib.BestCompression) - if err != nil { - return nil, err - } case "": trans = trans default: - return nil, fmt.Errorf("Invalid transport specified %s", transport) + return nil, nil, fmt.Errorf("Invalid transport specified %s", transport) + } + if err != nil { + return nil, nil, err } - if err = trans.Open(); err != nil { - return nil, err + return nil, nil, err } - client = thrifttest.NewThriftTestClientFactory(trans, protocolFactory) + iprot := protocolFactory.GetProtocol(trans) + oprot := protocolFactory.GetProtocol(trans) + client = thrifttest.NewThriftTestClient(thrift.NewTStandardClient(iprot, oprot)) return } diff --git a/vendor/git.apache.org/thrift.git/test/go/src/common/clientserver_test.go b/vendor/git.apache.org/thrift.git/test/go/src/common/clientserver_test.go index 549e8d1..9f93c4c 100644 --- a/vendor/git.apache.org/thrift.git/test/go/src/common/clientserver_test.go +++ b/vendor/git.apache.org/thrift.git/test/go/src/common/clientserver_test.go @@ -20,9 +20,11 @@ package common import ( + "context" "errors" "gen/thrifttest" "reflect" + "sync" "testing" "thrift" @@ -47,10 +49,15 @@ var units = []test_unit{ func TestAllConnection(t *testing.T) { certPath = "../../../keys" + wg := &sync.WaitGroup{} + wg.Add(len(units)) for _, unit := range units { - t.Logf("%#v", unit) - doUnit(t, &unit) + go func(u test_unit) { + defer wg.Done() + doUnit(t, &u) + }(unit) } + wg.Wait() } func doUnit(t *testing.T, unit *test_unit) { @@ -62,17 +69,17 @@ func doUnit(t *testing.T, unit *test_unit) { server := thrift.NewTSimpleServer4(processor, serverTransport, transportFactory, protocolFactory) if err = server.Listen(); err != nil { - t.Errorf("Unable to start server", err) - t.FailNow() + t.Errorf("Unable to start server: %v", err) + return } go server.AcceptLoop() defer server.Stop() - client, err := StartClient(unit.host, unit.port, unit.domain_socket, unit.transport, unit.protocol, unit.ssl) + client, trans, err := StartClient(unit.host, unit.port, unit.domain_socket, unit.transport, unit.protocol, unit.ssl) if err != nil { - t.Errorf("Unable to start client", err) - t.FailNow() + t.Errorf("Unable to start client: %v", err) + return } - defer client.Transport.Close() + defer trans.Close() callEverythingWithMock(t, client, handler) } @@ -89,91 +96,92 @@ var xxs = &thrifttest.Xtruct{ } var xcept = &thrifttest.Xception{ErrorCode: 1001, Message: "some"} +var defaultCtx = context.Background() func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, handler *MockThriftTest) { gomock.InOrder( - handler.EXPECT().TestVoid(), - handler.EXPECT().TestString("thing").Return("thing", nil), - handler.EXPECT().TestBool(true).Return(true, nil), - handler.EXPECT().TestBool(false).Return(false, nil), - handler.EXPECT().TestByte(int8(42)).Return(int8(42), nil), - handler.EXPECT().TestI32(int32(4242)).Return(int32(4242), nil), - handler.EXPECT().TestI64(int64(424242)).Return(int64(424242), nil), + handler.EXPECT().TestVoid(gomock.Any()), + handler.EXPECT().TestString(gomock.Any(), "thing").Return("thing", nil), + handler.EXPECT().TestBool(gomock.Any(), true).Return(true, nil), + handler.EXPECT().TestBool(gomock.Any(), false).Return(false, nil), + handler.EXPECT().TestByte(gomock.Any(), int8(42)).Return(int8(42), nil), + handler.EXPECT().TestI32(gomock.Any(), int32(4242)).Return(int32(4242), nil), + handler.EXPECT().TestI64(gomock.Any(), int64(424242)).Return(int64(424242), nil), // TODO: add TestBinary() - handler.EXPECT().TestDouble(float64(42.42)).Return(float64(42.42), nil), - handler.EXPECT().TestStruct(&thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}).Return(&thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}, nil), - handler.EXPECT().TestNest(&thrifttest.Xtruct2{StructThing: &thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}}).Return(&thrifttest.Xtruct2{StructThing: &thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}}, nil), - handler.EXPECT().TestMap(map[int32]int32{1: 2, 3: 4, 5: 42}).Return(map[int32]int32{1: 2, 3: 4, 5: 42}, nil), - handler.EXPECT().TestStringMap(map[string]string{"a": "2", "b": "blah", "some": "thing"}).Return(map[string]string{"a": "2", "b": "blah", "some": "thing"}, nil), - handler.EXPECT().TestSet(map[int32]struct{}{1: struct{}{}, 2: struct{}{}, 42: struct{}{}}).Return(map[int32]struct{}{1: struct{}{}, 2: struct{}{}, 42: struct{}{}}, nil), - handler.EXPECT().TestList([]int32{1, 2, 42}).Return([]int32{1, 2, 42}, nil), - handler.EXPECT().TestEnum(thrifttest.Numberz_TWO).Return(thrifttest.Numberz_TWO, nil), - handler.EXPECT().TestTypedef(thrifttest.UserId(42)).Return(thrifttest.UserId(42), nil), - handler.EXPECT().TestMapMap(int32(42)).Return(rmapmap, nil), + handler.EXPECT().TestDouble(gomock.Any(), float64(42.42)).Return(float64(42.42), nil), + handler.EXPECT().TestStruct(gomock.Any(), &thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}).Return(&thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}, nil), + handler.EXPECT().TestNest(gomock.Any(), &thrifttest.Xtruct2{StructThing: &thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}}).Return(&thrifttest.Xtruct2{StructThing: &thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}}, nil), + handler.EXPECT().TestMap(gomock.Any(), map[int32]int32{1: 2, 3: 4, 5: 42}).Return(map[int32]int32{1: 2, 3: 4, 5: 42}, nil), + handler.EXPECT().TestStringMap(gomock.Any(), map[string]string{"a": "2", "b": "blah", "some": "thing"}).Return(map[string]string{"a": "2", "b": "blah", "some": "thing"}, nil), + handler.EXPECT().TestSet(gomock.Any(), []int32{1, 2, 42}).Return([]int32{1, 2, 42}, nil), + handler.EXPECT().TestList(gomock.Any(), []int32{1, 2, 42}).Return([]int32{1, 2, 42}, nil), + handler.EXPECT().TestEnum(gomock.Any(), thrifttest.Numberz_TWO).Return(thrifttest.Numberz_TWO, nil), + handler.EXPECT().TestTypedef(gomock.Any(), thrifttest.UserId(42)).Return(thrifttest.UserId(42), nil), + handler.EXPECT().TestMapMap(gomock.Any(), int32(42)).Return(rmapmap, nil), // TODO: not testing insanity - handler.EXPECT().TestMulti(int8(42), int32(4242), int64(424242), map[int16]string{1: "blah", 2: "thing"}, thrifttest.Numberz_EIGHT, thrifttest.UserId(24)).Return(xxs, nil), - handler.EXPECT().TestException("some").Return(xcept), - handler.EXPECT().TestException("TException").Return(errors.New("Just random exception")), - handler.EXPECT().TestMultiException("Xception", "ignoreme").Return(nil, &thrifttest.Xception{ErrorCode: 1001, Message: "This is an Xception"}), - handler.EXPECT().TestMultiException("Xception2", "ignoreme").Return(nil, &thrifttest.Xception2{ErrorCode: 2002, StructThing: &thrifttest.Xtruct{StringThing: "This is an Xception2"}}), - handler.EXPECT().TestOneway(int32(2)).Return(nil), - handler.EXPECT().TestVoid(), + handler.EXPECT().TestMulti(gomock.Any(), int8(42), int32(4242), int64(424242), map[int16]string{1: "blah", 2: "thing"}, thrifttest.Numberz_EIGHT, thrifttest.UserId(24)).Return(xxs, nil), + handler.EXPECT().TestException(gomock.Any(), "some").Return(xcept), + handler.EXPECT().TestException(gomock.Any(), "TException").Return(errors.New("Just random exception")), + handler.EXPECT().TestMultiException(gomock.Any(), "Xception", "ignoreme").Return(nil, &thrifttest.Xception{ErrorCode: 1001, Message: "This is an Xception"}), + handler.EXPECT().TestMultiException(gomock.Any(), "Xception2", "ignoreme").Return(nil, &thrifttest.Xception2{ErrorCode: 2002, StructThing: &thrifttest.Xtruct{StringThing: "This is an Xception2"}}), + handler.EXPECT().TestOneway(gomock.Any(), int32(2)).Return(nil), + handler.EXPECT().TestVoid(gomock.Any()), ) var err error - if err = client.TestVoid(); err != nil { - t.Errorf("Unexpected error in TestVoid() call: ", err) + if err = client.TestVoid(defaultCtx); err != nil { + t.Errorf("Unexpected error in TestVoid() call: %s", err) } - thing, err := client.TestString("thing") + thing, err := client.TestString(defaultCtx, "thing") if err != nil { - t.Errorf("Unexpected error in TestString() call: ", err) + t.Errorf("Unexpected error in TestString() call: %s", err) } if thing != "thing" { t.Errorf("Unexpected TestString() result, expected 'thing' got '%s' ", thing) } - bl, err := client.TestBool(true) + bl, err := client.TestBool(defaultCtx, true) if err != nil { - t.Errorf("Unexpected error in TestBool() call: ", err) + t.Errorf("Unexpected error in TestBool() call: %s", err) } if !bl { - t.Errorf("Unexpected TestBool() result expected true, got %f ", bl) + t.Errorf("Unexpected TestBool() result expected true, got %v ", bl) } - bl, err = client.TestBool(false) + bl, err = client.TestBool(defaultCtx, false) if err != nil { - t.Errorf("Unexpected error in TestBool() call: ", err) + t.Errorf("Unexpected error in TestBool() call: %s", err) } if bl { - t.Errorf("Unexpected TestBool() result expected false, got %f ", bl) + t.Errorf("Unexpected TestBool() result expected false, got %v ", bl) } - b, err := client.TestByte(42) + b, err := client.TestByte(defaultCtx, 42) if err != nil { - t.Errorf("Unexpected error in TestByte() call: ", err) + t.Errorf("Unexpected error in TestByte() call: %s", err) } if b != 42 { t.Errorf("Unexpected TestByte() result expected 42, got %d ", b) } - i32, err := client.TestI32(4242) + i32, err := client.TestI32(defaultCtx, 4242) if err != nil { - t.Errorf("Unexpected error in TestI32() call: ", err) + t.Errorf("Unexpected error in TestI32() call: %s", err) } if i32 != 4242 { t.Errorf("Unexpected TestI32() result expected 4242, got %d ", i32) } - i64, err := client.TestI64(424242) + i64, err := client.TestI64(defaultCtx, 424242) if err != nil { - t.Errorf("Unexpected error in TestI64() call: ", err) + t.Errorf("Unexpected error in TestI64() call: %s", err) } if i64 != 424242 { t.Errorf("Unexpected TestI64() result expected 424242, got %d ", i64) } - d, err := client.TestDouble(42.42) + d, err := client.TestDouble(defaultCtx, 42.42) if err != nil { - t.Errorf("Unexpected error in TestDouble() call: ", err) + t.Errorf("Unexpected error in TestDouble() call: %s", err) } if d != 42.42 { t.Errorf("Unexpected TestDouble() result expected 42.42, got %f ", d) @@ -186,9 +194,9 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h xs.ByteThing = 42 xs.I32Thing = 4242 xs.I64Thing = 424242 - xsret, err := client.TestStruct(xs) + xsret, err := client.TestStruct(defaultCtx, xs) if err != nil { - t.Errorf("Unexpected error in TestStruct() call: ", err) + t.Errorf("Unexpected error in TestStruct() call: %s", err) } if *xs != *xsret { t.Errorf("Unexpected TestStruct() result expected %#v, got %#v ", xs, xsret) @@ -196,83 +204,90 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h x2 := thrifttest.NewXtruct2() x2.StructThing = xs - x2ret, err := client.TestNest(x2) + x2ret, err := client.TestNest(defaultCtx, x2) if err != nil { - t.Errorf("Unexpected error in TestNest() call: ", err) + t.Errorf("Unexpected error in TestNest() call: %s", err) } if !reflect.DeepEqual(x2, x2ret) { t.Errorf("Unexpected TestNest() result expected %#v, got %#v ", x2, x2ret) } m := map[int32]int32{1: 2, 3: 4, 5: 42} - mret, err := client.TestMap(m) + mret, err := client.TestMap(defaultCtx, m) if err != nil { - t.Errorf("Unexpected error in TestMap() call: ", err) + t.Errorf("Unexpected error in TestMap() call: %s", err) } if !reflect.DeepEqual(m, mret) { t.Errorf("Unexpected TestMap() result expected %#v, got %#v ", m, mret) } sm := map[string]string{"a": "2", "b": "blah", "some": "thing"} - smret, err := client.TestStringMap(sm) + smret, err := client.TestStringMap(defaultCtx, sm) if err != nil { - t.Errorf("Unexpected error in TestStringMap() call: ", err) + t.Errorf("Unexpected error in TestStringMap() call: %s", err) } if !reflect.DeepEqual(sm, smret) { t.Errorf("Unexpected TestStringMap() result expected %#v, got %#v ", sm, smret) } - s := map[int32]struct{}{1: struct{}{}, 2: struct{}{}, 42: struct{}{}} - sret, err := client.TestSet(s) + s := []int32{1, 2, 42} + sret, err := client.TestSet(defaultCtx, s) if err != nil { - t.Errorf("Unexpected error in TestSet() call: ", err) + t.Errorf("Unexpected error in TestSet() call: %s", err) } - if !reflect.DeepEqual(s, sret) { - t.Errorf("Unexpected TestSet() result expected %#v, got %#v ", s, sret) + // Sets can be in any order, but Go slices are ordered, so reflect.DeepEqual won't work. + stemp := map[int32]struct{}{} + for _, val := range s { + stemp[val] = struct{}{} + } + for _, val := range sret { + if _, ok := stemp[val]; !ok { + t.Fatalf("Unexpected TestSet() result expected %#v, got %#v ", s, sret) + } } l := []int32{1, 2, 42} - lret, err := client.TestList(l) + lret, err := client.TestList(defaultCtx, l) if err != nil { - t.Errorf("Unexpected error in TestList() call: ", err) + t.Errorf("Unexpected error in TestList() call: %s", err) } if !reflect.DeepEqual(l, lret) { - t.Errorf("Unexpected TestSet() result expected %#v, got %#v ", l, lret) + t.Errorf("Unexpected TestList() result expected %#v, got %#v ", l, lret) } - eret, err := client.TestEnum(thrifttest.Numberz_TWO) + eret, err := client.TestEnum(defaultCtx, thrifttest.Numberz_TWO) if err != nil { - t.Errorf("Unexpected error in TestEnum() call: ", err) + t.Errorf("Unexpected error in TestEnum() call: %s", err) } if eret != thrifttest.Numberz_TWO { t.Errorf("Unexpected TestEnum() result expected %#v, got %#v ", thrifttest.Numberz_TWO, eret) } - tret, err := client.TestTypedef(thrifttest.UserId(42)) + tret, err := client.TestTypedef(defaultCtx, thrifttest.UserId(42)) if err != nil { - t.Errorf("Unexpected error in TestTypedef() call: ", err) + t.Errorf("Unexpected error in TestTypedef() call: %s", err) } if tret != thrifttest.UserId(42) { t.Errorf("Unexpected TestTypedef() result expected %#v, got %#v ", thrifttest.UserId(42), tret) } - mapmap, err := client.TestMapMap(42) + mapmap, err := client.TestMapMap(defaultCtx, 42) if err != nil { - t.Errorf("Unexpected error in TestMapmap() call: ", err) + t.Errorf("Unexpected error in TestMapmap() call: %s", err) } if !reflect.DeepEqual(mapmap, rmapmap) { t.Errorf("Unexpected TestMapmap() result expected %#v, got %#v ", rmapmap, mapmap) } - xxsret, err := client.TestMulti(42, 4242, 424242, map[int16]string{1: "blah", 2: "thing"}, thrifttest.Numberz_EIGHT, thrifttest.UserId(24)) + xxsret, err := client.TestMulti(defaultCtx, 42, 4242, 424242, map[int16]string{1: "blah", 2: "thing"}, thrifttest.Numberz_EIGHT, thrifttest.UserId(24)) if err != nil { - t.Errorf("Unexpected error in TestMulti() call: ", err) + t.Errorf("Unexpected error in TestMulti() call: %s", err) } if !reflect.DeepEqual(xxs, xxsret) { t.Errorf("Unexpected TestMulti() result expected %#v, got %#v ", xxs, xxsret) } - err = client.TestException("some") + err = client.TestException(defaultCtx, "some") if err == nil { t.Errorf("Expecting exception in TestException() call") } @@ -281,13 +296,16 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h } // TODO: connection is being closed on this - err = client.TestException("TException") - tex, ok := err.(thrift.TApplicationException) - if err == nil || !ok || tex.TypeId() != thrift.INTERNAL_ERROR { - t.Errorf("Unexpected TestException() result expected ApplicationError, got %#v ", err) + err = client.TestException(defaultCtx, "TException") + if err == nil { + t.Error("expected exception got nil") + } else if tex, ok := err.(thrift.TApplicationException); !ok { + t.Errorf("Unexpected TestException() result expected ApplicationError, got %T ", err) + } else if tex.TypeId() != thrift.INTERNAL_ERROR { + t.Errorf("expected internal_error got %v", tex.TypeId()) } - ign, err := client.TestMultiException("Xception", "ignoreme") + ign, err := client.TestMultiException(defaultCtx, "Xception", "ignoreme") if ign != nil || err == nil { t.Errorf("Expecting exception in TestMultiException() call") } @@ -295,7 +313,7 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h t.Errorf("Unexpected TestMultiException() %#v ", err) } - ign, err = client.TestMultiException("Xception2", "ignoreme") + ign, err = client.TestMultiException(defaultCtx, "Xception2", "ignoreme") if ign != nil || err == nil { t.Errorf("Expecting exception in TestMultiException() call") } @@ -305,13 +323,13 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h t.Errorf("Unexpected TestMultiException() %#v ", err) } - err = client.TestOneway(2) + err = client.TestOneway(defaultCtx, 2) if err != nil { - t.Errorf("Unexpected error in TestOneway() call: ", err) + t.Errorf("Unexpected error in TestOneway() call: %s", err) } //Make sure the connection still alive - if err = client.TestVoid(); err != nil { - t.Errorf("Unexpected error in TestVoid() call: ", err) + if err = client.TestVoid(defaultCtx); err != nil { + t.Errorf("Unexpected error in TestVoid() call: %s", err) } } diff --git a/vendor/git.apache.org/thrift.git/test/go/src/common/context_test.go b/vendor/git.apache.org/thrift.git/test/go/src/common/context_test.go new file mode 100644 index 0000000..e64dbb9 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/go/src/common/context_test.go @@ -0,0 +1,98 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +package common + +import ( + "context" + "fmt" + "net" + "net/http" + "net/url" + "os" + "syscall" + "testing" + "thrift" + "time" +) + +type slowHttpHandler struct{} + +func (slowHttpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + time.Sleep(1 * time.Second) +} + +func TestHttpContextTimeout(t *testing.T) { + certPath = "../../../keys" + + unit := test_unit{"127.0.0.1", 9096, "", "http", "binary", false} + + server := &http.Server{Addr: unit.host + fmt.Sprintf(":%d", unit.port), Handler: slowHttpHandler{}} + go server.ListenAndServe() + + client, trans, err := StartClient(unit.host, unit.port, unit.domain_socket, unit.transport, unit.protocol, unit.ssl) + if err != nil { + t.Errorf("Unable to start client: %v", err) + return + } + defer trans.Close() + + unwrapErr := func(err error) error { + for { + switch err.(type) { + case thrift.TTransportException: + err = err.(thrift.TTransportException).Err() + case *url.Error: + err = err.(*url.Error).Err + case *net.OpError: + err = err.(*net.OpError).Err + case *os.SyscallError: + err = err.(*os.SyscallError).Err + default: + return err + } + } + } + + serverStartupDeadline := time.Now().Add(5 * time.Second) + for { + ctx, _ := context.WithTimeout(context.Background(), 50*time.Millisecond) + err = client.TestVoid(ctx) + err = unwrapErr(err) + if err != syscall.ECONNREFUSED || time.Now().After(serverStartupDeadline) { + break + } + time.Sleep(time.Millisecond) + } + + if err == nil { + t.Errorf("Request completed (should have timed out)") + return + } + + // We've got to switch on `err.Error()` here since go1.7 doesn't properly return + // `context.DeadlineExceeded` error and `http.errRequestCanceled` is not exported. + // See https://github.com/golang/go/issues/17711 + switch err.Error() { + case context.DeadlineExceeded.Error(), "net/http: request canceled": + // Expected error + default: + t.Errorf("Unexpected error: %s", err) + } +} diff --git a/vendor/git.apache.org/thrift.git/test/go/src/common/mock_handler.go b/vendor/git.apache.org/thrift.git/test/go/src/common/mock_handler.go deleted file mode 100644 index 6ae8130..0000000 --- a/vendor/git.apache.org/thrift.git/test/go/src/common/mock_handler.go +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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. - */ - -// Automatically generated by MockGen. DO NOT EDIT! -// Source: gen/thrifttest (interfaces: ThriftTest) - -package common - -import ( - gomock "github.com/golang/mock/gomock" - thrifttest "gen/thrifttest" -) - -// Mock of ThriftTest interface -type MockThriftTest struct { - ctrl *gomock.Controller - recorder *_MockThriftTestRecorder -} - -// Recorder for MockThriftTest (not exported) -type _MockThriftTestRecorder struct { - mock *MockThriftTest -} - -func NewMockThriftTest(ctrl *gomock.Controller) *MockThriftTest { - mock := &MockThriftTest{ctrl: ctrl} - mock.recorder = &_MockThriftTestRecorder{mock} - return mock -} - -func (_m *MockThriftTest) EXPECT() *_MockThriftTestRecorder { - return _m.recorder -} - -func (_m *MockThriftTest) TestBool(_param0 bool) (bool, error) { - ret := _m.ctrl.Call(_m, "TestBool", _param0) - ret0, _ := ret[0].(bool) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockThriftTestRecorder) TestBool(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestBool", arg0) -} - - -func (_m *MockThriftTest) TestByte(_param0 int8) (int8, error) { - ret := _m.ctrl.Call(_m, "TestByte", _param0) - ret0, _ := ret[0].(int8) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockThriftTestRecorder) TestByte(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestByte", arg0) -} - -func (_m *MockThriftTest) TestDouble(_param0 float64) (float64, error) { - ret := _m.ctrl.Call(_m, "TestDouble", _param0) - ret0, _ := ret[0].(float64) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockThriftTestRecorder) TestDouble(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestDouble", arg0) -} - -func (_m *MockThriftTest) TestBinary(_param0 []byte) ([]byte, error) { - ret := _m.ctrl.Call(_m, "TestBinary", _param0) - ret0, _ := ret[0].([]byte) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockThriftTestRecorder) TestBinary(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestBinary", arg0) -} - -func (_m *MockThriftTest) TestEnum(_param0 thrifttest.Numberz) (thrifttest.Numberz, error) { - ret := _m.ctrl.Call(_m, "TestEnum", _param0) - ret0, _ := ret[0].(thrifttest.Numberz) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockThriftTestRecorder) TestEnum(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestEnum", arg0) -} - -func (_m *MockThriftTest) TestException(_param0 string) error { - ret := _m.ctrl.Call(_m, "TestException", _param0) - ret0, _ := ret[0].(error) - return ret0 -} - -func (_mr *_MockThriftTestRecorder) TestException(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestException", arg0) -} - -func (_m *MockThriftTest) TestI32(_param0 int32) (int32, error) { - ret := _m.ctrl.Call(_m, "TestI32", _param0) - ret0, _ := ret[0].(int32) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockThriftTestRecorder) TestI32(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestI32", arg0) -} - -func (_m *MockThriftTest) TestI64(_param0 int64) (int64, error) { - ret := _m.ctrl.Call(_m, "TestI64", _param0) - ret0, _ := ret[0].(int64) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockThriftTestRecorder) TestI64(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestI64", arg0) -} - -func (_m *MockThriftTest) TestInsanity(_param0 *thrifttest.Insanity) (map[thrifttest.UserId]map[thrifttest.Numberz]*thrifttest.Insanity, error) { - ret := _m.ctrl.Call(_m, "TestInsanity", _param0) - ret0, _ := ret[0].(map[thrifttest.UserId]map[thrifttest.Numberz]*thrifttest.Insanity) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockThriftTestRecorder) TestInsanity(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestInsanity", arg0) -} - -func (_m *MockThriftTest) TestList(_param0 []int32) ([]int32, error) { - ret := _m.ctrl.Call(_m, "TestList", _param0) - ret0, _ := ret[0].([]int32) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockThriftTestRecorder) TestList(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestList", arg0) -} - -func (_m *MockThriftTest) TestMap(_param0 map[int32]int32) (map[int32]int32, error) { - ret := _m.ctrl.Call(_m, "TestMap", _param0) - ret0, _ := ret[0].(map[int32]int32) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockThriftTestRecorder) TestMap(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestMap", arg0) -} - -func (_m *MockThriftTest) TestMapMap(_param0 int32) (map[int32]map[int32]int32, error) { - ret := _m.ctrl.Call(_m, "TestMapMap", _param0) - ret0, _ := ret[0].(map[int32]map[int32]int32) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockThriftTestRecorder) TestMapMap(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestMapMap", arg0) -} - -func (_m *MockThriftTest) TestMulti(_param0 int8, _param1 int32, _param2 int64, _param3 map[int16]string, _param4 thrifttest.Numberz, _param5 thrifttest.UserId) (*thrifttest.Xtruct, error) { - ret := _m.ctrl.Call(_m, "TestMulti", _param0, _param1, _param2, _param3, _param4, _param5) - ret0, _ := ret[0].(*thrifttest.Xtruct) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockThriftTestRecorder) TestMulti(arg0, arg1, arg2, arg3, arg4, arg5 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestMulti", arg0, arg1, arg2, arg3, arg4, arg5) -} - -func (_m *MockThriftTest) TestMultiException(_param0 string, _param1 string) (*thrifttest.Xtruct, error) { - ret := _m.ctrl.Call(_m, "TestMultiException", _param0, _param1) - ret0, _ := ret[0].(*thrifttest.Xtruct) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockThriftTestRecorder) TestMultiException(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestMultiException", arg0, arg1) -} - -func (_m *MockThriftTest) TestNest(_param0 *thrifttest.Xtruct2) (*thrifttest.Xtruct2, error) { - ret := _m.ctrl.Call(_m, "TestNest", _param0) - ret0, _ := ret[0].(*thrifttest.Xtruct2) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockThriftTestRecorder) TestNest(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestNest", arg0) -} - -func (_m *MockThriftTest) TestOneway(_param0 int32) error { - ret := _m.ctrl.Call(_m, "TestOneway", _param0) - ret0, _ := ret[0].(error) - return ret0 -} - -func (_mr *_MockThriftTestRecorder) TestOneway(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestOneway", arg0) -} - -func (_m *MockThriftTest) TestSet(_param0 map[int32]struct{}) (map[int32]struct{}, error) { - ret := _m.ctrl.Call(_m, "TestSet", _param0) - ret0, _ := ret[0].(map[int32]struct{}) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockThriftTestRecorder) TestSet(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestSet", arg0) -} - -func (_m *MockThriftTest) TestString(_param0 string) (string, error) { - ret := _m.ctrl.Call(_m, "TestString", _param0) - ret0, _ := ret[0].(string) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockThriftTestRecorder) TestString(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestString", arg0) -} - -func (_m *MockThriftTest) TestStringMap(_param0 map[string]string) (map[string]string, error) { - ret := _m.ctrl.Call(_m, "TestStringMap", _param0) - ret0, _ := ret[0].(map[string]string) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockThriftTestRecorder) TestStringMap(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestStringMap", arg0) -} - -func (_m *MockThriftTest) TestStruct(_param0 *thrifttest.Xtruct) (*thrifttest.Xtruct, error) { - ret := _m.ctrl.Call(_m, "TestStruct", _param0) - ret0, _ := ret[0].(*thrifttest.Xtruct) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockThriftTestRecorder) TestStruct(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestStruct", arg0) -} - -func (_m *MockThriftTest) TestTypedef(_param0 thrifttest.UserId) (thrifttest.UserId, error) { - ret := _m.ctrl.Call(_m, "TestTypedef", _param0) - ret0, _ := ret[0].(thrifttest.UserId) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockThriftTestRecorder) TestTypedef(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestTypedef", arg0) -} - -func (_m *MockThriftTest) TestVoid() error { - ret := _m.ctrl.Call(_m, "TestVoid") - ret0, _ := ret[0].(error) - return ret0 -} - -func (_mr *_MockThriftTestRecorder) TestVoid() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestVoid") -} diff --git a/vendor/git.apache.org/thrift.git/test/go/src/common/printing_handler.go b/vendor/git.apache.org/thrift.git/test/go/src/common/printing_handler.go index afee8da..2b22d0c 100644 --- a/vendor/git.apache.org/thrift.git/test/go/src/common/printing_handler.go +++ b/vendor/git.apache.org/thrift.git/test/go/src/common/printing_handler.go @@ -20,9 +20,10 @@ package common import ( + "context" + "encoding/hex" "errors" "fmt" - "encoding/hex" . "gen/thrifttest" "time" ) @@ -32,7 +33,7 @@ var PrintingHandler = &printingHandler{} type printingHandler struct{} // Prints "testVoid()" and returns nothing. -func (p *printingHandler) TestVoid() (err error) { +func (p *printingHandler) TestVoid(ctx context.Context) (err error) { fmt.Println("testVoid()") return nil } @@ -43,7 +44,7 @@ func (p *printingHandler) TestVoid() (err error) { // // Parameters: // - Thing -func (p *printingHandler) TestString(thing string) (r string, err error) { +func (p *printingHandler) TestString(ctx context.Context, thing string) (r string, err error) { fmt.Printf("testString(\"%s\")\n", thing) return thing, nil } @@ -54,7 +55,7 @@ func (p *printingHandler) TestString(thing string) (r string, err error) { // // Parameters: // - Thing -func (p *printingHandler) TestBool(thing bool) (r bool, err error) { +func (p *printingHandler) TestBool(ctx context.Context, thing bool) (r bool, err error) { fmt.Printf("testBool(%t)\n", thing) return thing, nil } @@ -65,7 +66,7 @@ func (p *printingHandler) TestBool(thing bool) (r bool, err error) { // // Parameters: // - Thing -func (p *printingHandler) TestByte(thing int8) (r int8, err error) { +func (p *printingHandler) TestByte(ctx context.Context, thing int8) (r int8, err error) { fmt.Printf("testByte(%d)\n", thing) return thing, nil } @@ -76,7 +77,7 @@ func (p *printingHandler) TestByte(thing int8) (r int8, err error) { // // Parameters: // - Thing -func (p *printingHandler) TestI32(thing int32) (r int32, err error) { +func (p *printingHandler) TestI32(ctx context.Context, thing int32) (r int32, err error) { fmt.Printf("testI32(%d)\n", thing) return thing, nil } @@ -87,7 +88,7 @@ func (p *printingHandler) TestI32(thing int32) (r int32, err error) { // // Parameters: // - Thing -func (p *printingHandler) TestI64(thing int64) (r int64, err error) { +func (p *printingHandler) TestI64(ctx context.Context, thing int64) (r int64, err error) { fmt.Printf("testI64(%d)\n", thing) return thing, nil } @@ -98,7 +99,7 @@ func (p *printingHandler) TestI64(thing int64) (r int64, err error) { // // Parameters: // - Thing -func (p *printingHandler) TestDouble(thing float64) (r float64, err error) { +func (p *printingHandler) TestDouble(ctx context.Context, thing float64) (r float64, err error) { fmt.Printf("testDouble(%f)\n", thing) return thing, nil } @@ -109,7 +110,7 @@ func (p *printingHandler) TestDouble(thing float64) (r float64, err error) { // // Parameters: // - Thing -func (p *printingHandler) TestBinary(thing []byte) (r []byte, err error) { +func (p *printingHandler) TestBinary(ctx context.Context, thing []byte) (r []byte, err error) { fmt.Printf("testBinary(%s)\n", hex.EncodeToString(thing)) return thing, nil } @@ -120,7 +121,7 @@ func (p *printingHandler) TestBinary(thing []byte) (r []byte, err error) { // // Parameters: // - Thing -func (p *printingHandler) TestStruct(thing *Xtruct) (r *Xtruct, err error) { +func (p *printingHandler) TestStruct(ctx context.Context, thing *Xtruct) (r *Xtruct, err error) { fmt.Printf("testStruct({\"%s\", %d, %d, %d})\n", thing.StringThing, thing.ByteThing, thing.I32Thing, thing.I64Thing) return thing, err } @@ -131,7 +132,7 @@ func (p *printingHandler) TestStruct(thing *Xtruct) (r *Xtruct, err error) { // // Parameters: // - Thing -func (p *printingHandler) TestNest(nest *Xtruct2) (r *Xtruct2, err error) { +func (p *printingHandler) TestNest(ctx context.Context, nest *Xtruct2) (r *Xtruct2, err error) { thing := nest.StructThing fmt.Printf("testNest({%d, {\"%s\", %d, %d, %d}, %d})\n", nest.ByteThing, thing.StringThing, thing.ByteThing, thing.I32Thing, thing.I64Thing, nest.I32Thing) return nest, nil @@ -144,7 +145,7 @@ func (p *printingHandler) TestNest(nest *Xtruct2) (r *Xtruct2, err error) { // // Parameters: // - Thing -func (p *printingHandler) TestMap(thing map[int32]int32) (r map[int32]int32, err error) { +func (p *printingHandler) TestMap(ctx context.Context, thing map[int32]int32) (r map[int32]int32, err error) { fmt.Printf("testMap({") first := true for k, v := range thing { @@ -166,7 +167,7 @@ func (p *printingHandler) TestMap(thing map[int32]int32) (r map[int32]int32, err // // Parameters: // - Thing -func (p *printingHandler) TestStringMap(thing map[string]string) (r map[string]string, err error) { +func (p *printingHandler) TestStringMap(ctx context.Context, thing map[string]string) (r map[string]string, err error) { fmt.Printf("testStringMap({") first := true for k, v := range thing { @@ -188,7 +189,7 @@ func (p *printingHandler) TestStringMap(thing map[string]string) (r map[string]s // // Parameters: // - Thing -func (p *printingHandler) TestSet(thing map[int32]struct{}) (r map[int32]struct{}, err error) { +func (p *printingHandler) TestSet(ctx context.Context, thing []int32) (r []int32, err error) { fmt.Printf("testSet({") first := true for k, _ := range thing { @@ -210,7 +211,7 @@ func (p *printingHandler) TestSet(thing map[int32]struct{}) (r map[int32]struct{ // // Parameters: // - Thing -func (p *printingHandler) TestList(thing []int32) (r []int32, err error) { +func (p *printingHandler) TestList(ctx context.Context, thing []int32) (r []int32, err error) { fmt.Printf("testList({") for i, v := range thing { if i != 0 { @@ -228,7 +229,7 @@ func (p *printingHandler) TestList(thing []int32) (r []int32, err error) { // // Parameters: // - Thing -func (p *printingHandler) TestEnum(thing Numberz) (r Numberz, err error) { +func (p *printingHandler) TestEnum(ctx context.Context, thing Numberz) (r Numberz, err error) { fmt.Printf("testEnum(%d)\n", thing) return thing, nil } @@ -239,7 +240,7 @@ func (p *printingHandler) TestEnum(thing Numberz) (r Numberz, err error) { // // Parameters: // - Thing -func (p *printingHandler) TestTypedef(thing UserId) (r UserId, err error) { +func (p *printingHandler) TestTypedef(ctx context.Context, thing UserId) (r UserId, err error) { fmt.Printf("testTypedef(%d)\n", thing) return thing, nil } @@ -251,7 +252,7 @@ func (p *printingHandler) TestTypedef(thing UserId) (r UserId, err error) { // // Parameters: // - Hello -func (p *printingHandler) TestMapMap(hello int32) (r map[int32]map[int32]int32, err error) { +func (p *printingHandler) TestMapMap(ctx context.Context, hello int32) (r map[int32]map[int32]int32, err error) { fmt.Printf("testMapMap(%d)\n", hello) r = map[int32]map[int32]int32{ @@ -273,14 +274,14 @@ func (p *printingHandler) TestMapMap(hello int32) (r map[int32]map[int32]int32, // // Parameters: // - Argument -func (p *printingHandler) TestInsanity(argument *Insanity) (r map[UserId]map[Numberz]*Insanity, err error) { +func (p *printingHandler) TestInsanity(ctx context.Context, argument *Insanity) (r map[UserId]map[Numberz]*Insanity, err error) { fmt.Printf("testInsanity()\n") r = make(map[UserId]map[Numberz]*Insanity) - r[1] = map[Numberz]*Insanity { + r[1] = map[Numberz]*Insanity{ 2: argument, 3: argument, } - r[2] = map[Numberz]*Insanity { + r[2] = map[Numberz]*Insanity{ 6: NewInsanity(), } return @@ -303,7 +304,7 @@ func (p *printingHandler) TestInsanity(argument *Insanity) (r map[UserId]map[Num // - Arg3 // - Arg4 // - Arg5 -func (p *printingHandler) TestMulti(arg0 int8, arg1 int32, arg2 int64, arg3 map[int16]string, arg4 Numberz, arg5 UserId) (r *Xtruct, err error) { +func (p *printingHandler) TestMulti(ctx context.Context, arg0 int8, arg1 int32, arg2 int64, arg3 map[int16]string, arg4 Numberz, arg5 UserId) (r *Xtruct, err error) { fmt.Printf("testMulti()\n") r = NewXtruct() @@ -322,7 +323,7 @@ func (p *printingHandler) TestMulti(arg0 int8, arg1 int32, arg2 int64, arg3 map[ // // Parameters: // - Arg -func (p *printingHandler) TestException(arg string) (err error) { +func (p *printingHandler) TestException(ctx context.Context, arg string) (err error) { fmt.Printf("testException(%s)\n", arg) switch arg { case "Xception": @@ -346,7 +347,7 @@ func (p *printingHandler) TestException(arg string) (err error) { // Parameters: // - Arg0 // - Arg1 -func (p *printingHandler) TestMultiException(arg0 string, arg1 string) (r *Xtruct, err error) { +func (p *printingHandler) TestMultiException(ctx context.Context, arg0 string, arg1 string) (r *Xtruct, err error) { fmt.Printf("testMultiException(%s, %s)\n", arg0, arg1) switch arg0 { @@ -375,7 +376,7 @@ func (p *printingHandler) TestMultiException(arg0 string, arg1 string) (r *Xtruc // // Parameters: // - SecondsToSleep -func (p *printingHandler) TestOneway(secondsToSleep int32) (err error) { +func (p *printingHandler) TestOneway(ctx context.Context, secondsToSleep int32) (err error) { fmt.Printf("testOneway(%d): Sleeping...\n", secondsToSleep) time.Sleep(time.Second * time.Duration(secondsToSleep)) fmt.Printf("testOneway(%d): done sleeping!\n", secondsToSleep) diff --git a/vendor/git.apache.org/thrift.git/test/go/src/common/simple_handler.go b/vendor/git.apache.org/thrift.git/test/go/src/common/simple_handler.go index 7bd3a30..0c9463d 100644 --- a/vendor/git.apache.org/thrift.git/test/go/src/common/simple_handler.go +++ b/vendor/git.apache.org/thrift.git/test/go/src/common/simple_handler.go @@ -77,7 +77,7 @@ func (p *simpleHandler) TestStringMap(thing map[string]string) (r map[string]str return thing, nil } -func (p *simpleHandler) TestSet(thing map[int32]struct{}) (r map[int32]struct{}, err error) { +func (p *simpleHandler) TestSet(thing []int32) (r []int32, err error) { return thing, nil } diff --git a/vendor/git.apache.org/thrift.git/test/haxe/Makefile.am b/vendor/git.apache.org/thrift.git/test/haxe/Makefile.am index 1a32185..6c0483e 100644 --- a/vendor/git.apache.org/thrift.git/test/haxe/Makefile.am +++ b/vendor/git.apache.org/thrift.git/test/haxe/Makefile.am @@ -17,7 +17,6 @@ # under the License. # -THRIFT = $(top_builddir)/compiler/cpp/thrift THRIFTCMD = $(THRIFT) --gen haxe -r THRIFTTEST = $(top_srcdir)/test/ThriftTest.thrift @@ -88,16 +87,18 @@ check_php_web: $(BIN_PHP_WEB) $(BIN_CPP) EXTRA_DIST = \ - src \ - cpp.hxml \ - csharp.hxml \ - flash.hxml \ - java.hxml \ - javascript.hxml \ - neko.hxml \ - php.hxml \ - python.hxml \ - project.hide \ - TestClientServer.hxproj \ - make_all.bat \ - make_all.sh + src \ + cpp.hxml \ + csharp.hxml \ + flash.hxml \ + java.hxml \ + javascript.hxml \ + neko.hxml \ + php.hxml \ + python.hxml \ + router.php \ + project.hide \ + php-web-server.hxml \ + TestClientServer.hxproj \ + make_all.bat \ + make_all.sh diff --git a/vendor/git.apache.org/thrift.git/test/haxe/make_all.sh b/vendor/git.apache.org/thrift.git/test/haxe/make_all.sh old mode 100644 new mode 100755 index 2621258..eb2c9c2 --- a/vendor/git.apache.org/thrift.git/test/haxe/make_all.sh +++ b/vendor/git.apache.org/thrift.git/test/haxe/make_all.sh @@ -19,7 +19,7 @@ # # invoke Thrift comnpiler -thrift -r -gen haxe ../ThriftTest.thrift +../../compiler/cpp/thrift -r -gen haxe ../ThriftTest.thrift # output folder if [ ! -d bin ]; then diff --git a/vendor/git.apache.org/thrift.git/test/haxe/src/TestClient.hx b/vendor/git.apache.org/thrift.git/test/haxe/src/TestClient.hx index aa496dc..853319e 100644 --- a/vendor/git.apache.org/thrift.git/test/haxe/src/TestClient.hx +++ b/vendor/git.apache.org/thrift.git/test/haxe/src/TestClient.hx @@ -444,6 +444,10 @@ class TestClient { rslt.Expect( e.message == "Xception", 'testException("Xception") - e.message == "Xception"'); rslt.Expect( e.errorCode == 1001, 'testException("Xception") - e.errorCode == 1001'); } + catch (e : TException) + { + rslt.Expect( false, 'testException("Xception") - ${e} : ${e.errorMsg}'); + } catch (e : Dynamic) { rslt.Expect( false, 'testException("Xception") - $e'); @@ -457,7 +461,7 @@ class TestClient { } catch (e : TException) { - rslt.Expect( true, 'testException("TException") - $e'); + rslt.Expect( true, 'testException("TException") - $e : ${e.errorMsg}'); } catch (e : Dynamic) { @@ -475,6 +479,10 @@ class TestClient { client.testException("bla"); rslt.Expect( true, 'testException("bla") should not throw'); } + catch (e : TException) + { + rslt.Expect( false, 'testException("bla") - ${e} : ${e.errorMsg}'); + } catch (e : Dynamic) { rslt.Expect( false, 'testException("bla") - $e'); @@ -846,6 +854,18 @@ class TestClient { trace("}"); + /** + * So you think you've got this all worked, out eh? + * + * Creates a the returned map with these values and prints it out: + * { 1 => { 2 => argument, + * 3 => argument, + * }, + * 2 => { 6 => , }, + * } + * @return map> - a map with the above values + */ + var first_map = whoa.get(Int64.make(0,1)); var second_map = whoa.get(Int64.make(0,2)); rslt.Expect( (first_map != null) && (second_map != null), "(first_map != null) && (second_map != null)"); @@ -857,42 +877,27 @@ class TestClient { rslt.Expect( (crazy2 != null) && (crazy3 != null) && (looney != null), "(crazy2 != null) && (crazy3 != null) && (looney != null)"); - rslt.Expect( Int64.compare( crazy2.userMap.get(Numberz.EIGHT), Int64.make(0,8)) == 0, - "crazy2.UserMap.get(Numberz.EIGHT) == 8"); - rslt.Expect( Int64.compare( crazy3.userMap.get(Numberz.EIGHT), Int64.make(0,8)) == 0, - "crazy3.UserMap.get(Numberz.EIGHT) == 8"); - rslt.Expect( Int64.compare( crazy2.userMap.get(Numberz.FIVE), Int64.make(0,5)) == 0, - "crazy2.UserMap.get(Numberz.FIVE) == 5"); - rslt.Expect( Int64.compare( crazy3.userMap.get(Numberz.FIVE), Int64.make(0,5)) == 0, - "crazy3.UserMap.get(Numberz.FIVE) == 5"); - var crz2iter = crazy2.xtructs.iterator(); var crz3iter = crazy3.xtructs.iterator(); rslt.Expect( crz2iter.hasNext() && crz3iter.hasNext(), "crz2iter.hasNext() && crz3iter.hasNext()"); var goodbye2 = crz2iter.next(); var goodbye3 = crz3iter.next(); - rslt.Expect( crz2iter.hasNext() && crz3iter.hasNext(), "crz2iter.hasNext() && crz3iter.hasNext()"); - var hello2 = crz2iter.next(); - var hello3 = crz3iter.next(); rslt.Expect( ! (crz2iter.hasNext() || crz3iter.hasNext()), "! (crz2iter.hasNext() || crz3iter.hasNext())"); - rslt.Expect( hello2.string_thing == "Hello2", 'hello2.String_thing == "Hello2"'); - rslt.Expect( hello2.byte_thing == 2, 'hello2.Byte_thing == 2'); - rslt.Expect( hello2.i32_thing == 2, 'hello2.I32_thing == 2'); - rslt.Expect( Int64.compare( hello2.i64_thing, Int64.make(0,2)) == 0, 'hello2.I64_thing == 2'); - rslt.Expect( hello3.string_thing == "Hello2", 'hello3.String_thing == "Hello2"'); - rslt.Expect( hello3.byte_thing == 2, 'hello3.Byte_thing == 2'); - rslt.Expect( hello3.i32_thing == 2, 'hello3.I32_thing == 2'); - rslt.Expect( Int64.compare( hello3.i64_thing, Int64.make(0,2)) == 0, 'hello3.I64_thing == 2'); + rslt.Expect( Int64.compare( crazy2.userMap.get(Numberz.FIVE), insane.userMap.get(Numberz.FIVE)) == 0, "crazy2.userMap[5] == insane.userMap[5]"); + rslt.Expect( truck.string_thing == goodbye2.string_thing, "truck.string_thing == goodbye2.string_thing"); + rslt.Expect( truck.byte_thing == goodbye2.byte_thing, "truck.byte_thing == goodbye2.byte_thing"); + rslt.Expect( truck.i32_thing == goodbye2.i32_thing, "truck.i32_thing == goodbye2.i32_thing"); + rslt.Expect( Int64.compare( truck.i64_thing, goodbye2.i64_thing) == 0, "truck.i64_thing == goodbye2.i64_thing"); - rslt.Expect( goodbye2.string_thing == "Goodbye4", 'goodbye2.String_thing == "Goodbye4"'); - rslt.Expect( goodbye2.byte_thing == 4, 'goodbye2.Byte_thing == 4'); - rslt.Expect( goodbye2.i32_thing == 4, 'goodbye2.I32_thing == 4'); - rslt.Expect( Int64.compare( goodbye2.i64_thing, Int64.make(0,4)) == 0, 'goodbye2.I64_thing == 4'); - rslt.Expect( goodbye3.string_thing == "Goodbye4", 'goodbye3.String_thing == "Goodbye4"'); - rslt.Expect( goodbye3.byte_thing == 4, 'goodbye3.Byte_thing == 4'); - rslt.Expect( goodbye3.i32_thing == 4, 'goodbye3.I32_thing == 4'); - rslt.Expect( Int64.compare( goodbye3.i64_thing, Int64.make(0,4)) == 0, 'goodbye3.I64_thing == 4'); + rslt.Expect( Int64.compare( crazy3.userMap.get(Numberz.FIVE), insane.userMap.get(Numberz.FIVE)) == 0, "crazy3.userMap[5] == insane.userMap[5]"); + rslt.Expect( truck.string_thing == goodbye3.string_thing, "truck.string_thing == goodbye3.string_thing"); + rslt.Expect( truck.byte_thing == goodbye3.byte_thing, "truck.byte_thing == goodbye3.byte_thing"); + rslt.Expect( truck.i32_thing == goodbye3.i32_thing, "truck.i32_thing == goodbye3.i32_thing"); + rslt.Expect( Int64.compare( truck.i64_thing, goodbye3.i64_thing) == 0, "truck.i64_thing == goodbye3.i64_thing"); + + rslt.Expect( ! looney.isSet(1), "! looney.isSet(1)"); + rslt.Expect( ! looney.isSet(2), "! looney.isSet(2)"); } var arg0 = 1; diff --git a/vendor/git.apache.org/thrift.git/test/haxe/src/TestServerHandler.hx b/vendor/git.apache.org/thrift.git/test/haxe/src/TestServerHandler.hx index 9fba136..b8a2590 100644 --- a/vendor/git.apache.org/thrift.git/test/haxe/src/TestServerHandler.hx +++ b/vendor/git.apache.org/thrift.git/test/haxe/src/TestServerHandler.hx @@ -352,33 +352,12 @@ class TestServerHandler implements ThriftTest { { trace("testInsanity()"); - var hello = new Xtruct(); - hello.string_thing = "Hello2"; - hello.byte_thing = 2; - hello.i32_thing = 2; - hello.i64_thing = Int64.make(0, 2); - - var goodbye = new Xtruct(); - goodbye.string_thing = "Goodbye4"; - goodbye.byte_thing = 4; - goodbye.i32_thing = 4; - goodbye.i64_thing = Int64.make(0, 4); - - var crazy = new Insanity(); - crazy.userMap = new IntMap< haxe.Int64>(); - crazy.userMap.set(Numberz.EIGHT, Int64.make(0,8)); - crazy.xtructs = new List(); - crazy.xtructs.add(goodbye); - - var looney = new Insanity(); - crazy.userMap.set(Numberz.FIVE, Int64.make(0,5)); - crazy.xtructs.add(hello); - var first_map = new IntMap< Insanity>(); - first_map.set(Numberz.TWO, crazy); - first_map.set(Numberz.THREE, crazy); + first_map.set(Numberz.TWO, argument); + first_map.set(Numberz.THREE, argument); var second_map = new IntMap< Insanity>(); + var looney = new Insanity(); second_map.set(Numberz.SIX, looney); var insane = new Int64Map< IntMap< Insanity>>(); diff --git a/vendor/git.apache.org/thrift.git/test/hs/Makefile.am b/vendor/git.apache.org/thrift.git/test/hs/Makefile.am index 3f35396..1748906 100644 --- a/vendor/git.apache.org/thrift.git/test/hs/Makefile.am +++ b/vendor/git.apache.org/thrift.git/test/hs/Makefile.am @@ -17,8 +17,6 @@ # under the License. # -THRIFT = $(top_builddir)/compiler/cpp/thrift - stubs: $(THRIFT) ../ConstantsDemo.thrift ../DebugProtoTest.thrift ../ThriftTest.thrift ../Include.thrift $(THRIFT) --gen hs ../ConstantsDemo.thrift $(THRIFT) --gen hs ../DebugProtoTest.thrift diff --git a/vendor/git.apache.org/thrift.git/test/hs/TestClient.hs b/vendor/git.apache.org/thrift.git/test/hs/TestClient.hs index d1ebb3c..93fb591 100644 --- a/vendor/git.apache.org/thrift.git/test/hs/TestClient.hs +++ b/vendor/git.apache.org/thrift.git/test/hs/TestClient.hs @@ -46,6 +46,7 @@ import Thrift.Transport.HttpClient import Thrift.Protocol import Thrift.Protocol.Binary import Thrift.Protocol.Compact +import Thrift.Protocol.Header import Thrift.Protocol.JSON data Options = Options @@ -85,12 +86,14 @@ getTransport t host port = do return (NoTransport $ "Unsupported transport: " ++ data ProtocolType = Binary | Compact | JSON + | Header deriving (Show, Eq) getProtocol :: String -> ProtocolType getProtocol "binary" = Binary getProtocol "compact" = Compact getProtocol "json" = JSON +getProtocol "header" = Header getProtocol p = error $ "Unsupported Protocol: " ++ p defaultOptions :: Options @@ -104,7 +107,7 @@ defaultOptions = Options , testLoops = 1 } -runClient :: (Protocol p, Transport t) => p t -> IO () +runClient :: Protocol p => p -> IO () runClient p = do let prot = (p,p) putStrLn "Starting Tests" @@ -266,6 +269,7 @@ main = do Binary -> runClient $ BinaryProtocol t Compact -> runClient $ CompactProtocol t JSON -> runClient $ JSONProtocol t + Header -> createHeaderProtocol t t >>= runClient runTest loops p t = do let client = makeClient p t replicateM_ loops client diff --git a/vendor/git.apache.org/thrift.git/test/hs/TestServer.hs b/vendor/git.apache.org/thrift.git/test/hs/TestServer.hs index 4a88649..b7731ab 100644 --- a/vendor/git.apache.org/thrift.git/test/hs/TestServer.hs +++ b/vendor/git.apache.org/thrift.git/test/hs/TestServer.hs @@ -48,6 +48,7 @@ import Thrift.Transport.Framed import Thrift.Transport.Handle import Thrift.Protocol.Binary import Thrift.Protocol.Compact +import Thrift.Protocol.Header import Thrift.Protocol.JSON data Options = Options @@ -90,11 +91,13 @@ getTransport t = NoTransport $ "Unsupported transport: " ++ t data ProtocolType = Binary | Compact | JSON + | Header getProtocol :: String -> ProtocolType getProtocol "binary" = Binary getProtocol "compact" = Compact getProtocol "json" = JSON +getProtocol "header" = Header getProtocol p = error $"Unsupported Protocol: " ++ p defaultOptions :: Options @@ -261,13 +264,19 @@ main = do t <- f socket return (p t, p t) + headerAcceptor f socket = do + t <- f socket + p <- createHeaderProtocol1 t + return (p, p) + doRunServer p f = do runThreadedServer (acceptor p f) TestHandler ThriftTest.process . PortNumber . fromIntegral runServer p f port = case p of - Binary -> do doRunServer BinaryProtocol f port - Compact -> do doRunServer CompactProtocol f port - JSON -> do doRunServer JSONProtocol f port + Binary -> doRunServer BinaryProtocol f port + Compact -> doRunServer CompactProtocol f port + JSON -> doRunServer JSONProtocol f port + Header -> runThreadedServer (headerAcceptor f) TestHandler ThriftTest.process (PortNumber $ fromIntegral port) parseFlags :: [String] -> Options -> Maybe Options parseFlags (flag : flags) opts = do diff --git a/vendor/git.apache.org/thrift.git/test/known_failures_Linux.json b/vendor/git.apache.org/thrift.git/test/known_failures_Linux.json index edf0fbb..1ab2af5 100644 --- a/vendor/git.apache.org/thrift.git/test/known_failures_Linux.json +++ b/vendor/git.apache.org/thrift.git/test/known_failures_Linux.json @@ -1,88 +1,162 @@ [ - "cpp-cpp_binary_buffered-ip-ssl", - "cpp-cpp_binary_framed-ip-ssl", - "cpp-cpp_binary_http-domain", - "cpp-cpp_binary_http-ip", - "cpp-cpp_binary_http-ip-ssl", - "cpp-cpp_compact_buffered-ip-ssl", - "cpp-cpp_compact_framed-ip-ssl", - "cpp-cpp_compact_http-domain", - "cpp-cpp_compact_http-ip", - "cpp-cpp_compact_http-ip-ssl", - "cpp-cpp_header_buffered-ip-ssl", - "cpp-cpp_header_framed-ip-ssl", - "cpp-cpp_header_http-ip-ssl", - "cpp-cpp_json_buffered-ip-ssl", - "cpp-cpp_json_framed-ip", - "cpp-cpp_json_framed-ip-ssl", - "cpp-cpp_json_http-domain", - "cpp-cpp_json_http-ip", - "cpp-cpp_json_http-ip-ssl", + "c_glib-rs_multi_buffered-ip", + "c_glib-rs_multi_framed-ip", + "c_glib-rs_multic_buffered-ip", + "c_glib-rs_multic_framed-ip", + "cl-c_glib_binary_buffered-ip", + "cl-c_glib_binary_framed-ip", + "cl-c_glib_multi-binary_buffered-ip", + "cl-c_glib_multi-binary_framed-ip", + "cl-c_glib_multi_buffered-ip", + "cl-c_glib_multi_framed-ip", + "cl-go_binary_buffered-ip", + "cl-go_binary_framed-ip", + "cl-rb_binary-accel_buffered-ip", + "cl-rb_binary-accel_framed-ip", + "cl-rb_binary_buffered-ip", + "cl-rb_binary_framed-ip", + "cl-rs_binary_buffered-ip", + "cl-rs_binary_framed-ip", + "cl-rs_multi-binary_buffered-ip", + "cl-rs_multi-binary_framed-ip", + "cl-rs_multi_buffered-ip", + "cl-rs_multi_framed-ip", "cpp-dart_binary_http-ip", "cpp-dart_compact_http-ip", "cpp-dart_json_http-ip", + "cpp-dart_multi-binary_http-ip", + "cpp-dart_multic-compact_http-ip", + "cpp-dart_multij-json_http-ip", "cpp-go_binary_http-ip", "cpp-go_binary_http-ip-ssl", "cpp-go_compact_http-ip", "cpp-go_compact_http-ip-ssl", "cpp-go_json_http-ip", "cpp-go_json_http-ip-ssl", + "cpp-go_multi-binary_http-ip", + "cpp-go_multi-binary_http-ip-ssl", + "cpp-go_multic-compact_http-ip", + "cpp-go_multic-compact_http-ip-ssl", + "cpp-go_multij-json_http-ip", + "cpp-go_multij-json_http-ip-ssl", "cpp-java_binary_http-ip", "cpp-java_binary_http-ip-ssl", "cpp-java_compact_http-ip", "cpp-java_compact_http-ip-ssl", "cpp-java_json_http-ip", "cpp-java_json_http-ip-ssl", - "cpp-perl_binary_buffered-ip-ssl", - "cpp-perl_binary_framed-ip-ssl", - "cpp-py_binary-accel_framed-ip-ssl", - "csharp-cpp_binary_buffered-ip-ssl", - "csharp-cpp_binary_framed-ip-ssl", - "csharp-cpp_compact_buffered-ip-ssl", - "csharp-cpp_compact_framed-ip-ssl", - "csharp-cpp_json_buffered-ip-ssl", - "csharp-cpp_json_framed-ip-ssl", - "csharp-d_binary_buffered-ip-ssl", - "csharp-d_compact_buffered-ip-ssl", - "csharp-d_json_buffered-ip-ssl", - "csharp-erl_binary_buffered-ip-ssl", - "csharp-erl_binary_framed-ip-ssl", - "csharp-erl_compact_buffered-ip-ssl", - "csharp-erl_compact_framed-ip-ssl", - "csharp-go_binary_buffered-ip-ssl", - "csharp-go_binary_framed-ip-ssl", - "csharp-go_compact_buffered-ip-ssl", - "csharp-go_compact_framed-ip-ssl", - "csharp-go_json_buffered-ip-ssl", - "csharp-go_json_framed-ip-ssl", - "csharp-nodejs_binary_buffered-ip-ssl", - "csharp-nodejs_binary_framed-ip-ssl", - "csharp-nodejs_compact_buffered-ip-ssl", - "csharp-nodejs_compact_framed-ip-ssl", - "csharp-nodejs_json_buffered-ip-ssl", - "csharp-nodejs_json_framed-ip-ssl", - "csharp-perl_binary_buffered-ip-ssl", - "csharp-perl_binary_framed-ip-ssl", - "csharp-py3_binary-accel_buffered-ip-ssl", - "csharp-py3_binary-accel_framed-ip-ssl", - "csharp-py3_binary_buffered-ip-ssl", - "csharp-py3_binary_framed-ip-ssl", - "csharp-py3_compact-accelc_buffered-ip-ssl", - "csharp-py3_compact-accelc_framed-ip-ssl", - "csharp-py3_compact_buffered-ip-ssl", - "csharp-py3_compact_framed-ip-ssl", - "csharp-py3_json_buffered-ip-ssl", - "csharp-py3_json_framed-ip-ssl", - "csharp-py_binary-accel_buffered-ip-ssl", - "csharp-py_binary-accel_framed-ip-ssl", - "csharp-py_binary_buffered-ip-ssl", - "csharp-py_binary_framed-ip-ssl", - "csharp-py_compact-accelc_buffered-ip-ssl", - "csharp-py_compact-accelc_framed-ip-ssl", - "csharp-py_compact_buffered-ip-ssl", - "csharp-py_compact_framed-ip-ssl", - "csharp-py_json_buffered-ip-ssl", - "csharp-py_json_framed-ip-ssl", + "cpp-java_multi-binary_http-ip", + "cpp-java_multi-binary_http-ip-ssl", + "cpp-java_multi_http-ip", + "cpp-java_multi_http-ip-ssl", + "cpp-java_multic-compact_http-ip", + "cpp-java_multic-compact_http-ip-ssl", + "cpp-java_multic_http-ip", + "cpp-java_multic_http-ip-ssl", + "cpp-java_multij-json_http-ip", + "cpp-java_multij-json_http-ip-ssl", + "cpp-java_multij_http-ip", + "cpp-java_multij_http-ip-ssl", + "cpp-nodejs_binary_http-domain", + "cpp-nodejs_binary_http-ip", + "cpp-nodejs_binary_http-ip-ssl", + "cpp-nodejs_compact_http-domain", + "cpp-nodejs_compact_http-ip", + "cpp-nodejs_compact_http-ip-ssl", + "cpp-nodejs_json_http-domain", + "cpp-nodejs_json_http-ip", + "cpp-nodejs_json_http-ip-ssl", + "cpp-nodejs_multi-binary_http-domain", + "cpp-nodejs_multi-binary_http-ip", + "cpp-nodejs_multi-binary_http-ip-ssl", + "cpp-nodejs_multic-compact_http-domain", + "cpp-nodejs_multic-compact_http-ip", + "cpp-nodejs_multic-compact_http-ip-ssl", + "cpp-nodejs_multij-json_http-domain", + "cpp-nodejs_multij-json_http-ip", + "cpp-nodejs_multij-json_http-ip-ssl", + "cpp-py3_binary-accel_http-ip", + "cpp-py3_binary-accel_http-ip-ssl", + "cpp-py3_binary_http-ip", + "cpp-py3_binary_http-ip-ssl", + "cpp-py3_compact-accelc_http-ip", + "cpp-py3_compact-accelc_http-ip-ssl", + "cpp-py3_compact_http-ip", + "cpp-py3_compact_http-ip-ssl", + "cpp-py3_header_http-ip", + "cpp-py3_header_http-ip-ssl", + "cpp-py3_json_http-ip", + "cpp-py3_json_http-ip-ssl", + "cpp-py3_multi-accel_http-ip", + "cpp-py3_multi-accel_http-ip-ssl", + "cpp-py3_multi-binary_http-ip", + "cpp-py3_multi-binary_http-ip-ssl", + "cpp-py3_multi-multia_http-ip", + "cpp-py3_multi-multia_http-ip-ssl", + "cpp-py3_multi_http-ip", + "cpp-py3_multi_http-ip-ssl", + "cpp-py3_multic-accelc_http-ip", + "cpp-py3_multic-accelc_http-ip-ssl", + "cpp-py3_multic-compact_http-ip", + "cpp-py3_multic-compact_http-ip-ssl", + "cpp-py3_multic-multiac_http-ip", + "cpp-py3_multic-multiac_http-ip-ssl", + "cpp-py3_multic_http-ip", + "cpp-py3_multic_http-ip-ssl", + "cpp-py3_multih-header_http-ip", + "cpp-py3_multih-header_http-ip-ssl", + "cpp-py3_multij-json_http-ip", + "cpp-py3_multij-json_http-ip-ssl", + "cpp-py3_multij_http-ip", + "cpp-py3_multij_http-ip-ssl", + "cpp-py_binary-accel_http-ip", + "cpp-py_binary-accel_http-ip-ssl", + "cpp-py_binary_http-ip", + "cpp-py_binary_http-ip-ssl", + "cpp-py_compact-accelc_http-ip", + "cpp-py_compact-accelc_http-ip-ssl", + "cpp-py_compact_http-ip", + "cpp-py_compact_http-ip-ssl", + "cpp-py_header_http-ip", + "cpp-py_header_http-ip-ssl", + "cpp-py_json_http-ip", + "cpp-py_json_http-ip-ssl", + "cpp-py_multi-accel_http-ip", + "cpp-py_multi-accel_http-ip-ssl", + "cpp-py_multi-binary_http-ip", + "cpp-py_multi-binary_http-ip-ssl", + "cpp-py_multi-multia_http-ip", + "cpp-py_multi-multia_http-ip-ssl", + "cpp-py_multi_http-ip", + "cpp-py_multi_http-ip-ssl", + "cpp-py_multic-accelc_http-ip", + "cpp-py_multic-accelc_http-ip-ssl", + "cpp-py_multic-compact_http-ip", + "cpp-py_multic-compact_http-ip-ssl", + "cpp-py_multic-multiac_http-ip", + "cpp-py_multic-multiac_http-ip-ssl", + "cpp-py_multic_http-ip", + "cpp-py_multic_http-ip-ssl", + "cpp-py_multih-header_http-ip", + "cpp-py_multih-header_http-ip-ssl", + "cpp-py_multij-json_http-ip", + "cpp-py_multij-json_http-ip-ssl", + "cpp-py_multij_http-ip", + "cpp-py_multij_http-ip-ssl", + "cpp-rs_multi_buffered-ip", + "cpp-rs_multi_framed-ip", + "cpp-rs_multic_buffered-ip", + "cpp-rs_multic_framed-ip", + "csharp-rb_binary-accel_buffered-ip-ssl", + "csharp-rb_binary-accel_framed-ip-ssl", + "csharp-rb_binary_buffered-ip-ssl", + "csharp-rb_binary_framed-ip-ssl", + "csharp-rb_compact_buffered-ip-ssl", + "csharp-rb_compact_framed-ip-ssl", + "csharp-rb_json_buffered-ip-ssl", + "csharp-rb_json_framed-ip-ssl", + "d-cl_binary_buffered-ip", + "d-cl_binary_framed-ip", "d-cpp_binary_buffered-ip", "d-cpp_binary_buffered-ip-ssl", "d-cpp_binary_framed-ip", @@ -101,11 +175,11 @@ "d-cpp_json_framed-ip-ssl", "d-cpp_json_http-ip", "d-cpp_json_http-ip-ssl", - "d-dart_binary_framed-ip", + "d-d_binary_http-ip", + "d-d_compact_http-ip", + "d-d_json_http-ip", "d-dart_binary_http-ip", - "d-dart_compact_framed-ip", "d-dart_compact_http-ip", - "d-dart_json_framed-ip", "d-dart_json_http-ip", "d-go_binary_http-ip", "d-go_binary_http-ip-ssl", @@ -120,72 +194,104 @@ "d-java_json_http-ip", "d-java_json_http-ip-ssl", "d-js_json_http-ip", - "d-lua_json_buffered-ip", - "d-lua_json_framed-ip", "d-nodejs_binary_buffered-ip", "d-nodejs_binary_buffered-ip-ssl", "d-nodejs_binary_framed-ip", "d-nodejs_binary_framed-ip-ssl", + "d-nodejs_binary_http-ip", + "d-nodejs_binary_http-ip-ssl", "d-nodejs_compact_buffered-ip", "d-nodejs_compact_buffered-ip-ssl", "d-nodejs_compact_framed-ip", "d-nodejs_compact_framed-ip-ssl", + "d-nodejs_compact_http-ip", + "d-nodejs_compact_http-ip-ssl", "d-nodejs_json_buffered-ip", "d-nodejs_json_buffered-ip-ssl", "d-nodejs_json_framed-ip", "d-nodejs_json_framed-ip-ssl", - "d-perl_binary_buffered-ip-ssl", - "d-perl_binary_framed-ip-ssl", + "d-nodejs_json_http-ip", + "d-nodejs_json_http-ip-ssl", + "d-nodets_binary_buffered-ip", "d-py3_binary-accel_buffered-ip", "d-py3_binary-accel_buffered-ip-ssl", "d-py3_binary-accel_framed-ip", "d-py3_binary-accel_framed-ip-ssl", + "d-py3_binary-accel_http-ip", + "d-py3_binary-accel_http-ip-ssl", "d-py3_binary_buffered-ip", "d-py3_binary_buffered-ip-ssl", "d-py3_binary_framed-ip", "d-py3_binary_framed-ip-ssl", + "d-py3_binary_http-ip", + "d-py3_binary_http-ip-ssl", "d-py3_compact-accelc_buffered-ip", "d-py3_compact-accelc_buffered-ip-ssl", "d-py3_compact-accelc_framed-ip", "d-py3_compact-accelc_framed-ip-ssl", + "d-py3_compact-accelc_http-ip", + "d-py3_compact-accelc_http-ip-ssl", "d-py3_compact_buffered-ip", "d-py3_compact_buffered-ip-ssl", "d-py3_compact_framed-ip", "d-py3_compact_framed-ip-ssl", + "d-py3_compact_http-ip", + "d-py3_compact_http-ip-ssl", "d-py3_json_buffered-ip", "d-py3_json_buffered-ip-ssl", "d-py3_json_framed-ip", "d-py3_json_framed-ip-ssl", + "d-py3_json_http-ip", + "d-py3_json_http-ip-ssl", "d-py_binary-accel_buffered-ip", "d-py_binary-accel_buffered-ip-ssl", "d-py_binary-accel_framed-ip", "d-py_binary-accel_framed-ip-ssl", + "d-py_binary-accel_http-ip", + "d-py_binary-accel_http-ip-ssl", "d-py_binary_buffered-ip", "d-py_binary_buffered-ip-ssl", "d-py_binary_framed-ip", "d-py_binary_framed-ip-ssl", + "d-py_binary_http-ip", + "d-py_binary_http-ip-ssl", "d-py_compact-accelc_buffered-ip", "d-py_compact-accelc_buffered-ip-ssl", "d-py_compact-accelc_framed-ip", "d-py_compact-accelc_framed-ip-ssl", + "d-py_compact-accelc_http-ip", + "d-py_compact-accelc_http-ip-ssl", "d-py_compact_buffered-ip", "d-py_compact_buffered-ip-ssl", "d-py_compact_framed-ip", "d-py_compact_framed-ip-ssl", + "d-py_compact_http-ip", + "d-py_compact_http-ip-ssl", "d-py_json_buffered-ip", "d-py_json_buffered-ip-ssl", "d-py_json_framed-ip", "d-py_json_framed-ip-ssl", + "d-py_json_http-ip", + "d-py_json_http-ip-ssl", + "erl-cpp_binary_buffered-ip", + "erl-cpp_compact_buffered-ip", + "erl-csharp_binary_buffered-ip", + "erl-csharp_compact_buffered-ip", "erl-nodejs_binary_buffered-ip", "erl-nodejs_compact_buffered-ip", - "erl-perl_binary_buffered-ip-ssl", - "erl-perl_binary_framed-ip-ssl", + "erl-nodets_binary_buffered-ip", "erl-rb_binary-accel_buffered-ip", + "erl-rb_binary-accel_buffered-ip-ssl", "erl-rb_binary-accel_framed-ip", + "erl-rb_binary-accel_framed-ip-ssl", "erl-rb_binary_buffered-ip", + "erl-rb_binary_buffered-ip-ssl", "erl-rb_binary_framed-ip", + "erl-rb_binary_framed-ip-ssl", "erl-rb_compact_buffered-ip", + "erl-rb_compact_buffered-ip-ssl", "erl-rb_compact_framed-ip", + "erl-rb_compact_framed-ip-ssl", "go-cpp_binary_http-ip", "go-cpp_binary_http-ip-ssl", "go-cpp_compact_http-ip", @@ -198,10 +304,8 @@ "go-d_compact_http-ip-ssl", "go-d_json_http-ip", "go-d_json_http-ip-ssl", - "go-dart_binary_framed-ip", "go-dart_binary_http-ip", "go-dart_compact_http-ip", - "go-dart_json_framed-ip", "go-dart_json_http-ip", "go-java_binary_http-ip", "go-java_binary_http-ip-ssl", @@ -209,37 +313,182 @@ "go-java_compact_http-ip-ssl", "go-java_json_http-ip", "go-java_json_http-ip-ssl", - "go-nodejs_json_framed-ip", - "go-perl_binary_buffered-ip-ssl", - "go-perl_binary_framed-ip-ssl", + "go-py3_binary-accel_zlib-ip-ssl", + "go-py3_compact-accelc_zlib-ip-ssl", + "go-py_binary-accel_zlib-ip-ssl", + "go-py_compact-accelc_zlib-ip-ssl", + "hs-csharp_binary_buffered-ip", "hs-csharp_binary_framed-ip", + "hs-csharp_compact_buffered-ip", "hs-csharp_compact_framed-ip", - "hs-csharp_json_framed-ip", - "hs-dart_binary_framed-ip", - "hs-dart_compact_framed-ip", - "hs-dart_json_framed-ip", - "hs-py3_json_buffered-ip", - "hs-py3_json_framed-ip", - "hs-py_json_buffered-ip", - "hs-py_json_framed-ip", - "java-d_compact_buffered-ip", - "java-d_compact_buffered-ip-ssl", - "java-d_compact_framed-ip", - "java-perl_binary_buffered-ip-ssl", - "java-perl_binary_fastframed-framed-ip-ssl", - "java-perl_binary_framed-ip-ssl", - "nodejs-perl_binary_buffered-ip-ssl", - "nodejs-perl_binary_framed-ip-ssl", - "perl-perl_binary_buffered-ip-ssl", - "perl-perl_binary_framed-ip-ssl", - "perl-php_binary_framed-ip", - "py-cpp_compact_buffered-ip", - "py-perl_accel-binary_buffered-ip-ssl", - "py-perl_accel-binary_framed-ip-ssl", - "py-perl_binary_buffered-ip-ssl", - "py-perl_binary_framed-ip-ssl", - "py3-perl_accel-binary_buffered-ip-ssl", - "py3-perl_accel-binary_framed-ip-ssl", - "py3-perl_binary_buffered-ip-ssl", - "py3-perl_binary_framed-ip-ssl" -] + "nodejs-cpp_binary_http-domain", + "nodejs-cpp_binary_http-ip", + "nodejs-cpp_binary_http-ip-ssl", + "nodejs-cpp_compact_http-domain", + "nodejs-cpp_compact_http-ip", + "nodejs-cpp_compact_http-ip-ssl", + "nodejs-cpp_json_buffered-ip-ssl", + "nodejs-cpp_json_http-domain", + "nodejs-cpp_json_http-ip", + "nodejs-cpp_json_http-ip-ssl", + "nodejs-d_binary_http-ip", + "nodejs-d_binary_http-ip-ssl", + "nodejs-d_compact_http-ip", + "nodejs-d_compact_http-ip-ssl", + "nodejs-d_json_http-ip", + "nodejs-d_json_http-ip-ssl", + "nodejs-dart_binary_http-ip", + "nodejs-dart_compact_http-ip", + "nodejs-dart_json_http-ip", + "nodejs-go_binary_http-ip", + "nodejs-go_binary_http-ip-ssl", + "nodejs-go_compact_http-ip", + "nodejs-go_compact_http-ip-ssl", + "nodejs-go_json_http-ip", + "nodejs-go_json_http-ip-ssl", + "nodejs-hs_binary_http-ip", + "nodejs-hs_compact_http-ip", + "nodejs-hs_json_http-ip", + "nodejs-java_binary_http-ip", + "nodejs-java_binary_http-ip-ssl", + "nodejs-java_compact_http-ip", + "nodejs-java_compact_http-ip-ssl", + "nodejs-java_json_http-ip", + "nodejs-java_json_http-ip-ssl", + "nodejs-js_json_http-ip", + "nodejs-lua_binary_http-ip", + "nodejs-lua_compact_http-ip", + "nodejs-lua_json_http-ip", + "nodejs-py3_binary-accel_http-ip", + "nodejs-py3_binary-accel_http-ip-ssl", + "nodejs-py3_binary_http-ip", + "nodejs-py3_binary_http-ip-ssl", + "nodejs-py3_compact-accelc_http-ip", + "nodejs-py3_compact-accelc_http-ip-ssl", + "nodejs-py3_compact_http-ip", + "nodejs-py3_compact_http-ip-ssl", + "nodejs-py3_json_http-ip", + "nodejs-py3_json_http-ip-ssl", + "nodejs-py_binary-accel_http-ip", + "nodejs-py_binary-accel_http-ip-ssl", + "nodejs-py_binary_http-ip", + "nodejs-py_binary_http-ip-ssl", + "nodejs-py_compact-accelc_http-ip", + "nodejs-py_compact-accelc_http-ip-ssl", + "nodejs-py_compact_http-ip", + "nodejs-py_compact_http-ip-ssl", + "nodejs-py_json_http-ip", + "nodejs-py_json_http-ip-ssl", + "perl-rs_multi_buffered-ip", + "perl-rs_multi_framed-ip", + "py-cpp_accel-binary_http-ip", + "py-cpp_accel-binary_http-ip-ssl", + "py-cpp_accel-binary_zlib-ip", + "py-cpp_accel-binary_zlib-ip-ssl", + "py-cpp_accelc-compact_http-ip", + "py-cpp_accelc-compact_http-ip-ssl", + "py-cpp_accelc-compact_zlib-ip", + "py-cpp_accelc-compact_zlib-ip-ssl", + "py-cpp_binary_http-ip", + "py-cpp_binary_http-ip-ssl", + "py-cpp_compact_http-ip", + "py-cpp_compact_http-ip-ssl", + "py-cpp_header_http-ip", + "py-cpp_header_http-ip-ssl", + "py-cpp_json_http-ip", + "py-cpp_json_http-ip-ssl", + "py-d_accel-binary_http-ip", + "py-d_accel-binary_http-ip-ssl", + "py-d_accelc-compact_http-ip", + "py-d_accelc-compact_http-ip-ssl", + "py-d_binary_http-ip", + "py-d_binary_http-ip-ssl", + "py-d_compact_http-ip", + "py-d_compact_http-ip-ssl", + "py-d_json_http-ip", + "py-d_json_http-ip-ssl", + "py-dart_accel-binary_http-ip", + "py-dart_accelc-compact_http-ip", + "py-dart_binary_http-ip", + "py-dart_compact_http-ip", + "py-dart_json_http-ip", + "py-hs_accel-binary_http-ip", + "py-hs_accelc-compact_http-ip", + "py-hs_binary_http-ip", + "py-hs_compact_http-ip", + "py-hs_header_http-ip", + "py-hs_json_http-ip", + "py-java_accel-binary_http-ip", + "py-java_accel-binary_http-ip-ssl", + "py-java_accelc-compact_http-ip", + "py-java_accelc-compact_http-ip-ssl", + "py-java_binary_http-ip", + "py-java_binary_http-ip-ssl", + "py-java_compact_http-ip", + "py-java_compact_http-ip-ssl", + "py-java_json_http-ip", + "py-java_json_http-ip-ssl", + "py-lua_accel-binary_http-ip", + "py-lua_accelc-compact_http-ip", + "py-lua_binary_http-ip", + "py-lua_compact_http-ip", + "py-lua_json_http-ip", + "py3-cpp_accel-binary_http-ip", + "py3-cpp_accel-binary_http-ip-ssl", + "py3-cpp_accel-binary_zlib-ip", + "py3-cpp_accel-binary_zlib-ip-ssl", + "py3-cpp_accelc-compact_http-ip", + "py3-cpp_accelc-compact_http-ip-ssl", + "py3-cpp_accelc-compact_zlib-ip", + "py3-cpp_accelc-compact_zlib-ip-ssl", + "py3-cpp_binary_http-ip", + "py3-cpp_binary_http-ip-ssl", + "py3-cpp_compact_http-ip", + "py3-cpp_compact_http-ip-ssl", + "py3-cpp_header_http-ip", + "py3-cpp_header_http-ip-ssl", + "py3-cpp_json_http-ip", + "py3-cpp_json_http-ip-ssl", + "py3-d_accel-binary_http-ip", + "py3-d_accel-binary_http-ip-ssl", + "py3-d_accelc-compact_http-ip", + "py3-d_accelc-compact_http-ip-ssl", + "py3-d_binary_http-ip", + "py3-d_binary_http-ip-ssl", + "py3-d_compact_http-ip", + "py3-d_compact_http-ip-ssl", + "py3-d_json_http-ip", + "py3-d_json_http-ip-ssl", + "py3-dart_accel-binary_http-ip", + "py3-dart_accelc-compact_http-ip", + "py3-dart_binary_http-ip", + "py3-dart_compact_http-ip", + "py3-dart_json_http-ip", + "py3-hs_accel-binary_http-ip", + "py3-hs_accelc-compact_http-ip", + "py3-hs_binary_http-ip", + "py3-hs_compact_http-ip", + "py3-hs_header_http-ip", + "py3-hs_json_http-ip", + "py3-java_accel-binary_http-ip", + "py3-java_accel-binary_http-ip-ssl", + "py3-java_accelc-compact_http-ip", + "py3-java_accelc-compact_http-ip-ssl", + "py3-java_binary_http-ip", + "py3-java_binary_http-ip-ssl", + "py3-java_compact_http-ip", + "py3-java_compact_http-ip-ssl", + "py3-java_json_http-ip", + "py3-java_json_http-ip-ssl", + "py3-lua_accel-binary_http-ip", + "py3-lua_accelc-compact_http-ip", + "py3-lua_binary_http-ip", + "py3-lua_compact_http-ip", + "py3-lua_json_http-ip", + "rb-cpp_json_buffered-domain", + "rb-cpp_json_buffered-ip", + "rb-cpp_json_buffered-ip-ssl", + "rb-cpp_json_framed-domain", + "rb-cpp_json_framed-ip", + "rb-cpp_json_framed-ip-ssl" +] \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/test/netcore/Client/.gitignore b/vendor/git.apache.org/thrift.git/test/netcore/Client/.gitignore new file mode 100644 index 0000000..67d5510 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/netcore/Client/.gitignore @@ -0,0 +1,2 @@ +# ignore for autogenerated files +/ThriftTest diff --git a/vendor/git.apache.org/thrift.git/test/netcore/Client/Client.csproj b/vendor/git.apache.org/thrift.git/test/netcore/Client/Client.csproj new file mode 100644 index 0000000..f16af39 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/netcore/Client/Client.csproj @@ -0,0 +1,31 @@ + + + netcoreapp2.0 + Client + Client + Exe + false + false + false + false + false + false + + + + + + + + + + + + + + + + + + + diff --git a/vendor/git.apache.org/thrift.git/test/netcore/Client/Program.cs b/vendor/git.apache.org/thrift.git/test/netcore/Client/Program.cs new file mode 100644 index 0000000..72139d9 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/netcore/Client/Program.cs @@ -0,0 +1,72 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Collections.Generic; +using ThriftTest; + +namespace Client +{ + public class Program + { + public static int Main(string[] args) + { + try + { + Console.SetBufferSize(Console.BufferWidth, 4096); + } + catch (Exception) + { + Console.WriteLine("Failed to grow scroll-back buffer"); + } + + // split mode and options + var subArgs = new List(args); + var firstArg = string.Empty; + if (subArgs.Count > 0) + { + firstArg = subArgs[0]; + subArgs.RemoveAt(0); + } + + // run whatever mode is choosen + switch(firstArg) + { + case "client": + return TestClient.Execute(subArgs); + case "--help": + PrintHelp(); + return 0; + default: + PrintHelp(); + return -1; + } + } + + private static void PrintHelp() + { + Console.WriteLine("Usage:"); + Console.WriteLine(" Client client [options]'"); + Console.WriteLine(" Client --help"); + Console.WriteLine(""); + + TestClient.PrintOptionsHelp(); + } + } +} + + diff --git a/vendor/git.apache.org/thrift.git/test/netcore/Client/Properties/AssemblyInfo.cs b/vendor/git.apache.org/thrift.git/test/netcore/Client/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..157152b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/netcore/Client/Properties/AssemblyInfo.cs @@ -0,0 +1,43 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. + +[assembly: AssemblyTitle("Client")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("The Apache Software Foundation")] +[assembly: AssemblyProduct("Thrift")] +[assembly: AssemblyCopyright("The Apache Software Foundation")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. + +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM + +[assembly: Guid("B0C13DA0-3117-4844-8AE8-B1775E46223D")] + diff --git a/vendor/git.apache.org/thrift.git/test/netcore/Client/TestClient.cs b/vendor/git.apache.org/thrift.git/test/netcore/Client/TestClient.cs new file mode 100644 index 0000000..8be198c --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/netcore/Client/TestClient.cs @@ -0,0 +1,943 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; +using System.ServiceModel; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Thrift.Collections; +using Thrift.Protocols; +using Thrift.Transports; +using Thrift.Transports.Client; + +namespace ThriftTest +{ + public class TestClient + { + private class TestParams + { + public int numIterations = 1; + public IPAddress host = IPAddress.Any; + public int port = 9090; + public int numThreads = 1; + public string url; + public string pipe; + public bool buffered; + public bool framed; + public string protocol; + public bool encrypted = false; + + internal void Parse( List args) + { + for (var i = 0; i < args.Count; ++i) + { + if (args[i] == "-u") + { + url = args[++i]; + } + else if (args[i] == "-n") + { + numIterations = Convert.ToInt32(args[++i]); + } + else if (args[i].StartsWith("--pipe=")) + { + pipe = args[i].Substring(args[i].IndexOf("=") + 1); + Console.WriteLine("Using named pipes transport"); + } + else if (args[i].StartsWith("--host=")) + { + // check there for ipaddress + host = new IPAddress(Encoding.Unicode.GetBytes(args[i].Substring(args[i].IndexOf("=") + 1))); + } + else if (args[i].StartsWith("--port=")) + { + port = int.Parse(args[i].Substring(args[i].IndexOf("=") + 1)); + } + else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered") + { + buffered = true; + Console.WriteLine("Using buffered sockets"); + } + else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed") + { + framed = true; + Console.WriteLine("Using framed transport"); + } + else if (args[i] == "-t") + { + numThreads = Convert.ToInt32(args[++i]); + } + else if (args[i] == "--binary" || args[i] == "--protocol=binary") + { + protocol = "binary"; + Console.WriteLine("Using binary protocol"); + } + else if (args[i] == "--compact" || args[i] == "--protocol=compact") + { + protocol = "compact"; + Console.WriteLine("Using compact protocol"); + } + else if (args[i] == "--json" || args[i] == "--protocol=json") + { + protocol = "json"; + Console.WriteLine("Using JSON protocol"); + } + else if (args[i] == "--ssl") + { + encrypted = true; + Console.WriteLine("Using encrypted transport"); + } + else + { + //throw new ArgumentException(args[i]); + } + } + } + + private static X509Certificate2 GetClientCert() + { + var clientCertName = "client.p12"; + var possiblePaths = new List + { + "../../../keys/", + "../../keys/", + "../keys/", + "keys/", + }; + + string existingPath = null; + foreach (var possiblePath in possiblePaths) + { + var path = Path.GetFullPath(possiblePath + clientCertName); + if (File.Exists(path)) + { + existingPath = path; + break; + } + } + + if (string.IsNullOrEmpty(existingPath)) + { + throw new FileNotFoundException($"Cannot find file: {clientCertName}"); + } + + var cert = new X509Certificate2(existingPath, "thrift"); + + return cert; + } + + public TClientTransport CreateTransport() + { + if (url == null) + { + // endpoint transport + TClientTransport trans = null; + + if (pipe != null) + { + trans = new TNamedPipeClientTransport(pipe); + } + else + { + if (encrypted) + { + var cert = GetClientCert(); + + if (cert == null || !cert.HasPrivateKey) + { + throw new InvalidOperationException("Certificate doesn't contain private key"); + } + + trans = new TTlsSocketClientTransport(host, port, 0, cert, + (sender, certificate, chain, errors) => true, + null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12); + } + else + { + trans = new TSocketClientTransport(host, port); + } + } + + // layered transport + if (buffered) + { + trans = new TBufferedClientTransport(trans); + } + + if (framed) + { + trans = new TFramedClientTransport(trans); + } + + return trans; + } + + return new THttpClientTransport(new Uri(url), null); + } + + public TProtocol CreateProtocol(TClientTransport transport) + { + if (protocol == "compact") + { + return new TCompactProtocol(transport); + } + + if (protocol == "json") + { + return new TJsonProtocol(transport); + } + + return new TBinaryProtocol(transport); + } + } + + + private const int ErrorBaseTypes = 1; + private const int ErrorStructs = 2; + private const int ErrorContainers = 4; + private const int ErrorExceptions = 8; + private const int ErrorUnknown = 64; + + private class ClientTest + { + private readonly TClientTransport transport; + private readonly ThriftTest.Client client; + private readonly int numIterations; + private bool done; + + public int ReturnCode { get; set; } + + public ClientTest(TestParams param) + { + transport = param.CreateTransport(); + client = new ThriftTest.Client(param.CreateProtocol(transport)); + numIterations = param.numIterations; + } + + public void Execute() + { + var token = CancellationToken.None; + + if (done) + { + Console.WriteLine("Execute called more than once"); + throw new InvalidOperationException(); + } + + for (var i = 0; i < numIterations; i++) + { + try + { + if (!transport.IsOpen) + { + transport.OpenAsync(token).GetAwaiter().GetResult(); + } + } + catch (TTransportException ex) + { + Console.WriteLine("*** FAILED ***"); + Console.WriteLine("Connect failed: " + ex.Message); + ReturnCode |= ErrorUnknown; + Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); + continue; + } + catch (Exception ex) + { + Console.WriteLine("*** FAILED ***"); + Console.WriteLine("Connect failed: " + ex.Message); + ReturnCode |= ErrorUnknown; + Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); + continue; + } + + try + { + ReturnCode |= ExecuteClientTestAsync(client).GetAwaiter().GetResult(); ; + } + catch (Exception ex) + { + Console.WriteLine("*** FAILED ***"); + Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); + ReturnCode |= ErrorUnknown; + } + } + try + { + transport.Close(); + } + catch (Exception ex) + { + Console.WriteLine("Error while closing transport"); + Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); + } + done = true; + } + } + + internal static void PrintOptionsHelp() + { + Console.WriteLine("Client options:"); + Console.WriteLine(" -u "); + Console.WriteLine(" -t <# of threads to run> default = 1"); + Console.WriteLine(" -n <# of iterations> per thread"); + Console.WriteLine(" --pipe="); + Console.WriteLine(" --host="); + Console.WriteLine(" --port="); + Console.WriteLine(" --transport= one of buffered,framed (defaults to none)"); + Console.WriteLine(" --protocol= one of compact,json (defaults to binary)"); + Console.WriteLine(" --ssl"); + Console.WriteLine(); + } + + public static int Execute(List args) + { + try + { + var param = new TestParams(); + + try + { + param.Parse(args); + } + catch (Exception ex) + { + Console.WriteLine("*** FAILED ***"); + Console.WriteLine("Error while parsing arguments"); + Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); + return ErrorUnknown; + } + + var tests = Enumerable.Range(0, param.numThreads).Select(_ => new ClientTest(param)).ToArray(); + + //issue tests on separate threads simultaneously + var threads = tests.Select(test => new Task(test.Execute)).ToArray(); + var start = DateTime.Now; + foreach (var t in threads) + { + t.Start(); + } + + Task.WaitAll(threads); + + Console.WriteLine("Total time: " + (DateTime.Now - start)); + Console.WriteLine(); + return tests.Select(t => t.ReturnCode).Aggregate((r1, r2) => r1 | r2); + } + catch (Exception outerEx) + { + Console.WriteLine("*** FAILED ***"); + Console.WriteLine("Unexpected error"); + Console.WriteLine(outerEx.Message + " ST: " + outerEx.StackTrace); + return ErrorUnknown; + } + } + + public static string BytesToHex(byte[] data) + { + return BitConverter.ToString(data).Replace("-", string.Empty); + } + + public static byte[] PrepareTestData(bool randomDist) + { + var retval = new byte[0x100]; + var initLen = Math.Min(0x100, retval.Length); + + // linear distribution, unless random is requested + if (!randomDist) + { + for (var i = 0; i < initLen; ++i) + { + retval[i] = (byte)i; + } + return retval; + } + + // random distribution + for (var i = 0; i < initLen; ++i) + { + retval[i] = (byte)0; + } + var rnd = new Random(); + for (var i = 1; i < initLen; ++i) + { + while (true) + { + var nextPos = rnd.Next() % initLen; + if (retval[nextPos] == 0) + { + retval[nextPos] = (byte)i; + break; + } + } + } + return retval; + } + + public static async Task ExecuteClientTestAsync(ThriftTest.Client client) + { + var token = CancellationToken.None; + var returnCode = 0; + + Console.Write("testVoid()"); + await client.testVoidAsync(token); + Console.WriteLine(" = void"); + + Console.Write("testString(\"Test\")"); + var s = await client.testStringAsync("Test", token); + Console.WriteLine(" = \"" + s + "\""); + if ("Test" != s) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorBaseTypes; + } + + Console.Write("testBool(true)"); + var t = await client.testBoolAsync((bool)true, token); + Console.WriteLine(" = " + t); + if (!t) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorBaseTypes; + } + Console.Write("testBool(false)"); + var f = await client.testBoolAsync((bool)false, token); + Console.WriteLine(" = " + f); + if (f) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorBaseTypes; + } + + Console.Write("testByte(1)"); + var i8 = await client.testByteAsync((sbyte)1, token); + Console.WriteLine(" = " + i8); + if (1 != i8) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorBaseTypes; + } + + Console.Write("testI32(-1)"); + var i32 = await client.testI32Async(-1, token); + Console.WriteLine(" = " + i32); + if (-1 != i32) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorBaseTypes; + } + + Console.Write("testI64(-34359738368)"); + var i64 = await client.testI64Async(-34359738368, token); + Console.WriteLine(" = " + i64); + if (-34359738368 != i64) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorBaseTypes; + } + + // TODO: Validate received message + Console.Write("testDouble(5.325098235)"); + var dub = await client.testDoubleAsync(5.325098235, token); + Console.WriteLine(" = " + dub); + if (5.325098235 != dub) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorBaseTypes; + } + Console.Write("testDouble(-0.000341012439638598279)"); + dub = await client.testDoubleAsync(-0.000341012439638598279, token); + Console.WriteLine(" = " + dub); + if (-0.000341012439638598279 != dub) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorBaseTypes; + } + + var binOut = PrepareTestData(true); + Console.Write("testBinary(" + BytesToHex(binOut) + ")"); + try + { + var binIn = await client.testBinaryAsync(binOut, token); + Console.WriteLine(" = " + BytesToHex(binIn)); + if (binIn.Length != binOut.Length) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorBaseTypes; + } + for (var ofs = 0; ofs < Math.Min(binIn.Length, binOut.Length); ++ofs) + if (binIn[ofs] != binOut[ofs]) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorBaseTypes; + } + } + catch (Thrift.TApplicationException ex) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorBaseTypes; + Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); + } + + // binary equals? only with hashcode option enabled ... + Console.WriteLine("Test CrazyNesting"); + var one = new CrazyNesting(); + var two = new CrazyNesting(); + one.String_field = "crazy"; + two.String_field = "crazy"; + one.Binary_field = new byte[] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF }; + two.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF }; + if (typeof(CrazyNesting).GetMethod("Equals")?.DeclaringType == typeof(CrazyNesting)) + { + if (!one.Equals(two)) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorContainers; + throw new Exception("CrazyNesting.Equals failed"); + } + } + + // TODO: Validate received message + Console.Write("testStruct({\"Zero\", 1, -3, -5})"); + var o = new Xtruct(); + o.String_thing = "Zero"; + o.Byte_thing = (sbyte)1; + o.I32_thing = -3; + o.I64_thing = -5; + var i = await client.testStructAsync(o, token); + Console.WriteLine(" = {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}"); + + // TODO: Validate received message + Console.Write("testNest({1, {\"Zero\", 1, -3, -5}, 5})"); + var o2 = new Xtruct2(); + o2.Byte_thing = (sbyte)1; + o2.Struct_thing = o; + o2.I32_thing = 5; + var i2 = await client.testNestAsync(o2, token); + i = i2.Struct_thing; + Console.WriteLine(" = {" + i2.Byte_thing + ", {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}, " + i2.I32_thing + "}"); + + var mapout = new Dictionary(); + for (var j = 0; j < 5; j++) + { + mapout[j] = j - 10; + } + Console.Write("testMap({"); + var first = true; + foreach (var key in mapout.Keys) + { + if (first) + { + first = false; + } + else + { + Console.Write(", "); + } + Console.Write(key + " => " + mapout[key]); + } + Console.Write("})"); + + var mapin = await client.testMapAsync(mapout, token); + + Console.Write(" = {"); + first = true; + foreach (var key in mapin.Keys) + { + if (first) + { + first = false; + } + else + { + Console.Write(", "); + } + Console.Write(key + " => " + mapin[key]); + } + Console.WriteLine("}"); + + // TODO: Validate received message + var listout = new List(); + for (var j = -2; j < 3; j++) + { + listout.Add(j); + } + Console.Write("testList({"); + first = true; + foreach (var j in listout) + { + if (first) + { + first = false; + } + else + { + Console.Write(", "); + } + Console.Write(j); + } + Console.Write("})"); + + var listin = await client.testListAsync(listout, token); + + Console.Write(" = {"); + first = true; + foreach (var j in listin) + { + if (first) + { + first = false; + } + else + { + Console.Write(", "); + } + Console.Write(j); + } + Console.WriteLine("}"); + + //set + // TODO: Validate received message + var setout = new THashSet(); + for (var j = -2; j < 3; j++) + { + setout.Add(j); + } + Console.Write("testSet({"); + first = true; + foreach (int j in setout) + { + if (first) + { + first = false; + } + else + { + Console.Write(", "); + } + Console.Write(j); + } + Console.Write("})"); + + var setin = await client.testSetAsync(setout, token); + + Console.Write(" = {"); + first = true; + foreach (int j in setin) + { + if (first) + { + first = false; + } + else + { + Console.Write(", "); + } + Console.Write(j); + } + Console.WriteLine("}"); + + + Console.Write("testEnum(ONE)"); + var ret = await client.testEnumAsync(Numberz.ONE, token); + Console.WriteLine(" = " + ret); + if (Numberz.ONE != ret) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorStructs; + } + + Console.Write("testEnum(TWO)"); + ret = await client.testEnumAsync(Numberz.TWO, token); + Console.WriteLine(" = " + ret); + if (Numberz.TWO != ret) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorStructs; + } + + Console.Write("testEnum(THREE)"); + ret = await client.testEnumAsync(Numberz.THREE, token); + Console.WriteLine(" = " + ret); + if (Numberz.THREE != ret) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorStructs; + } + + Console.Write("testEnum(FIVE)"); + ret = await client.testEnumAsync(Numberz.FIVE, token); + Console.WriteLine(" = " + ret); + if (Numberz.FIVE != ret) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorStructs; + } + + Console.Write("testEnum(EIGHT)"); + ret = await client.testEnumAsync(Numberz.EIGHT, token); + Console.WriteLine(" = " + ret); + if (Numberz.EIGHT != ret) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorStructs; + } + + Console.Write("testTypedef(309858235082523)"); + var uid = await client.testTypedefAsync(309858235082523L, token); + Console.WriteLine(" = " + uid); + if (309858235082523L != uid) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorStructs; + } + + // TODO: Validate received message + Console.Write("testMapMap(1)"); + var mm = await client.testMapMapAsync(1, token); + Console.Write(" = {"); + foreach (var key in mm.Keys) + { + Console.Write(key + " => {"); + var m2 = mm[key]; + foreach (var k2 in m2.Keys) + { + Console.Write(k2 + " => " + m2[k2] + ", "); + } + Console.Write("}, "); + } + Console.WriteLine("}"); + + // TODO: Validate received message + var insane = new Insanity(); + insane.UserMap = new Dictionary(); + insane.UserMap[Numberz.FIVE] = 5000L; + var truck = new Xtruct(); + truck.String_thing = "Truck"; + truck.Byte_thing = (sbyte)8; + truck.I32_thing = 8; + truck.I64_thing = 8; + insane.Xtructs = new List(); + insane.Xtructs.Add(truck); + Console.Write("testInsanity()"); + var whoa = await client.testInsanityAsync(insane, token); + Console.Write(" = {"); + foreach (var key in whoa.Keys) + { + var val = whoa[key]; + Console.Write(key + " => {"); + + foreach (var k2 in val.Keys) + { + var v2 = val[k2]; + + Console.Write(k2 + " => {"); + var userMap = v2.UserMap; + + Console.Write("{"); + if (userMap != null) + { + foreach (var k3 in userMap.Keys) + { + Console.Write(k3 + " => " + userMap[k3] + ", "); + } + } + else + { + Console.Write("null"); + } + Console.Write("}, "); + + var xtructs = v2.Xtructs; + + Console.Write("{"); + if (xtructs != null) + { + foreach (var x in xtructs) + { + Console.Write("{\"" + x.String_thing + "\", " + x.Byte_thing + ", " + x.I32_thing + ", " + x.I32_thing + "}, "); + } + } + else + { + Console.Write("null"); + } + Console.Write("}"); + + Console.Write("}, "); + } + Console.Write("}, "); + } + Console.WriteLine("}"); + + sbyte arg0 = 1; + var arg1 = 2; + var arg2 = long.MaxValue; + var multiDict = new Dictionary(); + multiDict[1] = "one"; + + var tmpMultiDict = new List(); + foreach (var pair in multiDict) + tmpMultiDict.Add(pair.Key +" => "+ pair.Value); + + var arg4 = Numberz.FIVE; + long arg5 = 5000000; + Console.Write("Test Multi(" + arg0 + "," + arg1 + "," + arg2 + ",{" + string.Join(",", tmpMultiDict) + "}," + arg4 + "," + arg5 + ")"); + var multiResponse = await client.testMultiAsync(arg0, arg1, arg2, multiDict, arg4, arg5, token); + Console.Write(" = Xtruct(byte_thing:" + multiResponse.Byte_thing + ",String_thing:" + multiResponse.String_thing + + ",i32_thing:" + multiResponse.I32_thing + ",i64_thing:" + multiResponse.I64_thing + ")\n"); + + try + { + Console.WriteLine("testException(\"Xception\")"); + await client.testExceptionAsync("Xception", token); + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorExceptions; + } + catch (Xception ex) + { + if (ex.ErrorCode != 1001 || ex.Message != "Xception") + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorExceptions; + } + } + catch (Exception ex) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorExceptions; + Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); + } + try + { + Console.WriteLine("testException(\"TException\")"); + await client.testExceptionAsync("TException", token); + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorExceptions; + } + catch (Thrift.TException) + { + // OK + } + catch (Exception ex) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorExceptions; + Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); + } + try + { + Console.WriteLine("testException(\"ok\")"); + await client.testExceptionAsync("ok", token); + // OK + } + catch (Exception ex) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorExceptions; + Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); + } + + try + { + Console.WriteLine("testMultiException(\"Xception\", ...)"); + await client.testMultiExceptionAsync("Xception", "ignore", token); + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorExceptions; + } + catch (Xception ex) + { + if (ex.ErrorCode != 1001 || ex.Message != "This is an Xception") + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorExceptions; + } + } + catch (Exception ex) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorExceptions; + Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); + } + try + { + Console.WriteLine("testMultiException(\"Xception2\", ...)"); + await client.testMultiExceptionAsync("Xception2", "ignore", token); + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorExceptions; + } + catch (Xception2 ex) + { + if (ex.ErrorCode != 2002 || ex.Struct_thing.String_thing != "This is an Xception2") + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorExceptions; + } + } + catch (Exception ex) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorExceptions; + Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); + } + try + { + Console.WriteLine("testMultiException(\"success\", \"OK\")"); + if ("OK" != (await client.testMultiExceptionAsync("success", "OK", token)).String_thing) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorExceptions; + } + } + catch (Exception ex) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorExceptions; + Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); + } + + var sw = new Stopwatch(); + sw.Start(); + Console.WriteLine("Test Oneway(1)"); + await client.testOnewayAsync(1, token); + sw.Stop(); + if (sw.ElapsedMilliseconds > 1000) + { + Console.WriteLine("*** FAILED ***"); + returnCode |= ErrorBaseTypes; + } + + Console.Write("Test Calltime()"); + var times = 50; + sw.Reset(); + sw.Start(); + for (var k = 0; k < times; ++k) + await client.testVoidAsync(token); + sw.Stop(); + Console.WriteLine(" = {0} ms a testVoid() call", sw.ElapsedMilliseconds / times); + return returnCode; + } + } +} diff --git a/vendor/git.apache.org/thrift.git/test/netcore/Makefile.am b/vendor/git.apache.org/thrift.git/test/netcore/Makefile.am new file mode 100644 index 0000000..376ffb7 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/netcore/Makefile.am @@ -0,0 +1,41 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +SUBDIRS = . + +all-local: + $(DOTNETCORE) build + +precross: + $(DOTNETCORE) build + +clean-local: + $(RM) -r Client/bin + $(RM) -r Server/bin + $(RM) -r Client/obj + $(RM) -r Server/obj + $(RM) -r ThriftTest/ThriftTest + +EXTRA_DIST = \ + Client \ + README.md \ + Server \ + ThriftTest.sln \ + build.cmd \ + build.sh diff --git a/vendor/git.apache.org/thrift.git/test/netcore/README.md b/vendor/git.apache.org/thrift.git/test/netcore/README.md new file mode 100644 index 0000000..ed728d1 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/netcore/README.md @@ -0,0 +1,20 @@ +# Apache Thrift net-core-lib tests + +Tests for Thrift client library ported to Microsoft .Net Core + +# Content +- ThriftTest - tests for Thrift library + +# Reused components +- NET Core Standard 1.6 (SDK 2.0.0) + +# How to build on Windows +- Get Thrift IDL compiler executable, add to some folder and add path to this folder into PATH variable +- Open ThriftTest.sln in Visual Studio and build +or +- Build with scripts + +# How to build on Unix +- Ensure you have .NET Core 2.0.0 SDK installed or use the Ubuntu Xenial docker image +- Follow common build practice for Thrift: bootstrap, configure, and make precross + diff --git a/vendor/git.apache.org/thrift.git/test/netcore/Server/.gitignore b/vendor/git.apache.org/thrift.git/test/netcore/Server/.gitignore new file mode 100644 index 0000000..67d5510 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/netcore/Server/.gitignore @@ -0,0 +1,2 @@ +# ignore for autogenerated files +/ThriftTest diff --git a/vendor/git.apache.org/thrift.git/test/netcore/Server/Program.cs b/vendor/git.apache.org/thrift.git/test/netcore/Server/Program.cs new file mode 100644 index 0000000..e647e5b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/netcore/Server/Program.cs @@ -0,0 +1,72 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Collections.Generic; +using ThriftTest; + +namespace Server +{ + public class Program + { + public static int Main(string[] args) + { + try + { + Console.SetBufferSize(Console.BufferWidth, 4096); + } + catch (Exception) + { + Console.WriteLine("Failed to grow scroll-back buffer"); + } + + // split mode and options + var subArgs = new List(args); + var firstArg = string.Empty; + if (subArgs.Count > 0) + { + firstArg = subArgs[0]; + subArgs.RemoveAt(0); + } + + // run whatever mode is choosen + switch(firstArg) + { + case "server": + return TestServer.Execute(subArgs); + case "--help": + PrintHelp(); + return 0; + default: + PrintHelp(); + return -1; + } + } + + private static void PrintHelp() + { + Console.WriteLine("Usage:"); + Console.WriteLine(" Server server [options]'"); + Console.WriteLine(" Server --help"); + Console.WriteLine(""); + + TestServer.PrintOptionsHelp(); + } + } +} + + diff --git a/vendor/git.apache.org/thrift.git/test/netcore/Server/Properties/AssemblyInfo.cs b/vendor/git.apache.org/thrift.git/test/netcore/Server/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..265495c --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/netcore/Server/Properties/AssemblyInfo.cs @@ -0,0 +1,43 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. + +[assembly: AssemblyTitle("Server")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("The Apache Software Foundation")] +[assembly: AssemblyProduct("Thrift")] +[assembly: AssemblyCopyright("The Apache Software Foundation")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. + +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM + +[assembly: Guid("B0C13DA0-3117-4844-8AE8-B1775E46223D")] + diff --git a/vendor/git.apache.org/thrift.git/test/netcore/Server/Server.csproj b/vendor/git.apache.org/thrift.git/test/netcore/Server/Server.csproj new file mode 100644 index 0000000..2f9b4b1 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/netcore/Server/Server.csproj @@ -0,0 +1,31 @@ + + + netcoreapp2.0 + Server + Server + Exe + false + false + false + false + false + false + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/test/netcore/Server/TestServer.cs b/vendor/git.apache.org/thrift.git/test/netcore/Server/TestServer.cs new file mode 100644 index 0000000..bfd3335 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/netcore/Server/TestServer.cs @@ -0,0 +1,594 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Thrift; +using Thrift.Collections; +using Thrift.Protocols; +using Thrift.Server; +using Thrift.Transports; +using Thrift.Transports.Server; + +namespace ThriftTest +{ + internal class ServerParam + { + internal bool useBufferedSockets = false; + internal bool useFramed = false; + internal bool useEncryption = false; + internal bool compact = false; + internal bool json = false; + internal int port = 9090; + internal string pipe = null; + + internal void Parse(List args) + { + for (var i = 0; i < args.Count; i++) + { + if (args[i].StartsWith("--pipe=")) + { + pipe = args[i].Substring(args[i].IndexOf("=") + 1); + } + else if (args[i].StartsWith("--port=")) + { + port = int.Parse(args[i].Substring(args[i].IndexOf("=") + 1)); + } + else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered") + { + useBufferedSockets = true; + } + else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed") + { + useFramed = true; + } + else if (args[i] == "--binary" || args[i] == "--protocol=binary") + { + // nothing needed + } + else if (args[i] == "--compact" || args[i] == "--protocol=compact") + { + compact = true; + } + else if (args[i] == "--json" || args[i] == "--protocol=json") + { + json = true; + } + else if (args[i] == "--threaded" || args[i] == "--server-type=threaded") + { + throw new NotImplementedException(args[i]); + } + else if (args[i] == "--threadpool" || args[i] == "--server-type=threadpool") + { + throw new NotImplementedException(args[i]); + } + else if (args[i] == "--prototype" || args[i] == "--processor=prototype") + { + throw new NotImplementedException(args[i]); + } + else if (args[i] == "--ssl") + { + useEncryption = true; + } + else + { + //throw new ArgumentException(args[i]); + } + } + + } + } + + public class TestServer + { + public static int _clientID = -1; + public delegate void TestLogDelegate(string msg, params object[] values); + + public class MyServerEventHandler : TServerEventHandler + { + public int callCount = 0; + + public Task PreServeAsync(CancellationToken cancellationToken) + { + callCount++; + return Task.CompletedTask; + } + + public Task CreateContextAsync(TProtocol input, TProtocol output, CancellationToken cancellationToken) + { + callCount++; + return Task.FromResult(null); + } + + public Task DeleteContextAsync(object serverContext, TProtocol input, TProtocol output, CancellationToken cancellationToken) + { + callCount++; + return Task.CompletedTask; + } + + public Task ProcessContextAsync(object serverContext, TClientTransport transport, CancellationToken cancellationToken) + { + callCount++; + return Task.CompletedTask; + } + } + + public class TestHandlerAsync : ThriftTest.IAsync + { + public TBaseServer server { get; set; } + private int handlerID; + private StringBuilder sb = new StringBuilder(); + private TestLogDelegate logger; + + public TestHandlerAsync() + { + handlerID = Interlocked.Increment(ref _clientID); + logger += testConsoleLogger; + logger.Invoke("New TestHandler instance created"); + } + + public void testConsoleLogger(string msg, params object[] values) + { + sb.Clear(); + sb.AppendFormat("handler{0:D3}:", handlerID); + sb.AppendFormat(msg, values); + sb.AppendLine(); + Console.Write(sb.ToString()); + } + + public Task testVoidAsync(CancellationToken cancellationToken) + { + logger.Invoke("testVoid()"); + return Task.CompletedTask; + } + + public Task testStringAsync(string thing, CancellationToken cancellationToken) + { + logger.Invoke("testString({0})", thing); + return Task.FromResult(thing); + } + + public Task testBoolAsync(bool thing, CancellationToken cancellationToken) + { + logger.Invoke("testBool({0})", thing); + return Task.FromResult(thing); + } + + public Task testByteAsync(sbyte thing, CancellationToken cancellationToken) + { + logger.Invoke("testByte({0})", thing); + return Task.FromResult(thing); + } + + public Task testI32Async(int thing, CancellationToken cancellationToken) + { + logger.Invoke("testI32({0})", thing); + return Task.FromResult(thing); + } + + public Task testI64Async(long thing, CancellationToken cancellationToken) + { + logger.Invoke("testI64({0})", thing); + return Task.FromResult(thing); + } + + public Task testDoubleAsync(double thing, CancellationToken cancellationToken) + { + logger.Invoke("testDouble({0})", thing); + return Task.FromResult(thing); + } + + public Task testBinaryAsync(byte[] thing, CancellationToken cancellationToken) + { + var hex = BitConverter.ToString(thing).Replace("-", string.Empty); + logger.Invoke("testBinary({0:X})", hex); + return Task.FromResult(thing); + } + + public Task testStructAsync(Xtruct thing, CancellationToken cancellationToken) + { + logger.Invoke("testStruct({{\"{0}\", {1}, {2}, {3}}})", thing.String_thing, thing.Byte_thing, thing.I32_thing, thing.I64_thing); + return Task.FromResult(thing); + } + + public Task testNestAsync(Xtruct2 nest, CancellationToken cancellationToken) + { + var thing = nest.Struct_thing; + logger.Invoke("testNest({{{0}, {{\"{1}\", {2}, {3}, {4}, {5}}}}})", + nest.Byte_thing, + thing.String_thing, + thing.Byte_thing, + thing.I32_thing, + thing.I64_thing, + nest.I32_thing); + return Task.FromResult(nest); + } + + public Task> testMapAsync(Dictionary thing, CancellationToken cancellationToken) + { + sb.Clear(); + sb.Append("testMap({{"); + var first = true; + foreach (var key in thing.Keys) + { + if (first) + { + first = false; + } + else + { + sb.Append(", "); + } + sb.AppendFormat("{0} => {1}", key, thing[key]); + } + sb.Append("}})"); + logger.Invoke(sb.ToString()); + return Task.FromResult(thing); + } + + public Task> testStringMapAsync(Dictionary thing, CancellationToken cancellationToken) + { + sb.Clear(); + sb.Append("testStringMap({{"); + var first = true; + foreach (var key in thing.Keys) + { + if (first) + { + first = false; + } + else + { + sb.Append(", "); + } + sb.AppendFormat("{0} => {1}", key, thing[key]); + } + sb.Append("}})"); + logger.Invoke(sb.ToString()); + return Task.FromResult(thing); + } + + public Task> testSetAsync(THashSet thing, CancellationToken cancellationToken) + { + sb.Clear(); + sb.Append("testSet({{"); + var first = true; + foreach (int elem in thing) + { + if (first) + { + first = false; + } + else + { + sb.Append(", "); + } + sb.AppendFormat("{0}", elem); + } + sb.Append("}})"); + logger.Invoke(sb.ToString()); + return Task.FromResult(thing); + } + + public Task> testListAsync(List thing, CancellationToken cancellationToken) + { + sb.Clear(); + sb.Append("testList({{"); + var first = true; + foreach (var elem in thing) + { + if (first) + { + first = false; + } + else + { + sb.Append(", "); + } + sb.AppendFormat("{0}", elem); + } + sb.Append("}})"); + logger.Invoke(sb.ToString()); + return Task.FromResult(thing); + } + + public Task testEnumAsync(Numberz thing, CancellationToken cancellationToken) + { + logger.Invoke("testEnum({0})", thing); + return Task.FromResult(thing); + } + + public Task testTypedefAsync(long thing, CancellationToken cancellationToken) + { + logger.Invoke("testTypedef({0})", thing); + return Task.FromResult(thing); + } + + public Task>> testMapMapAsync(int hello, CancellationToken cancellationToken) + { + logger.Invoke("testMapMap({0})", hello); + var mapmap = new Dictionary>(); + + var pos = new Dictionary(); + var neg = new Dictionary(); + for (var i = 1; i < 5; i++) + { + pos[i] = i; + neg[-i] = -i; + } + + mapmap[4] = pos; + mapmap[-4] = neg; + + return Task.FromResult(mapmap); + } + + public Task>> testInsanityAsync(Insanity argument, CancellationToken cancellationToken) + { + logger.Invoke("testInsanity()"); + + /** from ThriftTest.thrift: + * So you think you've got this all worked, out eh? + * + * Creates a the returned map with these values and prints it out: + * { 1 => { 2 => argument, + * 3 => argument, + * }, + * 2 => { 6 => , }, + * } + * @return map> - a map with the above values + */ + + var first_map = new Dictionary(); + var second_map = new Dictionary(); ; + + first_map[Numberz.TWO] = argument; + first_map[Numberz.THREE] = argument; + + second_map[Numberz.SIX] = new Insanity(); + + var insane = new Dictionary> + { + [1] = first_map, + [2] = second_map + }; + + return Task.FromResult(insane); + } + + public Task testMultiAsync(sbyte arg0, int arg1, long arg2, Dictionary arg3, Numberz arg4, long arg5, + CancellationToken cancellationToken) + { + logger.Invoke("testMulti()"); + + var hello = new Xtruct(); ; + hello.String_thing = "Hello2"; + hello.Byte_thing = arg0; + hello.I32_thing = arg1; + hello.I64_thing = arg2; + return Task.FromResult(hello); + } + + public Task testExceptionAsync(string arg, CancellationToken cancellationToken) + { + logger.Invoke("testException({0})", arg); + if (arg == "Xception") + { + var x = new Xception + { + ErrorCode = 1001, + Message = arg + }; + throw x; + } + if (arg == "TException") + { + throw new TException(); + } + return Task.CompletedTask; + } + + public Task testMultiExceptionAsync(string arg0, string arg1, CancellationToken cancellationToken) + { + logger.Invoke("testMultiException({0}, {1})", arg0, arg1); + if (arg0 == "Xception") + { + var x = new Xception + { + ErrorCode = 1001, + Message = "This is an Xception" + }; + throw x; + } + + if (arg0 == "Xception2") + { + var x = new Xception2 + { + ErrorCode = 2002, + Struct_thing = new Xtruct { String_thing = "This is an Xception2" } + }; + throw x; + } + + var result = new Xtruct { String_thing = arg1 }; + return Task.FromResult(result); + } + + public Task testOnewayAsync(int secondsToSleep, CancellationToken cancellationToken) + { + logger.Invoke("testOneway({0}), sleeping...", secondsToSleep); + Task.Delay(secondsToSleep * 1000, cancellationToken).GetAwaiter().GetResult(); + logger.Invoke("testOneway finished"); + + return Task.CompletedTask; + } + } + + internal static void PrintOptionsHelp() + { + Console.WriteLine("Server options:"); + Console.WriteLine(" --pipe="); + Console.WriteLine(" --port="); + Console.WriteLine(" --transport= one of buffered,framed (defaults to none)"); + Console.WriteLine(" --protocol= one of compact,json (defaults to binary)"); + Console.WriteLine(" --server-type= one of threaded,threadpool (defaults to simple)"); + Console.WriteLine(" --processor="); + Console.WriteLine(" --ssl"); + Console.WriteLine(); + } + + private static X509Certificate2 GetServerCert() + { + var serverCertName = "server.p12"; + var possiblePaths = new List + { + "../../../keys/", + "../../keys/", + "../keys/", + "keys/", + }; + + string existingPath = null; + foreach (var possiblePath in possiblePaths) + { + var path = Path.GetFullPath(possiblePath + serverCertName); + if (File.Exists(path)) + { + existingPath = path; + break; + } + } + + if (string.IsNullOrEmpty(existingPath)) + { + throw new FileNotFoundException($"Cannot find file: {serverCertName}"); + } + + var cert = new X509Certificate2(existingPath, "thrift"); + + return cert; + } + + public static int Execute(List args) + { + var loggerFactory = new LoggerFactory();//.AddConsole().AddDebug(); + var logger = new LoggerFactory().CreateLogger("Test"); + + try + { + var param = new ServerParam(); + + try + { + param.Parse(args); + } + catch (Exception ex) + { + Console.WriteLine("*** FAILED ***"); + Console.WriteLine("Error while parsing arguments"); + Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); + return 1; + } + + + // Transport + TServerTransport trans; + if (param.pipe != null) + { + trans = new TNamedPipeServerTransport(param.pipe); + } +// else if (param.useFramed) +// { +// trans = new TServerFramedTransport(param.port); +// } + else + { + if (param.useEncryption) + { + var cert = GetServerCert(); + + if (cert == null || !cert.HasPrivateKey) + { + throw new InvalidOperationException("Certificate doesn't contain private key"); + } + + trans = new TTlsServerSocketTransport(param.port, param.useBufferedSockets, param.useFramed, cert, + (sender, certificate, chain, errors) => true, + null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12); + } + else + { + trans = new TServerSocketTransport(param.port, 0, param.useBufferedSockets, param.useFramed); + } + } + + ITProtocolFactory proto; + if (param.compact) + proto = new TCompactProtocol.Factory(); + else if (param.json) + proto = new TJsonProtocol.Factory(); + else + proto = new TBinaryProtocol.Factory(); + + ITProcessorFactory processorFactory; + + // Processor + var testHandler = new TestHandlerAsync(); + var testProcessor = new ThriftTest.AsyncProcessor(testHandler); + processorFactory = new SingletonTProcessorFactory(testProcessor); + + TTransportFactory transFactory = new TTransportFactory(); + + TBaseServer serverEngine = new AsyncBaseServer(processorFactory, trans, transFactory, transFactory, proto, proto, logger); + + //Server event handler + var serverEvents = new MyServerEventHandler(); + serverEngine.SetEventHandler(serverEvents); + + // Run it + var where = (! string.IsNullOrEmpty(param.pipe)) ? "on pipe " + param.pipe : "on port " + param.port; + Console.WriteLine("Starting the AsyncBaseServer " + where + + " with processor TPrototypeProcessorFactory prototype factory " + + (param.useBufferedSockets ? " with buffered socket" : "") + + (param.useFramed ? " with framed transport" : "") + + (param.useEncryption ? " with encryption" : "") + + (param.compact ? " with compact protocol" : "") + + (param.json ? " with json protocol" : "") + + "..."); + serverEngine.ServeAsync(CancellationToken.None).GetAwaiter().GetResult(); + Console.ReadLine(); + } + catch (Exception x) + { + Console.Error.Write(x); + return 1; + } + Console.WriteLine("done."); + return 0; + } + } + +} diff --git a/vendor/git.apache.org/thrift.git/test/netcore/ThriftTest.sln b/vendor/git.apache.org/thrift.git/test/netcore/ThriftTest.sln new file mode 100644 index 0000000..2ab241a --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/netcore/ThriftTest.sln @@ -0,0 +1,64 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26730.12 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Thrift", "..\..\lib\netcore\Thrift\Thrift.csproj", "{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Client", "Client\Client.csproj", "{21039F25-6ED7-4E80-A545-EBC93472EBD1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Server", "Server\Server.csproj", "{0C6E8685-F191-4479-9842-882A38961127}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|x64.ActiveCfg = Debug|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|x64.Build.0 = Debug|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|x86.ActiveCfg = Debug|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|x86.Build.0 = Debug|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|Any CPU.Build.0 = Release|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x64.ActiveCfg = Release|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x64.Build.0 = Release|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x86.ActiveCfg = Release|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x86.Build.0 = Release|Any CPU + {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Debug|x64.ActiveCfg = Debug|Any CPU + {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Debug|x64.Build.0 = Debug|Any CPU + {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Debug|x86.ActiveCfg = Debug|Any CPU + {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Debug|x86.Build.0 = Debug|Any CPU + {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Release|Any CPU.Build.0 = Release|Any CPU + {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Release|x64.ActiveCfg = Release|Any CPU + {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Release|x64.Build.0 = Release|Any CPU + {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Release|x86.ActiveCfg = Release|Any CPU + {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Release|x86.Build.0 = Release|Any CPU + {0C6E8685-F191-4479-9842-882A38961127}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0C6E8685-F191-4479-9842-882A38961127}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0C6E8685-F191-4479-9842-882A38961127}.Debug|x64.ActiveCfg = Debug|Any CPU + {0C6E8685-F191-4479-9842-882A38961127}.Debug|x64.Build.0 = Debug|Any CPU + {0C6E8685-F191-4479-9842-882A38961127}.Debug|x86.ActiveCfg = Debug|Any CPU + {0C6E8685-F191-4479-9842-882A38961127}.Debug|x86.Build.0 = Debug|Any CPU + {0C6E8685-F191-4479-9842-882A38961127}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0C6E8685-F191-4479-9842-882A38961127}.Release|Any CPU.Build.0 = Release|Any CPU + {0C6E8685-F191-4479-9842-882A38961127}.Release|x64.ActiveCfg = Release|Any CPU + {0C6E8685-F191-4479-9842-882A38961127}.Release|x64.Build.0 = Release|Any CPU + {0C6E8685-F191-4479-9842-882A38961127}.Release|x86.ActiveCfg = Release|Any CPU + {0C6E8685-F191-4479-9842-882A38961127}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {52CE9A12-F6CB-4F0C-BB42-0105612F5FF4} + EndGlobalSection +EndGlobal diff --git a/vendor/git.apache.org/thrift.git/test/netcore/build.cmd b/vendor/git.apache.org/thrift.git/test/netcore/build.cmd new file mode 100644 index 0000000..9b84ef2 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/netcore/build.cmd @@ -0,0 +1,25 @@ +@echo off +rem /* +rem * Licensed to the Apache Software Foundation (ASF) under one +rem * or more contributor license agreements. See the NOTICE file +rem * distributed with this work for additional information +rem * regarding copyright ownership. The ASF licenses this file +rem * to you under the Apache License, Version 2.0 (the +rem * "License"); you may not use this file except in compliance +rem * with the License. You may obtain a copy of the License at +rem * +rem * http://www.apache.org/licenses/LICENSE-2.0 +rem * +rem * Unless required by applicable law or agreed to in writing, +rem * software distributed under the License is distributed on an +rem * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +rem * KIND, either express or implied. See the License for the +rem * specific language governing permissions and limitations +rem * under the License. +rem */ +setlocal + +dotnet --info +dotnet build + +:eof diff --git a/vendor/git.apache.org/thrift.git/test/netcore/build.sh b/vendor/git.apache.org/thrift.git/test/netcore/build.sh new file mode 100755 index 0000000..c97e310 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/netcore/build.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash + +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +#exit if any command fails +set -e + +dotnet --info +dotnet build diff --git a/vendor/git.apache.org/thrift.git/test/perl/Makefile.am b/vendor/git.apache.org/thrift.git/test/perl/Makefile.am index d975f69..165b9a7 100644 --- a/vendor/git.apache.org/thrift.git/test/perl/Makefile.am +++ b/vendor/git.apache.org/thrift.git/test/perl/Makefile.am @@ -17,8 +17,6 @@ # under the License. # -THRIFT = $(top_builddir)/compiler/cpp/thrift - stubs: ../ThriftTest.thrift $(THRIFT) --gen perl ../ThriftTest.thrift diff --git a/vendor/git.apache.org/thrift.git/test/perl/TestClient.pl b/vendor/git.apache.org/thrift.git/test/perl/TestClient.pl index 7ec32bf..96e3bec 100755 --- a/vendor/git.apache.org/thrift.git/test/perl/TestClient.pl +++ b/vendor/git.apache.org/thrift.git/test/perl/TestClient.pl @@ -19,7 +19,7 @@ # under the License. # -require 5.6.0; +use 5.10.0; use strict; use warnings; use Data::Dumper; @@ -33,29 +33,35 @@ use Thrift; use Thrift::BinaryProtocol; use Thrift::BufferedTransport; use Thrift::FramedTransport; +use Thrift::MultiplexedProtocol; use Thrift::SSLSocket; use Thrift::Socket; use Thrift::UnixSocket; +use ThriftTest::SecondService; use ThriftTest::ThriftTest; use ThriftTest::Types; $|++; sub usage { - print < Use a unix domain socket. --help Show usage. + --key Certificate key. + Required if using --ssl. --port 9090 Port to use. --protocol {binary} binary Protocol to use. --ssl If present, use SSL. --transport {buffered|framed} buffered Transport to use. - + EOF } @@ -66,7 +72,10 @@ my %opts = ( ); GetOptions(\%opts, qw ( + ca=s cert=s + ciphers=s + key=s domain-socket=s help host=s @@ -81,100 +90,132 @@ if ($opts{help}) { exit 0; } -if ($opts{ssl} and not defined $opts{cert}) { - usage(); - exit 1; -} - my $socket = undef; -if ($opts{"domain-socket"}) { - $socket = new Thrift::UnixSocket($opts{"domain-socket"}); -} elsif ($opts{ssl}) { - $socket = new Thrift::SSLSocket($opts{host}, $opts{port}); -} else { - $socket = new Thrift::Socket($opts{host}, $opts{port}); +if ($opts{'domain-socket'}) { + $socket = Thrift::UnixSocket->new($opts{'domain-socket'}); +} +elsif ($opts{ssl}) { + $socket = Thrift::SSLSocket->new(\%opts); +} +else { + $socket = Thrift::Socket->new($opts{host}, $opts{port}); } my $transport; if ($opts{transport} eq 'buffered') { - $transport = new Thrift::BufferedTransport($socket, 1024, 1024); -} elsif ($opts{transport} eq 'framed') { - $transport = new Thrift::FramedTransport($socket); -} else { + $transport = Thrift::BufferedTransport->new($socket, 1024, 1024); +} +elsif ($opts{transport} eq 'framed') { + $transport = Thrift::FramedTransport->new($socket); +} +else { usage(); exit 1; } my $protocol; -if ($opts{protocol} eq 'binary') { - $protocol = new Thrift::BinaryProtocol($transport); -} else { +my $protocol2; +if ($opts{protocol} eq 'binary' || $opts{protocol} eq 'multi') { + $protocol = Thrift::BinaryProtocol->new($transport); +} +else { usage(); exit 1; } -my $testClient = new ThriftTest::ThriftTestClient($protocol); +my $secondService = undef; +if (index($opts{protocol}, 'multi') == 0) { + $protocol2 = Thrift::MultiplexedProtocol->new($protocol, 'SecondService'); + $protocol = Thrift::MultiplexedProtocol->new($protocol, 'ThriftTest'); + $secondService = ThriftTest::SecondServiceClient->new($protocol2); +} + +my $testClient = ThriftTest::ThriftTestClient->new($protocol); eval { $transport->open(); -}; +}; if($@){ die(Dumper($@)); } + +use constant ERR_BASETYPES => 1; +use constant ERR_STRUCTS => 2; +use constant ERR_CONTAINERS => 4; +use constant ERR_EXCEPTIONS => 8; +use constant ERR_PROTOCOL => 16; +use constant ERR_UNKNOWN => 64; + my $start = gettimeofday(); # # VOID TEST # -print("testVoid()"); +print('testVoid()'); $testClient->testVoid(); print(" = void\n"); # # STRING TEST # -print("testString(\"Test\")"); -my $s = $testClient->testString("Test"); -print(" = \"$s\"\n"); +print('testString("Test")'); +my $s = $testClient->testString('Test'); +print(qq| = "$s"\n|); +exit(ERR_BASETYPES) if ($s ne 'Test'); + +# +# MULTIPLEXED TEST +# +if (index($opts{protocol}, 'multi') == 0) { + print('secondtestString("Test2")'); + $s = $secondService->secondtestString('Test2'); + print(qq| = "$s"\n|); + exit(ERR_PROTOCOL) if ($s ne 'testString("Test2")'); +} # # BOOL TEST # -print("testBool(1)"); +print('testBool(1)'); my $t = $testClient->testBool(1); print(" = $t\n"); -print("testBool(0)"); +exit(ERR_BASETYPES) if ($t ne 1); +print('testBool(0)'); my $f = $testClient->testBool(0); print(" = $f\n"); +exit(ERR_BASETYPES) if ($f ne q||); # # BYTE TEST # -print("testByte(1)"); +print('testByte(1)'); my $u8 = $testClient->testByte(1); print(" = $u8\n"); # # I32 TEST # -print("testI32(-1)"); +print('testI32(-1)'); my $i32 = $testClient->testI32(-1); print(" = $i32\n"); +exit(ERR_BASETYPES) if ($i32 ne -1); # -#I64 TEST +# I64 TEST # -print("testI64(-34359738368)"); +print('testI64(-34359738368)'); my $i64 = $testClient->testI64(-34359738368); print(" = $i64\n"); +exit(ERR_BASETYPES) if ($i64 ne -34359738368); # # DOUBLE TEST # -print("testDouble(-852.234234234)"); +print('testDouble(-852.234234234)'); my $dub = $testClient->testDouble(-852.234234234); print(" = $dub\n"); +exit(ERR_BASETYPES) if ($dub ne -852.234234234); # # BINARY TEST --- TODO @@ -184,33 +225,33 @@ print(" = $dub\n"); # # STRUCT TEST # -print("testStruct({\"Zero\", 1, -3, -5})"); -my $out = new ThriftTest::Xtruct(); -$out->string_thing("Zero"); +print('testStruct({"Zero", 1, -3, -5})'); +my $out = ThriftTest::Xtruct->new(); +$out->string_thing('Zero'); $out->byte_thing(1); $out->i32_thing(-3); $out->i64_thing(-5); my $in = $testClient->testStruct($out); -print(" = {\"".$in->string_thing."\", ". - $in->byte_thing.", ". - $in->i32_thing.", ". +print(' = {"'.$in->string_thing.'", '. + $in->byte_thing.', '. + $in->i32_thing.', '. $in->i64_thing."}\n"); # # NESTED STRUCT TEST # -print("testNest({1, {\"Zero\", 1, -3, -5}, 5}"); -my $out2 = new ThriftTest::Xtruct2(); +print('testNest({1, {"Zero", 1, -3, -5}, 5}'); +my $out2 = ThriftTest::Xtruct2->new(); $out2->byte_thing(1); $out2->struct_thing($out); $out2->i32_thing(5); my $in2 = $testClient->testNest($out2); $in = $in2->struct_thing; -print(" = {".$in2->byte_thing.", {\"". - $in->string_thing."\", ". - $in->byte_thing.", ". - $in->i32_thing.", ". - $in->i64_thing."}, ". +print(' = {'.$in2->byte_thing.', {"'. + $in->string_thing.'", '. + $in->byte_thing.', '. + $in->i32_thing.', '. + $in->i64_thing.'}, '. $in2->i32_thing."}\n"); # @@ -220,28 +261,30 @@ my $mapout = {}; for (my $i = 0; $i < 5; ++$i) { $mapout->{$i} = $i-10; } -print("testMap({"); +print('testMap({'); my $first = 1; while( my($key,$val) = each %$mapout) { if ($first) { $first = 0; - } else { - print(", "); + } + else { + print(', '); } print("$key => $val"); } -print("})"); +print('})'); my $mapin = $testClient->testMap($mapout); -print(" = {"); +print(' = {'); $first = 1; while( my($key,$val) = each %$mapin){ if ($first) { $first = 0; - } else { - print(", "); + } + else { + print(', '); } print("$key => $val"); } @@ -255,11 +298,11 @@ for (my $i = -2; $i < 3; ++$i) { push(@$setout, $i); } -print("testSet({".join(",",@$setout)."})"); +print('testSet({'.join(',',@$setout).'})'); my $setin = $testClient->testSet($setout); -print(" = {".join(",",@$setout)."}\n"); +print(' = {'.join(',',@$setout)."}\n"); # # LIST TEST @@ -269,111 +312,111 @@ for (my $i = -2; $i < 3; ++$i) { push(@$listout, $i); } -print("testList({".join(",",@$listout)."})"); +print('testList({'.join(',',@$listout).'})'); my $listin = $testClient->testList($listout); -print(" = {".join(",",@$listin)."}\n"); +print(' = {'.join(',',@$listin)."}\n"); # # ENUM TEST # -print("testEnum(ONE)"); +print('testEnum(ONE)'); my $ret = $testClient->testEnum(ThriftTest::Numberz::ONE); print(" = $ret\n"); -print("testEnum(TWO)"); +print('testEnum(TWO)'); $ret = $testClient->testEnum(ThriftTest::Numberz::TWO); print(" = $ret\n"); -print("testEnum(THREE)"); +print('testEnum(THREE)'); $ret = $testClient->testEnum(ThriftTest::Numberz::THREE); print(" = $ret\n"); -print("testEnum(FIVE)"); +print('testEnum(FIVE)'); $ret = $testClient->testEnum(ThriftTest::Numberz::FIVE); print(" = $ret\n"); -print("testEnum(EIGHT)"); +print('testEnum(EIGHT)'); $ret = $testClient->testEnum(ThriftTest::Numberz::EIGHT); print(" = $ret\n"); # # TYPEDEF TEST # -print("testTypedef(309858235082523)"); +print('testTypedef(309858235082523)'); my $uid = $testClient->testTypedef(309858235082523); print(" = $uid\n"); # # NESTED MAP TEST # -print("testMapMap(1)"); +print('testMapMap(1)'); my $mm = $testClient->testMapMap(1); -print(" = {"); +print(' = {'); while( my ($key,$val) = each %$mm) { print("$key => {"); while( my($k2,$v2) = each %$val) { print("$k2 => $v2, "); } - print("}, "); + print('}, '); } print("}\n"); # # INSANITY TEST # -my $insane = new ThriftTest::Insanity(); +my $insane = ThriftTest::Insanity->new(); $insane->{userMap}->{ThriftTest::Numberz::FIVE} = 5000; -my $truck = new ThriftTest::Xtruct(); -$truck->string_thing("Hello2"); +my $truck = ThriftTest::Xtruct->new(); +$truck->string_thing('Hello2'); $truck->byte_thing(2); $truck->i32_thing(2); $truck->i64_thing(2); -my $truck2 = new ThriftTest::Xtruct(); -$truck2->string_thing("Goodbye4"); +my $truck2 = ThriftTest::Xtruct->new(); +$truck2->string_thing('Goodbye4'); $truck2->byte_thing(4); $truck2->i32_thing(4); $truck2->i64_thing(4); push(@{$insane->{xtructs}}, $truck); push(@{$insane->{xtructs}}, $truck2); -print("testInsanity()"); +print('testInsanity()'); my $whoa = $testClient->testInsanity($insane); -print(" = {"); +print(' = {'); while( my ($key,$val) = each %$whoa) { print("$key => {"); while( my($k2,$v2) = each %$val) { print("$k2 => {"); my $userMap = $v2->{userMap}; - print("{"); - if (ref($userMap) eq "HASH") { + print('{'); + if (ref($userMap) eq 'HASH') { while( my($k3,$v3) = each %$userMap) { print("$k3 => $v3, "); } } - print("}, "); + print('}, '); my $xtructs = $v2->{xtructs}; - print("{"); - if (ref($xtructs) eq "ARRAY") { + print('{'); + if (ref($xtructs) eq 'ARRAY') { foreach my $x (@$xtructs) { - print("{\"".$x->{string_thing}."\", ". - $x->{byte_thing}.", ".$x->{i32_thing}.", ".$x->{i64_thing}."}, "); + print('{"'.$x->{string_thing}.'", '. + $x->{byte_thing}.', '.$x->{i32_thing}.', '.$x->{i64_thing}.'}, '); } } - print("}"); + print('}'); - print("}, "); + print('}, '); } - print("}, "); + print('}, '); } print("}\n"); # # EXCEPTION TEST # -print("testException('Xception')"); +print(q|testException('Xception')|); eval { $testClient->testException('Xception'); print(" void\nFAILURE\n"); @@ -386,7 +429,7 @@ eval { # Normal tests done. # my $stop = gettimeofday(); -my $elp = sprintf("%d",1000*($stop - $start), 0); +my $elp = sprintf('%d',1000*($stop - $start), 0); print("Total time: $elp ms\n"); # diff --git a/vendor/git.apache.org/thrift.git/test/perl/TestServer.pl b/vendor/git.apache.org/thrift.git/test/perl/TestServer.pl index 4e0cc79..d2b9a38 100644 --- a/vendor/git.apache.org/thrift.git/test/perl/TestServer.pl +++ b/vendor/git.apache.org/thrift.git/test/perl/TestServer.pl @@ -19,13 +19,15 @@ # under the License. # -require 5.6.0; +use 5.10.0; use strict; use warnings; use Data::Dumper; use Getopt::Long qw(GetOptions); use Time::HiRes qw(gettimeofday); +$SIG{INT} = \&sigint_handler; + use lib '../../lib/perl/lib'; use lib 'gen-perl'; @@ -33,24 +35,27 @@ use Thrift; use Thrift::BinaryProtocol; use Thrift::BufferedTransport; use Thrift::FramedTransport; +use Thrift::MultiplexedProcessor; use Thrift::SSLServerSocket; use Thrift::ServerSocket; use Thrift::Server; use Thrift::UnixServerSocket; +use ThriftTest::SecondService; use ThriftTest::ThriftTest; use ThriftTest::Types; $|++; sub usage { - print < Use a unix domain socket. --help Show usage. --key Private key file for certificate. @@ -60,7 +65,7 @@ Options: (default) --protocol {binary} binary Protocol to use. --ssl If present, use SSL/TLS. --transport {buffered|framed} buffered Transport to use. - + EOF } @@ -73,6 +78,7 @@ my %opts = ( GetOptions(\%opts, qw ( ca=s cert=s + ciphers=s domain-socket=s help host=s @@ -93,47 +99,69 @@ if ($opts{ssl} and not defined $opts{cert}) { exit 1; } -my $handler = new ThriftTestHandler(); -my $processor = new ThriftTest::ThriftTestProcessor($handler); +my $handler = ThriftTestHandler->new(); +my $handler2 = SecondServiceHandler->new(); +my $processor = ThriftTest::ThriftTestProcessor->new($handler); +my $processor2 = ThriftTest::SecondServiceProcessor->new($handler2); + my $serversocket; -if ($opts{"domain-socket"}) { - unlink($opts{"domain-socket"}); - $serversocket = new Thrift::UnixServerSocket($opts{"domain-socket"}); -} elsif ($opts{ssl}) { - $serversocket = new Thrift::SSLServerSocket(\%opts); -} else { - $serversocket = new Thrift::ServerSocket(\%opts); +if ($opts{'domain-socket'}) { + unlink($opts{'domain-socket'}); + $serversocket = Thrift::UnixServerSocket->new($opts{'domain-socket'}); +} +elsif ($opts{ssl}) { + $serversocket = Thrift::SSLServerSocket->new(\%opts); +} +else { + $serversocket = Thrift::ServerSocket->new(\%opts); } my $transport; if ($opts{transport} eq 'buffered') { - $transport = new Thrift::BufferedTransportFactory(); -} elsif ($opts{transport} eq 'framed') { - $transport = new Thrift::FramedTransportFactory(); -} else { + $transport = Thrift::BufferedTransportFactory->new(); +} +elsif ($opts{transport} eq 'framed') { + $transport = Thrift::FramedTransportFactory->new(); +} +else { usage(); exit 1; } my $protocol; -if ($opts{protocol} eq 'binary') { - $protocol = new Thrift::BinaryProtocolFactory(); -} else { +if ($opts{protocol} eq 'binary' || $opts{protocol} eq 'multi') { + $protocol = Thrift::BinaryProtocolFactory->new(); +} +else { usage(); exit 1; } +if (index($opts{protocol}, 'multi') == 0) { + my $newProcessor = Thrift::MultiplexedProcessor->new($protocol); + $newProcessor->defaultProcessor($processor); + $newProcessor->registerProcessor('ThriftTest', $processor); + $newProcessor->registerProcessor('SecondService', $processor2); + $processor = $newProcessor; +} + my $ssltag = ''; if ($opts{ssl}) { - $ssltag = "(SSL)"; + $ssltag = '(SSL)'; } my $listening_on = "$opts{port} $ssltag"; -if ($opts{"domain-socket"}) { - $listening_on = $opts{"domain-socket"}; +if ($opts{'domain-socket'}) { + $listening_on = $opts{'domain-socket'}; } -my $server = new Thrift::SimpleServer($processor, $serversocket, $transport, $protocol); -print "Starting \"simple\" server ($opts{transport}/$opts{protocol}) listen on: $listening_on\n"; +my $server = Thrift::SimpleServer->new($processor, $serversocket, $transport, $protocol); +print qq|Starting "simple" server ($opts{transport}/$opts{protocol}) listen on: $listening_on\n|; $server->serve(); +print "done.\n"; -### +sub sigint_handler { + print "received SIGINT, stopping...\n"; + $server->stop(); +} + +### ### Test server implementation ### @@ -147,70 +175,67 @@ sub new { return bless($self, $classname); } -sub testVoid() { - print("testVoid()\n"); +sub testVoid { + print("testVoid()\n"); } -sub testString() { +sub testString { my $self = shift; my $thing = shift; print("testString($thing)\n"); return $thing; } -sub testBool() { +sub testBool { my $self = shift; my $thing = shift; - my $str = $thing ? "true" : "false"; + my $str = $thing ? 'true' : 'false'; print("testBool($str)\n"); return $thing; } -sub testByte() { +sub testByte { my $self = shift; my $thing = shift; print("testByte($thing)\n"); return $thing; } -sub testI32() { +sub testI32 { my $self = shift; my $thing = shift; print("testI32($thing)\n"); return $thing; } -sub testI64() { +sub testI64 { my $self = shift; my $thing = shift; print("testI64($thing)\n"); return $thing; } -sub testDouble() { +sub testDouble { my $self = shift; my $thing = shift; print("testDouble($thing)\n"); return $thing; } -sub testBinary() { +sub testBinary { my $self = shift; my $thing = shift; my @bytes = split //, $thing; - print("testBinary("); - foreach (@bytes) - { - printf "%02lx", ord $_; - } - print(")\n"); + print 'testBinary('; + printf( '%02lx', ord $_ ) foreach (@bytes); + print ")\n"; return $thing; } -sub testStruct() { +sub testStruct { my $self = shift; my $thing = shift; - printf("testStruct({\"%s\", %d, %d, %lld})\n", + printf(qq|testStruct({"%s", %d, %d, %lld})\n|, $thing->{string_thing}, $thing->{byte_thing}, $thing->{i32_thing}, @@ -218,11 +243,11 @@ sub testStruct() { return $thing; } -sub testNest() { +sub testNest { my $self = shift; my $nest = shift; my $thing = $nest->{struct_thing}; - printf("testNest({%d, {\"%s\", %d, %d, %lld}, %d})\n", + printf(qq|testNest({%d, {"%s", %d, %d, %lld}, %d})\n|, $nest->{byte_thing}, $thing->{string_thing}, $thing->{byte_thing}, @@ -232,119 +257,85 @@ sub testNest() { return $nest; } -sub testMap() { +sub testMap { my $self = shift; my $thing = shift; - print("testMap({"); - my $first = 1; - foreach my $key (keys %$thing) { - if ($first) { - $first = 0; - } else { - print(", "); - } - print("$key => $thing->{$key}"); - } - print("})\n"); + printf "testMap({%s})\n", + join( ', ', + map { $_ . ' => ' . $thing->{$_} } + sort keys %$thing + ); return $thing; } -sub testStringMap() { +sub testStringMap { my $self = shift; my $thing = shift; - print("testStringMap({"); - my $first = 1; - foreach my $key (keys %$thing) { - if ($first) { - $first = 0; - } else { - print(", "); - } - print("$key => $thing->{$key}"); - } - print("})\n"); + printf "testStringMap({%s})\n", + join( ', ', + map { $_ . ' => ' . $thing->{$_} } + sort keys %$thing + ); return $thing; } -sub testSet() { +sub testSet { my $self = shift; my $thing = shift; - my @arr; - my $result = \@arr; - print("testSet({"); - my $first = 1; - foreach my $key (keys %$thing) { - if ($first) { - $first = 0; - } else { - print(", "); - } - print("$key"); - push($result, $key); - } - print("})\n"); - return $result; + my @result = sort keys %$thing; + printf "testSet({%s})\n", join(', ', @result ); + return \@result; } -sub testList() { +sub testList { my $self = shift; my $thing = shift; - print("testList({"); - my $first = 1; - foreach my $key (@$thing) { - if ($first) { - $first = 0; - } else { - print(", "); - } - print("$key"); - } - print("})\n"); + print "testList({%s})\n", join(', ', @$thing); return $thing; } -sub testEnum() { +sub testEnum { my $self = shift; my $thing = shift; - print("testEnum($thing)\n"); + print "testEnum($thing)\n"; return $thing; } -sub testTypedef() { +sub testTypedef { my $self = shift; my $thing = shift; print("testTypedef($thing)\n"); return $thing; } -sub testMapMap() { +sub testMapMap { my $self = shift; my $hello = shift; - + printf("testMapMap(%d)\n", $hello); my $result = { 4 => { 1 => 1, 2 => 2, 3 => 3, 4 => 4 }, -4 => { -1 => -1, -2 => -2, -3 => -3, -4 => -4 } }; return $result; } -sub testInsanity() { +sub testInsanity { my $self = shift; my $argument = shift; print("testInsanity()\n"); - my $hello = new ThriftTest::Xtruct({string_thing => "Hello2", byte_thing => 2, i32_thing => 2, i64_thing => 2}); + my $hello = ThriftTest::Xtruct->new({string_thing => 'Hello2', byte_thing => 2, i32_thing => 2, i64_thing => 2}); my @hellos; push(@hellos, $hello); - my $goodbye = new ThriftTest::Xtruct({string_thing => "Goodbye4", byte_thing => 4, i32_thing => 4, i64_thing => 4}); + my $goodbye = ThriftTest::Xtruct->new({string_thing => 'Goodbye4', byte_thing => 4, i32_thing => 4, i64_thing => 4}); my @goodbyes; push(@goodbyes, $goodbye); - my $crazy = new ThriftTest::Insanity({userMap => { ThriftTest::Numberz::EIGHT => 8 }, xtructs => \@goodbyes}); - my $loony = new ThriftTest::Insanity(); + my $crazy = ThriftTest::Insanity->new({userMap => { ThriftTest::Numberz::EIGHT => 8 }, xtructs => \@goodbyes}); + my $loony = ThriftTest::Insanity->new(); my $result = { 1 => { ThriftTest::Numberz::TWO => $argument, ThriftTest::Numberz::THREE => $argument }, 2 => { ThriftTest::Numberz::SIX => $loony } }; return $result; } -sub testMulti() { +sub testMulti { my $self = shift; my $arg0 = shift; my $arg1 = shift; @@ -352,47 +343,69 @@ sub testMulti() { my $arg3 = shift; my $arg4 = shift; my $arg5 = shift; - + print("testMulti()\n"); - return new ThriftTest::Xtruct({string_thing => "Hello2", byte_thing => $arg0, i32_thing => $arg1, i64_thing => $arg2}); + return ThriftTest::Xtruct->new({string_thing => 'Hello2', byte_thing => $arg0, i32_thing => $arg1, i64_thing => $arg2}); } -sub testException() { +sub testException { my $self = shift; my $arg = shift; print("testException($arg)\n"); - if ($arg eq "Xception") { - die new ThriftTest::Xception({errorCode => 1001, message => $arg}); - } elsif ($arg eq "TException") { - die "astring"; # all unhandled exceptions become TExceptions - } else { - return new ThriftTest::Xtruct({string_thing => $arg}); + if ($arg eq 'Xception') { + die ThriftTest::Xception->new({errorCode => 1001, message => $arg}); + } + elsif ($arg eq 'TException') { + die 'astring'; # all unhandled exceptions become TExceptions + } + else { + return ThriftTest::Xtruct->new({string_thing => $arg}); } } -sub testMultiException() { +sub testMultiException { my $self = shift; my $arg0 = shift; my $arg1 = shift; printf("testMultiException(%s, %s)\n", $arg0, $arg1); - if ($arg0 eq "Xception") { - die new ThriftTest::Xception({errorCode => 1001, message => "This is an Xception"}); - } elsif ($arg0 eq "Xception2") { - my $struct_thing = new ThriftTest::Xtruct({string_thing => "This is an Xception2"}); - die new ThriftTest::Xception2({errorCode => 2002, struct_thing => $struct_thing}); - } else { - return new ThriftTest::Xtruct({string_thing => $arg1}); + if ($arg0 eq 'Xception') { + die ThriftTest::Xception->new({errorCode => 1001, message => 'This is an Xception'}); + } + elsif ($arg0 eq 'Xception2') { + my $struct_thing = ThriftTest::Xtruct->new({string_thing => 'This is an Xception2'}); + die ThriftTest::Xception2->new({errorCode => 2002, struct_thing => $struct_thing}); + } + else { + return ThriftTest::Xtruct->new({string_thing => $arg1}); } } -sub testOneway() { +sub testOneway { my $self = shift; - my $sleepFor = shift; - print("testOneway($sleepFor): Sleeping...\n"); - sleep $sleepFor; - print("testOneway($sleepFor): done sleeping!\n"); + my $num = shift; + print("testOneway($num): received\n"); } +### +### Test server implementation +### + +package SecondServiceHandler; + +use base qw( ThriftTest::SecondServiceIf ); + +sub new { + my $classname = shift; + my $self = {}; + return bless($self, $classname); +} + +sub secondtestString { + my $self = shift; + my $thing = shift; + print("testString($thing)\n"); + return qq|testString("$thing")|; +} 1; diff --git a/vendor/git.apache.org/thrift.git/test/php/Makefile.am b/vendor/git.apache.org/thrift.git/test/php/Makefile.am index 7c4347f..72f7fc5 100755 --- a/vendor/git.apache.org/thrift.git/test/php/Makefile.am +++ b/vendor/git.apache.org/thrift.git/test/php/Makefile.am @@ -17,20 +17,23 @@ # under the License. # -THRIFT = $(top_builddir)/compiler/cpp/thrift - stubs: ../ThriftTest.thrift $(THRIFT) --gen php ../ThriftTest.thrift $(THRIFT) --gen php:inlined ../ThriftTest.thrift - $(MKDIR_P) gen-php-psr4 - $(THRIFT) -out gen-php-psr4 --gen php:psr4 ../ThriftTest.thrift + $(MKDIR_P) gen-php-classmap + $(THRIFT) -out gen-php-classmap --gen php ../ThriftTest.thrift -precross: stubs +php_ext_dir: + mkdir -p php_ext_dir + ln -s ../../../lib/php/src/ext/thrift_protocol/modules/thrift_protocol.so php_ext_dir/ + ln -s "$$(php-config --extension-dir)/sockets.so" php_ext_dir/ -check: stubs +precross: stubs php_ext_dir + +check: stubs php_ext_dir clean-local: - $(RM) -r gen-php gen-phpi gen-php-psr4 + $(RM) -r gen-php gen-phpi gen-php-classmap php_ext_dir -client: stubs +client: stubs php_ext_dir php TestClient.php diff --git a/vendor/git.apache.org/thrift.git/test/php/TestPsr4.php b/vendor/git.apache.org/thrift.git/test/php/TestClassmap.php similarity index 96% rename from vendor/git.apache.org/thrift.git/test/php/TestPsr4.php rename to vendor/git.apache.org/thrift.git/test/php/TestClassmap.php index d30bf1c..6fd1594 100644 --- a/vendor/git.apache.org/thrift.git/test/php/TestPsr4.php +++ b/vendor/git.apache.org/thrift.git/test/php/TestClassmap.php @@ -18,6 +18,6 @@ */ diff --git a/vendor/git.apache.org/thrift.git/test/php/TestClient.php b/vendor/git.apache.org/thrift.git/test/php/TestClient.php index c1f6435..acd901d 100755 --- a/vendor/git.apache.org/thrift.git/test/php/TestClient.php +++ b/vendor/git.apache.org/thrift.git/test/php/TestClient.php @@ -2,7 +2,8 @@ namespace test\php; -require_once __DIR__.'/../../lib/php/lib/Thrift/ClassLoader/ThriftClassLoader.php'; +/** @var \Composer\Autoload\ClassLoader $loader */ +$loader = require __DIR__ . '/../../vendor/autoload.php'; use Thrift\ClassLoader\ThriftClassLoader; @@ -13,14 +14,14 @@ if (!isset($MODE)) { $MODE = 'normal'; } -$loader = new ThriftClassLoader(); -$loader->registerNamespace('Thrift', __DIR__ . '/../../lib/php/lib'); -if ($GEN_DIR === 'gen-php-psr4') { - $loader->registerNamespace('ThriftTest', $GEN_DIR); + +if ($GEN_DIR == 'gen-php') { + $loader->addPsr4('', $GEN_DIR); } else { + $loader = new ThriftClassLoader(); $loader->registerDefinition('ThriftTest', $GEN_DIR); + $loader->register(); } -$loader->register(); /* * Licensed to the Apache Software Foundation (ASF) under one @@ -94,7 +95,7 @@ foreach ($argv as $arg) { $MODE = substr($arg, 12); } else if (substr($arg, 0, 11) == '--protocol=') { $PROTO = substr($arg, 11); - } + } } $hosts = array('localhost'); @@ -266,6 +267,39 @@ if ($mapin != $mapout) { $exitcode |= ERR_CONTAINERS; } +$mapout = array(); +for ($i = 0; $i < 10; $i++) { + $mapout["key$i"] = "val$i"; +} +print_r('testStringMap({'); +$first = true; +foreach ($mapout as $key => $val) { + if ($first) { + $first = false; + } else { + print_r(", "); + } + print_r("\"$key\" => \"$val\""); +} +print_r("})"); +$mapin = $testClient->testStringMap($mapout); +print_r(" = {"); +$first = true; +foreach ($mapin as $key => $val) { + if ($first) { + $first = false; + } else { + print_r(", "); + } + print_r("\"$key\" => \"$val\""); +} +print_r("}\n"); +ksort($mapin); +if ($mapin != $mapout) { + echo "**FAILED**\n"; + $exitcode |= ERR_CONTAINERS; +} + /** * SET TEST */ @@ -459,6 +493,24 @@ try { print_r(' caught xception '.$x->errorCode.': '.$x->message."\n"); } +// Regression test for THRIFT-4263 +print_r("testBinarySerializer_Deserialize('foo')"); +try { + \Thrift\Serializer\TBinarySerializer::deserialize(base64_decode('foo'), \ThriftTest\Xtruct2::class); + echo "**FAILED**\n"; + $exitcode |= ERR_STRUCTS; +} catch (\Thrift\Exception\TTransportException $happy_exception) { + // We expected this due to binary data of base64_decode('foo') is less then 4 + // bytes and it tries to find thrift version number in the transport by + // reading i32() at the beginning. Casting to string validates that + // exception is still accessible in memory and not corrupted. Without patch, + // PHP will error log that the exception doesn't have any tostring method, + // which is a lie due to corrupted memory. + for($i=99; $i > 0; $i--) { + (string)$happy_exception; + } + print_r(" SUCCESS\n"); +} /** * Normal tests done. @@ -472,6 +524,19 @@ print_r("Total time: $elp ms\n"); * Extraneous "I don't trust PHP to pack/unpack integer" tests */ +if ($protocol instanceof TBinaryProtocolAccelerated) { + // Regression check: check that method name is not double-freed + // Method name should not be an interned string. + $method_name = "Void"; + $method_name = "test$method_name"; + + $seqid = 0; + $args = new \ThriftTest\ThriftTest_testVoid_args(); + thrift_protocol_write_binary($protocol, $method_name, \Thrift\Type\TMessageType::CALL, $args, $seqid, $protocol->isStrictWrite()); + $testClient->recv_testVoid(); + +} + // Max I32 $num = pow(2, 30) + (pow(2, 30) - 1); roundtrip($testClient, 'testI32', $num); diff --git a/vendor/git.apache.org/thrift.git/test/php/test_php.ini b/vendor/git.apache.org/thrift.git/test/php/test_php.ini new file mode 100644 index 0000000..3f9bb21 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/php/test_php.ini @@ -0,0 +1,2 @@ +extension=thrift_protocol.so +extension=sockets.so diff --git a/vendor/git.apache.org/thrift.git/test/py.tornado/test_suite.py b/vendor/git.apache.org/thrift.git/test/py.tornado/test_suite.py index 32d1c2e..447fde6 100755 --- a/vendor/git.apache.org/thrift.git/test/py.tornado/test_suite.py +++ b/vendor/git.apache.org/thrift.git/test/py.tornado/test_suite.py @@ -21,8 +21,8 @@ import datetime import glob -import sys import os +import sys import time import unittest @@ -40,8 +40,8 @@ from tornado import gen from tornado.testing import AsyncTestCase, get_unused_port, gen_test from thrift import TTornado +from thrift.Thrift import TApplicationException from thrift.protocol import TBinaryProtocol -from thrift.transport.TTransport import TTransportException from ThriftTest import ThriftTest from ThriftTest.ttypes import Xception, Xtruct @@ -55,6 +55,8 @@ class TestHandler(object): pass def testString(self, s): + if s == 'unexpected_error': + raise Exception(s) return s def testByte(self, b): @@ -85,7 +87,7 @@ class TestHandler(object): x.message = s raise x elif s == 'throw_undeclared': - raise ValueError("foo") + raise ValueError('testing undeclared exception') def testOneway(self, seconds): start = time.time() @@ -97,6 +99,7 @@ class TestHandler(object): self.test_instance.io_loop.add_timeout( datetime.timedelta(seconds=seconds), fire_oneway) + raise Exception('testing exception in oneway method') def testNest(self, thing): return thing @@ -187,10 +190,11 @@ class ThriftTestCase(AsyncTestCase): self.assertEqual(y.i32_thing, -3) self.assertEqual(y.i64_thing, -5) + @gen_test def test_oneway(self): - self.client.testOneway(0) - start, end, seconds = self.wait(timeout=1) - self.assertAlmostEqual(seconds, (end - start), places=3) + self.client.testOneway(1) + v = yield self.client.testI32(-1) + self.assertEqual(v, -1) @gen_test def test_map(self): @@ -203,8 +207,6 @@ class ThriftTestCase(AsyncTestCase): @gen_test def test_exception(self): - yield self.client.testException('Safe') - try: yield self.client.testException('Xception') except Xception as ex: @@ -214,11 +216,13 @@ class ThriftTestCase(AsyncTestCase): self.fail("should have gotten exception") try: yield self.client.testException('throw_undeclared') - except TTransportException as ex: + except TApplicationException: pass else: self.fail("should have gotten exception") + yield self.client.testException('Safe') + def suite(): suite = unittest.TestSuite() diff --git a/vendor/git.apache.org/thrift.git/test/py.twisted/Makefile.am b/vendor/git.apache.org/thrift.git/test/py.twisted/Makefile.am index 78cde22..d11908c 100644 --- a/vendor/git.apache.org/thrift.git/test/py.twisted/Makefile.am +++ b/vendor/git.apache.org/thrift.git/test/py.twisted/Makefile.am @@ -17,7 +17,6 @@ # under the License. # -THRIFT = $(top_builddir)/compiler/cpp/thrift TRIAL ?= trial stubs: ../ThriftTest.thrift ../SmallTest.thrift diff --git a/vendor/git.apache.org/thrift.git/test/py.twisted/test_suite.py b/vendor/git.apache.org/thrift.git/test/py.twisted/test_suite.py index 43149a4..02eb7f1 100755 --- a/vendor/git.apache.org/thrift.git/test/py.twisted/test_suite.py +++ b/vendor/git.apache.org/thrift.git/test/py.twisted/test_suite.py @@ -19,14 +19,17 @@ # under the License. # -import sys -import os import glob +import os +import sys import time + basepath = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(basepath, 'gen-py.twisted')) sys.path.insert(0, glob.glob(os.path.join(basepath, '../../lib/py/build/lib.*'))[0]) +from thrift.Thrift import TApplicationException + from ThriftTest import ThriftTest from ThriftTest.ttypes import Xception, Xtruct from thrift.transport import TTwisted @@ -36,12 +39,11 @@ from twisted.trial import unittest from twisted.internet import defer, reactor from twisted.internet.protocol import ClientCreator -from zope.interface import implements +from zope.interface import implementer +@implementer(ThriftTest.Iface) class TestHandler: - implements(ThriftTest.Iface) - def __init__(self): self.onewaysQueue = defer.DeferredQueue() @@ -85,6 +87,7 @@ class TestHandler: def fireOneway(t): self.onewaysQueue.put((t, time.time(), seconds)) reactor.callLater(seconds, fireOneway, time.time()) + raise Exception('') def testNest(self, thing): return thing @@ -172,7 +175,6 @@ class ThriftTestCase(unittest.TestCase): @defer.inlineCallbacks def testException(self): - yield self.client.testException('Safe') try: yield self.client.testException('Xception') self.fail("should have gotten exception") @@ -182,12 +184,15 @@ class ThriftTestCase(unittest.TestCase): try: yield self.client.testException("throw_undeclared") - self.fail("should have thrown exception") - except Exception: # type is undefined + self.fail("should have gotten exception") + except TApplicationException: pass + yield self.client.testException('Safe') + @defer.inlineCallbacks def testOneway(self): yield self.client.testOneway(1) start, end, seconds = yield self.handler.onewaysQueue.get() self.assertAlmostEquals(seconds, (end - start), places=1) + self.assertEquals((yield self.client.testI32(-1)), -1) diff --git a/vendor/git.apache.org/thrift.git/test/py/FastbinaryTest.py b/vendor/git.apache.org/thrift.git/test/py/FastbinaryTest.py index db3ef8b..05c0bb6 100755 --- a/vendor/git.apache.org/thrift.git/test/py/FastbinaryTest.py +++ b/vendor/git.apache.org/thrift.git/test/py/FastbinaryTest.py @@ -50,6 +50,7 @@ class TDevNullTransport(TTransport.TTransportBase): def isOpen(self): return True + ooe1 = OneOfEach() ooe1.im_true = True ooe1.im_false = False @@ -85,6 +86,10 @@ hm.big[1].a_bite = 0x22 hm.contain.add(("and a one", "and a two")) hm.contain.add(("then a one, two", "three!", "FOUR!")) +if sys.version_info[0] == 2 and os.environ.get('THRIFT_TEST_PY_NO_UTF8STRINGS'): + hm.contain.add((u"\xd7\n\a\t".encode('utf8'),)) +else: + hm.contain.add((u"\xd7\n\a\t",)) hm.contain.add(()) hm.bonks["nothing"] = [] diff --git a/vendor/git.apache.org/thrift.git/test/py/Makefile.am b/vendor/git.apache.org/thrift.git/test/py/Makefile.am index f105737..8296200 100644 --- a/vendor/git.apache.org/thrift.git/test/py/Makefile.am +++ b/vendor/git.apache.org/thrift.git/test/py/Makefile.am @@ -18,25 +18,38 @@ # AUTOMAKE_OPTIONS = serial-tests -THRIFT = $(top_builddir)/compiler/cpp/thrift - py_unit_tests = RunClientServer.py thrift_gen = \ gen-py/ThriftTest/__init__.py \ gen-py/DebugProtoTest/__init__.py \ + gen-py/DoubleConstantsTest/__init__.py \ + gen-py/Recursive/__init__.py \ gen-py-default/ThriftTest/__init__.py \ gen-py-default/DebugProtoTest/__init__.py \ + gen-py-default/DoubleConstantsTest/__init__.py \ + gen-py-default/Recursive/__init__.py \ gen-py-slots/ThriftTest/__init__.py \ gen-py-slots/DebugProtoTest/__init__.py \ + gen-py-slots/DoubleConstantsTest/__init__.py \ + gen-py-slots/Recursive/__init__.py \ gen-py-oldstyle/ThriftTest/__init__.py \ gen-py-oldstyle/DebugProtoTest/__init__.py \ + gen-py-oldstyle/DoubleConstantsTest/__init__.py \ + gen-py-oldstyle/Recursive/__init__.py \ gen-py-no_utf8strings/ThriftTest/__init__.py \ gen-py-no_utf8strings/DebugProtoTest/__init__.py \ + gen-py-no_utf8strings/DoubleConstantsTest/__init__.py \ + gen-py-no_utf8strings/Recursive/__init__.py \ gen-py-dynamic/ThriftTest/__init__.py \ gen-py-dynamic/DebugProtoTest/__init__.py \ + gen-py-dynamic/DoubleConstantsTest/__init__.py \ + gen-py-dynamic/Recursive/__init__.py \ gen-py-dynamicslots/ThriftTest/__init__.py \ - gen-py-dynamicslots/DebugProtoTest/__init__.py + gen-py-dynamicslots/DebugProtoTest/__init__.py \ + gen-py-dynamicslots/DoubleConstantsTest/__init__.py \ + gen-py-dynamicslots/Recursive/__init__.py + precross: $(thrift_gen) BUILT_SOURCES = $(thrift_gen) diff --git a/vendor/git.apache.org/thrift.git/test/py/RunClientServer.py b/vendor/git.apache.org/thrift.git/test/py/RunClientServer.py index c1443ec..56a408e 100755 --- a/vendor/git.apache.org/thrift.git/test/py/RunClientServer.py +++ b/vendor/git.apache.org/thrift.git/test/py/RunClientServer.py @@ -38,6 +38,7 @@ SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) SCRIPTS = [ 'FastbinaryTest.py', 'TestFrozen.py', + 'TestRenderedDoubleConstants.py', 'TSimpleJSONProtocolTest.py', 'SerializationTest.py', 'TestEof.py', @@ -46,7 +47,7 @@ SCRIPTS = [ ] FRAMED = ["TNonblockingServer"] SKIP_ZLIB = ['TNonblockingServer', 'THttpServer'] -SKIP_SSL = ['TNonblockingServer', 'THttpServer'] +SKIP_SSL = ['THttpServer'] EXTRA_DELAY = dict(TProcessPoolServer=5.5) PROTOS = [ @@ -55,6 +56,7 @@ PROTOS = [ 'binary', 'compact', 'json', + 'header', ] diff --git a/vendor/git.apache.org/thrift.git/test/py/SerializationTest.py b/vendor/git.apache.org/thrift.git/test/py/SerializationTest.py index efe3c6d..ef79835 100755 --- a/vendor/git.apache.org/thrift.git/test/py/SerializationTest.py +++ b/vendor/git.apache.org/thrift.git/test/py/SerializationTest.py @@ -35,6 +35,11 @@ from ThriftTest.ttypes import ( Xtruct2, ) +from Recursive.ttypes import RecTree +from Recursive.ttypes import RecList +from Recursive.ttypes import CoRec +from Recursive.ttypes import CoRec2 +from Recursive.ttypes import VectorTest from DebugProtoTest.ttypes import CompactProtoTestStruct, Empty from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol, TCompactProtocol, TJSONProtocol @@ -285,6 +290,67 @@ class AbstractTest(unittest.TestCase): for value in bad_values: self.assertRaises(Exception, self._serialize, value) + def testRecTree(self): + """Ensure recursive tree node can be created.""" + children = [] + for idx in range(1, 5): + node = RecTree(item=idx, children=None) + children.append(node) + + parent = RecTree(item=0, children=children) + serde_parent = self._deserialize(RecTree, self._serialize(parent)) + self.assertEquals(0, serde_parent.item) + self.assertEquals(4, len(serde_parent.children)) + for child in serde_parent.children: + # Cannot use assertIsInstance in python 2.6? + self.assertTrue(isinstance(child, RecTree)) + + def _buildLinkedList(self): + head = cur = RecList(item=0) + for idx in range(1, 5): + node = RecList(item=idx) + cur.nextitem = node + cur = node + return head + + def _collapseLinkedList(self, head): + out_list = [] + cur = head + while cur is not None: + out_list.append(cur.item) + cur = cur.nextitem + return out_list + + def testRecList(self): + """Ensure recursive linked list can be created.""" + rec_list = self._buildLinkedList() + serde_list = self._deserialize(RecList, self._serialize(rec_list)) + out_list = self._collapseLinkedList(serde_list) + self.assertEquals([0, 1, 2, 3, 4], out_list) + + def testCoRec(self): + """Ensure co-recursive structures can be created.""" + item1 = CoRec() + item2 = CoRec2() + + item1.other = item2 + item2.other = item1 + + # NOTE [econner724,2017-06-21]: These objects cannot be serialized as serialization + # results in an infinite loop. fbthrift also suffers from this + # problem. + + def testRecVector(self): + """Ensure a list of recursive nodes can be created.""" + mylist = [self._buildLinkedList(), self._buildLinkedList()] + myvec = VectorTest(lister=mylist) + + serde_vec = self._deserialize(VectorTest, self._serialize(myvec)) + golden_list = [0, 1, 2, 3, 4] + for cur_list in serde_vec.lister: + out_list = self._collapseLinkedList(cur_list) + self.assertEqual(golden_list, out_list) + class NormalBinaryTest(AbstractTest): protocol_factory = TBinaryProtocol.TBinaryProtocolFactory() @@ -386,5 +452,6 @@ def suite(): suite.addTest(loader.loadTestsFromTestCase(SerializersTest)) return suite + if __name__ == "__main__": unittest.main(defaultTest="suite", testRunner=unittest.TextTestRunner(verbosity=2)) diff --git a/vendor/git.apache.org/thrift.git/test/py/TestClient.py b/vendor/git.apache.org/thrift.git/test/py/TestClient.py index 18ef66b..ddcce8d 100755 --- a/vendor/git.apache.org/thrift.git/test/py/TestClient.py +++ b/vendor/git.apache.org/thrift.git/test/py/TestClient.py @@ -32,8 +32,18 @@ SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) class AbstractTest(unittest.TestCase): def setUp(self): - if options.http_path: - self.transport = THttpClient.THttpClient(options.host, port=options.port, path=options.http_path) + if options.trans == 'http': + uri = '{0}://{1}:{2}{3}'.format(('https' if options.ssl else 'http'), + options.host, + options.port, + (options.http_path if options.http_path else '/')) + if options.ssl: + __cafile = os.path.join(os.path.dirname(SCRIPT_DIR), "keys", "CA.pem") + __certfile = os.path.join(os.path.dirname(SCRIPT_DIR), "keys", "client.crt") + __keyfile = os.path.join(os.path.dirname(SCRIPT_DIR), "keys", "client.key") + self.transport = THttpClient.THttpClient(uri, cafile=__cafile, cert_file=__certfile, key_file=__keyfile) + else: + self.transport = THttpClient.THttpClient(uri) else: if options.ssl: from thrift.transport import TSSLSocket @@ -53,6 +63,9 @@ class AbstractTest(unittest.TestCase): self.transport.open() protocol = self.get_protocol(self.transport) self.client = ThriftTest.Client(protocol) + # for multiplexed services: + protocol2 = self.get_protocol2(self.transport) + self.client2 = SecondService.Client(protocol2) if protocol2 is not None else None def tearDown(self): self.transport.close() @@ -97,6 +110,11 @@ class AbstractTest(unittest.TestCase): self.assertEqual(self.client.testString(s1), s1) self.assertEqual(self.client.testString(s2), s2) + def testMultiplexed(self): + if self.client2 is not None: + print('testMultiplexed') + self.assertEqual(self.client2.secondtestString('foobar'), 'testString("foobar")') + def testBool(self): print('testBool') self.assertEqual(self.client.testBool(True), True) @@ -250,44 +268,117 @@ class AbstractTest(unittest.TestCase): self.assertEqual(self.client.testString('Python'), 'Python') -class NormalBinaryTest(AbstractTest): +class MultiplexedOptionalTest(AbstractTest): + def get_protocol2(self, transport): + return None + + +class BinaryTest(MultiplexedOptionalTest): def get_protocol(self, transport): return TBinaryProtocol.TBinaryProtocolFactory().getProtocol(transport) -class CompactTest(AbstractTest): +class MultiplexedBinaryTest(MultiplexedOptionalTest): def get_protocol(self, transport): - return TCompactProtocol.TCompactProtocolFactory().getProtocol(transport) + wrapped_proto = TBinaryProtocol.TBinaryProtocolFactory().getProtocol(transport) + return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "ThriftTest") + + def get_protocol2(self, transport): + wrapped_proto = TBinaryProtocol.TBinaryProtocolFactory().getProtocol(transport) + return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "SecondService") -class JSONTest(AbstractTest): - def get_protocol(self, transport): - return TJSONProtocol.TJSONProtocolFactory().getProtocol(transport) - - -class AcceleratedBinaryTest(AbstractTest): +class AcceleratedBinaryTest(MultiplexedOptionalTest): def get_protocol(self, transport): return TBinaryProtocol.TBinaryProtocolAcceleratedFactory(fallback=False).getProtocol(transport) -class AcceleratedCompactTest(AbstractTest): +class MultiplexedAcceleratedBinaryTest(MultiplexedOptionalTest): + def get_protocol(self, transport): + wrapped_proto = TBinaryProtocol.TBinaryProtocolAcceleratedFactory(fallback=False).getProtocol(transport) + return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "ThriftTest") + + def get_protocol2(self, transport): + wrapped_proto = TBinaryProtocol.TBinaryProtocolAcceleratedFactory(fallback=False).getProtocol(transport) + return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "SecondService") + + +class CompactTest(MultiplexedOptionalTest): + def get_protocol(self, transport): + return TCompactProtocol.TCompactProtocolFactory().getProtocol(transport) + + +class MultiplexedCompactTest(MultiplexedOptionalTest): + def get_protocol(self, transport): + wrapped_proto = TCompactProtocol.TCompactProtocolFactory().getProtocol(transport) + return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "ThriftTest") + + def get_protocol2(self, transport): + wrapped_proto = TCompactProtocol.TCompactProtocolFactory().getProtocol(transport) + return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "SecondService") + + +class AcceleratedCompactTest(MultiplexedOptionalTest): def get_protocol(self, transport): return TCompactProtocol.TCompactProtocolAcceleratedFactory(fallback=False).getProtocol(transport) +class MultiplexedAcceleratedCompactTest(MultiplexedOptionalTest): + def get_protocol(self, transport): + wrapped_proto = TCompactProtocol.TCompactProtocolAcceleratedFactory(fallback=False).getProtocol(transport) + return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "ThriftTest") + + def get_protocol2(self, transport): + wrapped_proto = TCompactProtocol.TCompactProtocolAcceleratedFactory(fallback=False).getProtocol(transport) + return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "SecondService") + + +class JSONTest(MultiplexedOptionalTest): + def get_protocol(self, transport): + return TJSONProtocol.TJSONProtocolFactory().getProtocol(transport) + + +class MultiplexedJSONTest(MultiplexedOptionalTest): + def get_protocol(self, transport): + wrapped_proto = TJSONProtocol.TJSONProtocolFactory().getProtocol(transport) + return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "ThriftTest") + + def get_protocol2(self, transport): + wrapped_proto = TJSONProtocol.TJSONProtocolFactory().getProtocol(transport) + return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "SecondService") + + +class HeaderTest(MultiplexedOptionalTest): + def get_protocol(self, transport): + factory = THeaderProtocol.THeaderProtocolFactory() + return factory.getProtocol(transport) + + def suite(): suite = unittest.TestSuite() loader = unittest.TestLoader() if options.proto == 'binary': # look for --proto on cmdline - suite.addTest(loader.loadTestsFromTestCase(NormalBinaryTest)) + suite.addTest(loader.loadTestsFromTestCase(BinaryTest)) elif options.proto == 'accel': suite.addTest(loader.loadTestsFromTestCase(AcceleratedBinaryTest)) - elif options.proto == 'compact': - suite.addTest(loader.loadTestsFromTestCase(CompactTest)) elif options.proto == 'accelc': suite.addTest(loader.loadTestsFromTestCase(AcceleratedCompactTest)) + elif options.proto == 'compact': + suite.addTest(loader.loadTestsFromTestCase(CompactTest)) + elif options.proto == 'header': + suite.addTest(loader.loadTestsFromTestCase(HeaderTest)) elif options.proto == 'json': suite.addTest(loader.loadTestsFromTestCase(JSONTest)) + elif options.proto == 'multi': + suite.addTest(loader.loadTestsFromTestCase(MultiplexedBinaryTest)) + elif options.proto == 'multia': + suite.addTest(loader.loadTestsFromTestCase(MultiplexedAcceleratedBinaryTest)) + elif options.proto == 'multiac': + suite.addTest(loader.loadTestsFromTestCase(MultiplexedAcceleratedCompactTest)) + elif options.proto == 'multic': + suite.addTest(loader.loadTestsFromTestCase(MultiplexedCompactTest)) + elif options.proto == 'multij': + suite.addTest(loader.loadTestsFromTestCase(MultiplexedJSONTest)) else: raise AssertionError('Unknown protocol given with --protocol: %s' % options.proto) return suite @@ -301,6 +392,7 @@ class OwnArgsTestProgram(unittest.TestProgram): self.testNames = ([self.defaultTest]) self.createTests() + if __name__ == "__main__": parser = OptionParser() parser.add_option('--libpydir', type='string', dest='libpydir', @@ -324,9 +416,9 @@ if __name__ == "__main__": dest="verbose", const=0, help="minimal output") parser.add_option('--protocol', dest="proto", type="string", - help="protocol to use, one of: accel, binary, compact, json") + help="protocol to use, one of: accel, accelc, binary, compact, header, json, multi, multia, multiac, multic, multij") parser.add_option('--transport', dest="trans", type="string", - help="transport to use, one of: buffered, framed") + help="transport to use, one of: buffered, framed, http") parser.set_defaults(framed=False, http_path=None, verbose=1, host='localhost', port=9090, proto='binary') options, args = parser.parse_args() @@ -334,6 +426,10 @@ if __name__ == "__main__": sys.path.insert(0, os.path.join(SCRIPT_DIR, options.genpydir)) sys.path.insert(0, local_libpath()) + if options.http_path: + options.trans = 'http' + + from ThriftTest import SecondService from ThriftTest import ThriftTest from ThriftTest.ttypes import Xtruct, Xtruct2, Numberz, Xception, Xception2 from thrift.Thrift import TException @@ -343,6 +439,8 @@ if __name__ == "__main__": from thrift.transport import TZlibTransport from thrift.protocol import TBinaryProtocol from thrift.protocol import TCompactProtocol + from thrift.protocol import THeaderProtocol from thrift.protocol import TJSONProtocol + from thrift.protocol import TMultiplexedProtocol OwnArgsTestProgram(defaultTest="suite", testRunner=unittest.TextTestRunner(verbosity=1)) diff --git a/vendor/git.apache.org/thrift.git/test/py/TestEof.py b/vendor/git.apache.org/thrift.git/test/py/TestEof.py index cda1050..0b4a829 100755 --- a/vendor/git.apache.org/thrift.git/test/py/TestEof.py +++ b/vendor/git.apache.org/thrift.git/test/py/TestEof.py @@ -127,5 +127,6 @@ def suite(): suite.addTest(loader.loadTestsFromTestCase(TestEof)) return suite + if __name__ == "__main__": unittest.main(defaultTest="suite", testRunner=unittest.TextTestRunner(verbosity=2)) diff --git a/vendor/git.apache.org/thrift.git/test/py/TestFrozen.py b/vendor/git.apache.org/thrift.git/test/py/TestFrozen.py index e568e8c..6d2595c 100755 --- a/vendor/git.apache.org/thrift.git/test/py/TestFrozen.py +++ b/vendor/git.apache.org/thrift.git/test/py/TestFrozen.py @@ -118,5 +118,6 @@ def suite(): suite.addTest(loader.loadTestsFromTestCase(TestFrozenAcceleratedCompact)) return suite + if __name__ == "__main__": unittest.main(defaultTest="suite", testRunner=unittest.TextTestRunner(verbosity=2)) diff --git a/vendor/git.apache.org/thrift.git/test/py/TestRenderedDoubleConstants.py b/vendor/git.apache.org/thrift.git/test/py/TestRenderedDoubleConstants.py new file mode 100644 index 0000000..20903d8 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/py/TestRenderedDoubleConstants.py @@ -0,0 +1,177 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +import unittest + +from DoubleConstantsTest import constants + +# +# In order to run the test under Windows. We need to create symbolic link +# name 'thrift' to '../src' folder by using: +# +# mklink /D thrift ..\src +# + + +class TestRenderedDoubleConstants(unittest.TestCase): + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST = \ + "failed to verify a double constant generated by Thrift (expected = %f, got = %f)" + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_LIST_TEST =\ + "failed to verify a list item by Thrift (expected = %f, got = %f)" + ASSERTION_MESSAGE_FOR_TYPE_CHECKS = "the rendered variable with name %s is not of double type" + + # to make sure the variables inside Thrift files are generated correctly + def test_rendered_double_constants(self): + EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT = 1.0 + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT = -100.0 + EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT = 9223372036854775807.0 + EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT = -9223372036854775807.0 + EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS = 3.14159265359 + EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE = 1000000.1 + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE = -1000000.1 + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE = 1.7e+308 + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE = 9223372036854775816.43 + EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE = -1.7e+308 + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE = -9223372036854775816.43 + self.assertAlmostEqual( + constants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT, places=7, + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % ( + EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT, constants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST)) + self.assertAlmostEqual( + constants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT, + places=7, + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % ( + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT, + constants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST)) + self.assertAlmostEqual( + constants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT, + places=7, + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % ( + EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT, + constants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST)) + self.assertAlmostEqual( + constants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT, + places=7, + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % ( + EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT, + constants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST)) + self.assertAlmostEqual( + constants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS, places=7, + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % ( + EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS, + constants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST)) + self.assertAlmostEqual( + constants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE, + places=7, + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % ( + EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE, + constants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST)) + self.assertAlmostEqual( + constants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE, places=7, + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % ( + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE, + constants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST)) + self.assertAlmostEqual( + constants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE, places=7, + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % ( + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE, + constants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST)) + self.assertAlmostEqual( + constants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE, places=7, + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % ( + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE, + constants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST)) + self.assertAlmostEqual( + constants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE, places=7, + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % ( + EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE, + constants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST)) + self.assertAlmostEqual( + constants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE, places=7, + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % ( + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE, + constants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST)) + self.assertTrue( + isinstance(constants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST, float), + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS % + "DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST") + self.assertTrue( + isinstance(constants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST, float), + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS % + "DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST") + self.assertTrue( + isinstance(constants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST, float), + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS % + "DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST") + self.assertTrue( + isinstance(constants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST, float), + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS % + "DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST") + self.assertTrue( + isinstance(constants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST, float), + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS % + "DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST") + self.assertTrue( + isinstance(constants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST, float), + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS % + "DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST") + self.assertTrue( + isinstance(constants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST, float), + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS % + "DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST") + self.assertTrue( + isinstance(constants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST, float), + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS % + "DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST") + self.assertTrue( + isinstance(constants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST, float), + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS % + "DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST") + self.assertTrue( + isinstance(constants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST, float), + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS % + "DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST") + self.assertTrue( + isinstance(constants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST, float), + msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS % + "DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST") + + # to make sure the variables inside Thrift files are generated correctly + def test_rendered_double_list(self): + EXPECTED_DOUBLE_LIST = [1.0, -100.0, 100.0, 9223372036854775807.0, -9223372036854775807.0, 3.14159265359, + 1000000.1, -1000000.1, 1.7e+308, -1.7e+308, 9223372036854775816.43, + -9223372036854775816.43] + self.assertEqual(len(constants.DOUBLE_LIST_TEST), len(EXPECTED_DOUBLE_LIST)) + for i, expectedValue in enumerate(EXPECTED_DOUBLE_LIST): + self.assertAlmostEqual(constants.DOUBLE_LIST_TEST[i], expectedValue, places=7) + + +def suite(): + suite = unittest.TestSuite() + loader = unittest.TestLoader() + suite.addTest(loader.loadTestsFromTestCase(TestRenderedDoubleConstants)) + return suite + + +if __name__ == "__main__": + unittest.main(defaultTest="suite", testRunner=unittest.TextTestRunner(verbosity=2)) diff --git a/vendor/git.apache.org/thrift.git/test/py/TestServer.py b/vendor/git.apache.org/thrift.git/test/py/TestServer.py index 070560c..aba0d42 100755 --- a/vendor/git.apache.org/thrift.git/test/py/TestServer.py +++ b/vendor/git.apache.org/thrift.git/test/py/TestServer.py @@ -21,6 +21,7 @@ from __future__ import division import logging import os +import signal import sys import time from optparse import OptionParser @@ -180,20 +181,26 @@ class TestHandler(object): def main(options): # set up the protocol factory form the --protocol option prot_factories = { - 'binary': TBinaryProtocol.TBinaryProtocolFactory, - 'accel': TBinaryProtocol.TBinaryProtocolAcceleratedFactory, - 'compact': TCompactProtocol.TCompactProtocolFactory, - 'accelc': TCompactProtocol.TCompactProtocolAcceleratedFactory, - 'json': TJSONProtocol.TJSONProtocolFactory, + 'accel': TBinaryProtocol.TBinaryProtocolAcceleratedFactory(), + 'accelc': TCompactProtocol.TCompactProtocolAcceleratedFactory(), + 'binary': TBinaryProtocol.TBinaryProtocolFactory(), + 'compact': TCompactProtocol.TCompactProtocolFactory(), + 'header': THeaderProtocol.THeaderProtocolFactory(allowed_client_types=[ + THeaderTransport.THeaderClientType.HEADERS, + THeaderTransport.THeaderClientType.FRAMED_BINARY, + THeaderTransport.THeaderClientType.UNFRAMED_BINARY, + THeaderTransport.THeaderClientType.FRAMED_COMPACT, + THeaderTransport.THeaderClientType.UNFRAMED_COMPACT, + ]), + 'json': TJSONProtocol.TJSONProtocolFactory(), } - pfactory_cls = prot_factories.get(options.proto, None) - if pfactory_cls is None: + pfactory = prot_factories.get(options.proto, None) + if pfactory is None: raise AssertionError('Unknown --protocol option: %s' % options.proto) - pfactory = pfactory_cls() try: pfactory.string_length_limit = options.string_limit pfactory.container_length_limit = options.container_limit - except: + except Exception: # Ignore errors for those protocols that does not support length limit pass @@ -201,14 +208,23 @@ def main(options): if len(args) > 1: raise AssertionError('Only one server type may be specified, not multiple types.') server_type = args[0] + if options.trans == 'http': + server_type = 'THttpServer' # Set up the handler and processor objects handler = TestHandler() processor = ThriftTest.Processor(handler) + global server + # Handle THttpServer as a special case if server_type == 'THttpServer': - server = THttpServer.THttpServer(processor, ('', options.port), pfactory) + if options.ssl: + __certfile = os.path.join(os.path.dirname(SCRIPT_DIR), "keys", "server.crt") + __keyfile = os.path.join(os.path.dirname(SCRIPT_DIR), "keys", "server.key") + server = THttpServer.THttpServer(processor, ('', options.port), pfactory, cert_file=__certfile, key_file=__keyfile) + else: + server = THttpServer.THttpServer(processor, ('', options.port), pfactory) server.serve() sys.exit(0) @@ -255,7 +271,7 @@ def main(options): logging.info('Requesting server to stop()') try: server.stop() - except: + except Exception: pass signal.signal(signal.SIGALRM, clean_shutdown) signal.alarm(4) @@ -267,7 +283,16 @@ def main(options): # enter server main loop server.serve() + +def exit_gracefully(signum, frame): + print("SIGINT received\n") + server.shutdown() # doesn't work properly, yet + sys.exit(0) + + if __name__ == '__main__': + signal.signal(signal.SIGINT, exit_gracefully) + parser = OptionParser() parser.add_option('--libpydir', type='string', dest='libpydir', help='include this directory to sys.path for locating library code') @@ -287,12 +312,12 @@ if __name__ == '__main__': dest="verbose", const=0, help="minimal output") parser.add_option('--protocol', dest="proto", type="string", - help="protocol to use, one of: accel, binary, compact, json") + help="protocol to use, one of: accel, accelc, binary, compact, json") parser.add_option('--transport', dest="trans", type="string", - help="transport to use, one of: buffered, framed") + help="transport to use, one of: buffered, framed, http") parser.add_option('--container-limit', dest='container_limit', type='int', default=None) parser.add_option('--string-limit', dest='string_limit', type='int', default=None) - parser.set_defaults(port=9090, verbose=1, proto='binary') + parser.set_defaults(port=9090, verbose=1, proto='binary', transport='buffered') options, args = parser.parse_args() # Print TServer log to stdout so that the test-runner can redirect it to log files @@ -304,11 +329,13 @@ if __name__ == '__main__': from ThriftTest import ThriftTest from ThriftTest.ttypes import Xtruct, Xception, Xception2, Insanity from thrift.Thrift import TException + from thrift.transport import THeaderTransport from thrift.transport import TTransport from thrift.transport import TSocket from thrift.transport import TZlibTransport from thrift.protocol import TBinaryProtocol from thrift.protocol import TCompactProtocol + from thrift.protocol import THeaderProtocol from thrift.protocol import TJSONProtocol from thrift.server import TServer, TNonblockingServer, THttpServer diff --git a/vendor/git.apache.org/thrift.git/test/py/TestSocket.py b/vendor/git.apache.org/thrift.git/test/py/TestSocket.py index a3c5ff0..619eb10 100755 --- a/vendor/git.apache.org/thrift.git/test/py/TestSocket.py +++ b/vendor/git.apache.org/thrift.git/test/py/TestSocket.py @@ -36,7 +36,7 @@ class TimeoutTest(unittest.TestCase): self.listen_sock.bind(('localhost', self.port)) self.listen_sock.listen(5) break - except: + except Exception: if i == 49: raise @@ -50,7 +50,7 @@ class TimeoutTest(unittest.TestCase): socket.setTimeout(10) socket.open() leaky.append(socket) - except: + except Exception: self.assert_(time.time() - starttime < 5.0) def testWriteTimeout(self): @@ -64,9 +64,10 @@ class TimeoutTest(unittest.TestCase): while True: lsock.write("hi" * 100) - except: + except Exception: self.assert_(time.time() - starttime < 5.0) + if __name__ == '__main__': suite = unittest.TestSuite() loader = unittest.TestLoader() diff --git a/vendor/git.apache.org/thrift.git/test/py/generate.cmake b/vendor/git.apache.org/thrift.git/test/py/generate.cmake index 44c5357..4ed14cc 100644 --- a/vendor/git.apache.org/thrift.git/test/py/generate.cmake +++ b/vendor/git.apache.org/thrift.git/test/py/generate.cmake @@ -20,3 +20,17 @@ generate(${MY_PROJECT_DIR}/test/DebugProtoTest.thrift py:old_style gen-py-oldsty generate(${MY_PROJECT_DIR}/test/DebugProtoTest.thrift py:no_utf8strings gen-py-no_utf8strings) generate(${MY_PROJECT_DIR}/test/DebugProtoTest.thrift py:dynamic gen-py-dynamic) generate(${MY_PROJECT_DIR}/test/DebugProtoTest.thrift py:dynamic,slots gen-py-dynamicslots) + +generate(${MY_PROJECT_DIR}/test/DoubleConstantsTest.thrift py gen-py-default) +generate(${MY_PROJECT_DIR}/test/DoubleConstantsTest.thrift py:slots gen-py-slots) +generate(${MY_PROJECT_DIR}/test/DoubleConstantsTest.thrift py:old_style gen-py-oldstyle) +generate(${MY_PROJECT_DIR}/test/DoubleConstantsTest.thrift py:no_utf8strings gen-py-no_utf8strings) +generate(${MY_PROJECT_DIR}/test/DoubleConstantsTest.thrift py:dynamic gen-py-dynamic) +generate(${MY_PROJECT_DIR}/test/DoubleConstantsTest.thrift py:dynamic,slots gen-py-dynamicslots) + +generate(${MY_PROJECT_DIR}/test/Recursive.thrift py gen-py-default) +generate(${MY_PROJECT_DIR}/test/Recursive.thrift py:slots gen-py-slots) +generate(${MY_PROJECT_DIR}/test/Recursive.thrift py:old_style gen-py-oldstyle) +generate(${MY_PROJECT_DIR}/test/Recursive.thrift py:no_utf8strings gen-py-no_utf8strings) +generate(${MY_PROJECT_DIR}/test/Recursive.thrift py:dynamic gen-py-dynamic) +generate(${MY_PROJECT_DIR}/test/Recursive.thrift py:dynamic,slots gen-py-dynamicslots) diff --git a/vendor/git.apache.org/thrift.git/test/rb/Gemfile b/vendor/git.apache.org/thrift.git/test/rb/Gemfile index 58c04aa..4ff0539 100644 --- a/vendor/git.apache.org/thrift.git/test/rb/Gemfile +++ b/vendor/git.apache.org/thrift.git/test/rb/Gemfile @@ -2,6 +2,6 @@ source "http://rubygems.org" require "rubygems" -gem "rack", "~> 1.5.2" -gem "thin", "~> 1.5.0" -gem "test-unit" +gem 'rack', '~> 2.0', '>= 2.0.4' +gem 'thin', '~> 1.7', '>= 1.7.2' +gem 'test-unit', '~> 3.2', '>= 3.2.7' diff --git a/vendor/git.apache.org/thrift.git/test/rb/Makefile.am b/vendor/git.apache.org/thrift.git/test/rb/Makefile.am index 7b74c6c..cfdc149 100644 --- a/vendor/git.apache.org/thrift.git/test/rb/Makefile.am +++ b/vendor/git.apache.org/thrift.git/test/rb/Makefile.am @@ -17,11 +17,10 @@ # under the License. # -THRIFT = $(top_builddir)/compiler/cpp/thrift - stubs: $(THRIFT) ../ThriftTest.thrift ../SmallTest.thrift $(THRIFT) --gen rb ../ThriftTest.thrift $(THRIFT) --gen rb ../SmallTest.thrift + $(THRIFT) --gen rb ../Recursive.thrift precross: stubs diff --git a/vendor/git.apache.org/thrift.git/test/rb/generation/test_recursive.rb b/vendor/git.apache.org/thrift.git/test/rb/generation/test_recursive.rb new file mode 100644 index 0000000..e912f72 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/rb/generation/test_recursive.rb @@ -0,0 +1,41 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +require File.join(File.dirname(__FILE__), '../test_helper') +require 'recursive_types' + +class TestRecursiveGeneration < Test::Unit::TestCase + CHILD_ITEM = "child item" + PARENT_ITEM = "parent item" + + def test_can_create_recursive_tree + + child_tree = RecTree.new + child_tree.item = CHILD_ITEM + + parent_tree = RecTree.new + parent_tree.item = PARENT_ITEM + parent_tree.children = [child_tree] + + assert_equal(PARENT_ITEM, parent_tree.item) + assert_equal(1, parent_tree.children.length) + assert_equal(CHILD_ITEM, parent_tree.children.first.item) + assert_nil(parent_tree.children.first.children) + end +end diff --git a/vendor/git.apache.org/thrift.git/test/rb/integration/TestClient.rb b/vendor/git.apache.org/thrift.git/test/rb/integration/TestClient.rb index beebe44..639aca9 100755 --- a/vendor/git.apache.org/thrift.git/test/rb/integration/TestClient.rb +++ b/vendor/git.apache.org/thrift.git/test/rb/integration/TestClient.rb @@ -26,35 +26,63 @@ require 'test_helper' require 'thrift' require 'thrift_test' -$protocolType = "binary" +$domain_socket = nil $host = "localhost" $port = 9090 +$protocolType = "binary" +$ssl = false $transport = "buffered" + ARGV.each do|a| if a == "--help" puts "Allowed options:" puts "\t -h [ --help ] \t produce help message" - puts "\t--host arg (=localhost) \t Host to connect" - puts "\t--port arg (=9090) \t Port number to listen" - puts "\t--protocol arg (=binary) \t protocol: binary, accel" + puts "\t--domain-socket arg (=) \t Unix domain socket path" + puts "\t--host arg (=localhost) \t Host to connect \t not valid with domain-socket" + puts "\t--port arg (=9090) \t Port number to listen \t not valid with domain-socket" + puts "\t--protocol arg (=binary) \t protocol: accel, binary, compact, json" + puts "\t--ssl \t use ssl \t not valid with domain-socket" puts "\t--transport arg (=buffered) transport: buffered, framed, http" exit + elsif a.start_with?("--domain-socket") + $domain_socket = a.split("=")[1] elsif a.start_with?("--host") $host = a.split("=")[1] elsif a.start_with?("--protocol") $protocolType = a.split("=")[1] + elsif a == "--ssl" + $ssl = true elsif a.start_with?("--transport") $transport = a.split("=")[1] elsif a.start_with?("--port") $port = a.split("=")[1].to_i end end -ARGV=[] class SimpleClientTest < Test::Unit::TestCase def setup unless @socket - @socket = Thrift::Socket.new($host, $port) + if $domain_socket.to_s.strip.empty? + if $ssl + # the working directory for ruby crosstest is test/rb/gen-rb + keysDir = File.join(File.dirname(File.dirname(Dir.pwd)), "keys") + ctx = OpenSSL::SSL::SSLContext.new + ctx.ca_file = File.join(keysDir, "CA.pem") + ctx.cert = OpenSSL::X509::Certificate.new(File.open(File.join(keysDir, "client.crt"))) + ctx.cert_store = OpenSSL::X509::Store.new + ctx.cert_store.add_file(File.join(keysDir, 'server.pem')) + ctx.key = OpenSSL::PKey::RSA.new(File.open(File.join(keysDir, "client.key"))) + ctx.options = OpenSSL::SSL::OP_NO_SSLv2 | OpenSSL::SSL::OP_NO_SSLv3 + ctx.ssl_version = :SSLv23 + ctx.verify_mode = OpenSSL::SSL::VERIFY_PEER + @socket = Thrift::SSLSocket.new($host, $port, nil, ctx) + else + @socket = Thrift::Socket.new($host, $port) + end + else + @socket = Thrift::UNIXSocket.new($domain_socket) + end + if $transport == "buffered" transportFactory = Thrift::BufferedTransport.new(@socket) elsif $transport == "framed" @@ -74,7 +102,7 @@ class SimpleClientTest < Test::Unit::TestCase else raise 'Unknown protocol type' end - @client = Thrift::Test::ThriftTest::Client.new(@protocol) + @client = Thrift::Test::ThriftTest::Client.new(@protocol) @socket.open end end diff --git a/vendor/git.apache.org/thrift.git/test/rb/integration/TestServer.rb b/vendor/git.apache.org/thrift.git/test/rb/integration/TestServer.rb index bab723a..7caf6a8 100755 --- a/vendor/git.apache.org/thrift.git/test/rb/integration/TestServer.rb +++ b/vendor/git.apache.org/thrift.git/test/rb/integration/TestServer.rb @@ -106,21 +106,30 @@ class SimpleHandler end -protocol = "binary" +domain_socket = nil port = 9090 +protocol = "binary" +@protocolFactory = nil +ssl = false transport = "buffered" -@transportFactory = Thrift::BufferedTransportFactory.new -@protocolFactory = Thrift::BinaryProtocolFactory.new +@transportFactory = nil + ARGV.each do|a| if a == "--help" puts "Allowed options:" puts "\t -h [ --help ] \t produce help message" - puts "\t--port arg (=9090) \t Port number to listen" - puts "\t--protocol arg (=binary) \t protocol: binary, accel" + puts "\t--domain-socket arg (=) \t Unix domain socket path" + puts "\t--port arg (=9090) \t Port number to listen \t not valid with domain-socket" + puts "\t--protocol arg (=binary) \t protocol: accel, binary, compact, json" + puts "\t--ssl \t use ssl \t not valid with domain-socket" puts "\t--transport arg (=buffered) transport: buffered, framed, http" exit + elsif a.start_with?("--domain-socket") + domain_socket = a.split("=")[1] elsif a.start_with?("--protocol") protocol = a.split("=")[1] + elsif a == "--ssl" + ssl = true elsif a.start_with?("--transport") transport = a.split("=")[1] elsif a.start_with?("--port") @@ -128,9 +137,7 @@ ARGV.each do|a| end end -if protocol == "binary" - @protocolFactory = Thrift::BinaryProtocolFactory.new -elsif protocol == "" +if protocol == "binary" || protocol.to_s.strip.empty? @protocolFactory = Thrift::BinaryProtocolFactory.new elsif protocol == "compact" @protocolFactory = Thrift::CompactProtocolFactory.new @@ -142,9 +149,7 @@ else raise 'Unknown protocol type' end -if transport == "buffered" - @transportFactory = Thrift::BufferedTransportFactory.new -elsif transport == "" +if transport == "buffered" || transport.to_s.strip.empty? @transportFactory = Thrift::BufferedTransportFactory.new elsif transport == "framed" @transportFactory = Thrift::FramedTransportFactory.new @@ -152,8 +157,32 @@ else raise 'Unknown transport type' end -@handler = SimpleHandler.new +@handler = SimpleHandler.new @processor = Thrift::Test::ThriftTest::Processor.new(@handler) -@transport = Thrift::ServerSocket.new(port) -@server = Thrift::ThreadedServer.new(@processor, @transport, @transportFactory, @protocolFactory) +@transport = nil +if domain_socket.to_s.strip.empty? + if ssl + # the working directory for ruby crosstest is test/rb/gen-rb + keysDir = File.join(File.dirname(File.dirname(Dir.pwd)), "keys") + ctx = OpenSSL::SSL::SSLContext.new + ctx.ca_file = File.join(keysDir, "CA.pem") + ctx.cert = OpenSSL::X509::Certificate.new(File.open(File.join(keysDir, "server.crt"))) + ctx.cert_store = OpenSSL::X509::Store.new + ctx.cert_store.add_file(File.join(keysDir, 'client.pem')) + ctx.key = OpenSSL::PKey::RSA.new(File.open(File.join(keysDir, "server.key"))) + ctx.options = OpenSSL::SSL::OP_NO_SSLv2 | OpenSSL::SSL::OP_NO_SSLv3 + ctx.ssl_version = :SSLv23 + ctx.verify_mode = OpenSSL::SSL::VERIFY_PEER + @transport = Thrift::SSLServerSocket.new(nil, port, ctx) + else + @transport = Thrift::ServerSocket.new(port) + end +else + @transport = Thrift::UNIXServerSocket.new(domain_socket) +end + +@server = Thrift::ThreadedServer.new(@processor, @transport, @transportFactory, @protocolFactory) + +puts "Starting TestServer #{@server.to_s}" @server.serve +puts "done." diff --git a/vendor/git.apache.org/thrift.git/test/rs/Cargo.toml b/vendor/git.apache.org/thrift.git/test/rs/Cargo.toml new file mode 100644 index 0000000..9b35e3c --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/rs/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "thrift-test" +version = "0.1.0" +license = "Apache-2.0" +authors = ["Apache Thrift Developers "] +publish = false + +[dependencies] +clap = "<2.28.0" +env_logger = "0.4.0" +log = "0.3.7" +ordered-float = "0.3.0" +try_from = "0.2.0" + +[dependencies.thrift] +path = "../../lib/rs" + diff --git a/vendor/git.apache.org/thrift.git/test/rs/Makefile.am b/vendor/git.apache.org/thrift.git/test/rs/Makefile.am new file mode 100644 index 0000000..54905b4 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/rs/Makefile.am @@ -0,0 +1,40 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +stubs: ../ThriftTest.thrift + $(THRIFT) -I ./thrifts -out src --gen rs ../ThriftTest.thrift + +precross: stubs + $(CARGO) build + [ -d bin ] || mkdir bin + cp target/debug/test_server bin/test_server + cp target/debug/test_client bin/test_client + +clean-local: + $(CARGO) clean + -$(RM) Cargo.lock + -$(RM) src/thrift_test.rs + -$(RM) -r bin + +EXTRA_DIST = \ + Cargo.toml \ + src/lib.rs \ + src/bin/test_server.rs \ + src/bin/test_client.rs + diff --git a/vendor/git.apache.org/thrift.git/test/rs/src/bin/test_client.rs b/vendor/git.apache.org/thrift.git/test/rs/src/bin/test_client.rs new file mode 100644 index 0000000..29b5b88 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/rs/src/bin/test_client.rs @@ -0,0 +1,605 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +#[macro_use] +extern crate log; +extern crate env_logger; + +#[macro_use] +extern crate clap; +extern crate ordered_float; +extern crate thrift; +extern crate thrift_test; // huh. I have to do this to use my lib + +use ordered_float::OrderedFloat; +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt::Debug; + +use thrift::protocol::{TBinaryInputProtocol, TBinaryOutputProtocol, TCompactInputProtocol, + TCompactOutputProtocol, TInputProtocol, TMultiplexedOutputProtocol, + TOutputProtocol}; +use thrift::transport::{ReadHalf, TBufferedReadTransport, TBufferedWriteTransport, + TFramedReadTransport, TFramedWriteTransport, TIoChannel, TReadTransport, + TTcpChannel, TWriteTransport, WriteHalf}; +use thrift_test::*; + +fn main() { + env_logger::init().expect("logger setup failed"); + + debug!("initialized logger - running cross-test client"); + + match run() { + Ok(()) => info!("cross-test client succeeded"), + Err(e) => { + info!("cross-test client failed with error {:?}", e); + std::process::exit(1); + } + } +} + +fn run() -> thrift::Result<()> { + // unsupported options: + // --domain-socket + // --named-pipe + // --anon-pipes + // --ssl + // --threads + let matches = clap_app!(rust_test_client => + (version: "1.0") + (author: "Apache Thrift Developers ") + (about: "Rust Thrift test client") + (@arg host: --host +takes_value "Host on which the Thrift test server is located") + (@arg port: --port +takes_value "Port on which the Thrift test server is listening") + (@arg transport: --transport +takes_value "Thrift transport implementation to use (\"buffered\", \"framed\")") + (@arg protocol: --protocol +takes_value "Thrift protocol implementation to use (\"binary\", \"compact\")") + (@arg testloops: -n --testloops +takes_value "Number of times to run tests") + ) + .get_matches(); + + let host = matches.value_of("host").unwrap_or("127.0.0.1"); + let port = value_t!(matches, "port", u16).unwrap_or(9090); + let testloops = value_t!(matches, "testloops", u8).unwrap_or(1); + let transport = matches.value_of("transport").unwrap_or("buffered"); + let protocol = matches.value_of("protocol").unwrap_or("binary"); + + + let mut thrift_test_client = { + let (i_prot, o_prot) = build_protocols(host, port, transport, protocol, "ThriftTest")?; + ThriftTestSyncClient::new(i_prot, o_prot) + }; + + let mut second_service_client = if protocol.starts_with("multi") { + let (i_prot, o_prot) = build_protocols(host, port, transport, protocol, "SecondService")?; + Some(SecondServiceSyncClient::new(i_prot, o_prot)) + } else { + None + }; + + info!( + "connecting to {}:{} with {}+{} stack", + host, + port, + protocol, + transport + ); + + for _ in 0..testloops { + make_thrift_calls(&mut thrift_test_client, &mut second_service_client)? + } + + Ok(()) +} + +fn build_protocols( + host: &str, + port: u16, + transport: &str, + protocol: &str, + service_name: &str, +) -> thrift::Result<(Box, Box)> { + let (i_chan, o_chan) = tcp_channel(host, port)?; + + let (i_tran, o_tran): (Box, Box) = match transport { + "buffered" => { + (Box::new(TBufferedReadTransport::new(i_chan)), + Box::new(TBufferedWriteTransport::new(o_chan))) + } + "framed" => { + (Box::new(TFramedReadTransport::new(i_chan)), + Box::new(TFramedWriteTransport::new(o_chan))) + } + unmatched => return Err(format!("unsupported transport {}", unmatched).into()), + }; + + let (i_prot, o_prot): (Box, Box) = match protocol { + "binary" => { + (Box::new(TBinaryInputProtocol::new(i_tran, true)), + Box::new(TBinaryOutputProtocol::new(o_tran, true))) + } + "multi" => { + (Box::new(TBinaryInputProtocol::new(i_tran, true)), + Box::new( + TMultiplexedOutputProtocol::new( + service_name, + TBinaryOutputProtocol::new(o_tran, true), + ), + )) + } + "compact" => { + (Box::new(TCompactInputProtocol::new(i_tran)), + Box::new(TCompactOutputProtocol::new(o_tran))) + } + "multic" => { + (Box::new(TCompactInputProtocol::new(i_tran)), + Box::new(TMultiplexedOutputProtocol::new(service_name, TCompactOutputProtocol::new(o_tran)),)) + } + unmatched => return Err(format!("unsupported protocol {}", unmatched).into()), + }; + + Ok((i_prot, o_prot)) +} + +// FIXME: expose "open" through the client interface so I don't have to early +// open +fn tcp_channel( + host: &str, + port: u16, +) -> thrift::Result<(ReadHalf, WriteHalf)> { + let mut c = TTcpChannel::new(); + c.open(&format!("{}:{}", host, port))?; + c.split() +} + +type BuildThriftTestClient = ThriftTestSyncClient, Box>; +type BuiltSecondServiceClient = SecondServiceSyncClient, Box>; + +#[cfg_attr(feature = "cargo-clippy", allow(cyclomatic_complexity))] +fn make_thrift_calls( + thrift_test_client: &mut BuildThriftTestClient, + second_service_client: &mut Option, +) -> Result<(), thrift::Error> { + info!("testVoid"); + thrift_test_client.test_void()?; + + info!("testString"); + verify_expected_result( + thrift_test_client.test_string("thing".to_owned()), + "thing".to_owned(), + )?; + + info!("testBool"); + verify_expected_result(thrift_test_client.test_bool(true), true)?; + + info!("testBool"); + verify_expected_result(thrift_test_client.test_bool(false), false)?; + + info!("testByte"); + verify_expected_result(thrift_test_client.test_byte(42), 42)?; + + info!("testi32"); + verify_expected_result(thrift_test_client.test_i32(1159348374), 1159348374)?; + + info!("testi64"); + // try!(verify_expected_result(thrift_test_client.test_i64(-8651829879438294565), + // -8651829879438294565)); + verify_expected_result( + thrift_test_client.test_i64(i64::min_value()), + i64::min_value(), + )?; + + info!("testDouble"); + verify_expected_result( + thrift_test_client.test_double(OrderedFloat::from(42.42)), + OrderedFloat::from(42.42), + )?; + + info!("testTypedef"); + { + let u_snd: UserId = 2348; + let u_cmp: UserId = 2348; + verify_expected_result(thrift_test_client.test_typedef(u_snd), u_cmp)?; + } + + info!("testEnum"); + { + verify_expected_result(thrift_test_client.test_enum(Numberz::Two), Numberz::Two)?; + } + + info!("testBinary"); + { + let b_snd = vec![0x77, 0x30, 0x30, 0x74, 0x21, 0x20, 0x52, 0x75, 0x73, 0x74]; + let b_cmp = vec![0x77, 0x30, 0x30, 0x74, 0x21, 0x20, 0x52, 0x75, 0x73, 0x74]; + verify_expected_result(thrift_test_client.test_binary(b_snd), b_cmp)?; + } + + info!("testStruct"); + { + let x_snd = Xtruct { + string_thing: Some("foo".to_owned()), + byte_thing: Some(12), + i32_thing: Some(219129), + i64_thing: Some(12938492818), + }; + let x_cmp = Xtruct { + string_thing: Some("foo".to_owned()), + byte_thing: Some(12), + i32_thing: Some(219129), + i64_thing: Some(12938492818), + }; + verify_expected_result(thrift_test_client.test_struct(x_snd), x_cmp)?; + } + + // Xtruct again, with optional values + // FIXME: apparently the erlang thrift server does not like opt-in-req-out + // parameters that are undefined. Joy. + // { + // let x_snd = Xtruct { string_thing: Some("foo".to_owned()), byte_thing: None, + // i32_thing: None, i64_thing: Some(12938492818) }; + // let x_cmp = Xtruct { string_thing: Some("foo".to_owned()), byte_thing: + // Some(0), i32_thing: Some(0), i64_thing: Some(12938492818) }; // the C++ + // server is responding correctly + // try!(verify_expected_result(thrift_test_client.test_struct(x_snd), x_cmp)); + // } + // + + info!("testNest"); // (FIXME: try Xtruct2 with optional values) + { + let x_snd = Xtruct2 { + byte_thing: Some(32), + struct_thing: Some( + Xtruct { + string_thing: Some("foo".to_owned()), + byte_thing: Some(1), + i32_thing: Some(324382098), + i64_thing: Some(12938492818), + }, + ), + i32_thing: Some(293481098), + }; + let x_cmp = Xtruct2 { + byte_thing: Some(32), + struct_thing: Some( + Xtruct { + string_thing: Some("foo".to_owned()), + byte_thing: Some(1), + i32_thing: Some(324382098), + i64_thing: Some(12938492818), + }, + ), + i32_thing: Some(293481098), + }; + verify_expected_result(thrift_test_client.test_nest(x_snd), x_cmp)?; + } + + // do the multiplexed calls while making the main ThriftTest calls + if let Some(ref mut client) = second_service_client.as_mut() { + info!("SecondService secondtestString"); + { + verify_expected_result( + client.secondtest_string("test_string".to_owned()), + "testString(\"test_string\")".to_owned(), + )?; + } + } + + info!("testList"); + { + let mut v_snd: Vec = Vec::new(); + v_snd.push(29384); + v_snd.push(238); + v_snd.push(32498); + + let mut v_cmp: Vec = Vec::new(); + v_cmp.push(29384); + v_cmp.push(238); + v_cmp.push(32498); + + verify_expected_result(thrift_test_client.test_list(v_snd), v_cmp)?; + } + + info!("testSet"); + { + let mut s_snd: BTreeSet = BTreeSet::new(); + s_snd.insert(293481); + s_snd.insert(23); + s_snd.insert(3234); + + let mut s_cmp: BTreeSet = BTreeSet::new(); + s_cmp.insert(293481); + s_cmp.insert(23); + s_cmp.insert(3234); + + verify_expected_result(thrift_test_client.test_set(s_snd), s_cmp)?; + } + + info!("testMap"); + { + let mut m_snd: BTreeMap = BTreeMap::new(); + m_snd.insert(2, 4); + m_snd.insert(4, 6); + m_snd.insert(8, 7); + + let mut m_cmp: BTreeMap = BTreeMap::new(); + m_cmp.insert(2, 4); + m_cmp.insert(4, 6); + m_cmp.insert(8, 7); + + verify_expected_result(thrift_test_client.test_map(m_snd), m_cmp)?; + } + + info!("testStringMap"); + { + let mut m_snd: BTreeMap = BTreeMap::new(); + m_snd.insert("2".to_owned(), "4_string".to_owned()); + m_snd.insert("4".to_owned(), "6_string".to_owned()); + m_snd.insert("8".to_owned(), "7_string".to_owned()); + + let mut m_rcv: BTreeMap = BTreeMap::new(); + m_rcv.insert("2".to_owned(), "4_string".to_owned()); + m_rcv.insert("4".to_owned(), "6_string".to_owned()); + m_rcv.insert("8".to_owned(), "7_string".to_owned()); + + verify_expected_result(thrift_test_client.test_string_map(m_snd), m_rcv)?; + } + + // nested map + // expect : {-4 => {-4 => -4, -3 => -3, -2 => -2, -1 => -1, }, 4 => {1 => 1, 2 + // => 2, 3 => 3, 4 => 4, }, } + info!("testMapMap"); + { + let mut m_cmp_nested_0: BTreeMap = BTreeMap::new(); + for i in (-4 as i32)..0 { + m_cmp_nested_0.insert(i, i); + } + let mut m_cmp_nested_1: BTreeMap = BTreeMap::new(); + for i in 1..5 { + m_cmp_nested_1.insert(i, i); + } + + let mut m_cmp: BTreeMap> = BTreeMap::new(); + m_cmp.insert(-4, m_cmp_nested_0); + m_cmp.insert(4, m_cmp_nested_1); + + verify_expected_result(thrift_test_client.test_map_map(42), m_cmp)?; + } + + info!("testMulti"); + { + let mut m_snd: BTreeMap = BTreeMap::new(); + m_snd.insert(1298, "fizz".to_owned()); + m_snd.insert(-148, "buzz".to_owned()); + + let s_cmp = Xtruct { + string_thing: Some("Hello2".to_owned()), + byte_thing: Some(1), + i32_thing: Some(-123948), + i64_thing: Some(-19234123981), + }; + + verify_expected_result( + thrift_test_client.test_multi(1, -123948, -19234123981, m_snd, Numberz::Eight, 81), + s_cmp, + )?; + } + + // Insanity + // returns: + // { 1 => { 2 => argument, + // 3 => argument, + // }, + // 2 => { 6 => , }, + // } + { + let mut arg_map_usermap: BTreeMap = BTreeMap::new(); + arg_map_usermap.insert(Numberz::One, 4289); + arg_map_usermap.insert(Numberz::Eight, 19); + + let mut arg_vec_xtructs: Vec = Vec::new(); + arg_vec_xtructs.push( + Xtruct { + string_thing: Some("foo".to_owned()), + byte_thing: Some(8), + i32_thing: Some(29), + i64_thing: Some(92384), + }, + ); + arg_vec_xtructs.push( + Xtruct { + string_thing: Some("bar".to_owned()), + byte_thing: Some(28), + i32_thing: Some(2), + i64_thing: Some(-1281), + }, + ); + arg_vec_xtructs.push( + Xtruct { + string_thing: Some("baz".to_owned()), + byte_thing: Some(0), + i32_thing: Some(3948539), + i64_thing: Some(-12938492), + }, + ); + + let mut s_cmp_nested_1: BTreeMap = BTreeMap::new(); + let insanity = Insanity { + user_map: Some(arg_map_usermap), + xtructs: Some(arg_vec_xtructs), + }; + s_cmp_nested_1.insert(Numberz::Two, insanity.clone()); + s_cmp_nested_1.insert(Numberz::Three, insanity.clone()); + + let mut s_cmp_nested_2: BTreeMap = BTreeMap::new(); + let empty_insanity = Insanity { + user_map: Some(BTreeMap::new()), + xtructs: Some(Vec::new()), + }; + s_cmp_nested_2.insert(Numberz::Six, empty_insanity); + + let mut s_cmp: BTreeMap> = BTreeMap::new(); + s_cmp.insert(1 as UserId, s_cmp_nested_1); + s_cmp.insert(2 as UserId, s_cmp_nested_2); + + verify_expected_result(thrift_test_client.test_insanity(insanity.clone()), s_cmp)?; + } + + info!("testException - remote throws Xception"); + { + let r = thrift_test_client.test_exception("Xception".to_owned()); + let x = match r { + Err(thrift::Error::User(ref e)) => { + match e.downcast_ref::() { + Some(x) => Ok(x), + None => Err(thrift::Error::User("did not get expected Xception struct".into()),), + } + } + _ => Err(thrift::Error::User("did not get exception".into())), + }?; + + let x_cmp = Xception { + error_code: Some(1001), + message: Some("Xception".to_owned()), + }; + + verify_expected_result(Ok(x), &x_cmp)?; + } + + info!("testException - remote throws TApplicationException"); + { + let r = thrift_test_client.test_exception("TException".to_owned()); + match r { + Err(thrift::Error::Application(ref e)) => { + info!("received an {:?}", e); + Ok(()) + } + _ => Err(thrift::Error::User("did not get exception".into())), + }?; + } + + info!("testException - remote succeeds"); + { + let r = thrift_test_client.test_exception("foo".to_owned()); + match r { + Ok(_) => Ok(()), + _ => Err(thrift::Error::User("received an exception".into())), + }?; + } + + info!("testMultiException - remote throws Xception"); + { + let r = + thrift_test_client.test_multi_exception("Xception".to_owned(), "ignored".to_owned()); + let x = match r { + Err(thrift::Error::User(ref e)) => { + match e.downcast_ref::() { + Some(x) => Ok(x), + None => Err(thrift::Error::User("did not get expected Xception struct".into()),), + } + } + _ => Err(thrift::Error::User("did not get exception".into())), + }?; + + let x_cmp = Xception { + error_code: Some(1001), + message: Some("This is an Xception".to_owned()), + }; + + verify_expected_result(Ok(x), &x_cmp)?; + } + + info!("testMultiException - remote throws Xception2"); + { + let r = + thrift_test_client.test_multi_exception("Xception2".to_owned(), "ignored".to_owned()); + let x = match r { + Err(thrift::Error::User(ref e)) => { + match e.downcast_ref::() { + Some(x) => Ok(x), + None => Err(thrift::Error::User("did not get expected Xception struct".into()),), + } + } + _ => Err(thrift::Error::User("did not get exception".into())), + }?; + + let x_cmp = Xception2 { + error_code: Some(2002), + struct_thing: Some( + Xtruct { + string_thing: Some("This is an Xception2".to_owned()), + // since this is an OPT_IN_REQ_OUT field the sender sets a default + byte_thing: Some(0), + // since this is an OPT_IN_REQ_OUT field the sender sets a default + i32_thing: Some(0), + // since this is an OPT_IN_REQ_OUT field the sender sets a default + i64_thing: Some(0), + }, + ), + }; + + verify_expected_result(Ok(x), &x_cmp)?; + } + + info!("testMultiException - remote succeeds"); + { + let r = thrift_test_client.test_multi_exception("haha".to_owned(), "RETURNED".to_owned()); + let x = match r { + Err(e) => Err(thrift::Error::User(format!("received an unexpected exception {:?}", e).into(),),), + _ => r, + }?; + + let x_cmp = Xtruct { + string_thing: Some("RETURNED".to_owned()), + // since this is an OPT_IN_REQ_OUT field the sender sets a default + byte_thing: Some(0), + // since this is an OPT_IN_REQ_OUT field the sender sets a default + i32_thing: Some(0), + // since this is an OPT_IN_REQ_OUT field the sender sets a default + i64_thing: Some(0), + }; + + verify_expected_result(Ok(x), x_cmp)?; + } + + info!("testOneWay - remote sleeps for 1 second"); + { + thrift_test_client.test_oneway(1)?; + } + + // final test to verify that the connection is still writable after the one-way + // call + thrift_test_client.test_void() +} + +#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))] +fn verify_expected_result( + actual: Result, + expected: T, +) -> Result<(), thrift::Error> { + info!("*** EXPECTED: Ok({:?})", expected); + info!("*** ACTUAL : {:?}", actual); + match actual { + Ok(v) => { + if v == expected { + info!("*** OK ***"); + Ok(()) + } else { + info!("*** FAILED ***"); + Err(thrift::Error::User(format!("expected {:?} but got {:?}", &expected, &v).into()),) + } + } + Err(e) => Err(e), + } +} diff --git a/vendor/git.apache.org/thrift.git/test/rs/src/bin/test_server.rs b/vendor/git.apache.org/thrift.git/test/rs/src/bin/test_server.rs new file mode 100644 index 0000000..81c1ec7 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/rs/src/bin/test_server.rs @@ -0,0 +1,398 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +#[macro_use] +extern crate log; +extern crate env_logger; + +#[macro_use] +extern crate clap; +extern crate ordered_float; +extern crate thrift; +extern crate thrift_test; + +use ordered_float::OrderedFloat; +use std::collections::{BTreeMap, BTreeSet}; +use std::thread; +use std::time::Duration; + +use thrift::protocol::{TBinaryInputProtocolFactory, TBinaryOutputProtocolFactory, + TCompactInputProtocolFactory, TCompactOutputProtocolFactory, + TInputProtocolFactory, TOutputProtocolFactory}; +use thrift::server::{TMultiplexedProcessor, TServer}; +use thrift::transport::{TBufferedReadTransportFactory, TBufferedWriteTransportFactory, + TFramedReadTransportFactory, TFramedWriteTransportFactory, + TReadTransportFactory, TWriteTransportFactory}; +use thrift_test::*; + +fn main() { + env_logger::init().expect("logger setup failed"); + + debug!("initialized logger - running cross-test server"); + + match run() { + Ok(()) => info!("cross-test server succeeded"), + Err(e) => { + info!("cross-test server failed with error {:?}", e); + std::process::exit(1); + } + } +} + +fn run() -> thrift::Result<()> { + + // unsupported options: + // --domain-socket + // --named-pipe + // --ssl + let matches = clap_app!(rust_test_client => + (version: "1.0") + (author: "Apache Thrift Developers ") + (about: "Rust Thrift test server") + (@arg port: --port +takes_value "port on which the test server listens") + (@arg transport: --transport +takes_value "transport implementation to use (\"buffered\", \"framed\")") + (@arg protocol: --protocol +takes_value "protocol implementation to use (\"binary\", \"compact\")") + (@arg server_type: --server_type +takes_value "type of server instantiated (\"simple\", \"thread-pool\")") + (@arg workers: -n --workers +takes_value "number of thread-pool workers (\"4\")") + ) + .get_matches(); + + let port = value_t!(matches, "port", u16).unwrap_or(9090); + let transport = matches.value_of("transport").unwrap_or("buffered"); + let protocol = matches.value_of("protocol").unwrap_or("binary"); + let server_type = matches.value_of("server_type").unwrap_or("thread-pool"); + let workers = value_t!(matches, "workers", usize).unwrap_or(4); + let listen_address = format!("127.0.0.1:{}", port); + + info!("binding to {}", listen_address); + + let (i_transport_factory, o_transport_factory): (Box, + Box) = + match &*transport { + "buffered" => { + (Box::new(TBufferedReadTransportFactory::new()), + Box::new(TBufferedWriteTransportFactory::new())) + } + "framed" => { + (Box::new(TFramedReadTransportFactory::new()), + Box::new(TFramedWriteTransportFactory::new())) + } + unknown => { + return Err(format!("unsupported transport type {}", unknown).into()); + } + }; + + let (i_protocol_factory, o_protocol_factory): (Box, + Box) = + match &*protocol { + "binary" | "multi" | "multi:binary" => { + (Box::new(TBinaryInputProtocolFactory::new()), + Box::new(TBinaryOutputProtocolFactory::new())) + } + "compact" | "multic" | "multi:compact" => { + (Box::new(TCompactInputProtocolFactory::new()), + Box::new(TCompactOutputProtocolFactory::new())) + } + unknown => { + return Err(format!("unsupported transport type {}", unknown).into()); + } + }; + + let test_processor = ThriftTestSyncProcessor::new(ThriftTestSyncHandlerImpl {}); + + match &*server_type { + "simple" | "thread-pool" => { + if protocol == "multi" || protocol == "multic" { + let second_service_processor = SecondServiceSyncProcessor::new(SecondServiceSyncHandlerImpl {},); + + let mut multiplexed_processor = TMultiplexedProcessor::new(); + multiplexed_processor + .register("ThriftTest", Box::new(test_processor), true)?; + multiplexed_processor + .register("SecondService", Box::new(second_service_processor), false)?; + + let mut server = TServer::new( + i_transport_factory, + i_protocol_factory, + o_transport_factory, + o_protocol_factory, + multiplexed_processor, + workers, + ); + + server.listen(&listen_address) + } else { + let mut server = TServer::new( + i_transport_factory, + i_protocol_factory, + o_transport_factory, + o_protocol_factory, + test_processor, + workers, + ); + + server.listen(&listen_address) + } + } + unknown => Err(format!("unsupported server type {}", unknown).into()), + } +} + +struct ThriftTestSyncHandlerImpl; +impl ThriftTestSyncHandler for ThriftTestSyncHandlerImpl { + fn handle_test_void(&self) -> thrift::Result<()> { + info!("testVoid()"); + Ok(()) + } + + fn handle_test_string(&self, thing: String) -> thrift::Result { + info!("testString({})", &thing); + Ok(thing) + } + + fn handle_test_bool(&self, thing: bool) -> thrift::Result { + info!("testBool({})", thing); + Ok(thing) + } + + fn handle_test_byte(&self, thing: i8) -> thrift::Result { + info!("testByte({})", thing); + Ok(thing) + } + + fn handle_test_i32(&self, thing: i32) -> thrift::Result { + info!("testi32({})", thing); + Ok(thing) + } + + fn handle_test_i64(&self, thing: i64) -> thrift::Result { + info!("testi64({})", thing); + Ok(thing) + } + + fn handle_test_double(&self, thing: OrderedFloat) -> thrift::Result> { + info!("testDouble({})", thing); + Ok(thing) + } + + fn handle_test_binary(&self, thing: Vec) -> thrift::Result> { + info!("testBinary({:?})", thing); + Ok(thing) + } + + fn handle_test_struct(&self, thing: Xtruct) -> thrift::Result { + info!("testStruct({:?})", thing); + Ok(thing) + } + + fn handle_test_nest(&self, thing: Xtruct2) -> thrift::Result { + info!("testNest({:?})", thing); + Ok(thing) + } + + fn handle_test_map(&self, thing: BTreeMap) -> thrift::Result> { + info!("testMap({:?})", thing); + Ok(thing) + } + + fn handle_test_string_map( + &self, + thing: BTreeMap, + ) -> thrift::Result> { + info!("testStringMap({:?})", thing); + Ok(thing) + } + + fn handle_test_set(&self, thing: BTreeSet) -> thrift::Result> { + info!("testSet({:?})", thing); + Ok(thing) + } + + fn handle_test_list(&self, thing: Vec) -> thrift::Result> { + info!("testList({:?})", thing); + Ok(thing) + } + + fn handle_test_enum(&self, thing: Numberz) -> thrift::Result { + info!("testEnum({:?})", thing); + Ok(thing) + } + + fn handle_test_typedef(&self, thing: UserId) -> thrift::Result { + info!("testTypedef({})", thing); + Ok(thing) + } + + /// @return map> - returns a dictionary with these values: + /// {-4 => {-4 => -4, -3 => -3, -2 => -2, -1 => -1, }, 4 => {1 => 1, 2 => + /// 2, 3 => 3, 4 => 4, }, } + fn handle_test_map_map(&self, hello: i32) -> thrift::Result>> { + info!("testMapMap({})", hello); + + let mut inner_map_0: BTreeMap = BTreeMap::new(); + for i in -4..(0 as i32) { + inner_map_0.insert(i, i); + } + + let mut inner_map_1: BTreeMap = BTreeMap::new(); + for i in 1..5 { + inner_map_1.insert(i, i); + } + + let mut ret_map: BTreeMap> = BTreeMap::new(); + ret_map.insert(-4, inner_map_0); + ret_map.insert(4, inner_map_1); + + Ok(ret_map) + } + + /// Creates a the returned map with these values and prints it out: + /// { 1 => { 2 => argument, + /// 3 => argument, + /// }, + /// 2 => { 6 => , }, + /// } + /// return map> - a map with the above values + fn handle_test_insanity( + &self, + argument: Insanity, + ) -> thrift::Result>> { + info!("testInsanity({:?})", argument); + let mut map_0: BTreeMap = BTreeMap::new(); + map_0.insert(Numberz::Two, argument.clone()); + map_0.insert(Numberz::Three, argument.clone()); + + let mut map_1: BTreeMap = BTreeMap::new(); + let insanity = Insanity { + user_map: None, + xtructs: None, + }; + map_1.insert(Numberz::Six, insanity); + + let mut ret: BTreeMap> = BTreeMap::new(); + ret.insert(1, map_0); + ret.insert(2, map_1); + + Ok(ret) + } + + /// returns an Xtruct with: + /// string_thing = "Hello2", byte_thing = arg0, i32_thing = arg1 and + /// i64_thing = arg2 + fn handle_test_multi( + &self, + arg0: i8, + arg1: i32, + arg2: i64, + _: BTreeMap, + _: Numberz, + _: UserId, + ) -> thrift::Result { + let x_ret = Xtruct { + string_thing: Some("Hello2".to_owned()), + byte_thing: Some(arg0), + i32_thing: Some(arg1), + i64_thing: Some(arg2), + }; + + Ok(x_ret) + } + + /// if arg == "Xception" throw Xception with errorCode = 1001 and message = + /// arg + /// else if arg == "TException" throw TException + /// else do not throw anything + fn handle_test_exception(&self, arg: String) -> thrift::Result<()> { + info!("testException({})", arg); + + match &*arg { + "Xception" => { + Err( + (Xception { + error_code: Some(1001), + message: Some(arg), + }) + .into(), + ) + } + "TException" => Err("this is a random error".into()), + _ => Ok(()), + } + } + + /// if arg0 == "Xception": + /// throw Xception with errorCode = 1001 and message = "This is an + /// Xception" + /// else if arg0 == "Xception2": + /// throw Xception2 with errorCode = 2002 and struct_thing.string_thing = + /// "This is an Xception2" + // else: + // do not throw anything and return Xtruct with string_thing = arg1 + fn handle_test_multi_exception(&self, arg0: String, arg1: String) -> thrift::Result { + match &*arg0 { + "Xception" => { + Err( + (Xception { + error_code: Some(1001), + message: Some("This is an Xception".to_owned()), + }) + .into(), + ) + } + "Xception2" => { + Err( + (Xception2 { + error_code: Some(2002), + struct_thing: Some( + Xtruct { + string_thing: Some("This is an Xception2".to_owned()), + byte_thing: None, + i32_thing: None, + i64_thing: None, + }, + ), + }) + .into(), + ) + } + _ => { + Ok( + Xtruct { + string_thing: Some(arg1), + byte_thing: None, + i32_thing: None, + i64_thing: None, + }, + ) + } + } + } + + fn handle_test_oneway(&self, seconds_to_sleep: i32) -> thrift::Result<()> { + thread::sleep(Duration::from_secs(seconds_to_sleep as u64)); + Ok(()) + } +} + +struct SecondServiceSyncHandlerImpl; +impl SecondServiceSyncHandler for SecondServiceSyncHandlerImpl { + fn handle_secondtest_string(&self, thing: String) -> thrift::Result { + info!("(second)testString({})", &thing); + let ret = format!("testString(\"{}\")", &thing); + Ok(ret) + } +} diff --git a/vendor/git.apache.org/thrift.git/test/rs/src/lib.rs b/vendor/git.apache.org/thrift.git/test/rs/src/lib.rs new file mode 100644 index 0000000..479bf90 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/test/rs/src/lib.rs @@ -0,0 +1,23 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +extern crate ordered_float; +extern crate thrift; +extern crate try_from; + +mod thrift_test; +pub use thrift_test::*; diff --git a/vendor/git.apache.org/thrift.git/test/test.py b/vendor/git.apache.org/thrift.git/test/test.py index 9305967..f59256a 100755 --- a/vendor/git.apache.org/thrift.git/test/test.py +++ b/vendor/git.apache.org/thrift.git/test/test.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file @@ -18,12 +18,13 @@ # under the License. # -# Apache Thrift - integration test suite +# +# Apache Thrift - integration (cross) test suite # # tests different server-client, protocol and transport combinations # -# This script supports python 2.7 and later. -# python 3.x is recommended for better stability. +# This script requires python 3.x due to the improvements in +# subprocess management that are needed for reliability. # from __future__ import print_function @@ -38,6 +39,12 @@ import sys import crossrunner from crossrunner.compat import path_join +# 3.3 introduced subprocess timeouts on waiting for child +req_version = (3, 3) +cur_version = sys.version_info +assert (cur_version >= req_version), "Python 3.3 or later is required for proper operation." + + ROOT_DIR = os.path.dirname(os.path.realpath(os.path.dirname(__file__))) TEST_DIR_RELATIVE = 'test' TEST_DIR = path_join(ROOT_DIR, TEST_DIR_RELATIVE) @@ -45,7 +52,7 @@ FEATURE_DIR_RELATIVE = path_join(TEST_DIR_RELATIVE, 'features') CONFIG_FILE = 'tests.json' -def run_cross_tests(server_match, client_match, jobs, skip_known_failures, retry_count, regex): +def run_cross_tests(server_match, client_match, jobs, skip_known_failures, only_known_failures, retry_count, regex): logger = multiprocessing.get_logger() logger.debug('Collecting tests') with open(path_join(TEST_DIR, CONFIG_FILE), 'r') as fp: @@ -56,6 +63,10 @@ def run_cross_tests(server_match, client_match, jobs, skip_known_failures, retry print(' servers: %s' % server_match, file=sys.stderr) print(' clients: %s' % client_match, file=sys.stderr) return False + if only_known_failures: + logger.debug('Only running known failures') + known = crossrunner.load_known_failures(TEST_DIR) + tests = list(filter(lambda t: crossrunner.test_name(**t) in known, tests)) if skip_known_failures: logger.debug('Skipping known failures') known = crossrunner.load_known_failures(TEST_DIR) @@ -74,7 +85,7 @@ def run_cross_tests(server_match, client_match, jobs, skip_known_failures, retry return False -def run_feature_tests(server_match, feature_match, jobs, skip_known_failures, retry_count, regex): +def run_feature_tests(server_match, feature_match, jobs, skip_known_failures, only_known_failures, retry_count, regex): basedir = path_join(ROOT_DIR, FEATURE_DIR_RELATIVE) logger = multiprocessing.get_logger() logger.debug('Collecting tests') @@ -88,6 +99,10 @@ def run_feature_tests(server_match, feature_match, jobs, skip_known_failures, re print(' servers: %s' % server_match, file=sys.stderr) print(' features: %s' % feature_match, file=sys.stderr) return False + if only_known_failures: + logger.debug('Only running known failures') + known = crossrunner.load_known_failures(basedir) + tests = list(filter(lambda t: crossrunner.test_name(**t) in known, tests)) if skip_known_failures: logger.debug('Skipping known failures') known = crossrunner.load_known_failures(basedir) @@ -123,6 +138,8 @@ def main(argv): parser.add_argument('-F', '--features', nargs='*', default=None, help='run server feature tests instead of cross language tests') parser.add_argument('-R', '--regex', help='test name pattern to run') + parser.add_argument('-o', '--only-known_failures', action='store_true', dest='only_known_failures', + help='only execute tests that are known to fail') parser.add_argument('-s', '--skip-known-failures', action='store_true', dest='skip_known_failures', help='do not execute tests that are known to fail') parser.add_argument('-r', '--retry-count', type=int, @@ -161,10 +178,15 @@ def main(argv): options.update_failures, options.print_failures) elif options.features is not None: features = options.features or ['.*'] - res = run_feature_tests(server_match, features, options.jobs, options.skip_known_failures, options.retry_count, options.regex) + res = run_feature_tests(server_match, features, options.jobs, + options.skip_known_failures, options.only_known_failures, + options.retry_count, options.regex) else: - res = run_cross_tests(server_match, client_match, options.jobs, options.skip_known_failures, options.retry_count, options.regex) + res = run_cross_tests(server_match, client_match, options.jobs, + options.skip_known_failures, options.only_known_failures, + options.retry_count, options.regex) return 0 if res else 1 + if __name__ == '__main__': sys.exit(main(sys.argv[1:])) diff --git a/vendor/git.apache.org/thrift.git/test/tests.json b/vendor/git.apache.org/thrift.git/test/tests.json index 2460b83..43d6ded 100644 --- a/vendor/git.apache.org/thrift.git/test/tests.json +++ b/vendor/git.apache.org/thrift.git/test/tests.json @@ -6,12 +6,25 @@ ], "server": { "command": [ - "test_server" + "test_server", + "--lt-debug" + ], + "protocols": [ + "binary:multi", + "compact:multic" ] }, "client": { "command": [ - "test_client" + "test_client", + "--lt-debug" + ], + "protocols": [ + "multi:binary", + "multic:compact" + ], + "sockets": [ + "ip-ssl" ] }, "transports": [ @@ -23,15 +36,35 @@ ], "protocols": [ "binary", - "compact" + "compact", + "multi", + "multic" ], "workdir": "c_glib" }, + { + "name": "cl", + "server": { + "command": ["TestServer"], + "workdir": "cl", + "protocols": ["binary", "multi"], + "transports": ["buffered", "framed"], + "sockets": ["ip"] + }, + "client": { + "command": ["TestClient"], + "workdir": "cl", + "protocols": ["binary", "multi"], + "transports": ["buffered", "framed"], + "sockets": ["ip"] + } + }, { "name": "d", "server": { "command": [ - "thrift_test_server" + "thrift_test_server", + "--trace" ] }, "client": { @@ -72,7 +105,8 @@ "transports": [ "buffered", "framed", - "http" + "http", + "zlib" ], "sockets": [ "ip", @@ -87,29 +121,30 @@ }, { "name": "java", - "join_args": true, - "command": [ - "ant", - "-f", - "build.xml", - "-Dno-gen-thrift=\"\"", - "-Dtestargs" - ], - "prepare": [ - "ant", - "-f", - "build.xml", - "compile-test" - ], + "join_args": false, "server": { - "delay": 10, - "extra_args": ["run-testserver"] + "delay": 15, + "command": [ + "build/runserver" + ], + "protocols": [ + "binary:multi", + "compact:multic", + "json:multij" + ] }, "client": { "timeout": 13, - "extra_args": ["run-testclient"], + "command": [ + "build/runclient" + ], "transports": [ "http" + ], + "protocols": [ + "multi:binary", + "multic:compact", + "multij:json" ] }, "transports": [ @@ -118,13 +153,16 @@ "framed:fastframed" ], "sockets": [ - "ip-ssl", - "ip" + "ip", + "ip-ssl" ], "protocols": [ - "compact", "binary", - "json" + "compact", + "json", + "multi", + "multic", + "multij" ], "workdir": "../lib/java" }, @@ -141,7 +179,7 @@ ] }, "client": { - "timeout": 2.9, + "timeout": 6, "command": [ "node", "client.js", @@ -150,11 +188,13 @@ }, "transports": [ "buffered", - "framed" + "framed", + "http" ], "sockets": [ "ip", - "ip-ssl" + "ip-ssl", + "domain" ], "protocols": [ "compact", @@ -187,6 +227,7 @@ "ip" ], "protocols": [ + "header", "compact", "binary", "json" @@ -210,11 +251,20 @@ "--verbose", "--host=localhost", "--genpydir=gen-py" + ], + "protocols": [ + "multi", + "multi:multia", + "multic", + "multic:multiac", + "multij" ] }, "transports": [ "buffered", - "framed" + "framed", + "http", + "zlib" ], "sockets": [ "ip", @@ -225,7 +275,8 @@ "binary", "json", "binary:accel", - "compact:accelc" + "compact:accelc", + "header" ], "workdir": "py" }, @@ -248,22 +299,32 @@ "TestClient.py", "--host=localhost", "--genpydir=gen-py" + ], + "protocols": [ + "multi", + "multi:multia", + "multic", + "multic:multiac", + "multij" ] }, "transports": [ "buffered", - "framed" + "framed", + "http", + "zlib" ], "sockets": [ - "ip-ssl", - "ip" + "ip", + "ip-ssl" ], "protocols": [ "compact", "binary", "json", "binary:accel", - "compact:accelc" + "compact:accelc", + "header" ], "workdir": "py" }, @@ -272,18 +333,31 @@ "server": { "command": [ "TestServer" + ], + "protocols": [ + "binary:multi", + "compact:multic", + "header:multih", + "json:multij" ] }, "client": { "timeout": 8, "command": [ "TestClient" + ], + "protocols": [ + "multi:binary", + "multic:compact", + "multih:header", + "multij:json" ] }, "transports": [ "buffered", "http", - "framed" + "framed", + "zlib" ], "sockets": [ "ip", @@ -294,7 +368,11 @@ "compact", "binary", "json", - "header" + "header", + "multi", + "multic", + "multih", + "multij" ], "workdir": "cpp" }, @@ -310,7 +388,8 @@ "timeout": 5, "command": [ "ruby", - "../integration/TestClient.rb" + "../integration/TestClient.rb", + "--" ] }, "transports": [ @@ -318,13 +397,15 @@ "framed" ], "sockets": [ - "ip" + "domain", + "ip", + "ip-ssl" ], "protocols": [ - "compact", "binary", - "json", - "binary:accel" + "binary:accel", + "compact", + "json" ], "workdir": "rb/gen-rb" }, @@ -359,10 +440,52 @@ "mono", "TestClientServer.exe", "client" + ], + "protocols": [ + "multi", + "multic", + "multi:binary", + "multic:compact" ] }, "workdir": "csharp" }, + { + "name": "netcore", + "transports": [ + "buffered", + "framed" + ], + "sockets": [ + "ip", + "ip-ssl" + ], + "protocols": [ + "binary", + "compact", + "json" + ], + "server": { + "command": [ + "dotnet", + "run", + "--no-build", + "--project=Server/Server.csproj", + "server" + ] + }, + "client": { + "timeout": 10, + "command": [ + "dotnet", + "run", + "--no-build", + "--project=Client/Client.csproj", + "client" + ] + }, + "workdir": "netcore" + }, { "name": "perl", "transports": [ @@ -375,7 +498,8 @@ "domain" ], "protocols": [ - "binary" + "binary", + "multi" ], "client": { "command": [ @@ -383,7 +507,12 @@ "-Igen-perl/", "-I../../lib/perl/lib/", "TestClient.pl", - "--cert=../keys/client.pem" + "--ca=../keys/CA.pem", + "--cert=../keys/client.crt", + "--key=../keys/client.key" + ], + "protocols": [ + "multi:binary" ] }, "server": { @@ -392,8 +521,11 @@ "-Igen-perl/", "-I../../lib/perl/lib/", "TestServer.pl", - "--cert=../keys/server.pem", + "--cert=../keys/server.crt", "--key=../keys/server.key" + ], + "protocols": [ + "binary:multi" ] }, "workdir": "perl" @@ -416,8 +548,8 @@ ], "command": [ "php", - "-dextension_dir=../../lib/php/src/ext/thrift_protocol/modules/", - "--php-ini=../../lib/php/thrift_protocol.ini", + "-dextension_dir=php_ext_dir", + "--php-ini=test_php.ini", "--no-php-ini", "-ddisplay_errors=stderr", "-dlog_errors=0", @@ -546,5 +678,72 @@ ] }, "workdir": "lua" + }, + { + "name": "rs", + "env": { + "RUST_BACKTRACE": "1", + "RUST_LOG": "info" + }, + "server": { + "command": [ + "test_server" + ], + "protocols": [ + "binary:multi", + "compact:multic" + ] + }, + "client": { + "timeout": 6, + "command": [ + "test_client" + ], + "protocols": [ + "multi:binary", + "multic:compact" + ] + }, + "sockets": [ + "ip" + ], + "transports": [ + "buffered", + "framed" + ], + "protocols": [ + "binary", + "compact", + "multi", + "multic" + ], + "workdir": "rs/bin" + }, + { + "name": "nodets", + "env": { + "NODE_PATH": "../lib" + }, + "server": { + "command": [ + "runServer.sh" + ] + }, + "client": { + "timeout": 6, + "command": [ + "runClient.sh" + ] + }, + "protocols": [ + "binary" + ], + "sockets": [ + "ip" + ], + "transports": [ + "buffered" + ], + "workdir": "../lib/nodets/test" } ] diff --git a/vendor/git.apache.org/thrift.git/test/valgrind.suppress b/vendor/git.apache.org/thrift.git/test/valgrind.suppress index 41f9414..de17cb8 100644 --- a/vendor/git.apache.org/thrift.git/test/valgrind.suppress +++ b/vendor/git.apache.org/thrift.git/test/valgrind.suppress @@ -5,5 +5,49 @@ fun:malloc fun:_ZN5boost6detail25get_once_per_thread_epochEv } +{ + boostthreads/once/ignore + Helgrind:Race + fun:_ZN5boost13thread_detail17enter_once_regionERNS_9once_flagE + fun:_ZN5boost6detail23get_current_thread_dataEv + fun:_ZN5boost6detail20interruption_checkerC1EP15pthread_mutex_tP14pthread_cond_t + fun:_ZN5boost22condition_variable_any4waitINS_11unique_lockINS_11timed_mutexEEEEEvRT_ + fun:_ZN6apache6thrift11concurrency7Monitor4Impl11waitForeverEv + fun:_ZN6apache6thrift11concurrency7Monitor4Impl19waitForTimeRelativeEl + fun:_ZN6apache6thrift11concurrency7Monitor4Impl4waitEl + fun:_ZNK6apache6thrift11concurrency7Monitor4waitEl + fun:_ZN6apache6thrift11concurrency11BoostThread5startEv + fun:_ZN6apache6thrift11concurrency4test18ThreadFactoryTests12reapNThreadsEii + fun:main +} +{ + pthread/creation-tls/ignore + Helgrind:Race + fun:mempcpy + fun:_dl_allocate_tls_init + fun:get_cached_stack + fun:allocate_stack + fun:pthread_create@@GLIBC_2.2* + obj:/usr/lib/valgrind/vgpreload_helgrind-amd64-linux.so + fun:_ZN6apache6thrift11concurrency13PthreadThread5startEv + fun:_ZN6apache6thrift11concurrency4test18ThreadFactoryTests12reapNThreadsEii + fun:main +} +{ + boost-thread/creation-tls/ignore + Helgrind:Race + fun:mempcpy + fun:_dl_allocate_tls_init + fun:get_cached_stack + fun:allocate_stack + fun:pthread_create@@GLIBC_2.2.5 + obj:/usr/lib/valgrind/vgpreload_helgrind-amd64-linux.so + fun:_ZN5boost6thread21start_thread_noexceptEv + fun:_ZN5boost6thread12start_threadEv + fun:_ZN5boost6threadC1ISt5_BindIFPFPvS3_ES3_EEEEOT_ + fun:_ZN6apache6thrift11concurrency11BoostThread5startEv + fun:_ZN6apache6thrift11concurrency4test18ThreadFactoryTests12reapNThreadsEii + fun:main +} diff --git a/vendor/git.apache.org/thrift.git/tutorial/Makefile.am b/vendor/git.apache.org/thrift.git/tutorial/Makefile.am index 5865c54..0499460 100755 --- a/vendor/git.apache.org/thrift.git/tutorial/Makefile.am +++ b/vendor/git.apache.org/thrift.git/tutorial/Makefile.am @@ -58,6 +58,10 @@ if WITH_HAXE SUBDIRS += haxe endif +if WITH_DOTNETCORE +SUBDIRS += netcore +endif + if WITH_GO SUBDIRS += go endif @@ -70,6 +74,14 @@ if WITH_DART SUBDIRS += dart endif +if WITH_RS +SUBDIRS += rs +endif + +if WITH_CL +SUBDIRS += cl +endif + # # generate html for ThriftTest.thrift # diff --git a/vendor/git.apache.org/thrift.git/tutorial/c_glib/Makefile.am b/vendor/git.apache.org/thrift.git/tutorial/c_glib/Makefile.am index 565f635..4dbe655 100755 --- a/vendor/git.apache.org/thrift.git/tutorial/c_glib/Makefile.am +++ b/vendor/git.apache.org/thrift.git/tutorial/c_glib/Makefile.am @@ -24,11 +24,9 @@ BUILT_SOURCES = \ gen-c_glib/shared_types.h \ gen-c_glib/tutorial_types.h -AM_CFLAGS = -g -Wall -Wextra -pedantic $(GLIB_CFLAGS) $(GOBJECT_CFLAGS) @GCOV_CFLAGS@ +AM_CFLAGS = -g -Wall -Wextra -pedantic $(GLIB_CFLAGS) $(GOBJECT_CFLAGS) $(OPENSSL_INCLUDES) @GCOV_CFLAGS@ AM_CPPFLAGS = -I$(top_srcdir)/lib/c_glib/src -Igen-c_glib -AM_LDFLAGS = $(GLIB_LIBS) $(GOBJECT_LIBS) @GCOV_LDFLAGS@ - -THRIFT = $(top_builddir)/compiler/cpp/thrift +AM_LDFLAGS = $(GLIB_LIBS) $(GOBJECT_LIBS) $(OPENSSL_LDFLAGS) $(OPENSSL_LIBS) @GCOV_LDFLAGS@ noinst_LTLIBRARIES = \ libtutorialgencglib.la @@ -55,6 +53,7 @@ noinst_PROGRAMS = \ tutorial_server_SOURCES = \ c_glib_server.c +tutorial_server_LDFLAGS = $(OPENSSL_LIBS) tutorial_server_LDADD = \ libtutorialgencglib.la \ diff --git a/vendor/git.apache.org/thrift.git/tutorial/cl/Makefile.am b/vendor/git.apache.org/thrift.git/tutorial/cl/Makefile.am new file mode 100755 index 0000000..2b2013a --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/cl/Makefile.am @@ -0,0 +1,65 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +setup-local-lisp-env: ensure-externals.sh + bash ensure-externals.sh + +gen-cl: $(top_srcdir)/tutorial/tutorial.thrift + $(THRIFT) --gen cl -r $< + +ALL_FILE_PREREQS = \ + load-locally.lisp \ + make-tutorial-server.lisp \ + make-tutorial-client.lisp \ + shared-implementation.lisp \ + thrift-tutorial.asd \ + tutorial-implementation.lisp + +# NOTE: the server and client cannot be built in parallel +# because on loading the make-tutorial-* scripts SBCL will +# attempt to compile their dependencies. Unfortunately, +# because their dependencies are shared, parallel jobs can +# end up overwriting or corrupting the compiled files +all-local: gen-cl setup-local-lisp-env $(ALL_FILE_PREREQS) + $(SBCL) --script make-tutorial-server.lisp + $(SBCL) --script make-tutorial-client.lisp + +tutorialserver: all + ./TutorialServer + +tutorialclient: all + ./TutorialClient + +clean-local: + -$(RM) -r gen-* + -$(RM) -r externals + -$(RM) -r quicklisp + -$(RM) -r lib + -$(RM) quicklisp.lisp + -$(RM) backport-update.zip + -$(RM) shared-implementation.fasl + -$(RM) tutorial-implementation.fasl + -$(RM) TutorialServer + -$(RM) TutorialClient + +EXTRA_DIST = \ + tutorial-implementation.lisp \ + shared-implementation.lisp \ + thrift-tutorial.asd \ + make-tutorial-server.lisp \ + make-tutorial-client.lisp diff --git a/vendor/git.apache.org/thrift.git/tutorial/cl/ensure-externals.sh b/vendor/git.apache.org/thrift.git/tutorial/cl/ensure-externals.sh new file mode 120000 index 0000000..5ae8c56 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/cl/ensure-externals.sh @@ -0,0 +1 @@ +../../lib/cl/ensure-externals.sh \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/tutorial/cl/load-locally.lisp b/vendor/git.apache.org/thrift.git/tutorial/cl/load-locally.lisp new file mode 100644 index 0000000..b52a0a2 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/cl/load-locally.lisp @@ -0,0 +1,22 @@ +(in-package #:cl-user) + +;;;; 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. + +;;;; Just a script for loading the library itself, using bundled dependencies. +;;;; This is an identical copy of the file in lib/cl. + +(require "asdf") + +(load (merge-pathnames "externals/bundle.lisp" *load-truename*)) +(asdf:load-asd (merge-pathnames "lib/de.setf.thrift-backport-update/thrift.asd" *load-truename*)) +(asdf:load-system :thrift) diff --git a/vendor/git.apache.org/thrift.git/tutorial/cl/make-tutorial-client.lisp b/vendor/git.apache.org/thrift.git/tutorial/cl/make-tutorial-client.lisp new file mode 100644 index 0000000..3a6d861 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/cl/make-tutorial-client.lisp @@ -0,0 +1,51 @@ +(in-package #:cl-user) + +;;;; 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. + +(require "asdf") +(load (merge-pathnames "load-locally.lisp" *load-truename*)) +(asdf:load-system :net.didierverna.clon) +(asdf:load-asd (merge-pathnames "gen-cl/shared/thrift-gen-shared.asd" *load-truename*)) +(asdf:load-asd (merge-pathnames "gen-cl/tutorial/thrift-gen-tutorial.asd" *load-truename*)) +(asdf:load-asd (merge-pathnames "thrift-tutorial.asd" *load-truename*)) +(asdf:load-system :thrift-tutorial) + +(net.didierverna.clon:nickname-package) + +(defun main () + "Entry point for the binary." + (thrift:with-client (prot #u"thrift://127.0.0.1:9090") + (tutorial.calculator:ping prot) + (format t "ping()~%") + (format t "1 + 1 = ~a~%" (tutorial.calculator:add prot 1 1)) + (let ((work-instance (tutorial:make-work :num1 5 + :num2 0 + :op tutorial:operation.divide + :comment "Booya!"))) + (handler-case (format t + "5 / 0 = ~a - Oh, really? An exception should have been thrown here.~%" + (tutorial.calculator:calculate prot 1 work-instance)) + (tutorial:invalidoperation (e) + (format t "---~%(Expected) Invalid Operation caught: ~%~a~%---~%" e)))) + (let ((work-instance (tutorial:make-work :num1 15 + :num2 10 + :op tutorial:operation.subtract + :comment "Playing nice this time."))) + (handler-case (format t + "15 - 10 = ~a~%" + (tutorial.calculator:calculate prot 1 work-instance)) + (tutorial:invalidoperation (e) + (format t "---~%(Unexpected) Invalid Operation caught: ~%~a~%---~%" e)))) + (format t "Check log: ~a~%" (shared.shared-service:get-struct prot 1)))) + +(clon:dump "TutorialClient" main) diff --git a/vendor/git.apache.org/thrift.git/tutorial/cl/make-tutorial-server.lisp b/vendor/git.apache.org/thrift.git/tutorial/cl/make-tutorial-server.lisp new file mode 100644 index 0000000..4cf1a90 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/cl/make-tutorial-server.lisp @@ -0,0 +1,29 @@ +(in-package #:cl-user) + +;;;; 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. + +(require "asdf") +(load (merge-pathnames "load-locally.lisp" *load-truename*)) +(asdf:load-system :net.didierverna.clon) +(asdf:load-asd (merge-pathnames "gen-cl/shared/thrift-gen-shared.asd" *load-truename*)) +(asdf:load-asd (merge-pathnames "gen-cl/tutorial/thrift-gen-tutorial.asd" *load-truename*)) +(asdf:load-asd (merge-pathnames "thrift-tutorial.asd" *load-truename*)) +(asdf:load-system :thrift-tutorial) + +(net.didierverna.clon:nickname-package) + +(defun main () + "Entry point for the binary." + (thrift:serve #u"thrift://127.0.0.1:9090" tutorial:calculator)) + +(clon:dump "TutorialServer" main) diff --git a/vendor/git.apache.org/thrift.git/tutorial/cl/shared-implementation.lisp b/vendor/git.apache.org/thrift.git/tutorial/cl/shared-implementation.lisp new file mode 100644 index 0000000..c197626 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/cl/shared-implementation.lisp @@ -0,0 +1,25 @@ +(in-package #:shared-implementation) + +;;;; 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. + +(defvar *structs* (make-hash-table)) + +(defun shared.shared-service-implementation:get-struct (key) + (format t "getStruct(~a)~%" key) + (gethash key *structs*)) + +(defun add-log (key value) + (setf (gethash key *structs*) + (make-instance 'shared:sharedstruct + :key key + :value (write-to-string value)))) diff --git a/vendor/git.apache.org/thrift.git/tutorial/cl/thrift-tutorial.asd b/vendor/git.apache.org/thrift.git/tutorial/cl/thrift-tutorial.asd new file mode 100644 index 0000000..8a03537 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/cl/thrift-tutorial.asd @@ -0,0 +1,17 @@ +;;;; 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. + +(asdf:defsystem #:thrift-tutorial + :depends-on (#:thrift-gen-tutorial) + :serial t + :components ((:file "shared-implementation") + (:file "tutorial-implementation"))) diff --git a/vendor/git.apache.org/thrift.git/tutorial/cl/tutorial-implementation.lisp b/vendor/git.apache.org/thrift.git/tutorial/cl/tutorial-implementation.lisp new file mode 100644 index 0000000..5c92fe4 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/cl/tutorial-implementation.lisp @@ -0,0 +1,41 @@ +(in-package #:tutorial-implementation) + +;;;; 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. + +(defun tutorial.calculator-implementation:ping () + (format t "ping()~%")) + +(defun tutorial.calculator-implementation:add (num1 num2) + (format t "add(~a, ~a)~%" num1 num2) + (+ num1 num2)) + +(defun tutorial.calculator-implementation:calculate (logid work) + (format t "calculate(~a, ~a)~%" logid work) + (handler-case + (let* ((num1 (tutorial:work-num1 work)) + (num2 (tutorial:work-num2 work)) + (op (tutorial:work-op work)) + (result + (cond + ((= op tutorial:operation.add) (+ num1 num2)) + ((= op tutorial:operation.subtract) (- num1 num2)) + ((= op tutorial:operation.multiply) (* num1 num2)) + ((= op tutorial:operation.divide) (/ num1 num2))))) + (shared-implementation::add-log logid result) + result) + (division-by-zero () (error 'tutorial:invalidoperation + :why "Division by zero." + :what-op (tutorial:work-op work))))) + +(defun tutorial.calculator-implementation:zip () + (format t "zip()~%")) diff --git a/vendor/git.apache.org/thrift.git/tutorial/cpp/CMakeLists.txt b/vendor/git.apache.org/thrift.git/tutorial/cpp/CMakeLists.txt index 1feec2c..8634b41 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/cpp/CMakeLists.txt +++ b/vendor/git.apache.org/thrift.git/tutorial/cpp/CMakeLists.txt @@ -44,9 +44,13 @@ add_custom_command(OUTPUT gen-cpp/Calculator.cpp gen-cpp/SharedService.cpp gen-c add_executable(TutorialServer CppServer.cpp) target_link_libraries(TutorialServer tutorialgencpp) LINK_AGAINST_THRIFT_LIBRARY(TutorialServer thrift) -target_link_libraries(TutorialServer ${ZLIB_LIBRARIES}) +if (ZLIB_FOUND) + target_link_libraries(TutorialServer ${ZLIB_LIBRARIES}) +endif () add_executable(TutorialClient CppClient.cpp) target_link_libraries(TutorialClient tutorialgencpp) LINK_AGAINST_THRIFT_LIBRARY(TutorialClient thrift) -target_link_libraries(TutorialClient ${ZLIB_LIBRARIES}) +if (ZLIB_FOUND) + target_link_libraries(TutorialClient ${ZLIB_LIBRARIES}) +endif () diff --git a/vendor/git.apache.org/thrift.git/tutorial/cpp/CppClient.cpp b/vendor/git.apache.org/thrift.git/tutorial/cpp/CppClient.cpp index 2763fee..f10c725 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/cpp/CppClient.cpp +++ b/vendor/git.apache.org/thrift.git/tutorial/cpp/CppClient.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include "../gen-cpp/Calculator.h" @@ -34,9 +35,9 @@ using namespace tutorial; using namespace shared; int main() { - boost::shared_ptr socket(new TSocket("localhost", 9090)); - boost::shared_ptr transport(new TBufferedTransport(socket)); - boost::shared_ptr protocol(new TBinaryProtocol(transport)); + stdcxx::shared_ptr socket(new TSocket("localhost", 9090)); + stdcxx::shared_ptr transport(new TBufferedTransport(socket)); + stdcxx::shared_ptr protocol(new TBinaryProtocol(transport)); CalculatorClient client(protocol); try { diff --git a/vendor/git.apache.org/thrift.git/tutorial/cpp/CppServer.cpp b/vendor/git.apache.org/thrift.git/tutorial/cpp/CppServer.cpp index eafffa9..80b100e 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/cpp/CppServer.cpp +++ b/vendor/git.apache.org/thrift.git/tutorial/cpp/CppServer.cpp @@ -27,8 +27,7 @@ #include #include #include - -#include +#include #include #include @@ -118,7 +117,7 @@ class CalculatorCloneFactory : virtual public CalculatorIfFactory { virtual ~CalculatorCloneFactory() {} virtual CalculatorIf* getHandler(const ::apache::thrift::TConnectionInfo& connInfo) { - boost::shared_ptr sock = boost::dynamic_pointer_cast(connInfo.transport); + stdcxx::shared_ptr sock = stdcxx::dynamic_pointer_cast(connInfo.transport); cout << "Incoming connection\n"; cout << "\tSocketInfo: " << sock->getSocketInfo() << "\n"; cout << "\tPeerHost: " << sock->getPeerHost() << "\n"; @@ -133,18 +132,18 @@ class CalculatorCloneFactory : virtual public CalculatorIfFactory { int main() { TThreadedServer server( - boost::make_shared(boost::make_shared()), - boost::make_shared(9090), //port - boost::make_shared(), - boost::make_shared()); + stdcxx::make_shared(stdcxx::make_shared()), + stdcxx::make_shared(9090), //port + stdcxx::make_shared(), + stdcxx::make_shared()); /* // if you don't need per-connection state, do the following instead TThreadedServer server( - boost::make_shared(boost::make_shared()), - boost::make_shared(9090), //port - boost::make_shared(), - boost::make_shared()); + stdcxx::make_shared(stdcxx::make_shared()), + stdcxx::make_shared(9090), //port + stdcxx::make_shared(), + stdcxx::make_shared()); */ /** @@ -152,25 +151,25 @@ int main() { // This server only allows one connection at a time, but spawns no threads TSimpleServer server( - boost::make_shared(boost::make_shared()), - boost::make_shared(9090), - boost::make_shared(), - boost::make_shared()); + stdcxx::make_shared(stdcxx::make_shared()), + stdcxx::make_shared(9090), + stdcxx::make_shared(), + stdcxx::make_shared()); const int workerCount = 4; - boost::shared_ptr threadManager = + stdcxx::shared_ptr threadManager = ThreadManager::newSimpleThreadManager(workerCount); threadManager->threadFactory( - boost::make_shared()); + stdcxx::make_shared()); threadManager->start(); // This server allows "workerCount" connection at a time, and reuses threads TThreadPoolServer server( - boost::make_shared(boost::make_shared()), - boost::make_shared(9090), - boost::make_shared(), - boost::make_shared(), + stdcxx::make_shared(stdcxx::make_shared()), + stdcxx::make_shared(9090), + stdcxx::make_shared(), + stdcxx::make_shared(), threadManager); */ diff --git a/vendor/git.apache.org/thrift.git/tutorial/cpp/Makefile.am b/vendor/git.apache.org/thrift.git/tutorial/cpp/Makefile.am index 184a69d..49cf3be 100755 --- a/vendor/git.apache.org/thrift.git/tutorial/cpp/Makefile.am +++ b/vendor/git.apache.org/thrift.git/tutorial/cpp/Makefile.am @@ -61,8 +61,6 @@ TutorialClient_LDADD = \ # # Common thrift code generation rules # -THRIFT = $(top_builddir)/compiler/cpp/thrift - gen-cpp/Calculator.cpp gen-cpp/SharedService.cpp gen-cpp/shared_constants.cpp gen-cpp/shared_types.cpp gen-cpp/tutorial_constants.cpp gen-cpp/tutorial_types.cpp: $(top_srcdir)/tutorial/tutorial.thrift $(THRIFT) --gen cpp -r $< diff --git a/vendor/git.apache.org/thrift.git/tutorial/csharp/CsharpClient/Properties/AssemblyInfo.cs b/vendor/git.apache.org/thrift.git/tutorial/csharp/CsharpClient/Properties/AssemblyInfo.cs index bf4bc5d..2e7f736 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/csharp/CsharpClient/Properties/AssemblyInfo.cs +++ b/vendor/git.apache.org/thrift.git/tutorial/csharp/CsharpClient/Properties/AssemblyInfo.cs @@ -27,9 +27,9 @@ using System.Runtime.InteropServices; [assembly: AssemblyTitle("CsharpClient")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("CsharpClient")] -[assembly: AssemblyCopyright("Copyright © 2010 The Apache Software Foundation")] +[assembly: AssemblyCompany("The Apache Software Foundation")] +[assembly: AssemblyProduct("Thrift")] +[assembly: AssemblyCopyright("The Apache Software Foundation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] @@ -51,5 +51,5 @@ using System.Runtime.InteropServices; // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("0.10.0.0")] -[assembly: AssemblyFileVersion("0.10.0.0")] +[assembly: AssemblyVersion("0.12.0.0")] +[assembly: AssemblyFileVersion("0.12.0.0")] diff --git a/vendor/git.apache.org/thrift.git/tutorial/csharp/CsharpServer/Properties/AssemblyInfo.cs b/vendor/git.apache.org/thrift.git/tutorial/csharp/CsharpServer/Properties/AssemblyInfo.cs index c416acc..14067dd 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/csharp/CsharpServer/Properties/AssemblyInfo.cs +++ b/vendor/git.apache.org/thrift.git/tutorial/csharp/CsharpServer/Properties/AssemblyInfo.cs @@ -27,9 +27,9 @@ using System.Runtime.InteropServices; [assembly: AssemblyTitle("CsharpServer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("CsharpServer")] -[assembly: AssemblyCopyright("Copyright © 2010 The Apache Software Foundation")] +[assembly: AssemblyCompany("The Apache Software Foundation")] +[assembly: AssemblyProduct("Thrift")] +[assembly: AssemblyCopyright("The Apache Software Foundation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] @@ -51,5 +51,5 @@ using System.Runtime.InteropServices; // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("0.10.0.0")] -[assembly: AssemblyFileVersion("0.10.0.0")] +[assembly: AssemblyVersion("0.12.0.0")] +[assembly: AssemblyFileVersion("0.12.0.0")] diff --git a/vendor/git.apache.org/thrift.git/tutorial/dart/Makefile.am b/vendor/git.apache.org/thrift.git/tutorial/dart/Makefile.am index ccca598..0495aca 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/dart/Makefile.am +++ b/vendor/git.apache.org/thrift.git/tutorial/dart/Makefile.am @@ -19,8 +19,6 @@ BUILT_SOURCES = gen-dart/tutorial/lib/tutorial.dart gen-dart/shared/lib/shared.dart -THRIFT = $(top_builddir)/compiler/cpp/thrift - gen-dart/tutorial/lib/tutorial.dart gen-dart/shared/lib/shared.dart: $(top_srcdir)/tutorial/tutorial.thrift $(THRIFT) --gen dart -r $< @@ -30,6 +28,7 @@ clean-local: $(RM) -r gen-* find . -type d -name "packages" | xargs $(RM) -r find . -type f -name ".packages" | xargs $(RM) + find . -type f -name "pubspec.lock" | xargs $(RM) pub-get: pub-get-gen pub-get-client pub-get-console-client pub-get-server @@ -68,4 +67,7 @@ EXTRA_DIST = \ console_client/pubspec.yaml \ server/bin/main.dart \ server/pubspec.yaml \ + console_client/.analysis_options \ + client/.analysis_options \ + server/.analysis_options \ build.sh diff --git a/vendor/git.apache.org/thrift.git/tutorial/dart/client/pubspec.yaml b/vendor/git.apache.org/thrift.git/tutorial/dart/client/pubspec.yaml index 5f60f67..78ee527 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/dart/client/pubspec.yaml +++ b/vendor/git.apache.org/thrift.git/tutorial/dart/client/pubspec.yaml @@ -16,7 +16,7 @@ # under the License. name: tutorial_client -version: 0.10.0 +version: 0.12.0 description: A Dart client implementation of the Apache Thrift tutorial author: Apache Thrift Developers homepage: http://thrift.apache.org diff --git a/vendor/git.apache.org/thrift.git/tutorial/dart/console_client/pubspec.yaml b/vendor/git.apache.org/thrift.git/tutorial/dart/console_client/pubspec.yaml index 32fd4ff..be7328e 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/dart/console_client/pubspec.yaml +++ b/vendor/git.apache.org/thrift.git/tutorial/dart/console_client/pubspec.yaml @@ -16,7 +16,7 @@ # under the License. name: tutorial_console_client -version: 0.10.0 +version: 0.12.0 description: > A Dart console client to implementation of the Apache Thrift tutorial author: Apache Thrift Developers diff --git a/vendor/git.apache.org/thrift.git/tutorial/dart/server/pubspec.yaml b/vendor/git.apache.org/thrift.git/tutorial/dart/server/pubspec.yaml index 2a26448..6c616b3 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/dart/server/pubspec.yaml +++ b/vendor/git.apache.org/thrift.git/tutorial/dart/server/pubspec.yaml @@ -16,7 +16,7 @@ # under the License. name: tutorial_server -version: 0.10.0 +version: 0.12.0 description: A Dart server to support the Apache Thrift tutorial author: Apache Thrift Developers homepage: http://thrift.apache.org diff --git a/vendor/git.apache.org/thrift.git/tutorial/delphi/DelphiClient/DelphiClient.dpr b/vendor/git.apache.org/thrift.git/tutorial/delphi/DelphiClient/DelphiClient.dpr index 0f380b0..74d0d45 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/delphi/DelphiClient/DelphiClient.dpr +++ b/vendor/git.apache.org/thrift.git/tutorial/delphi/DelphiClient/DelphiClient.dpr @@ -26,7 +26,7 @@ uses Generics.Collections, Thrift in '..\..\..\lib\delphi\src\Thrift.pas', Thrift.Collections in '..\..\..\lib\delphi\src\Thrift.Collections.pas', - Thrift.Console in '..\..\..\lib\delphi\src\Thrift.Console.pas', + Thrift.Exception in '..\..\..\lib\delphi\src\Thrift.Exception.pas', Thrift.Utils in '..\..\..\lib\delphi\src\Thrift.Utils.pas', Thrift.Stream in '..\..\..\lib\delphi\src\Thrift.Stream.pas', Thrift.Protocol in '..\..\..\lib\delphi\src\Thrift.Protocol.pas', @@ -62,10 +62,10 @@ begin transport.Open; client.ping; - Console.WriteLine('ping()'); + WriteLn('ping()'); sum := client.add( 1, 1); - Console.WriteLine( Format( '1+1=%d', [sum])); + WriteLn( Format( '1+1=%d', [sum])); work := TWorkImpl.Create; @@ -74,11 +74,11 @@ begin work.Num2 := 0; try quotient := client.calculate(1, work); - Console.WriteLine( 'Whoa we can divide by 0'); - Console.WriteLine( Format('1/0=%d',[quotient])); + WriteLn( 'Whoa we can divide by 0'); + WriteLn( Format('1/0=%d',[quotient])); except on io: TInvalidOperation - do Console.WriteLine( 'Invalid operation: ' + io.Why); + do WriteLn( 'Invalid operation: ' + io.Why); end; work.Op := TOperation.SUBTRACT; @@ -86,20 +86,20 @@ begin work.Num2 := 10; try diff := client.calculate( 1, work); - Console.WriteLine( Format('15-10=%d', [diff])); + WriteLn( Format('15-10=%d', [diff])); except on io: TInvalidOperation - do Console.WriteLine( 'Invalid operation: ' + io.Why); + do WriteLn( 'Invalid operation: ' + io.Why); end; log := client.getStruct(1); - Console.WriteLine( Format( 'Check log: %s', [log.Value])); + WriteLn( Format( 'Check log: %s', [log.Value])); transport.Close(); except on e : Exception - do Console.WriteLine( e.ClassName+': '+e.Message); + do WriteLn( e.ClassName+': '+e.Message); end; end; diff --git a/vendor/git.apache.org/thrift.git/tutorial/delphi/DelphiClient/DelphiClient.dproj b/vendor/git.apache.org/thrift.git/tutorial/delphi/DelphiClient/DelphiClient.dproj index 34aa533..dd58781 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/delphi/DelphiClient/DelphiClient.dproj +++ b/vendor/git.apache.org/thrift.git/tutorial/delphi/DelphiClient/DelphiClient.dproj @@ -1,119 +1,119 @@ - - - {2B8FB3A1-2F9E-4883-8C53-0F56220B34F6} - DelphiClient.dpr - 12.3 - True - Debug - Win32 - Console - None - DCC32 - - - true - - - true - Base - true - - - true - Base - true - - - ..\..\..\lib\delphi\src;$(DCC_UnitSearchPath) - 00400000 - .\dcu\$(Config)\$(Platform) - WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;$(DCC_UnitAlias) - ..\bin\$(Config)\$(Platform) - false - false - false - false - false - - - DEBUG;$(DCC_Define) - false - true - - - false - RELEASE;$(DCC_Define) - 0 - false - - - - MainSource - - - - - - - - - - - - - Cfg_2 - Base - - - Base - - - Cfg_1 - Base - - - - - - Delphi.Personality.12 - - - - - True - False - 1 - 0 - 0 - 0 - False - False - False - False - False - 1033 - 1252 - - - - Thrift Tutorial - 1.0.0.0 - DelphiClient - Copyright © 2012 The Apache Software Foundation - - DelphiClient.exe - Thrift - 1.0.0.0 - - - - DelphiClient.dpr - - - - True - - - 12 - - + + + {2B8FB3A1-2F9E-4883-8C53-0F56220B34F6} + DelphiClient.dpr + 12.3 + True + Debug + Win32 + Console + None + DCC32 + + + true + + + true + Base + true + + + true + Base + true + + + ..\..\..\lib\delphi\src;$(DCC_UnitSearchPath) + 00400000 + .\dcu\$(Config)\$(Platform) + WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;$(DCC_UnitAlias) + ..\bin\$(Config)\$(Platform) + false + false + false + false + false + + + DEBUG;$(DCC_Define) + false + true + + + false + RELEASE;$(DCC_Define) + 0 + false + + + + MainSource + + + + + + + + + + + + + Cfg_2 + Base + + + Base + + + Cfg_1 + Base + + + + + + Delphi.Personality.12 + + + + + True + False + 0 + 12 + 0 + 0 + False + False + False + False + False + 1033 + 1252 + + + + Thrift Tutorial + 0.12.0.0 + DelphiClient + Copyright © 2012 The Apache Software Foundation + + DelphiClient.exe + Thrift + 1.0.0.0 + + + + DelphiClient.dpr + + + + True + + + 12 + + diff --git a/vendor/git.apache.org/thrift.git/tutorial/delphi/DelphiServer/DelphiServer.dpr b/vendor/git.apache.org/thrift.git/tutorial/delphi/DelphiServer/DelphiServer.dpr index 9d54a2e..5f42e7e 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/delphi/DelphiServer/DelphiServer.dpr +++ b/vendor/git.apache.org/thrift.git/tutorial/delphi/DelphiServer/DelphiServer.dpr @@ -28,7 +28,7 @@ uses Generics.Collections, Thrift in '..\..\..\lib\delphi\src\Thrift.pas', Thrift.Collections in '..\..\..\lib\delphi\src\Thrift.Collections.pas', - Thrift.Console in '..\..\..\lib\delphi\src\Thrift.Console.pas', + Thrift.Exception in '..\..\..\lib\delphi\src\Thrift.Exception.pas', Thrift.Utils in '..\..\..\lib\delphi\src\Thrift.Utils.pas', Thrift.Stream in '..\..\..\lib\delphi\src\Thrift.Stream.pas', Thrift.Protocol in '..\..\..\lib\delphi\src\Thrift.Protocol.pas', @@ -86,13 +86,13 @@ end; procedure TCalculatorHandler.ping; begin - Console.WriteLine( 'ping()'); + WriteLn( 'ping()'); end; function TCalculatorHandler.add(num1: Integer; num2: Integer): Integer; begin - Console.WriteLine( Format( 'add( %d, %d)', [num1, num2])); + WriteLn( Format( 'add( %d, %d)', [num1, num2])); result := num1 + num2; end; @@ -101,7 +101,7 @@ function TCalculatorHandler.calculate(logid: Integer; const w: IWork): Integer; var entry : ISharedStruct; begin try - Console.WriteLine( Format('calculate( %d, [%d,%d,%d])', [logid, Ord(w.Op), w.Num1, w.Num2])); + WriteLn( Format('calculate( %d, [%d,%d,%d])', [logid, Ord(w.Op), w.Num1, w.Num2])); case w.Op of TOperation.ADD : result := w.Num1 + w.Num2; @@ -126,14 +126,14 @@ end; function TCalculatorHandler.getStruct(key: Integer): ISharedStruct; begin - Console.WriteLine( Format( 'getStruct(%d)', [key])); + WriteLn( Format( 'getStruct(%d)', [key])); result := FLog[key]; end; procedure TCalculatorHandler.zip; begin - Console.WriteLine( 'zip()'); + WriteLn( 'zip()'); end; @@ -152,14 +152,14 @@ begin transport := TServerSocketImpl.Create( 9090); server := TSimpleServer.Create( processor, transport); - Console.WriteLine( 'Starting the server...'); + WriteLn( 'Starting the server...'); server.Serve(); except - on e: Exception do Console.WriteLine( e.Message); + on e: Exception do WriteLn( e.Message); end; - Console.WriteLine('done.'); + WriteLn('done.'); end; diff --git a/vendor/git.apache.org/thrift.git/tutorial/delphi/DelphiServer/DelphiServer.dproj b/vendor/git.apache.org/thrift.git/tutorial/delphi/DelphiServer/DelphiServer.dproj index 74811bc..3f9fc4d 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/delphi/DelphiServer/DelphiServer.dproj +++ b/vendor/git.apache.org/thrift.git/tutorial/delphi/DelphiServer/DelphiServer.dproj @@ -1,118 +1,118 @@ - - - {2B8FB3A1-2F9E-4883-8C53-0F56220B34F6} - DelphiServer.dpr - 12.3 - True - Debug - Win32 - Console - None - DCC32 - - - true - - - true - Base - true - - - true - Base - true - - - 00400000 - .\dcu\$(Config)\$(Platform) - WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;$(DCC_UnitAlias) - ..\bin\$(Config)\$(Platform) - false - false - false - false - false - - - DEBUG;$(DCC_Define) - false - true - - - false - RELEASE;$(DCC_Define) - 0 - false - - - - MainSource - - - - - - - - - - - - - Cfg_2 - Base - - - Base - - - Cfg_1 - Base - - - - - - Delphi.Personality.12 - - - - - True - False - 1 - 0 - 0 - 0 - False - False - False - False - False - 1033 - 1252 - - - - Thrift Tutorial - 1.0.0.0 - DelphiServer - Copyright © 2012 The Apache Software Foundation - - DelphiServer.exe - Thrift - 1.0.0.0 - - - - DelphiServer.dpr - - - - True - - - 12 - - + + + {2B8FB3A1-2F9E-4883-8C53-0F56220B34F6} + DelphiServer.dpr + 12.3 + True + Debug + Win32 + Console + None + DCC32 + + + true + + + true + Base + true + + + true + Base + true + + + 00400000 + .\dcu\$(Config)\$(Platform) + WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;$(DCC_UnitAlias) + ..\bin\$(Config)\$(Platform) + false + false + false + false + false + + + DEBUG;$(DCC_Define) + false + true + + + false + RELEASE;$(DCC_Define) + 0 + false + + + + MainSource + + + + + + + + + + + + + Cfg_2 + Base + + + Base + + + Cfg_1 + Base + + + + + + Delphi.Personality.12 + + + + + True + False + 0 + 12 + 0 + 0 + False + False + False + False + False + 1033 + 1252 + + + + Thrift Tutorial + 0.12.0.0 + DelphiServer + Copyright © 2012 The Apache Software Foundation + + DelphiServer.exe + Thrift + 1.0.0.0 + + + + DelphiServer.dpr + + + + True + + + 12 + + diff --git a/vendor/git.apache.org/thrift.git/tutorial/erl/client.erl b/vendor/git.apache.org/thrift.git/tutorial/erl/client.erl index 5d40916..0374220 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/erl/client.erl +++ b/vendor/git.apache.org/thrift.git/tutorial/erl/client.erl @@ -28,7 +28,7 @@ p(X) -> ok. t() -> - Port = 9999, + Port = 9090, {ok, Client0} = thrift_client_util:new("127.0.0.1", Port, @@ -44,7 +44,7 @@ t() -> {Client3, {ok, Sum1}} = thrift_client:call(Client2, add, [1, 4]), io:format("1+4=~p~n", [Sum1]), - Work = #work{op=?tutorial_Operation_SUBTRACT, + Work = #'Work'{op=?TUTORIAL_OPERATION_SUBTRACT, num1=15, num2=10}, {Client4, {ok, Diff}} = thrift_client:call(Client3, calculate, [1, Work]), @@ -55,7 +55,7 @@ t() -> Client6 = try - Work1 = #work{op=?tutorial_Operation_DIVIDE, + Work1 = #'Work'{op=?TUTORIAL_OPERATION_DIVIDE, num1=1, num2=0}, {ClientS1, {ok, _Quot}} = thrift_client:call(Client5, calculate, [2, Work1]), diff --git a/vendor/git.apache.org/thrift.git/tutorial/erl/client.sh b/vendor/git.apache.org/thrift.git/tutorial/erl/client.sh deleted file mode 120000 index a417e0d..0000000 --- a/vendor/git.apache.org/thrift.git/tutorial/erl/client.sh +++ /dev/null @@ -1 +0,0 @@ -server.sh \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/tutorial/erl/client.sh b/vendor/git.apache.org/thrift.git/tutorial/erl/client.sh new file mode 100755 index 0000000..775afb6 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/erl/client.sh @@ -0,0 +1,37 @@ +#!/bin/sh + +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +ERL_THRIFT=../../lib/erl + +if ! [ -d ${ERL_THRIFT}/ebin ]; then + echo "Please build the Thrift library by running \`make' in ${ERL_THRIFT}" + exit 1 +fi + +if ! [ -d gen-erl ]; then + ../../compiler/cpp/thrift -r --gen erl ../tutorial.thrift +fi + + +erlc -I ${ERL_THRIFT}/include -I ${ERL_THRIFT}/ebin \ + -I gen-erl -o gen-erl gen-erl/*.erl && + erlc -I ${ERL_THRIFT}/include -I gen-erl *.erl && + erl +K true -pa ${ERL_THRIFT}/ebin -pa gen-erl diff --git a/vendor/git.apache.org/thrift.git/tutorial/erl/json_client.erl b/vendor/git.apache.org/thrift.git/tutorial/erl/json_client.erl index 312b01e..0b39ced 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/erl/json_client.erl +++ b/vendor/git.apache.org/thrift.git/tutorial/erl/json_client.erl @@ -55,7 +55,7 @@ t() -> {Client3, {ok, Sum1}} = thrift_client:call(Client2, add, [1, 4]), io:format("1+4=~p~n", [Sum1]), - Work = #work{op=?tutorial_Operation_SUBTRACT, + Work = #'Work'{op=?TUTORIAL_OPERATION_SUBTRACT, num1=15, num2=10}, {Client4, {ok, Diff}} = thrift_client:call(Client3, calculate, [1, Work]), @@ -66,7 +66,7 @@ t() -> Client6 = try - Work1 = #work{op=?tutorial_Operation_DIVIDE, + Work1 = #'Work'{op=?TUTORIAL_OPERATION_DIVIDE, num1=1, num2=0}, {ClientS1, {ok, _Quot}} = thrift_client:call(Client5, calculate, [2, Work1]), diff --git a/vendor/git.apache.org/thrift.git/tutorial/erl/server.erl b/vendor/git.apache.org/thrift.git/tutorial/erl/server.erl index f1e7357..647cc24 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/erl/server.erl +++ b/vendor/git.apache.org/thrift.git/tutorial/erl/server.erl @@ -36,25 +36,25 @@ add(N1, N2) -> N1+N2. calculate(Logid, Work) -> - { Op, Num1, Num2 } = { Work#work.op, Work#work.num1, Work#work.num2 }, + { Op, Num1, Num2 } = { Work#'Work'.op, Work#'Work'.num1, Work#'Work'.num2 }, debug("calculate(~p, {~p,~p,~p})", [Logid, Op, Num1, Num2]), case Op of - ?tutorial_Operation_ADD -> Num1 + Num2; - ?tutorial_Operation_SUBTRACT -> Num1 - Num2; - ?tutorial_Operation_MULTIPLY -> Num1 * Num2; + ?TUTORIAL_OPERATION_ADD -> Num1 + Num2; + ?TUTORIAL_OPERATION_SUBTRACT -> Num1 - Num2; + ?TUTORIAL_OPERATION_MULTIPLY -> Num1 * Num2; - ?tutorial_Operation_DIVIDE when Num2 == 0 -> - throw(#invalidOperation{whatOp=Op, why="Cannot divide by 0"}); - ?tutorial_Operation_DIVIDE -> + ?TUTORIAL_OPERATION_DIVIDE when Num2 == 0 -> + throw(#'InvalidOperation'{whatOp=Op, why="Cannot divide by 0"}); + ?TUTORIAL_OPERATION_DIVIDE -> Num1 div Num2; _Else -> - throw(#invalidOperation{whatOp=Op, why="Invalid operation"}) + throw(#'InvalidOperation'{whatOp=Op, why="Invalid operation"}) end. getStruct(Key) -> debug("getStruct(~p)", [Key]), - #sharedStruct{key=Key, value="RARG"}. + #'SharedStruct'{key=Key, value="RARG"}. zip() -> debug("zip", []), @@ -63,7 +63,7 @@ zip() -> %% start() -> - start(9999). + start(9090). start(Port) -> Handler = ?MODULE, diff --git a/vendor/git.apache.org/thrift.git/tutorial/erl/server.sh b/vendor/git.apache.org/thrift.git/tutorial/erl/server.sh deleted file mode 100755 index 775afb6..0000000 --- a/vendor/git.apache.org/thrift.git/tutorial/erl/server.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/sh - -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you 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. -# - -ERL_THRIFT=../../lib/erl - -if ! [ -d ${ERL_THRIFT}/ebin ]; then - echo "Please build the Thrift library by running \`make' in ${ERL_THRIFT}" - exit 1 -fi - -if ! [ -d gen-erl ]; then - ../../compiler/cpp/thrift -r --gen erl ../tutorial.thrift -fi - - -erlc -I ${ERL_THRIFT}/include -I ${ERL_THRIFT}/ebin \ - -I gen-erl -o gen-erl gen-erl/*.erl && - erlc -I ${ERL_THRIFT}/include -I gen-erl *.erl && - erl +K true -pa ${ERL_THRIFT}/ebin -pa gen-erl diff --git a/vendor/git.apache.org/thrift.git/tutorial/erl/server.sh b/vendor/git.apache.org/thrift.git/tutorial/erl/server.sh new file mode 120000 index 0000000..26b3c58 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/erl/server.sh @@ -0,0 +1 @@ +client.sh \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/tutorial/go/Makefile.am b/vendor/git.apache.org/thrift.git/tutorial/go/Makefile.am index a707d5d..bd57d65 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/go/Makefile.am +++ b/vendor/git.apache.org/thrift.git/tutorial/go/Makefile.am @@ -17,30 +17,28 @@ # under the License. # -THRIFT = $(top_builddir)/compiler/cpp/thrift - gen-go/tutorial/calculator.go gen-go/shared/shared_service.go: $(top_srcdir)/tutorial/tutorial.thrift - $(THRIFT) --gen go -r $< + $(THRIFT) --gen go$(COMPILER_EXTRAFLAG) -r $< all-local: gen-go/tutorial/calculator.go - -check: src/git.apache.org/thrift.git/lib/go/thrift - $(THRIFT) -r --gen go $(top_srcdir)/tutorial/tutorial.thrift +check: src/github.com/apache/thrift/lib/go/thrift thirdparty-dep + $(THRIFT) -r --gen go$(COMPILER_EXTRAFLAG) $(top_srcdir)/tutorial/tutorial.thrift cp -r gen-go/* src/ - GOPATH=`pwd` $(GO) build ./... - GOPATH=`pwd` $(GO) build -o go-tutorial src/*.go + GOPATH=`pwd` $(GO) build -o go-tutorial ./src GOPATH=`pwd` $(GO) build -o calculator-remote src/tutorial/calculator-remote/calculator-remote.go -src/git.apache.org/thrift.git/lib/go/thrift: - mkdir -p src/git.apache.org/thrift.git/lib/go - ln -sf $(realpath $(top_srcdir)/lib/go/thrift) src/git.apache.org/thrift.git/lib/go/thrift +src/github.com/apache/thrift/lib/go/thrift: + mkdir -p src/github.com/apache/thrift/lib/go + ln -sf $(realpath $(top_srcdir)/lib/go/thrift) src/github.com/apache/thrift/lib/go/thrift + +thirdparty-dep: tutorialserver: all GOPATH=`pwd` $(GO) run src/*.go -server=true tutorialclient: all - GOPATH=`pwd` $(GO) run src/*.go + GOPATH=`pwd` $(GO) run src/*.go tutorialsecureserver: all GOPATH=`pwd` $(GO) run src/*.go -server=true -secure=true diff --git a/vendor/git.apache.org/thrift.git/tutorial/go/src/client.go b/vendor/git.apache.org/thrift.git/tutorial/go/src/client.go index 9106ac9..e3ebe00 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/go/src/client.go +++ b/vendor/git.apache.org/thrift.git/tutorial/go/src/client.go @@ -20,24 +20,28 @@ package main */ import ( + "context" "crypto/tls" "fmt" - "git.apache.org/thrift.git/lib/go/thrift" "tutorial" + + "github.com/apache/thrift/lib/go/thrift" ) +var defaultCtx = context.Background() + func handleClient(client *tutorial.CalculatorClient) (err error) { - client.Ping() + client.Ping(defaultCtx) fmt.Println("ping()") - sum, _ := client.Add(1, 1) + sum, _ := client.Add(defaultCtx, 1, 1) fmt.Print("1+1=", sum, "\n") work := tutorial.NewWork() work.Op = tutorial.Operation_DIVIDE work.Num1 = 1 work.Num2 = 0 - quotient, err := client.Calculate(1, work) + quotient, err := client.Calculate(defaultCtx, 1, work) if err != nil { switch v := err.(type) { case *tutorial.InvalidOperation: @@ -53,7 +57,7 @@ func handleClient(client *tutorial.CalculatorClient) (err error) { work.Op = tutorial.Operation_SUBTRACT work.Num1 = 15 work.Num2 = 10 - diff, err := client.Calculate(1, work) + diff, err := client.Calculate(defaultCtx, 1, work) if err != nil { switch v := err.(type) { case *tutorial.InvalidOperation: @@ -66,7 +70,7 @@ func handleClient(client *tutorial.CalculatorClient) (err error) { fmt.Print("15-10=", diff, "\n") } - log, err := client.GetStruct(1) + log, err := client.GetStruct(defaultCtx, 1) if err != nil { fmt.Println("Unable to get struct:", err) return err @@ -98,5 +102,7 @@ func runClient(transportFactory thrift.TTransportFactory, protocolFactory thrift if err := transport.Open(); err != nil { return err } - return handleClient(tutorial.NewCalculatorClientFactory(transport, protocolFactory)) + iprot := protocolFactory.GetProtocol(transport) + oprot := protocolFactory.GetProtocol(transport) + return handleClient(tutorial.NewCalculatorClient(thrift.NewTStandardClient(iprot, oprot))) } diff --git a/vendor/git.apache.org/thrift.git/tutorial/go/src/handler.go b/vendor/git.apache.org/thrift.git/tutorial/go/src/handler.go index 1763832..5c0eed0 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/go/src/handler.go +++ b/vendor/git.apache.org/thrift.git/tutorial/go/src/handler.go @@ -20,6 +20,7 @@ package main */ import ( + "context" "fmt" "shared" "strconv" @@ -34,17 +35,17 @@ func NewCalculatorHandler() *CalculatorHandler { return &CalculatorHandler{log: make(map[int]*shared.SharedStruct)} } -func (p *CalculatorHandler) Ping() (err error) { +func (p *CalculatorHandler) Ping(ctx context.Context) (err error) { fmt.Print("ping()\n") return nil } -func (p *CalculatorHandler) Add(num1 int32, num2 int32) (retval17 int32, err error) { +func (p *CalculatorHandler) Add(ctx context.Context, num1 int32, num2 int32) (retval17 int32, err error) { fmt.Print("add(", num1, ",", num2, ")\n") return num1 + num2, nil } -func (p *CalculatorHandler) Calculate(logid int32, w *tutorial.Work) (val int32, err error) { +func (p *CalculatorHandler) Calculate(ctx context.Context, logid int32, w *tutorial.Work) (val int32, err error) { fmt.Print("calculate(", logid, ", {", w.Op, ",", w.Num1, ",", w.Num2, "})\n") switch w.Op { case tutorial.Operation_ADD: @@ -89,13 +90,13 @@ func (p *CalculatorHandler) Calculate(logid int32, w *tutorial.Work) (val int32, return val, err } -func (p *CalculatorHandler) GetStruct(key int32) (*shared.SharedStruct, error) { +func (p *CalculatorHandler) GetStruct(ctx context.Context, key int32) (*shared.SharedStruct, error) { fmt.Print("getStruct(", key, ")\n") v, _ := p.log[int(key)] return v, nil } -func (p *CalculatorHandler) Zip() (err error) { +func (p *CalculatorHandler) Zip(ctx context.Context) (err error) { fmt.Print("zip()\n") return nil } diff --git a/vendor/git.apache.org/thrift.git/tutorial/go/src/main.go b/vendor/git.apache.org/thrift.git/tutorial/go/src/main.go index 63154e3..7730d7b 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/go/src/main.go +++ b/vendor/git.apache.org/thrift.git/tutorial/go/src/main.go @@ -22,7 +22,7 @@ package main import ( "flag" "fmt" - "git.apache.org/thrift.git/lib/go/thrift" + "github.com/apache/thrift/lib/go/thrift" "os" ) diff --git a/vendor/git.apache.org/thrift.git/tutorial/go/src/server.go b/vendor/git.apache.org/thrift.git/tutorial/go/src/server.go index e4c4b97..95708eb 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/go/src/server.go +++ b/vendor/git.apache.org/thrift.git/tutorial/go/src/server.go @@ -22,7 +22,7 @@ package main import ( "crypto/tls" "fmt" - "git.apache.org/thrift.git/lib/go/thrift" + "github.com/apache/thrift/lib/go/thrift" "tutorial" ) diff --git a/vendor/git.apache.org/thrift.git/tutorial/haxe/Makefile.am b/vendor/git.apache.org/thrift.git/tutorial/haxe/Makefile.am index e9c8820..e6f2713 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/haxe/Makefile.am +++ b/vendor/git.apache.org/thrift.git/tutorial/haxe/Makefile.am @@ -17,13 +17,10 @@ # under the License. # -THRIFT = $(top_builddir)/compiler/cpp/thrift - BIN_CPP = bin/Main-debug BIN_PHP = bin/php/Main-debug.php BIN_PHP_WEB = bin/php-web-server/Main-debug.php - gen-haxe/tutorial/calculator.hx gen-haxe/shared/shared_service.hx: $(top_srcdir)/tutorial/tutorial.thrift $(THRIFT) --gen haxe -r $< @@ -83,16 +80,18 @@ clean-local: $(RM) -r gen-haxe bin EXTRA_DIST = \ - src \ - cpp.hxml \ - csharp.hxml \ - flash.hxml \ - java.hxml \ - javascript.hxml \ - neko.hxml \ - php.hxml \ - python.hxml \ - project.hide \ - Tutorial.hxproj \ - make_all.bat \ - make_all.sh + src \ + cpp.hxml \ + csharp.hxml \ + flash.hxml \ + java.hxml \ + javascript.hxml \ + php-web-server.hxml \ + neko.hxml \ + php.hxml \ + python.hxml \ + router.php \ + project.hide \ + Tutorial.hxproj \ + make_all.bat \ + make_all.sh diff --git a/vendor/git.apache.org/thrift.git/tutorial/hs/LICENSE b/vendor/git.apache.org/thrift.git/tutorial/hs/LICENSE new file mode 100644 index 0000000..3b6d7d7 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/hs/LICENSE @@ -0,0 +1,239 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + +-------------------------------------------------- +SOFTWARE DISTRIBUTED WITH THRIFT: + +The Apache Thrift software includes a number of subcomponents with +separate copyright notices and license terms. Your use of the source +code for the these subcomponents is subject to the terms and +conditions of the following licenses. + +-------------------------------------------------- +Portions of the following files are licensed under the MIT License: + + lib/erl/src/Makefile.am + +Please see doc/otp-base-license.txt for the full terms of this license. + +-------------------------------------------------- +For the aclocal/ax_boost_base.m4 and contrib/fb303/aclocal/ax_boost_base.m4 components: + +# Copyright (c) 2007 Thomas Porschberg +# +# Copying and distribution of this file, with or without +# modification, are permitted in any medium without royalty provided +# the copyright notice and this notice are preserved. + +-------------------------------------------------- +For the lib/nodejs/lib/thrift/json_parse.js: + +/* + json_parse.js + 2015-05-02 + Public Domain. + NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + +*/ +(By Douglas Crockford ) +-------------------------------------------------- diff --git a/vendor/git.apache.org/thrift.git/tutorial/hs/Makefile.am b/vendor/git.apache.org/thrift.git/tutorial/hs/Makefile.am index f274eb6..a3eccc2 100755 --- a/vendor/git.apache.org/thrift.git/tutorial/hs/Makefile.am +++ b/vendor/git.apache.org/thrift.git/tutorial/hs/Makefile.am @@ -37,3 +37,6 @@ tutorialserver: all tutorialclient: all dist/build/HaskellClient/HaskellClient + +EXTRA_DIST = \ + LICENSE diff --git a/vendor/git.apache.org/thrift.git/tutorial/hs/ThriftTutorial.cabal b/vendor/git.apache.org/thrift.git/tutorial/hs/ThriftTutorial.cabal index d342ad5..64af3ec 100755 --- a/vendor/git.apache.org/thrift.git/tutorial/hs/ThriftTutorial.cabal +++ b/vendor/git.apache.org/thrift.git/tutorial/hs/ThriftTutorial.cabal @@ -18,7 +18,7 @@ -- Name: ThriftTutorial -Version: 0.10.0 +Version: 0.12.0 Cabal-Version: >= 1.4 License: OtherLicense Category: Foreign @@ -27,7 +27,7 @@ Synopsis: Thrift Tutorial library package Homepage: http://thrift.apache.org Bug-Reports: https://issues.apache.org/jira/browse/THRIFT Maintainer: dev@thrift.apache.org -License-File: ../../LICENSE +License-File: LICENSE Description: Haskell tutorial for the Apache Thrift RPC system. Requires the use of the thrift code generator. diff --git a/vendor/git.apache.org/thrift.git/tutorial/java/build.xml b/vendor/git.apache.org/thrift.git/tutorial/java/build.xml index 7638d5b..55cdb8f 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/java/build.xml +++ b/vendor/git.apache.org/thrift.git/tutorial/java/build.xml @@ -25,11 +25,13 @@ - - - + + + + + - + @@ -42,7 +44,7 @@ - + @@ -50,8 +52,8 @@ - - + + diff --git a/vendor/git.apache.org/thrift.git/tutorial/js/build.xml b/vendor/git.apache.org/thrift.git/tutorial/js/build.xml index a9a9ad4..03a6e7c 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/js/build.xml +++ b/vendor/git.apache.org/thrift.git/tutorial/js/build.xml @@ -31,11 +31,13 @@ - - - + + + + + - + @@ -51,13 +53,13 @@ - - + + - + @@ -80,7 +82,7 @@ - + diff --git a/vendor/git.apache.org/thrift.git/tutorial/netcore/.gitignore b/vendor/git.apache.org/thrift.git/tutorial/netcore/.gitignore new file mode 100644 index 0000000..9938bb2 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/netcore/.gitignore @@ -0,0 +1 @@ +!**/*.pfx \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/tutorial/netcore/Client/Client.csproj b/vendor/git.apache.org/thrift.git/tutorial/netcore/Client/Client.csproj new file mode 100644 index 0000000..911272d --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/netcore/Client/Client.csproj @@ -0,0 +1,19 @@ + + + + netcoreapp2.0 + Client + Client + Exe + false + false + false + false + + + + + + + + diff --git a/vendor/git.apache.org/thrift.git/tutorial/netcore/Client/Program.cs b/vendor/git.apache.org/thrift.git/tutorial/netcore/Client/Program.cs new file mode 100644 index 0000000..ce5d8c7 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/netcore/Client/Program.cs @@ -0,0 +1,355 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Security; +using System.Security.Cryptography.X509Certificates; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Thrift; +using Thrift.Protocols; +using Thrift.Transports; +using Thrift.Transports.Client; +using tutorial; +using shared; + +namespace Client +{ + public class Program + { + private static readonly ILogger Logger = new LoggerFactory().AddConsole().AddDebug().CreateLogger(nameof(Client)); + + private static void DisplayHelp() + { + Logger.LogInformation(@" +Usage: + Client.exe -help + will diplay help information + + Client.exe -tr: -pr: -mc: + will run client with specified arguments (tcp transport and binary protocol by default) and with 1 client + +Options: + -tr (transport): + tcp - (default) tcp transport will be used (host - ""localhost"", port - 9090) + tcpbuffered - buffered transport over tcp will be used (host - ""localhost"", port - 9090) + namedpipe - namedpipe transport will be used (pipe address - "".test"") + http - http transport will be used (address - ""http://localhost:9090"") + tcptls - tcp tls transport will be used (host - ""localhost"", port - 9090) + framed - tcp framed transport will be used (host - ""localhost"", port - 9090) + + -pr (protocol): + binary - (default) binary protocol will be used + compact - compact protocol will be used + json - json protocol will be used + multiplexed - multiplexed protocol will be used + + -mc (multiple clients): + - number of multiple clients to connect to server (max 100, default 1) + +Sample: + Client.exe -tr:tcp -p:binary +"); + } + + public static void Main(string[] args) + { + args = args ?? new string[0]; + + if (args.Any(x => x.StartsWith("-help", StringComparison.OrdinalIgnoreCase))) + { + DisplayHelp(); + return; + } + + Logger.LogInformation("Starting client..."); + + using (var source = new CancellationTokenSource()) + { + RunAsync(args, source.Token).GetAwaiter().GetResult(); + } + } + + private static async Task RunAsync(string[] args, CancellationToken cancellationToken) + { + var numClients = GetNumberOfClients(args); + + Logger.LogInformation($"Selected # of clients: {numClients}"); + + var transports = new TClientTransport[numClients]; + for (int i = 0; i < numClients; i++) + { + var t = GetTransport(args); + transports[i] = t; + } + + Logger.LogInformation($"Selected client transport: {transports[0]}"); + + var protocols = new Tuple[numClients]; + for (int i = 0; i < numClients; i++) + { + var p = GetProtocol(args, transports[i]); + protocols[i] = p; + } + + Logger.LogInformation($"Selected client protocol: {protocols[0].Item1}"); + + var tasks = new Task[numClients]; + for (int i = 0; i < numClients; i++) + { + var task = RunClientAsync(protocols[i], cancellationToken); + tasks[i] = task; + } + + Task.WaitAll(tasks); + + await Task.CompletedTask; + } + + private static TClientTransport GetTransport(string[] args) + { + var transport = args.FirstOrDefault(x => x.StartsWith("-tr"))?.Split(':')?[1]; + + Transport selectedTransport; + if (Enum.TryParse(transport, true, out selectedTransport)) + { + switch (selectedTransport) + { + case Transport.Tcp: + return new TSocketClientTransport(IPAddress.Loopback, 9090); + case Transport.NamedPipe: + return new TNamedPipeClientTransport(".test"); + case Transport.Http: + return new THttpClientTransport(new Uri("http://localhost:9090"), null); + case Transport.TcpBuffered: + return new TBufferedClientTransport(new TSocketClientTransport(IPAddress.Loopback, 9090)); + case Transport.TcpTls: + return new TTlsSocketClientTransport(IPAddress.Loopback, 9090, GetCertificate(), CertValidator, LocalCertificateSelectionCallback); + case Transport.Framed: + return new TFramedClientTransport(new TSocketClientTransport(IPAddress.Loopback, 9090)); + } + } + + return new TSocketClientTransport(IPAddress.Loopback, 9090); + } + + private static int GetNumberOfClients(string[] args) + { + var numClients = args.FirstOrDefault(x => x.StartsWith("-mc"))?.Split(':')?[1]; + + Logger.LogInformation($"Selected # of clients: {numClients}"); + + int c; + if( int.TryParse(numClients, out c) && (0 < c) && (c <= 100)) + return c; + else + return 1; + } + + private static X509Certificate2 GetCertificate() + { + // due to files location in net core better to take certs from top folder + var certFile = GetCertPath(Directory.GetParent(Directory.GetCurrentDirectory())); + return new X509Certificate2(certFile, "ThriftTest"); + } + + private static string GetCertPath(DirectoryInfo di, int maxCount = 6) + { + var topDir = di; + var certFile = + topDir.EnumerateFiles("ThriftTest.pfx", SearchOption.AllDirectories) + .FirstOrDefault(); + if (certFile == null) + { + if (maxCount == 0) + throw new FileNotFoundException("Cannot find file in directories"); + return GetCertPath(di.Parent, maxCount - 1); + } + + return certFile.FullName; + } + + private static X509Certificate LocalCertificateSelectionCallback(object sender, + string targetHost, X509CertificateCollection localCertificates, + X509Certificate remoteCertificate, string[] acceptableIssuers) + { + return GetCertificate(); + } + + private static bool CertValidator(object sender, X509Certificate certificate, + X509Chain chain, SslPolicyErrors sslPolicyErrors) + { + return true; + } + + private static Tuple GetProtocol(string[] args, TClientTransport transport) + { + var protocol = args.FirstOrDefault(x => x.StartsWith("-pr"))?.Split(':')?[1]; + + Protocol selectedProtocol; + if (Enum.TryParse(protocol, true, out selectedProtocol)) + { + switch (selectedProtocol) + { + case Protocol.Binary: + return new Tuple(selectedProtocol, new TBinaryProtocol(transport)); + case Protocol.Compact: + return new Tuple(selectedProtocol, new TCompactProtocol(transport)); + case Protocol.Json: + return new Tuple(selectedProtocol, new TJsonProtocol(transport)); + case Protocol.Multiplexed: + // it returns BinaryProtocol to avoid making wrapped protocol as public in TProtocolDecorator (in RunClientAsync it will be wrapped into Multiplexed protocol) + return new Tuple(selectedProtocol, new TBinaryProtocol(transport)); + } + } + + return new Tuple(selectedProtocol, new TBinaryProtocol(transport)); + } + + private static async Task RunClientAsync(Tuple protocolTuple, CancellationToken cancellationToken) + { + try + { + var protocol = protocolTuple.Item2; + var protocolType = protocolTuple.Item1; + + TBaseClient client = null; + + try + { + if (protocolType != Protocol.Multiplexed) + { + + client = new Calculator.Client(protocol); + await ExecuteCalculatorClientOperations(cancellationToken, (Calculator.Client)client); + } + else + { + // it uses binary protocol there to create Multiplexed protocols + var multiplex = new TMultiplexedProtocol(protocol, nameof(Calculator)); + client = new Calculator.Client(multiplex); + await ExecuteCalculatorClientOperations(cancellationToken, (Calculator.Client)client); + + multiplex = new TMultiplexedProtocol(protocol, nameof(SharedService)); + client = new SharedService.Client(multiplex); + await ExecuteSharedServiceClientOperations(cancellationToken, (SharedService.Client)client); + } + } + catch (Exception ex) + { + Logger.LogError($"{client?.ClientId} " + ex); + } + finally + { + protocol.Transport.Close(); + } + } + catch (TApplicationException x) + { + Logger.LogError(x.ToString()); + } + } + + private static async Task ExecuteCalculatorClientOperations(CancellationToken cancellationToken, Calculator.Client client) + { + await client.OpenTransportAsync(cancellationToken); + + // Async version + + Logger.LogInformation($"{client.ClientId} PingAsync()"); + await client.pingAsync(cancellationToken); + + Logger.LogInformation($"{client.ClientId} AddAsync(1,1)"); + var sum = await client.addAsync(1, 1, cancellationToken); + Logger.LogInformation($"{client.ClientId} AddAsync(1,1)={sum}"); + + var work = new Work + { + Op = Operation.DIVIDE, + Num1 = 1, + Num2 = 0 + }; + + try + { + Logger.LogInformation($"{client.ClientId} CalculateAsync(1)"); + await client.calculateAsync(1, work, cancellationToken); + Logger.LogInformation($"{client.ClientId} Whoa we can divide by 0"); + } + catch (InvalidOperation io) + { + Logger.LogInformation($"{client.ClientId} Invalid operation: " + io); + } + + work.Op = Operation.SUBTRACT; + work.Num1 = 15; + work.Num2 = 10; + + try + { + Logger.LogInformation($"{client.ClientId} CalculateAsync(1)"); + var diff = await client.calculateAsync(1, work, cancellationToken); + Logger.LogInformation($"{client.ClientId} 15-10={diff}"); + } + catch (InvalidOperation io) + { + Logger.LogInformation($"{client.ClientId} Invalid operation: " + io); + } + + Logger.LogInformation($"{client.ClientId} GetStructAsync(1)"); + var log = await client.getStructAsync(1, cancellationToken); + Logger.LogInformation($"{client.ClientId} Check log: {log.Value}"); + + Logger.LogInformation($"{client.ClientId} ZipAsync() with delay 100mc on server side"); + await client.zipAsync(cancellationToken); + } + private static async Task ExecuteSharedServiceClientOperations(CancellationToken cancellationToken, SharedService.Client client) + { + await client.OpenTransportAsync(cancellationToken); + + // Async version + + Logger.LogInformation($"{client.ClientId} SharedService GetStructAsync(1)"); + var log = await client.getStructAsync(1, cancellationToken); + Logger.LogInformation($"{client.ClientId} SharedService Value: {log.Value}"); + } + + + private enum Transport + { + Tcp, + NamedPipe, + Http, + TcpBuffered, + Framed, + TcpTls + } + + private enum Protocol + { + Binary, + Compact, + Json, + Multiplexed + } + } +} diff --git a/vendor/git.apache.org/thrift.git/tutorial/netcore/Client/Properties/AssemblyInfo.cs b/vendor/git.apache.org/thrift.git/tutorial/netcore/Client/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..568382e --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/netcore/Client/Properties/AssemblyInfo.cs @@ -0,0 +1,40 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. + +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("The Apache Software Foundation")] +[assembly: AssemblyProduct("Thrift")] +[assembly: AssemblyCopyright("The Apache Software Foundation")] +[assembly: AssemblyTrademark("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. + +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM + +[assembly: Guid("de78a01b-f7c6-49d1-97da-669d2ed37641")] \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/tutorial/netcore/Client/Properties/launchSettings.json b/vendor/git.apache.org/thrift.git/tutorial/netcore/Client/Properties/launchSettings.json new file mode 100644 index 0000000..6b7b60d --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/netcore/Client/Properties/launchSettings.json @@ -0,0 +1,8 @@ +{ + "profiles": { + "Client": { + "commandName": "Project", + "commandLineArgs": "-p:multiplexed" + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/tutorial/netcore/Client/ThriftTest.pfx b/vendor/git.apache.org/thrift.git/tutorial/netcore/Client/ThriftTest.pfx new file mode 100644 index 0000000000000000000000000000000000000000..f0ded28173dc2c33cebbb2b74e1e9e9e870b5876 GIT binary patch literal 2661 zcmY+Fc{r5q7ssC&Gb1!J$(kiQNi-_kNTzK}lBB4-#%>tDNgCV8K7;IKOK6d75tC&a zp={ZTH)}K@WXZmpv83PB^)A`wF(pXt7XpsY=bHUSlV3;5-A{d&ZS=A9rAjL!JLlxE zU_0M6u}dL5dyZUM*eZRTK7%!HnQk@RhDO-B4XYapVO%Fw7K^smqmrq9#TGaL=NEIm z?!`FK&>hR?Z@)%UKPau-%?m`A(>#}=i#q*6>Xe+P#mwBs6Q0@@Ixp|5@9I+wut zA#tRevtir~_G0T(aAFKzvy!O$=C`*W)A|(nrt(YY1n}Kp^LEZq_lyzXl)hwOG@G=i zxbiB-SnTQD^sz>x%QCdt1fw!Er?MpQ>#O~U^B1Ih|GdFM1{`4ISt#RHN4|ZYyq|=< z{j;$~n=*954;otf@)^47LvcfPIKt$_Y2BL+D}7sV7s{aov!F89pkkhg#@d`RVvtv8 zqhf(QFGtL@?Vi^c`LJWbZE9|TN_1?X9?l3DaIjMO5`V9F;~;j1FwiWFV#DZK zPZjSTs!0RAwSeaugCPfE_z~82e~?}o;1!SDpMJeV`Q?+Y@TQRE z%jhKjwXIG1?LW{8%1ry~$CvoFtuttc!kQ${aiZfTlsc}(9#g1pD3VzLU3ij7h2^CD z;6Lz8^m(Xe5?)8Y0Gr#QxBP*P)`mX~ycEnzpRed9N46To2eUk?5^Lp}$Xu=>65C8xu{J&6G(`>&f z-~~7X>HrGR1atr=u0{d&fFqaa0!O&99#K(?2gPlgcy9MFU_Ez}9Obs^@?Q}%0v{+j;MU>669QYwovF;u<-Oys<_RI{b3>F|lw0+!xJ>$_T%M|8 z*-&MWR7IRjyg|Rdz}Y^1c3>+=Wp`aAotnEcJk{mR2!9S=p@lzc?XYcYm9LJXMtHbTOVA7ageNhdBfi0|v1eLr9PtqI`)XEsA zC0p*r#f2MT4Hybzy5V<-3)*Qcno)THYn1lrjq6Dik zc86XkszLcvn;9QTVpJ9nk<@$OqssciMrRF6FvCqZbspu(u*qkj2*`%Mz8yK zJdDp2+luWj&vuSBXbE_thM;=6A| zTxptZh*kG4;p+`oVSXP~RY=Ckmncb%Q_UISo?$+pr{w0qs^nnM(Hjvem6Iv&+#MtM zv{NJq4}S()s9l6QL`u&D)**e1PVG7Kle}4G&E6j*6WUk@Gf{A7t$m7Kzgxiio)Vux zaUZfKT(@FZ>2x``Vy-=XKo?(27vH5gZ(9I{TgrlFvqh3z9qJGySLfwbj9a-H4Nq*qFpUg@ld}K z)hFz#CqBwVT7Rl=a|*hQAa-`0o9X{L*g@fX}@vnbf G^#21?=Cu0& literal 0 HcmV?d00001 diff --git a/vendor/git.apache.org/thrift.git/tutorial/netcore/Interfaces/.gitignore b/vendor/git.apache.org/thrift.git/tutorial/netcore/Interfaces/.gitignore new file mode 100644 index 0000000..2e7446e --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/netcore/Interfaces/.gitignore @@ -0,0 +1,3 @@ +# ignore for autogenerated files +/shared +/tutorial diff --git a/vendor/git.apache.org/thrift.git/tutorial/netcore/Interfaces/Interfaces.csproj b/vendor/git.apache.org/thrift.git/tutorial/netcore/Interfaces/Interfaces.csproj new file mode 100644 index 0000000..4297a06 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/netcore/Interfaces/Interfaces.csproj @@ -0,0 +1,30 @@ + + + + netstandard2.0 + Interfaces + Interfaces + false + false + false + false + + + + + + + + + + + + + + + + + + + + diff --git a/vendor/git.apache.org/thrift.git/tutorial/netcore/Interfaces/Properties/AssemblyInfo.cs b/vendor/git.apache.org/thrift.git/tutorial/netcore/Interfaces/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..9126b17 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/netcore/Interfaces/Properties/AssemblyInfo.cs @@ -0,0 +1,40 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. + +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("The Apache Software Foundation")] +[assembly: AssemblyProduct("Thrift")] +[assembly: AssemblyCopyright("The Apache Software Foundation")] +[assembly: AssemblyTrademark("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. + +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM + +[assembly: Guid("4d13163d-9067-4c9c-8af0-64e08451397d")] \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/tutorial/netcore/Makefile.am b/vendor/git.apache.org/thrift.git/tutorial/netcore/Makefile.am new file mode 100644 index 0000000..e305556 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/netcore/Makefile.am @@ -0,0 +1,42 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +SUBDIRS = . + +all-local: + $(DOTNETCORE) build + +clean-local: + $(RM) Interfaces.dll + $(RM) -r Client/bin + $(RM) -r Client/obj + $(RM) -r Server/bin + $(RM) -r Server/obj + $(RM) -r Interfaces/bin + $(RM) -r Interfaces/obj + +EXTRA_DIST = \ + Client \ + Interfaces \ + README.md \ + Server \ + Tutorial.sln \ + build.cmd \ + build.sh + diff --git a/vendor/git.apache.org/thrift.git/tutorial/netcore/README.md b/vendor/git.apache.org/thrift.git/tutorial/netcore/README.md new file mode 100644 index 0000000..626ef92 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/netcore/README.md @@ -0,0 +1,278 @@ +# Building of samples for different platforms + +# Reused components +- NET Core Standard 2.0 +- NET Core App 2.0 + +# How to build +- Download and install the latest .NET Core SDK for your platform https://www.microsoft.com/net/core#windowsvs2015 (archive for SDK 1.0.0-preview2-003121 located by: https://github.com/dotnet/core/blob/master/release-notes/download-archive.md) +- Ensure that you have thrift.exe which supports netcore lib and it added to PATH +- Go to current folder +- Run **build.sh** or **build.cmd** from the root of cloned repository +- Check tests in **src/Tests** folder +- Continue with /tutorials/netcore + +# How to run + +Notes: dotnet run supports passing arguments to app after -- symbols (https://docs.microsoft.com/en-us/dotnet/articles/core/tools/dotnet-run) - example: **dotnet run -- -h** will show help for app + +- build +- go to folder (Client/Server) +- run with specifying of correct parameters **dotnet run -tr:tcp -pr:multiplexed**, **dotnet run -help** (later, after migration to csproj and latest SDK will be possibility to use more usable form **dotnet run -- arguments**) + +#Notes +- Possible adding additional platforms after stabilization of .NET Core (runtimes, platforms (Red Hat Linux, OpenSuse, etc.) + +#Known issues +- In trace logging mode you can see some not important internal exceptions + +# Running of samples +Please install Thrift C# .NET Core library or copy sources and build them to correcly build and run samples + +# NetCore Server + +Usage: + + Server.exe -h + will diplay help information + + Server.exe -tr: -pr: + will run server with specified arguments (tcp transport and binary protocol by default) + +Options: + + -tr (transport): + tcp - (default) tcp transport will be used (host - ""localhost"", port - 9090) + tcpbuffered - tcp buffered transport will be used (host - ""localhost"", port - 9090) + namedpipe - namedpipe transport will be used (pipe address - "".test"") + http - http transport will be used (http address - ""localhost:9090"") + tcptls - tcp transport with tls will be used (host - ""localhost"", port - 9090) + framed - tcp framed transport will be used (host - ""localhost"", port - 9090) + + -pr (protocol): + binary - (default) binary protocol will be used + compact - compact protocol will be used + json - json protocol will be used + +Sample: + + Server.exe -tr:tcp + +**Remarks**: + + For TcpTls mode certificate's file ThriftTest.pfx should be in directory with binaries in case of command line usage (or at project level in case of debugging from IDE). + Password for certificate - "ThriftTest". + + + +# NetCore Client + +Usage: + + Client.exe -h + will diplay help information + + Client.exe -tr: -pr: -mc: + will run client with specified arguments (tcp transport and binary protocol by default) + +Options: + + -tr (transport): + tcp - (default) tcp transport will be used (host - ""localhost"", port - 9090) + tcpbuffered - buffered transport over tcp will be used (host - ""localhost"", port - 9090) + namedpipe - namedpipe transport will be used (pipe address - "".test"") + http - http transport will be used (address - ""http://localhost:9090"") + tcptls - tcp tls transport will be used (host - ""localhost"", port - 9090) + framed - tcp framed transport will be used (host - ""localhost"", port - 9090) + + -pr (protocol): + binary - (default) binary protocol will be used + compact - compact protocol will be used + json - json protocol will be used + + -mc (multiple clients): + - number of multiple clients to connect to server (max 100, default 1) + +Sample: + + Client.exe -tr:tcp -pr:binary -mc:10 + +Remarks: + + For TcpTls mode certificate's file ThriftTest.pfx should be in directory + with binaries in case of command line usage (or at project level in case of debugging from IDE). + Password for certificate - "ThriftTest". + +# How to test communication between NetCore and Python + +* Generate code with the latest **thrift.exe** util +* Ensure that **thrift.exe** util generated folder **gen-py** with generated code for Python +* Create **client.py** and **server.py** from the code examples below and save them to the folder with previosly generated folder **gen-py** +* Run netcore samples (client and server) and python samples (client and server) + +Remarks: + +Samples of client and server code below use correct methods (operations) +and fields (properties) according to generated contracts from *.thrift files + +At Windows 10 add record **127.0.0.1 testserver** to **C:\Windows\System32\drivers\etc\hosts** file +for correct work of python server + + +**Python Client:** + +```python +import sys +import glob +sys.path.append('gen-py') + +from tutorial import Calculator +from tutorial.ttypes import InvalidOperation, Operation, Work + +from thrift import Thrift +from thrift.transport import TSocket +from thrift.transport import TTransport +from thrift.protocol import TBinaryProtocol + + +def main(): + # Make socket + transport = TSocket.TSocket('127.0.0.1', 9090) + + # Buffering is critical. Raw sockets are very slow + transport = TTransport.TBufferedTransport(transport) + + # Wrap in a protocol + protocol = TBinaryProtocol.TBinaryProtocol(transport) + + # Create a client to use the protocol encoder + client = Calculator.Client(protocol) + + # Connect! + transport.open() + + client.Ping() + print('ping()') + + sum = client.Add(1, 1) + print(('1+1=%d' % (sum))) + + work = Work() + + work.Op = Operation.Divide + work.Num1 = 1 + work.Num2 = 0 + + try: + quotient = client.Calculate(1, work) + print('Whoa? You know how to divide by zero?') + print('FYI the answer is %d' % quotient) + except InvalidOperation as e: + print(('InvalidOperation: %r' % e)) + + work.Op = Operation.Substract + work.Num1 = 15 + work.Num2 = 10 + + diff = client.Calculate(1, work) + print(('15-10=%d' % (diff))) + + log = client.GetStruct(1) + print(('Check log: %s' % (log.Value))) + + client.Zip() + print('zip()') + + # Close! + transport.close() + +if __name__ == '__main__': + try: + main() + except Thrift.TException as tx: + print('%s' % tx.message) +``` + + +**Python Server:** + + +```python +import glob +import sys +sys.path.append('gen-py') + +from tutorial import Calculator +from tutorial.ttypes import InvalidOperation, Operation + +from shared.ttypes import SharedStruct + +from thrift.transport import TSocket +from thrift.transport import TTransport +from thrift.protocol import TBinaryProtocol +from thrift.server import TServer + + +class CalculatorHandler: + def __init__(self): + self.log = {} + + def Ping(self): + print('ping()') + + def Add(self, n1, n2): + print('add(%d,%d)' % (n1, n2)) + return n1 + n2 + + def Calculate(self, logid, work): + print('calculate(%d, %r)' % (logid, work)) + + if work.Op == Operation.Add: + val = work.Num1 + work.Num2 + elif work.Op == Operation.Substract: + val = work.Num1 - work.Num2 + elif work.Op == Operation.Multiply: + val = work.Num1 * work.Num2 + elif work.Op == Operation.Divide: + if work.Num2 == 0: + x = InvalidOperation() + x.WhatOp = work.Op + x.Why = 'Cannot divide by 0' + raise x + val = work.Num1 / work.Num2 + else: + x = InvalidOperation() + x.WhatOp = work.Op + x.Why = 'Invalid operation' + raise x + + log = SharedStruct() + log.Key = logid + log.Value = '%d' % (val) + self.log[logid] = log + + return val + + def GetStruct(self, key): + print('getStruct(%d)' % (key)) + return self.log[key] + + def Zip(self): + print('zip()') + +if __name__ == '__main__': + handler = CalculatorHandler() + processor = Calculator.Processor(handler) + transport = TSocket.TServerSocket(host="testserver", port=9090) + tfactory = TTransport.TBufferedTransportFactory() + pfactory = TBinaryProtocol.TBinaryProtocolFactory() + + server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) + print('Starting the server...') + server.serve() + print('done.') + + # You could do one of these for a multithreaded server + # server = TServer.TThreadedServer(processor, transport, tfactory, pfactory) + # server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory) +``` diff --git a/vendor/git.apache.org/thrift.git/tutorial/netcore/Server/Program.cs b/vendor/git.apache.org/thrift.git/tutorial/netcore/Server/Program.cs new file mode 100644 index 0000000..6a181ba --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/netcore/Server/Program.cs @@ -0,0 +1,428 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Security; +using System.Security.Cryptography.X509Certificates; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Thrift; +using Thrift.Protocols; +using Thrift.Server; +using Thrift.Transports; +using Thrift.Transports.Server; +using tutorial; +using shared; + +namespace Server +{ + public class Program + { + private static readonly ILogger Logger = new LoggerFactory().AddConsole(LogLevel.Trace).AddDebug(LogLevel.Trace).CreateLogger(nameof(Server)); + + public static void Main(string[] args) + { + args = args ?? new string[0]; + + if (args.Any(x => x.StartsWith("-help", StringComparison.OrdinalIgnoreCase))) + { + DisplayHelp(); + return; + } + + using (var source = new CancellationTokenSource()) + { + RunAsync(args, source.Token).GetAwaiter().GetResult(); + + Logger.LogInformation("Press any key to stop..."); + + Console.ReadLine(); + source.Cancel(); + } + + Logger.LogInformation("Server stopped"); + } + + private static void DisplayHelp() + { + Logger.LogInformation(@" +Usage: + Server.exe -help + will diplay help information + + Server.exe -tr: -pr: + will run server with specified arguments (tcp transport and binary protocol by default) + +Options: + -tr (transport): + tcp - (default) tcp transport will be used (host - ""localhost"", port - 9090) + tcpbuffered - tcp buffered transport will be used (host - ""localhost"", port - 9090) + namedpipe - namedpipe transport will be used (pipe address - "".test"") + http - http transport will be used (http address - ""localhost:9090"") + tcptls - tcp transport with tls will be used (host - ""localhost"", port - 9090) + framed - tcp framed transport will be used (host - ""localhost"", port - 9090) + + -pr (protocol): + binary - (default) binary protocol will be used + compact - compact protocol will be used + json - json protocol will be used + multiplexed - multiplexed protocol will be used + +Sample: + Server.exe -tr:tcp +"); + } + + private static async Task RunAsync(string[] args, CancellationToken cancellationToken) + { + var selectedTransport = GetTransport(args); + var selectedProtocol = GetProtocol(args); + + if (selectedTransport == Transport.Http) + { + new HttpServerSample().Run(cancellationToken); + } + else + { + await RunSelectedConfigurationAsync(selectedTransport, selectedProtocol, cancellationToken); + } + } + + private static Protocol GetProtocol(string[] args) + { + var transport = args.FirstOrDefault(x => x.StartsWith("-pr"))?.Split(':')?[1]; + + Enum.TryParse(transport, true, out Protocol selectedProtocol); + + return selectedProtocol; + } + + private static Transport GetTransport(string[] args) + { + var transport = args.FirstOrDefault(x => x.StartsWith("-tr"))?.Split(':')?[1]; + + Enum.TryParse(transport, true, out Transport selectedTransport); + + return selectedTransport; + } + + private static async Task RunSelectedConfigurationAsync(Transport transport, Protocol protocol, CancellationToken cancellationToken) + { + var fabric = new LoggerFactory().AddConsole(LogLevel.Trace).AddDebug(LogLevel.Trace); + var handler = new CalculatorAsyncHandler(); + ITAsyncProcessor processor = null; + + TServerTransport serverTransport = null; + + switch (transport) + { + case Transport.Tcp: + serverTransport = new TServerSocketTransport(9090); + break; + case Transport.TcpBuffered: + serverTransport = new TServerSocketTransport(port: 9090, clientTimeout: 10000, useBufferedSockets: true); + break; + case Transport.NamedPipe: + serverTransport = new TNamedPipeServerTransport(".test"); + break; + case Transport.TcpTls: + serverTransport = new TTlsServerSocketTransport(9090, false, GetCertificate(), ClientCertValidator, LocalCertificateSelectionCallback); + break; + case Transport.Framed: + serverTransport = new TServerFramedTransport(9090); + break; + } + + ITProtocolFactory inputProtocolFactory; + ITProtocolFactory outputProtocolFactory; + + switch (protocol) + { + case Protocol.Binary: + { + inputProtocolFactory = new TBinaryProtocol.Factory(); + outputProtocolFactory = new TBinaryProtocol.Factory(); + processor = new Calculator.AsyncProcessor(handler); + } + break; + case Protocol.Compact: + { + inputProtocolFactory = new TCompactProtocol.Factory(); + outputProtocolFactory = new TCompactProtocol.Factory(); + processor = new Calculator.AsyncProcessor(handler); + } + break; + case Protocol.Json: + { + inputProtocolFactory = new TJsonProtocol.Factory(); + outputProtocolFactory = new TJsonProtocol.Factory(); + processor = new Calculator.AsyncProcessor(handler); + } + break; + case Protocol.Multiplexed: + { + inputProtocolFactory = new TBinaryProtocol.Factory(); + outputProtocolFactory = new TBinaryProtocol.Factory(); + + var calcHandler = new CalculatorAsyncHandler(); + var calcProcessor = new Calculator.AsyncProcessor(calcHandler); + + var sharedServiceHandler = new SharedServiceAsyncHandler(); + var sharedServiceProcessor = new SharedService.AsyncProcessor(sharedServiceHandler); + + var multiplexedProcessor = new TMultiplexedProcessor(); + multiplexedProcessor.RegisterProcessor(nameof(Calculator), calcProcessor); + multiplexedProcessor.RegisterProcessor(nameof(SharedService), sharedServiceProcessor); + + processor = multiplexedProcessor; + } + break; + default: + throw new ArgumentOutOfRangeException(nameof(protocol), protocol, null); + } + + try + { + Logger.LogInformation( + $"Selected TAsyncServer with {serverTransport} transport, {processor} processor and {inputProtocolFactory} protocol factories"); + + var server = new AsyncBaseServer(processor, serverTransport, inputProtocolFactory, outputProtocolFactory, fabric); + + Logger.LogInformation("Starting the server..."); + await server.ServeAsync(cancellationToken); + } + catch (Exception x) + { + Logger.LogInformation(x.ToString()); + } + } + + private static X509Certificate2 GetCertificate() + { + // due to files location in net core better to take certs from top folder + var certFile = GetCertPath(Directory.GetParent(Directory.GetCurrentDirectory())); + return new X509Certificate2(certFile, "ThriftTest"); + } + + private static string GetCertPath(DirectoryInfo di, int maxCount = 6) + { + var topDir = di; + var certFile = + topDir.EnumerateFiles("ThriftTest.pfx", SearchOption.AllDirectories) + .FirstOrDefault(); + if (certFile == null) + { + if (maxCount == 0) + throw new FileNotFoundException("Cannot find file in directories"); + return GetCertPath(di.Parent, maxCount - 1); + } + + return certFile.FullName; + } + + private static X509Certificate LocalCertificateSelectionCallback(object sender, + string targetHost, X509CertificateCollection localCertificates, + X509Certificate remoteCertificate, string[] acceptableIssuers) + { + return GetCertificate(); + } + + private static bool ClientCertValidator(object sender, X509Certificate certificate, + X509Chain chain, SslPolicyErrors sslPolicyErrors) + { + return true; + } + + private enum Transport + { + Tcp, + TcpBuffered, + NamedPipe, + Http, + TcpTls, + Framed + } + + private enum Protocol + { + Binary, + Compact, + Json, + Multiplexed + } + + public class HttpServerSample + { + public void Run(CancellationToken cancellationToken) + { + var config = new ConfigurationBuilder() + .AddEnvironmentVariables(prefix: "ASPNETCORE_") + .Build(); + + var host = new WebHostBuilder() + .UseConfiguration(config) + .UseKestrel() + .UseUrls("http://localhost:9090") + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseStartup() + .Build(); + + host.RunAsync(cancellationToken).GetAwaiter().GetResult(); + } + + public class Startup + { + public Startup(IHostingEnvironment env) + { + var builder = new ConfigurationBuilder() + .SetBasePath(env.ContentRootPath) + .AddEnvironmentVariables(); + + Configuration = builder.Build(); + } + + public IConfigurationRoot Configuration { get; } + + // This method gets called by the runtime. Use this method to add services to the container. + public void ConfigureServices(IServiceCollection services) + { + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IHostingEnvironment env, + ILoggerFactory loggerFactory) + { + app.UseMiddleware(); + } + } + } + + public class CalculatorAsyncHandler : Calculator.IAsync + { + private readonly Dictionary _log = new Dictionary(); + + public CalculatorAsyncHandler() + { + } + + public async Task getStructAsync(int key, + CancellationToken cancellationToken) + { + Logger.LogInformation("GetStructAsync({0})", key); + return await Task.FromResult(_log[key]); + } + + public async Task pingAsync(CancellationToken cancellationToken) + { + Logger.LogInformation("PingAsync()"); + await Task.CompletedTask; + } + + public async Task addAsync(int num1, int num2, CancellationToken cancellationToken) + { + Logger.LogInformation($"AddAsync({num1},{num2})"); + return await Task.FromResult(num1 + num2); + } + + public async Task calculateAsync(int logid, Work w, CancellationToken cancellationToken) + { + Logger.LogInformation($"CalculateAsync({logid}, [{w.Op},{w.Num1},{w.Num2}])"); + + var val = 0; + switch (w.Op) + { + case Operation.ADD: + val = w.Num1 + w.Num2; + break; + + case Operation.SUBTRACT: + val = w.Num1 - w.Num2; + break; + + case Operation.MULTIPLY: + val = w.Num1 * w.Num2; + break; + + case Operation.DIVIDE: + if (w.Num2 == 0) + { + var io = new InvalidOperation + { + WhatOp = (int) w.Op, + Why = "Cannot divide by 0" + }; + + throw io; + } + val = w.Num1 / w.Num2; + break; + + default: + { + var io = new InvalidOperation + { + WhatOp = (int) w.Op, + Why = "Unknown operation" + }; + + throw io; + } + } + + var entry = new SharedStruct + { + Key = logid, + Value = val.ToString() + }; + + _log[logid] = entry; + + return await Task.FromResult(val); + } + + public async Task zipAsync(CancellationToken cancellationToken) + { + Logger.LogInformation("ZipAsync() with delay 100mc"); + await Task.Delay(100, CancellationToken.None); + } + } + + public class SharedServiceAsyncHandler : SharedService.IAsync + { + public async Task getStructAsync(int key, CancellationToken cancellationToken) + { + Logger.LogInformation("GetStructAsync({0})", key); + return await Task.FromResult(new SharedStruct() + { + Key = key, + Value = "GetStructAsync" + }); + } + } + } +} diff --git a/vendor/git.apache.org/thrift.git/tutorial/netcore/Server/Properties/AssemblyInfo.cs b/vendor/git.apache.org/thrift.git/tutorial/netcore/Server/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..a044235 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/netcore/Server/Properties/AssemblyInfo.cs @@ -0,0 +1,40 @@ +// Licensed to the Apache Software Foundation(ASF) under one +// or more contributor license agreements.See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership.The ASF licenses this file +// to you 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. + +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. + +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("The Apache Software Foundation")] +[assembly: AssemblyProduct("Thrift")] +[assembly: AssemblyCopyright("The Apache Software Foundation")] +[assembly: AssemblyTrademark("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. + +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM + +[assembly: Guid("e210fc10-5aff-4b04-ac21-58afc7b74b0c")] \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/tutorial/netcore/Server/Properties/launchSettings.json b/vendor/git.apache.org/thrift.git/tutorial/netcore/Server/Properties/launchSettings.json new file mode 100644 index 0000000..78076ff --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/netcore/Server/Properties/launchSettings.json @@ -0,0 +1,8 @@ +{ + "profiles": { + "Server": { + "commandName": "Project", + "commandLineArgs": "-p:multiplexed" + } + } +} \ No newline at end of file diff --git a/vendor/git.apache.org/thrift.git/tutorial/netcore/Server/Server.csproj b/vendor/git.apache.org/thrift.git/tutorial/netcore/Server/Server.csproj new file mode 100644 index 0000000..0fbd303 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/netcore/Server/Server.csproj @@ -0,0 +1,26 @@ + + + + netcoreapp2.0 + Server + Server + Exe + false + false + false + false + + + + + + + + + + + + + + + diff --git a/vendor/git.apache.org/thrift.git/tutorial/netcore/Server/ThriftTest.pfx b/vendor/git.apache.org/thrift.git/tutorial/netcore/Server/ThriftTest.pfx new file mode 100644 index 0000000000000000000000000000000000000000..f0ded28173dc2c33cebbb2b74e1e9e9e870b5876 GIT binary patch literal 2661 zcmY+Fc{r5q7ssC&Gb1!J$(kiQNi-_kNTzK}lBB4-#%>tDNgCV8K7;IKOK6d75tC&a zp={ZTH)}K@WXZmpv83PB^)A`wF(pXt7XpsY=bHUSlV3;5-A{d&ZS=A9rAjL!JLlxE zU_0M6u}dL5dyZUM*eZRTK7%!HnQk@RhDO-B4XYapVO%Fw7K^smqmrq9#TGaL=NEIm z?!`FK&>hR?Z@)%UKPau-%?m`A(>#}=i#q*6>Xe+P#mwBs6Q0@@Ixp|5@9I+wut zA#tRevtir~_G0T(aAFKzvy!O$=C`*W)A|(nrt(YY1n}Kp^LEZq_lyzXl)hwOG@G=i zxbiB-SnTQD^sz>x%QCdt1fw!Er?MpQ>#O~U^B1Ih|GdFM1{`4ISt#RHN4|ZYyq|=< z{j;$~n=*954;otf@)^47LvcfPIKt$_Y2BL+D}7sV7s{aov!F89pkkhg#@d`RVvtv8 zqhf(QFGtL@?Vi^c`LJWbZE9|TN_1?X9?l3DaIjMO5`V9F;~;j1FwiWFV#DZK zPZjSTs!0RAwSeaugCPfE_z~82e~?}o;1!SDpMJeV`Q?+Y@TQRE z%jhKjwXIG1?LW{8%1ry~$CvoFtuttc!kQ${aiZfTlsc}(9#g1pD3VzLU3ij7h2^CD z;6Lz8^m(Xe5?)8Y0Gr#QxBP*P)`mX~ycEnzpRed9N46To2eUk?5^Lp}$Xu=>65C8xu{J&6G(`>&f z-~~7X>HrGR1atr=u0{d&fFqaa0!O&99#K(?2gPlgcy9MFU_Ez}9Obs^@?Q}%0v{+j;MU>669QYwovF;u<-Oys<_RI{b3>F|lw0+!xJ>$_T%M|8 z*-&MWR7IRjyg|Rdz}Y^1c3>+=Wp`aAotnEcJk{mR2!9S=p@lzc?XYcYm9LJXMtHbTOVA7ageNhdBfi0|v1eLr9PtqI`)XEsA zC0p*r#f2MT4Hybzy5V<-3)*Qcno)THYn1lrjq6Dik zc86XkszLcvn;9QTVpJ9nk<@$OqssciMrRF6FvCqZbspu(u*qkj2*`%Mz8yK zJdDp2+luWj&vuSBXbE_thM;=6A| zTxptZh*kG4;p+`oVSXP~RY=Ckmncb%Q_UISo?$+pr{w0qs^nnM(Hjvem6Iv&+#MtM zv{NJq4}S()s9l6QL`u&D)**e1PVG7Kle}4G&E6j*6WUk@Gf{A7t$m7Kzgxiio)Vux zaUZfKT(@FZ>2x``Vy-=XKo?(27vH5gZ(9I{TgrlFvqh3z9qJGySLfwbj9a-H4Nq*qFpUg@ld}K z)hFz#CqBwVT7Rl=a|*hQAa-`0o9X{L*g@fX}@vnbf G^#21?=Cu0& literal 0 HcmV?d00001 diff --git a/vendor/git.apache.org/thrift.git/tutorial/netcore/Tutorial.sln b/vendor/git.apache.org/thrift.git/tutorial/netcore/Tutorial.sln new file mode 100644 index 0000000..2ddcd46 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/netcore/Tutorial.sln @@ -0,0 +1,78 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26114.2 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Thrift", "..\..\lib\netcore\Thrift\Thrift.csproj", "{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Interfaces", "Interfaces\Interfaces.csproj", "{B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Client", "Client\Client.csproj", "{E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Server", "Server\Server.csproj", "{E08F5B84-2B4A-4E09-82D1-E0715775CE5E}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|x64.ActiveCfg = Debug|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|x64.Build.0 = Debug|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|x86.ActiveCfg = Debug|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|x86.Build.0 = Debug|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|Any CPU.Build.0 = Release|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x64.ActiveCfg = Release|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x64.Build.0 = Release|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x86.ActiveCfg = Release|Any CPU + {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x86.Build.0 = Release|Any CPU + {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|x64.ActiveCfg = Debug|Any CPU + {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|x64.Build.0 = Debug|Any CPU + {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|x86.ActiveCfg = Debug|Any CPU + {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|x86.Build.0 = Debug|Any CPU + {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|Any CPU.Build.0 = Release|Any CPU + {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|x64.ActiveCfg = Release|Any CPU + {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|x64.Build.0 = Release|Any CPU + {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|x86.ActiveCfg = Release|Any CPU + {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|x86.Build.0 = Release|Any CPU + {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|x64.ActiveCfg = Debug|Any CPU + {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|x64.Build.0 = Debug|Any CPU + {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|x86.ActiveCfg = Debug|Any CPU + {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|x86.Build.0 = Debug|Any CPU + {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|Any CPU.Build.0 = Release|Any CPU + {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|x64.ActiveCfg = Release|Any CPU + {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|x64.Build.0 = Release|Any CPU + {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|x86.ActiveCfg = Release|Any CPU + {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|x86.Build.0 = Release|Any CPU + {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|x64.ActiveCfg = Debug|Any CPU + {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|x64.Build.0 = Debug|Any CPU + {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|x86.ActiveCfg = Debug|Any CPU + {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|x86.Build.0 = Debug|Any CPU + {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|Any CPU.Build.0 = Release|Any CPU + {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|x64.ActiveCfg = Release|Any CPU + {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|x64.Build.0 = Release|Any CPU + {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|x86.ActiveCfg = Release|Any CPU + {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {070A5D1D-B29D-4603-999D-693DB444AD0D} + EndGlobalSection +EndGlobal diff --git a/vendor/git.apache.org/thrift.git/tutorial/netcore/build.cmd b/vendor/git.apache.org/thrift.git/tutorial/netcore/build.cmd new file mode 100644 index 0000000..9b84ef2 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/netcore/build.cmd @@ -0,0 +1,25 @@ +@echo off +rem /* +rem * Licensed to the Apache Software Foundation (ASF) under one +rem * or more contributor license agreements. See the NOTICE file +rem * distributed with this work for additional information +rem * regarding copyright ownership. The ASF licenses this file +rem * to you under the Apache License, Version 2.0 (the +rem * "License"); you may not use this file except in compliance +rem * with the License. You may obtain a copy of the License at +rem * +rem * http://www.apache.org/licenses/LICENSE-2.0 +rem * +rem * Unless required by applicable law or agreed to in writing, +rem * software distributed under the License is distributed on an +rem * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +rem * KIND, either express or implied. See the License for the +rem * specific language governing permissions and limitations +rem * under the License. +rem */ +setlocal + +dotnet --info +dotnet build + +:eof diff --git a/vendor/git.apache.org/thrift.git/tutorial/netcore/build.sh b/vendor/git.apache.org/thrift.git/tutorial/netcore/build.sh new file mode 100755 index 0000000..c97e310 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/netcore/build.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash + +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +#exit if any command fails +set -e + +dotnet --info +dotnet build diff --git a/vendor/git.apache.org/thrift.git/tutorial/nodejs/Makefile.am b/vendor/git.apache.org/thrift.git/tutorial/nodejs/Makefile.am index ecf3b2b..1516fec 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/nodejs/Makefile.am +++ b/vendor/git.apache.org/thrift.git/tutorial/nodejs/Makefile.am @@ -17,8 +17,6 @@ # under the License. # -THRIFT = $(top_builddir)/compiler/cpp/thrift - gen-nodejs/Calculator.js gen-nodejs/SharedService.js: $(top_srcdir)/tutorial/tutorial.thrift $(THRIFT) --gen js:node -r $< diff --git a/vendor/git.apache.org/thrift.git/tutorial/nodejs/NodeClient.js b/vendor/git.apache.org/thrift.git/tutorial/nodejs/NodeClient.js index 130ba57..b4886e8 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/nodejs/NodeClient.js +++ b/vendor/git.apache.org/thrift.git/tutorial/nodejs/NodeClient.js @@ -20,7 +20,7 @@ var thrift = require('thrift'); var Calculator = require('./gen-nodejs/Calculator'); var ttypes = require('./gen-nodejs/tutorial_types'); - +const assert = require('assert'); var transport = thrift.TBufferedTransport; var protocol = thrift.TBinaryProtocol; diff --git a/vendor/git.apache.org/thrift.git/tutorial/nodejs/NodeClientPromise.js b/vendor/git.apache.org/thrift.git/tutorial/nodejs/NodeClientPromise.js index fac12ba..2cdc184 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/nodejs/NodeClientPromise.js +++ b/vendor/git.apache.org/thrift.git/tutorial/nodejs/NodeClientPromise.js @@ -20,7 +20,7 @@ var thrift = require('thrift'); var Calculator = require('./gen-nodejs/Calculator'); var ttypes = require('./gen-nodejs/tutorial_types'); - +const assert = require('assert'); var transport = thrift.TBufferedTransport; var protocol = thrift.TBinaryProtocol; diff --git a/vendor/git.apache.org/thrift.git/tutorial/ocaml/_oasis b/vendor/git.apache.org/thrift.git/tutorial/ocaml/_oasis index 23abdc6..a0ea6c5 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/ocaml/_oasis +++ b/vendor/git.apache.org/thrift.git/tutorial/ocaml/_oasis @@ -1,5 +1,5 @@ Name: tutorial -Version: 0.10.0 +Version: 0.12.0 OASISFormat: 0.3 Synopsis: OCaml Tutorial example Authors: Apache Thrift Developers diff --git a/vendor/git.apache.org/thrift.git/tutorial/perl/PerlClient.pl b/vendor/git.apache.org/thrift.git/tutorial/perl/PerlClient.pl index 1d59656..7c23289 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/perl/PerlClient.pl +++ b/vendor/git.apache.org/thrift.git/tutorial/perl/PerlClient.pl @@ -37,10 +37,10 @@ use tutorial::Types; use Data::Dumper; -my $socket = new Thrift::Socket('localhost',9090); -my $transport = new Thrift::BufferedTransport($socket,1024,1024); -my $protocol = new Thrift::BinaryProtocol($transport); -my $client = new tutorial::CalculatorClient($protocol); +my $socket = Thrift::Socket->new('localhost',9090); +my $transport = Thrift::BufferedTransport->new($socket,1024,1024); +my $protocol = Thrift::BinaryProtocol->new($transport); +my $client = tutorial::CalculatorClient->new($protocol); eval{ @@ -53,7 +53,7 @@ eval{ my $sum = $client->add(1,1); print "1+1=$sum\n"; - my $work = new tutorial::Work(); + my $work = tutorial::Work->new(); $work->op(tutorial::Operation::DIVIDE); $work->num1(1); @@ -63,7 +63,7 @@ eval{ $client->calculate(1, $work); print "Whoa! We can divide by zero?\n"; }; if($@) { - warn "InvalidOperation: ".Dumper($@); + warn 'InvalidOperation: '.Dumper($@); } $work->op(tutorial::Operation::SUBTRACT); diff --git a/vendor/git.apache.org/thrift.git/tutorial/perl/PerlServer.pl b/vendor/git.apache.org/thrift.git/tutorial/perl/PerlServer.pl index adec978..dfe6b89 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/perl/PerlServer.pl +++ b/vendor/git.apache.org/thrift.git/tutorial/perl/PerlServer.pl @@ -1,4 +1,4 @@ -#!/usr/bin/perl +#!/usr/bin/env perl # # Licensed to the Apache Software Foundation (ASF) under one @@ -67,20 +67,20 @@ sub calculate } elsif ($op == tutorial::Operation::DIVIDE) { if ($num2 == 0) { - my $x = new tutorial::InvalidOperation; + my $x = tutorial::InvalidOperation->new(); $x->whatOp($op); $x->why('Cannot divide by 0'); die $x; } $val = $num1 / $num2; } else { - my $x = new tutorial::InvalidOperation; + my $x = tutorial::InvalidOperation->new(); $x->whatOp($op); $x->why('Invalid operation'); die $x; } - my $log = new shared::SharedStruct; + my $log = shared::SharedStruct->new(); $log->key($logid); $log->value(int($val)); $self->{log}->{$logid} = $log; @@ -104,10 +104,10 @@ sub zip eval { - my $handler = new CalculatorHandler; - my $processor = new tutorial::CalculatorProcessor($handler); - my $serversocket = new Thrift::ServerSocket(9090); - my $forkingserver = new Thrift::ForkingServer($processor, $serversocket); + my $handler = CalculatorHandler->new(); + my $processor = tutorial::CalculatorProcessor->new($handler); + my $serversocket = Thrift::ServerSocket->new(9090); + my $forkingserver = Thrift::ForkingServer->new($processor, $serversocket); print "Starting the server...\n"; $forkingserver->serve(); print "done.\n"; diff --git a/vendor/git.apache.org/thrift.git/tutorial/php/PhpClient.php b/vendor/git.apache.org/thrift.git/tutorial/php/PhpClient.php index d262b8f..92dc3cb 100755 --- a/vendor/git.apache.org/thrift.git/tutorial/php/PhpClient.php +++ b/vendor/git.apache.org/thrift.git/tutorial/php/PhpClient.php @@ -5,7 +5,7 @@ namespace tutorial\php; error_reporting(E_ALL); -require_once __DIR__.'/../../lib/php/lib/Thrift/ClassLoader/ThriftClassLoader.php'; +require_once __DIR__.'/../../lib/php/lib/ClassLoader/ThriftClassLoader.php'; use Thrift\ClassLoader\ThriftClassLoader; diff --git a/vendor/git.apache.org/thrift.git/tutorial/php/PhpServer.php b/vendor/git.apache.org/thrift.git/tutorial/php/PhpServer.php index 22ae43e..5a9b49b 100755 --- a/vendor/git.apache.org/thrift.git/tutorial/php/PhpServer.php +++ b/vendor/git.apache.org/thrift.git/tutorial/php/PhpServer.php @@ -5,7 +5,7 @@ namespace tutorial\php; error_reporting(E_ALL); -require_once __DIR__.'/../../lib/php/lib/Thrift/ClassLoader/ThriftClassLoader.php'; +require_once __DIR__.'/../../lib/php/lib/ClassLoader/ThriftClassLoader.php'; use Thrift\ClassLoader\ThriftClassLoader; diff --git a/vendor/git.apache.org/thrift.git/tutorial/py.tornado/Makefile.am b/vendor/git.apache.org/thrift.git/tutorial/py.tornado/Makefile.am index 6ac6023..4b73c1e 100755 --- a/vendor/git.apache.org/thrift.git/tutorial/py.tornado/Makefile.am +++ b/vendor/git.apache.org/thrift.git/tutorial/py.tornado/Makefile.am @@ -17,8 +17,6 @@ # under the License. # -THRIFT = $(top_builddir)/compiler/cpp/thrift - gen-py.tornado/tutorial/Calculator.py gen-py.tornado/shared/SharedService.py: $(top_srcdir)/tutorial/tutorial.thrift $(THRIFT) --gen py:tornado -r $< diff --git a/vendor/git.apache.org/thrift.git/tutorial/py.twisted/Makefile.am b/vendor/git.apache.org/thrift.git/tutorial/py.twisted/Makefile.am index c6cbd45..50cd342 100755 --- a/vendor/git.apache.org/thrift.git/tutorial/py.twisted/Makefile.am +++ b/vendor/git.apache.org/thrift.git/tutorial/py.twisted/Makefile.am @@ -17,8 +17,6 @@ # under the License. # -THRIFT = $(top_builddir)/compiler/cpp/thrift - gen-py/tutorial/Calculator.py gen-py/shared/SharedService.py: $(top_srcdir)/tutorial/tutorial.thrift $(THRIFT) --gen py:twisted -r $< diff --git a/vendor/git.apache.org/thrift.git/tutorial/py/Makefile.am b/vendor/git.apache.org/thrift.git/tutorial/py/Makefile.am index d891640..7db816d 100755 --- a/vendor/git.apache.org/thrift.git/tutorial/py/Makefile.am +++ b/vendor/git.apache.org/thrift.git/tutorial/py/Makefile.am @@ -17,8 +17,6 @@ # under the License. # -THRIFT = $(top_builddir)/compiler/cpp/thrift - gen-py/tutorial/Calculator.py gen-py/shared/SharedService.py: $(top_srcdir)/tutorial/tutorial.thrift $(THRIFT) --gen py -r $< diff --git a/vendor/git.apache.org/thrift.git/tutorial/py/PythonClient.py b/vendor/git.apache.org/thrift.git/tutorial/py/PythonClient.py index c659716..a6c1966 100755 --- a/vendor/git.apache.org/thrift.git/tutorial/py/PythonClient.py +++ b/vendor/git.apache.org/thrift.git/tutorial/py/PythonClient.py @@ -81,6 +81,7 @@ def main(): # Close! transport.close() + if __name__ == '__main__': try: main() diff --git a/vendor/git.apache.org/thrift.git/tutorial/py/PythonServer.py b/vendor/git.apache.org/thrift.git/tutorial/py/PythonServer.py index eb132a1..e6421ef 100755 --- a/vendor/git.apache.org/thrift.git/tutorial/py/PythonServer.py +++ b/vendor/git.apache.org/thrift.git/tutorial/py/PythonServer.py @@ -82,10 +82,11 @@ class CalculatorHandler: def zip(self): print('zip()') + if __name__ == '__main__': handler = CalculatorHandler() processor = Calculator.Processor(handler) - transport = TSocket.TServerSocket(port=9090) + transport = TSocket.TServerSocket(host='127.0.0.1', port=9090) tfactory = TTransport.TBufferedTransportFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory() diff --git a/vendor/git.apache.org/thrift.git/tutorial/rb/Makefile.am b/vendor/git.apache.org/thrift.git/tutorial/rb/Makefile.am index 369e903..9372413 100755 --- a/vendor/git.apache.org/thrift.git/tutorial/rb/Makefile.am +++ b/vendor/git.apache.org/thrift.git/tutorial/rb/Makefile.am @@ -17,8 +17,6 @@ # under the License. # -THRIFT = $(top_builddir)/compiler/cpp/thrift - gen-py/calculator.rb gen-py/shared_service.rb: $(top_srcdir)/tutorial/tutorial.thrift $(THRIFT) --gen rb -r $< diff --git a/vendor/git.apache.org/thrift.git/tutorial/rs/Cargo.toml b/vendor/git.apache.org/thrift.git/tutorial/rs/Cargo.toml new file mode 100644 index 0000000..210a0da --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/rs/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "thrift-tutorial" +version = "0.1.0" +license = "Apache-2.0" +authors = ["Apache Thrift Developers "] +exclude = ["Makefile*", "shared.rs", "tutorial.rs"] +publish = false + +[dependencies] +clap = "<2.28.0" +ordered-float = "0.3.0" +try_from = "0.2.0" + +[dependencies.thrift] +path = "../../lib/rs" + diff --git a/vendor/git.apache.org/thrift.git/tutorial/rs/Makefile.am b/vendor/git.apache.org/thrift.git/tutorial/rs/Makefile.am new file mode 100644 index 0000000..666331e --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/rs/Makefile.am @@ -0,0 +1,52 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# + +THRIFT = $(top_builddir)/compiler/cpp/thrift + +gen-rs/tutorial.rs gen-rs/shared.rs: $(top_srcdir)/tutorial/tutorial.thrift + $(THRIFT) -out src --gen rs -r $< + +all-local: gen-rs/tutorial.rs + $(CARGO) build + [ -d bin ] || mkdir bin + cp target/debug/tutorial_server bin/tutorial_server + cp target/debug/tutorial_client bin/tutorial_client + +check: all + +tutorialserver: all + bin/tutorial_server + +tutorialclient: all + bin/tutorial_client + +clean-local: + $(CARGO) clean + -$(RM) Cargo.lock + -$(RM) src/shared.rs + -$(RM) src/tutorial.rs + -$(RM) -r bin + +EXTRA_DIST = \ + Cargo.toml \ + src/lib.rs \ + src/bin/tutorial_server.rs \ + src/bin/tutorial_client.rs \ + README.md + diff --git a/vendor/git.apache.org/thrift.git/tutorial/rs/README.md b/vendor/git.apache.org/thrift.git/tutorial/rs/README.md new file mode 100644 index 0000000..384e9f8 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/rs/README.md @@ -0,0 +1,317 @@ +# Rust Language Bindings for Thrift + +## Getting Started + +1. Get the [Thrift compiler](https://thrift.apache.org). + +2. Add the following crates to your `Cargo.toml`. + +```toml +thrift = "x.y.z" # x.y.z is the version of the thrift compiler +ordered_float = "0.3.0" +try_from = "0.2.0" +``` + +3. Add the same crates to your `lib.rs` or `main.rs`. + +```rust +extern crate ordered_float; +extern crate thrift; +extern crate try_from; +``` + +4. Generate Rust sources for your IDL (for example, `Tutorial.thrift`). + +```shell +thrift -out my_rust_program/src --gen rs -r Tutorial.thrift +``` + +5. Use the generated source in your code. + +```rust +// add extern crates here, or in your lib.rs +extern crate ordered_float; +extern crate thrift; +extern crate try_from; + +// generated Rust module +use tutorial; + +use thrift::protocol::{TCompactInputProtocol, TCompactOutputProtocol}; +use thrift::protocol::{TInputProtocol, TOutputProtocol}; +use thrift::transport::{TFramedReadTransport, TFramedWriteTransport}; +use thrift::transport::{TIoChannel, TTcpChannel}; +use tutorial::{CalculatorSyncClient, TCalculatorSyncClient}; +use tutorial::{Operation, Work}; + +fn main() { + match run() { + Ok(()) => println!("client ran successfully"), + Err(e) => { + println!("client failed with {:?}", e); + std::process::exit(1); + } + } +} + +fn run() -> thrift::Result<()> { + // + // build client + // + + println!("connect to server on 127.0.0.1:9090"); + let mut c = TTcpTransport::new(); + c.open("127.0.0.1:9090")?; + + let (i_chan, o_chan) = c.split()?; + + let i_prot = TCompactInputProtocol::new( + TFramedReadTransport::new(i_chan) + ); + let o_prot = TCompactOutputProtocol::new( + TFramedWriteTransport::new(o_chan) + ); + + let client = CalculatorSyncClient::new(i_prot, o_prot); + + // + // alright! - let's make some calls + // + + // two-way, void return + client.ping()?; + + // two-way with some return + let res = client.calculate( + 72, + Work::new(7, 8, Operation::MULTIPLY, None) + )?; + println!("multiplied 7 and 8, got {}", res); + + // two-way and returns a Thrift-defined exception + let res = client.calculate( + 77, + Work::new(2, 0, Operation::DIVIDE, None) + ); + match res { + Ok(v) => panic!("shouldn't have succeeded with result {}", v), + Err(e) => println!("divide by zero failed with {:?}", e), + } + + // one-way + client.zip()?; + + // done! + Ok(()) +} +``` + +## Code Generation + +### Thrift Files and Generated Modules + +The Thrift code generator takes each Thrift file and generates a Rust module +with the same name snake-cased. For example, running the compiler on +`ThriftTest.thrift` creates `thrift_test.rs`. To use these generated files add +`mod ...` and `use ...` declarations to your `lib.rs` or `main.rs` - one for +each generated file. + +### Results and Errors + +The Thrift runtime library defines a `thrift::Result` and a `thrift::Error` type, +both of which are used throught the runtime library and in all generated code. +Conversions are defined from `std::io::Error`, `str` and `String` into +`thrift::Error`. + +### Thrift Type and their Rust Equivalents + +Thrift defines a number of types, each of which is translated into its Rust +equivalent by the code generator. + +* Primitives (bool, i8, i16, i32, i64, double, string, binary) +* Typedefs +* Enums +* Containers +* Structs +* Unions +* Exceptions +* Services +* Constants (primitives, containers, structs) + +In addition, unless otherwise noted, thrift includes are translated into +`use ...` statements in the generated code, and all declarations, parameters, +traits and types in the generated code are namespaced appropriately. + +The following subsections cover each type and their generated Rust equivalent. + +### Primitives + +Thrift primitives have straightforward Rust equivalents. + +* bool: `bool` +* i8: `i8` +* i16: `i16` +* i32: `i32` +* i64: `i64` +* double: `OrderedFloat` +* string: `String` +* binary: `Vec` + +### Typedefs + +A typedef is translated to a `pub type` declaration. + +```thrift +typedef i64 UserId + +typedef map MapType +``` +```rust +pub type UserId = i64; + +pub type MapType = BTreeMap; +``` + +### Enums + +A Thrift enum is represented as a Rust enum, and each variant is transcribed 1:1. + +```thrift +enum Numberz +{ + ONE = 1, + TWO, + THREE, + FIVE = 5, + SIX, + EIGHT = 8 +} +``` + +```rust +#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] +pub enum Numberz { + ONE = 1, + TWO = 2, + THREE = 3, + FIVE = 5, + SIX = 6, + EIGHT = 8, +} + +impl TryFrom for Numberz { + // ... +} + +``` + +### Containers + +Thrift has three container types: list, set and map. They are translated into +Rust `Vec`, `BTreeSet` and `BTreeMap` respectively. Any Thrift type (this +includes structs, enums and typedefs) can be a list/set element or a map +key/value. + +#### List + +```thrift +list numbers +``` + +```rust +numbers: Vec +``` + +#### Set + +```thrift +set numbers +``` + +```rust +numbers: BTreeSet +``` + +#### Map + +```thrift +map numbers +``` + +```rust +numbers: BTreeMap +``` + +### Structs + +A Thrift struct is represented as a Rust struct, and each field transcribed 1:1. + +```thrift +struct CrazyNesting { + 1: string string_field, + 2: optional set set_field, + 3: required list< + map, map>>>> + > + 4: binary binary_field +} +``` +```rust +#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] +pub struct CrazyNesting { + pub string_field: Option, + pub set_field: Option>, + pub list_field: Vec< + BTreeMap< + BTreeSet, + BTreeMap>>> + > + >, + pub binary_field: Option>, +} + +impl CrazyNesting { + pub fn read_from_in_protocol(i_prot: &mut TInputProtocol) + -> + thrift::Result { + // ... + } + pub fn write_to_out_protocol(&self, o_prot: &mut TOutputProtocol) + -> + thrift::Result<()> { + // ... + } +} + +``` +##### Optionality + +Thrift has 3 "optionality" types: + +1. Required +2. Optional +3. Default + +The Rust code generator encodes *Required* fields as the bare type itself, while +*Optional* and *Default* fields are encoded as `Option`. + +```thrift +struct Foo { + 1: required string bar // 1. required + 2: optional string baz // 2. optional + 3: string qux // 3. default +} +``` + +```rust +pub struct Foo { + bar: String, // 1. required + baz: Option, // 2. optional + qux: Option, // 3. default +} +``` + +## Known Issues + +* Struct constants are not supported +* Map, list and set constants require a const holder struct diff --git a/vendor/git.apache.org/thrift.git/tutorial/rs/src/bin/tutorial_client.rs b/vendor/git.apache.org/thrift.git/tutorial/rs/src/bin/tutorial_client.rs new file mode 100644 index 0000000..c80fafc --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/rs/src/bin/tutorial_client.rs @@ -0,0 +1,130 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +#[macro_use] +extern crate clap; + +extern crate thrift; +extern crate thrift_tutorial; + +use thrift::protocol::{TCompactInputProtocol, TCompactOutputProtocol}; +use thrift::transport::{ + ReadHalf, TFramedReadTransport, TFramedWriteTransport, TIoChannel, TTcpChannel, WriteHalf, +}; + +use thrift_tutorial::shared::TSharedServiceSyncClient; +use thrift_tutorial::tutorial::{CalculatorSyncClient, Operation, TCalculatorSyncClient, Work}; + +fn main() { + match run() { + Ok(()) => println!("tutorial client ran successfully"), + Err(e) => { + println!("tutorial client failed with error {:?}", e); + std::process::exit(1); + } + } +} + +fn run() -> thrift::Result<()> { + let options = clap_app!(rust_tutorial_client => + (version: "0.1.0") + (author: "Apache Thrift Developers ") + (about: "Thrift Rust tutorial client") + (@arg host: --host +takes_value "host on which the tutorial server listens") + (@arg port: --port +takes_value "port on which the tutorial server listens") + ); + let matches = options.get_matches(); + + // get any passed-in args or the defaults + let host = matches.value_of("host").unwrap_or("127.0.0.1"); + let port = value_t!(matches, "port", u16).unwrap_or(9090); + + // build our client and connect to the host:port + let mut client = new_client(host, port)?; + + // alright! + // let's start making some calls + + // let's start with a ping; the server should respond + println!("ping!"); + client.ping()?; + + // simple add + println!("add"); + let res = client.add(1, 2)?; + println!("added 1, 2 and got {}", res); + + let logid = 32; + + // let's do...a multiply! + let res = client.calculate(logid, Work::new(7, 8, Operation::Multiply, None))?; + println!("multiplied 7 and 8 and got {}", res); + + // let's get the log for it + let res = client.get_struct(32)?; + println!("got log {:?} for operation {}", res, logid); + + // ok - let's be bad :( + // do a divide by 0 + // logid doesn't matter; won't be recorded + let res = client.calculate(77, Work::new(2, 0, Operation::Divide, "we bad".to_owned())); + + // we should have gotten an exception back + match res { + Ok(v) => panic!("should not have succeeded with result {}", v), + Err(e) => println!("divide by zero failed with error {:?}", e), + } + + // let's do a one-way call + println!("zip"); + client.zip()?; + + // and then close out with a final ping + println!("ping!"); + client.ping()?; + + Ok(()) +} + +type ClientInputProtocol = TCompactInputProtocol>>; +type ClientOutputProtocol = TCompactOutputProtocol>>; + +fn new_client( + host: &str, + port: u16, +) -> thrift::Result> { + let mut c = TTcpChannel::new(); + + // open the underlying TCP stream + println!("connecting to tutorial server on {}:{}", host, port); + c.open(&format!("{}:{}", host, port))?; + + // clone the TCP channel into two halves, one which + // we'll use for reading, the other for writing + let (i_chan, o_chan) = c.split()?; + + // wrap the raw sockets (slow) with a buffered transport of some kind + let i_tran = TFramedReadTransport::new(i_chan); + let o_tran = TFramedWriteTransport::new(o_chan); + + // now create the protocol implementations + let i_prot = TCompactInputProtocol::new(i_tran); + let o_prot = TCompactOutputProtocol::new(o_tran); + + // we're done! + Ok(CalculatorSyncClient::new(i_prot, o_prot)) +} diff --git a/vendor/git.apache.org/thrift.git/tutorial/rs/src/bin/tutorial_server.rs b/vendor/git.apache.org/thrift.git/tutorial/rs/src/bin/tutorial_server.rs new file mode 100644 index 0000000..95b1a2b --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/rs/src/bin/tutorial_server.rs @@ -0,0 +1,179 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +#[macro_use] +extern crate clap; + +extern crate thrift; +extern crate thrift_tutorial; + +use std::collections::HashMap; +use std::convert::{From, Into}; +use std::default::Default; +use std::sync::Mutex; + +use thrift::protocol::{TCompactInputProtocolFactory, TCompactOutputProtocolFactory}; +use thrift::server::TServer; + +use thrift::transport::{TFramedReadTransportFactory, TFramedWriteTransportFactory}; +use thrift_tutorial::shared::{SharedServiceSyncHandler, SharedStruct}; +use thrift_tutorial::tutorial::{CalculatorSyncHandler, CalculatorSyncProcessor}; +use thrift_tutorial::tutorial::{InvalidOperation, Operation, Work}; + +fn main() { + match run() { + Ok(()) => println!("tutorial server ran successfully"), + Err(e) => { + println!("tutorial server failed with error {:?}", e); + std::process::exit(1); + } + } +} + +fn run() -> thrift::Result<()> { + let options = clap_app!(rust_tutorial_server => + (version: "0.1.0") + (author: "Apache Thrift Developers ") + (about: "Thrift Rust tutorial server") + (@arg port: --port +takes_value "port on which the tutorial server listens") + ); + let matches = options.get_matches(); + + let port = value_t!(matches, "port", u16).unwrap_or(9090); + let listen_address = format!("127.0.0.1:{}", port); + + println!("binding to {}", listen_address); + + let i_tran_fact = TFramedReadTransportFactory::new(); + let i_prot_fact = TCompactInputProtocolFactory::new(); + + let o_tran_fact = TFramedWriteTransportFactory::new(); + let o_prot_fact = TCompactOutputProtocolFactory::new(); + + // demux incoming messages + let processor = CalculatorSyncProcessor::new(CalculatorServer { + ..Default::default() + }); + + // create the server and start listening + let mut server = TServer::new( + i_tran_fact, + i_prot_fact, + o_tran_fact, + o_prot_fact, + processor, + 10, + ); + + server.listen(&listen_address) +} + +/// Handles incoming Calculator service calls. +struct CalculatorServer { + log: Mutex>, +} + +impl Default for CalculatorServer { + fn default() -> CalculatorServer { + CalculatorServer { + log: Mutex::new(HashMap::new()), + } + } +} + +// since Calculator extends SharedService we have to implement the +// handler for both traits. +// + +// SharedService handler +impl SharedServiceSyncHandler for CalculatorServer { + fn handle_get_struct(&self, key: i32) -> thrift::Result { + let log = self.log.lock().unwrap(); + log.get(&key) + .cloned() + .ok_or_else(|| format!("could not find log for key {}", key).into()) + } +} + +// Calculator handler +impl CalculatorSyncHandler for CalculatorServer { + fn handle_ping(&self) -> thrift::Result<()> { + println!("pong!"); + Ok(()) + } + + fn handle_add(&self, num1: i32, num2: i32) -> thrift::Result { + println!("handling add: n1:{} n2:{}", num1, num2); + Ok(num1 + num2) + } + + fn handle_calculate(&self, logid: i32, w: Work) -> thrift::Result { + println!("handling calculate: l:{}, w:{:?}", logid, w); + + let res = if let Some(ref op) = w.op { + if w.num1.is_none() || w.num2.is_none() { + Err(InvalidOperation { + what_op: Some(*op as i32), + why: Some("no operands specified".to_owned()), + }) + } else { + // so that I don't have to call unwrap() multiple times below + let num1 = w.num1.as_ref().expect("operands checked"); + let num2 = w.num2.as_ref().expect("operands checked"); + + match *op { + Operation::Add => Ok(num1 + num2), + Operation::Subtract => Ok(num1 - num2), + Operation::Multiply => Ok(num1 * num2), + Operation::Divide => { + if *num2 == 0 { + Err(InvalidOperation { + what_op: Some(*op as i32), + why: Some("divide by 0".to_owned()), + }) + } else { + Ok(num1 / num2) + } + } + } + } + } else { + Err(InvalidOperation::new( + None, + "no operation specified".to_owned(), + )) + }; + + // if the operation was successful log it + if let Ok(ref v) = res { + let mut log = self.log.lock().unwrap(); + log.insert(logid, SharedStruct::new(logid, format!("{}", v))); + } + + // the try! macro automatically maps errors + // but, since we aren't using that here we have to map errors manually + // + // exception structs defined in the IDL have an auto-generated + // impl of From::from + res.map_err(From::from) + } + + fn handle_zip(&self) -> thrift::Result<()> { + println!("handling zip"); + Ok(()) + } +} diff --git a/vendor/git.apache.org/thrift.git/tutorial/rs/src/lib.rs b/vendor/git.apache.org/thrift.git/tutorial/rs/src/lib.rs new file mode 100644 index 0000000..40007e5 --- /dev/null +++ b/vendor/git.apache.org/thrift.git/tutorial/rs/src/lib.rs @@ -0,0 +1,23 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +extern crate ordered_float; +extern crate thrift; +extern crate try_from; + +pub mod shared; +pub mod tutorial; diff --git a/vendor/git.apache.org/thrift.git/tutorial/shared.thrift b/vendor/git.apache.org/thrift.git/tutorial/shared.thrift index 386000b..f1685bd 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/shared.thrift +++ b/vendor/git.apache.org/thrift.git/tutorial/shared.thrift @@ -22,6 +22,7 @@ * these definitions. */ +namespace cl shared namespace cpp shared namespace d share // "shared" would collide with the eponymous D keyword. namespace dart shared @@ -29,6 +30,7 @@ namespace java shared namespace perl shared namespace php shared namespace haxe shared +namespace netcore shared struct SharedStruct { 1: i32 key diff --git a/vendor/git.apache.org/thrift.git/tutorial/tutorial.thrift b/vendor/git.apache.org/thrift.git/tutorial/tutorial.thrift index c4a96f0..e027546 100644 --- a/vendor/git.apache.org/thrift.git/tutorial/tutorial.thrift +++ b/vendor/git.apache.org/thrift.git/tutorial/tutorial.thrift @@ -62,6 +62,8 @@ include "shared.thrift" * Thrift files can namespace, package, or prefix their output in various * target languages. */ + +namespace cl tutorial namespace cpp tutorial namespace d tutorial namespace dart tutorial @@ -69,6 +71,7 @@ namespace java tutorial namespace php tutorial namespace perl tutorial namespace haxe tutorial +namespace netcore tutorial /** * Thrift lets you do typedefs to get pretty names for your types. Standard diff --git a/vendor/github.com/paypal/gorealis/.aurora-config/security.ini b/vendor/github.com/paypal/gorealis/.aurora-config/security.ini new file mode 100644 index 0000000..411fedb --- /dev/null +++ b/vendor/github.com/paypal/gorealis/.aurora-config/security.ini @@ -0,0 +1,5 @@ +[users] +aurora = secret, admin + +[roles] +admin = * diff --git a/vendor/github.com/paypal/gorealis/.gitattributes b/vendor/github.com/paypal/gorealis/.gitattributes new file mode 100644 index 0000000..c2f77d7 --- /dev/null +++ b/vendor/github.com/paypal/gorealis/.gitattributes @@ -0,0 +1,3 @@ +gen-go/ linguist-generated=true +vendor/ linguist-generated=true +Gopkg.lock linguist-generated=true diff --git a/vendor/github.com/paypal/gorealis/.travis.yml b/vendor/github.com/paypal/gorealis/.travis.yml index f9daf34..8e6f3e7 100644 --- a/vendor/github.com/paypal/gorealis/.travis.yml +++ b/vendor/github.com/paypal/gorealis/.travis.yml @@ -3,7 +3,7 @@ sudo: required language: go go: - - "1.10.x" + - "1.11.x" env: global: diff --git a/vendor/github.com/paypal/gorealis/Gopkg.lock b/vendor/github.com/paypal/gorealis/Gopkg.lock index 7ae916d..e130308 100644 --- a/vendor/github.com/paypal/gorealis/Gopkg.lock +++ b/vendor/github.com/paypal/gorealis/Gopkg.lock @@ -2,43 +2,59 @@ [[projects]] - branch = "0.10.0-http-client-fix" + branch = "0.12.0" + digest = "1:0d6d7a897b900dd5924e36bfa05dea429d7049b4b0b87bd3f93cb5f0acc35a21" name = "git.apache.org/thrift.git" packages = ["lib/go/thrift"] - revision = "cb1afec972a85791e9b24a04b60fc9dbbfc3cda3" - source = "github.com/rdelval/thrift" + pruneopts = "" + revision = "5c1ecb67cde4d9aff7ed3188ab11566184b27bf0" [[projects]] + digest = "1:56c130d885a4aacae1dd9c7b71cfe39912c7ebc1ff7d2b46083c8812996dc43b" name = "github.com/davecgh/go-spew" packages = ["spew"] + pruneopts = "" revision = "346938d642f2ec3594ed81d874461961cd0faa76" version = "v1.1.0" [[projects]] + digest = "1:df48fb76fb2a40edea0c9b3d960bc95e326660d82ff1114e1f88001f7a236b40" name = "github.com/pkg/errors" packages = ["."] + pruneopts = "" revision = "e881fd58d78e04cf6d0de1217f8707c8cc2249bc" [[projects]] + digest = "1:256484dbbcd271f9ecebc6795b2df8cad4c458dd0f5fd82a8c2fa0c29f233411" name = "github.com/pmezard/go-difflib" packages = ["difflib"] + pruneopts = "" revision = "792786c7400a136282c1664665ae0a8db921c6c2" version = "v1.0.0" [[projects]] + digest = "1:78bea5e26e82826dacc5fd64a1013a6711b7075ec8072819b89e6ad76cb8196d" name = "github.com/samuel/go-zookeeper" packages = ["zk"] + pruneopts = "" revision = "471cd4e61d7a78ece1791fa5faa0345dc8c7d5a5" [[projects]] + digest = "1:2d0dc026c4aef5e2f3a0e06a4dabe268b840d8f63190cf6894e02134a03f52c5" name = "github.com/stretchr/testify" packages = ["assert"] + pruneopts = "" revision = "b91bfb9ebec76498946beb6af7c0230c7cc7ba6c" version = "v1.2.0" [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "fdb631400420ca7299ad56b66175c9157ca073e3de52f666a84fc1d6fa893978" + input-imports = [ + "git.apache.org/thrift.git/lib/go/thrift", + "github.com/pkg/errors", + "github.com/samuel/go-zookeeper/zk", + "github.com/stretchr/testify/assert", + ] solver-name = "gps-cdcl" solver-version = 1 diff --git a/vendor/github.com/paypal/gorealis/Gopkg.toml b/vendor/github.com/paypal/gorealis/Gopkg.toml index d8c0ef0..c85824b 100644 --- a/vendor/github.com/paypal/gorealis/Gopkg.toml +++ b/vendor/github.com/paypal/gorealis/Gopkg.toml @@ -1,7 +1,6 @@ [[constraint]] name = "git.apache.org/thrift.git" - branch = "0.10.0-http-client-fix" - source = "github.com/rdelval/thrift" + branch = "0.12.0" [[constraint]] name = "github.com/pkg/errors" diff --git a/vendor/github.com/paypal/gorealis/clusters.go b/vendor/github.com/paypal/gorealis/clusters.go index 0d20db5..49e93f6 100644 --- a/vendor/github.com/paypal/gorealis/clusters.go +++ b/vendor/github.com/paypal/gorealis/clusters.go @@ -54,3 +54,14 @@ func LoadClusters(config string) (map[string]Cluster, error) { return m, nil } + +func GetDefaultClusterFromZKUrl(zkURL string) *Cluster { + return &Cluster{ + Name: "defaultCluster", + AuthMechanism: "UNAUTHENTICATED", + ZK: zkURL, + SchedZKPath: "/aurora/scheduler", + AgentRunDir: "latest", + AgentRoot: "/var/lib/mesos", + } +} diff --git a/vendor/github.com/paypal/gorealis/clusters_test.go b/vendor/github.com/paypal/gorealis/clusters_test.go index 4d34038..0663cdc 100644 --- a/vendor/github.com/paypal/gorealis/clusters_test.go +++ b/vendor/github.com/paypal/gorealis/clusters_test.go @@ -18,7 +18,7 @@ import ( "fmt" "testing" - "github.com/paypal/gorealis" + realis "github.com/paypal/gorealis" "github.com/stretchr/testify/assert" ) diff --git a/vendor/github.com/paypal/gorealis/container.go b/vendor/github.com/paypal/gorealis/container.go index 5735ec8..a79aaf6 100644 --- a/vendor/github.com/paypal/gorealis/container.go +++ b/vendor/github.com/paypal/gorealis/container.go @@ -22,28 +22,24 @@ type Container interface { Build() *aurora.Container } -type MesosContainer struct { - container *aurora.MesosContainer -} - type DockerContainer struct { container *aurora.DockerContainer } -func NewDockerContainer() DockerContainer { - return DockerContainer{container: aurora.NewDockerContainer()} +func NewDockerContainer() *DockerContainer { + return &DockerContainer{container: aurora.NewDockerContainer()} } -func (c DockerContainer) Build() *aurora.Container { +func (c *DockerContainer) Build() *aurora.Container { return &aurora.Container{Docker: c.container} } -func (c DockerContainer) Image(image string) DockerContainer { +func (c *DockerContainer) Image(image string) *DockerContainer { c.container.Image = image return c } -func (c DockerContainer) AddParameter(name, value string) DockerContainer { +func (c *DockerContainer) AddParameter(name, value string) *DockerContainer { c.container.Parameters = append(c.container.Parameters, &aurora.DockerParameter{ Name: name, Value: value, @@ -51,15 +47,19 @@ func (c DockerContainer) AddParameter(name, value string) DockerContainer { return c } -func NewMesosContainer() MesosContainer { - return MesosContainer{container: aurora.NewMesosContainer()} +type MesosContainer struct { + container *aurora.MesosContainer } -func (c MesosContainer) Build() *aurora.Container { +func NewMesosContainer() *MesosContainer { + return &MesosContainer{container: aurora.NewMesosContainer()} +} + +func (c *MesosContainer) Build() *aurora.Container { return &aurora.Container{Mesos: c.container} } -func (c MesosContainer) DockerImage(name, tag string) MesosContainer { +func (c *MesosContainer) DockerImage(name, tag string) *MesosContainer { if c.container.Image == nil { c.container.Image = aurora.NewImage() } @@ -68,7 +68,7 @@ func (c MesosContainer) DockerImage(name, tag string) MesosContainer { return c } -func (c MesosContainer) AppcImage(name, imageId string) MesosContainer { +func (c *MesosContainer) AppcImage(name, imageId string) *MesosContainer { if c.container.Image == nil { c.container.Image = aurora.NewImage() } @@ -76,3 +76,12 @@ func (c MesosContainer) AppcImage(name, imageId string) MesosContainer { c.container.Image.Appc = &aurora.AppcImage{Name: name, ImageId: imageId} return c } + +func (c *MesosContainer) AddVolume(hostPath, containerPath string, mode aurora.Mode) *MesosContainer { + c.container.Volumes = append(c.container.Volumes, &aurora.Volume{ + HostPath: hostPath, + ContainerPath: containerPath, + Mode: mode}) + + return c +} diff --git a/vendor/github.com/paypal/gorealis/docker-compose.yml b/vendor/github.com/paypal/gorealis/docker-compose.yml index ee0cff6..3632491 100644 --- a/vendor/github.com/paypal/gorealis/docker-compose.yml +++ b/vendor/github.com/paypal/gorealis/docker-compose.yml @@ -65,6 +65,12 @@ services: CLUSTER_NAME: test-cluster ZK_ENDPOINTS: "192.168.33.2:2181" MESOS_MASTER: "zk://192.168.33.2:2181/mesos" + EXTRA_SCHEDULER_ARGS: > + -http_authentication_mechanism=BASIC + -shiro_realm_modules=INI_AUTHNZ + -shiro_ini_path=/etc/aurora/security.ini + volumes: + - ./.aurora-config:/etc/aurora networks: aurora_cluster: ipv4_address: 192.168.33.7 diff --git a/vendor/github.com/paypal/gorealis/errors.go b/vendor/github.com/paypal/gorealis/errors.go index 7007f83..6469b69 100644 --- a/vendor/github.com/paypal/gorealis/errors.go +++ b/vendor/github.com/paypal/gorealis/errors.go @@ -17,7 +17,7 @@ package realis // Using a pattern described by Dave Cheney to differentiate errors // https://dave.cheney.net/2016/04/27/dont-just-check-errors-handle-them-gracefully -// Timeout errors are returned when a function is unable to continue executing due +// Timedout errors are returned when a function is unable to continue executing due // to a time constraint or meeting a set number of retries. type timeout interface { Timedout() bool diff --git a/vendor/github.com/paypal/gorealis/examples/client.go b/vendor/github.com/paypal/gorealis/examples/client.go index 4d62630..d4ea8f0 100644 --- a/vendor/github.com/paypal/gorealis/examples/client.go +++ b/vendor/github.com/paypal/gorealis/examples/client.go @@ -22,19 +22,18 @@ import ( "strings" "time" - "github.com/paypal/gorealis" + realis "github.com/paypal/gorealis" "github.com/paypal/gorealis/gen-go/apache/aurora" - "github.com/paypal/gorealis/response" ) var cmd, executor, url, clustersConfig, clusterName, updateId, username, password, zkUrl, hostList, role string var caCertsPath string var clientKey, clientCert string -var CONNECTION_TIMEOUT = 20000 +var ConnectionTimeout = 20 * time.Second func init() { - flag.StringVar(&cmd, "cmd", "", "Job request type to send to Aurora Scheduler") + flag.StringVar(&cmd, "cmd", "", "Aurora Job request type to send to Aurora Scheduler") flag.StringVar(&executor, "executor", "thermos", "Executor to use") flag.StringVar(&url, "url", "", "URL at which the Aurora Scheduler exists as [url]:[port]") flag.StringVar(&clustersConfig, "clusters", "", "Location of the clusters.json file used by aurora.") @@ -74,15 +73,14 @@ func init() { func main() { - var job realis.Job + var job *realis.AuroraJob var err error - var monitor *realis.Monitor - var r realis.Realis + var r *realis.Client clientOptions := []realis.ClientOption{ realis.BasicAuth(username, password), realis.ThriftJSON(), - realis.TimeoutMS(CONNECTION_TIMEOUT), + realis.Timeout(ConnectionTimeout), realis.BackOff(realis.Backoff{ Steps: 2, Duration: 10 * time.Second, @@ -92,7 +90,7 @@ func main() { realis.Debug(), } - //check if zkUrl is available. + // Check if zkUrl is available. if zkUrl != "" { fmt.Println("zkUrl: ", zkUrl) clientOptions = append(clientOptions, realis.ZKUrl(zkUrl)) @@ -101,18 +99,17 @@ func main() { } if caCertsPath != "" { - clientOptions = append(clientOptions, realis.Certspath(caCertsPath)) + clientOptions = append(clientOptions, realis.CertsPath(caCertsPath)) } if clientKey != "" && clientCert != "" { clientOptions = append(clientOptions, realis.ClientCerts(clientKey, clientCert)) } - r, err = realis.NewRealisClient(clientOptions...) + r, err = realis.NewClient(clientOptions...) if err != nil { log.Fatalln(err) } - monitor = &realis.Monitor{r} defer r.Close() switch executor { @@ -167,14 +164,13 @@ func main() { switch cmd { case "create": fmt.Println("Creating job") - resp, err := r.CreateJob(job) + err := r.CreateJob(job) if err != nil { log.Fatalln(err) } - fmt.Println(resp.String()) - if ok, mErr := monitor.Instances(job.JobKey(), job.GetInstanceCount(), 5, 50); !ok || mErr != nil { - _, err := r.KillJob(job.JobKey()) + if ok, mErr := r.InstancesMonitor(job.JobKey(), job.GetInstanceCount(), 5*time.Second, 50*time.Second); !ok || mErr != nil { + err := r.KillJob(job.JobKey()) if err != nil { log.Fatalln(err) } @@ -184,18 +180,16 @@ func main() { case "createService": // Create a service with three instances using the update API instead of the createJob API fmt.Println("Creating service") - settings := realis.NewUpdateSettings() - job.InstanceCount(3) - resp, result, err := r.CreateService(job, settings) + settings := realis.JobUpdateFromConfig(job.TaskConfig()).InstanceCount(3) + result, err := r.CreateService(settings) if err != nil { - log.Println("error: ", err) - log.Fatal("response: ", resp.String()) + log.Fatal("error: ", err) } fmt.Println(result.String()) - if ok, mErr := monitor.JobUpdate(*result.GetKey(), 5, 180); !ok || mErr != nil { - _, err := r.AbortJobUpdate(*result.GetKey(), "Monitor timed out") - _, err = r.KillJob(job.JobKey()) + if ok, mErr := r.JobUpdateMonitor(*result.GetKey(), 5*time.Second, 180*time.Second); !ok || mErr != nil { + err := r.AbortJobUpdate(*result.GetKey(), "Monitor timed out") + err = r.KillJob(job.JobKey()) if err != nil { log.Fatal(err) } @@ -206,14 +200,13 @@ func main() { fmt.Println("Creating a docker based job") container := realis.NewDockerContainer().Image("python:2.7").AddParameter("network", "host") job.Container(container) - resp, err := r.CreateJob(job) + err := r.CreateJob(job) if err != nil { log.Fatal(err) } - fmt.Println(resp.String()) - if ok, err := monitor.Instances(job.JobKey(), job.GetInstanceCount(), 10, 300); !ok || err != nil { - _, err := r.KillJob(job.JobKey()) + if ok, err := r.InstancesMonitor(job.JobKey(), job.GetInstanceCount(), 10*time.Second, 300*time.Second); !ok || err != nil { + err := r.KillJob(job.JobKey()) if err != nil { log.Fatal(err) } @@ -223,14 +216,13 @@ func main() { fmt.Println("Creating a docker based job") container := realis.NewMesosContainer().DockerImage("python", "2.7") job.Container(container) - resp, err := r.CreateJob(job) + err := r.CreateJob(job) if err != nil { log.Fatal(err) } - fmt.Println(resp.String()) - if ok, err := monitor.Instances(job.JobKey(), job.GetInstanceCount(), 10, 300); !ok || err != nil { - _, err := r.KillJob(job.JobKey()) + if ok, err := r.InstancesMonitor(job.JobKey(), job.GetInstanceCount(), 10*time.Second, 300*time.Second); !ok || err != nil { + err := r.KillJob(job.JobKey()) if err != nil { log.Fatal(err) } @@ -241,50 +233,44 @@ func main() { // Cron config job.CronSchedule("* * * * *") job.IsService(false) - resp, err := r.ScheduleCronJob(job) + err := r.ScheduleCronJob(job) if err != nil { log.Fatal(err) } - fmt.Println(resp.String()) case "startCron": fmt.Println("Starting a Cron job") - resp, err := r.StartCronJob(job.JobKey()) + err := r.StartCronJob(job.JobKey()) if err != nil { log.Fatal(err) } - fmt.Println(resp.String()) case "descheduleCron": fmt.Println("Descheduling a Cron job") - resp, err := r.DescheduleCronJob(job.JobKey()) + err := r.DescheduleCronJob(job.JobKey()) if err != nil { log.Fatal(err) } - fmt.Println(resp.String()) case "kill": fmt.Println("Killing job") - resp, err := r.KillJob(job.JobKey()) + err := r.KillJob(job.JobKey()) if err != nil { log.Fatal(err) } - if ok, err := monitor.Instances(job.JobKey(), 0, 5, 50); !ok || err != nil { + if ok, err := r.InstancesMonitor(job.JobKey(), 0, 5*time.Second, 50*time.Second); !ok || err != nil { log.Fatal("Unable to kill all instances of job") } - fmt.Println(resp.String()) case "restart": fmt.Println("Restarting job") - resp, err := r.RestartJob(job.JobKey()) + err := r.RestartJob(job.JobKey()) if err != nil { log.Fatal(err) } - fmt.Println(resp.String()) - case "liveCount": fmt.Println("Getting instance count") @@ -303,114 +289,110 @@ func main() { log.Fatal(err) } - fmt.Println("Number of live instances: ", len(live)) + fmt.Println("Active instances: ", live) case "flexUp": fmt.Println("Flexing up job") - numOfInstances := int32(4) + numOfInstances := 4 live, err := r.GetInstanceIds(job.JobKey(), aurora.ACTIVE_STATES) if err != nil { log.Fatal(err) } - currInstances := int32(len(live)) + currInstances := len(live) fmt.Println("Current num of instances: ", currInstances) - var instId int32 - for k := range live { - instId = k - } - resp, err := r.AddInstances(aurora.InstanceKey{ - JobKey: job.JobKey(), - InstanceId: instId, + + key := job.JobKey() + err = r.AddInstances(aurora.InstanceKey{ + JobKey: &key, + InstanceId: live[0], }, - numOfInstances) + int32(numOfInstances)) if err != nil { log.Fatal(err) } - if ok, err := monitor.Instances(job.JobKey(), currInstances+numOfInstances, 5, 50); !ok || err != nil { + if ok, err := r.InstancesMonitor(job.JobKey(), int32(currInstances+numOfInstances), 5*time.Second, 50*time.Second); !ok || err != nil { fmt.Println("Flexing up failed") } - fmt.Println(resp.String()) case "flexDown": fmt.Println("Flexing down job") - numOfInstances := int32(2) + numOfInstances := 2 live, err := r.GetInstanceIds(job.JobKey(), aurora.ACTIVE_STATES) if err != nil { log.Fatal(err) } - currInstances := int32(len(live)) + currInstances := len(live) fmt.Println("Current num of instances: ", currInstances) - resp, err := r.RemoveInstances(job.JobKey(), numOfInstances) + err = r.RemoveInstances(job.JobKey(), numOfInstances) if err != nil { log.Fatal(err) } - if ok, err := monitor.Instances(job.JobKey(), currInstances-numOfInstances, 5, 100); !ok || err != nil { + if ok, err := r.InstancesMonitor(job.JobKey(), int32(currInstances-numOfInstances), 5*time.Second, 100*time.Second); !ok || err != nil { fmt.Println("flexDown failed") } - fmt.Println(resp.String()) - case "update": fmt.Println("Updating a job with with more RAM and to 5 instances") live, err := r.GetInstanceIds(job.JobKey(), aurora.ACTIVE_STATES) if err != nil { log.Fatal(err) } - var instId int32 - for k := range live { - instId = k - } + + key := job.JobKey() taskConfig, err := r.FetchTaskConfig(aurora.InstanceKey{ - JobKey: job.JobKey(), - InstanceId: instId, + JobKey: &key, + InstanceId: live[0], }) if err != nil { log.Fatal(err) } - updateJob := realis.NewDefaultUpdateJob(taskConfig) - updateJob.InstanceCount(5).RAM(128) + updateJob := realis.JobUpdateFromConfig(taskConfig).InstanceCount(5).RAM(128) - resp, err := r.StartJobUpdate(updateJob, "") + result, err := r.StartJobUpdate(updateJob, "") if err != nil { log.Fatal(err) } - jobUpdateKey := response.JobUpdateKey(resp) - monitor.JobUpdate(*jobUpdateKey, 5, 500) + jobUpdateKey := result.GetKey() + _, err = r.JobUpdateMonitor(*jobUpdateKey, 5*time.Second, 6*time.Minute) + if err != nil { + log.Fatal(err) + } case "pauseJobUpdate": - resp, err := r.PauseJobUpdate(&aurora.JobUpdateKey{ - Job: job.JobKey(), + key := job.JobKey() + err := r.PauseJobUpdate(&aurora.JobUpdateKey{ + Job: &key, ID: updateId, }, "") if err != nil { log.Fatal(err) } - fmt.Println("PauseJobUpdate response: ", resp.String()) case "resumeJobUpdate": - resp, err := r.ResumeJobUpdate(&aurora.JobUpdateKey{ - Job: job.JobKey(), + key := job.JobKey() + err := r.ResumeJobUpdate(&aurora.JobUpdateKey{ + Job: &key, ID: updateId, }, "") if err != nil { log.Fatal(err) } - fmt.Println("ResumeJobUpdate response: ", resp.String()) case "pulseJobUpdate": + key := job.JobKey() resp, err := r.PulseJobUpdate(&aurora.JobUpdateKey{ - Job: job.JobKey(), + Job: &key, ID: updateId, }) if err != nil { @@ -420,9 +402,10 @@ func main() { fmt.Println("PulseJobUpdate response: ", resp.String()) case "updateDetails": - resp, err := r.JobUpdateDetails(aurora.JobUpdateQuery{ + key := job.JobKey() + result, err := r.JobUpdateDetails(aurora.JobUpdateQuery{ Key: &aurora.JobUpdateKey{ - Job: job.JobKey(), + Job: &key, ID: updateId, }, Limit: 1, @@ -432,12 +415,13 @@ func main() { log.Fatal(err) } - fmt.Println(response.JobUpdateDetails(resp)) + fmt.Println(result) case "abortUpdate": fmt.Println("Abort update") - resp, err := r.AbortJobUpdate(aurora.JobUpdateKey{ - Job: job.JobKey(), + key := job.JobKey() + err := r.AbortJobUpdate(aurora.JobUpdateKey{ + Job: &key, ID: updateId, }, "") @@ -445,12 +429,12 @@ func main() { if err != nil { log.Fatal(err) } - fmt.Println(resp.String()) case "rollbackUpdate": fmt.Println("Abort update") - resp, err := r.RollbackJobUpdate(aurora.JobUpdateKey{ - Job: job.JobKey(), + key := job.JobKey() + err := r.RollbackJobUpdate(aurora.JobUpdateKey{ + Job: &key, ID: updateId, }, "") @@ -458,7 +442,6 @@ func main() { if err != nil { log.Fatal(err) } - fmt.Println(resp.String()) case "taskConfig": fmt.Println("Getting job info") @@ -467,14 +450,10 @@ func main() { log.Fatal(err) } - var instId int32 - for k := range live { - instId = k - break - } + key := job.JobKey() config, err := r.FetchTaskConfig(aurora.InstanceKey{ - JobKey: job.JobKey(), - InstanceId: instId, + JobKey: &key, + InstanceId: live[0], }) if err != nil { @@ -485,9 +464,10 @@ func main() { case "updatesummary": fmt.Println("Getting job update summary") + key := job.JobKey() jobquery := &aurora.JobUpdateQuery{ - Role: &job.JobKey().Role, - JobKey: job.JobKey(), + Role: &key.Role, + JobKey: &key, } updatesummary, err := r.GetJobUpdateSummaries(jobquery) if err != nil { @@ -498,10 +478,11 @@ func main() { case "taskStatus": fmt.Println("Getting task status") + key := job.JobKey() taskQ := &aurora.TaskQuery{ - Role: &job.JobKey().Role, - Environment: &job.JobKey().Environment, - JobName: &job.JobKey().Name, + Role: &key.Role, + Environment: &key.Environment, + JobName: &key.Name, } tasks, err := r.GetTaskStatus(taskQ) if err != nil { @@ -513,10 +494,11 @@ func main() { case "tasksWithoutConfig": fmt.Println("Getting task status") + key := job.JobKey() taskQ := &aurora.TaskQuery{ - Role: &job.JobKey().Role, - Environment: &job.JobKey().Environment, - JobName: &job.JobKey().Name, + Role: &key.Role, + Environment: &key.Environment, + JobName: &key.Name, } tasks, err := r.GetTasksWithoutConfigs(taskQ) if err != nil { @@ -532,17 +514,17 @@ func main() { log.Fatal("No hosts specified to drain") } hosts := strings.Split(hostList, ",") - _, result, err := r.DrainHosts(hosts...) + _, err := r.DrainHosts(hosts...) if err != nil { log.Fatalf("error: %+v\n", err.Error()) } // Monitor change to DRAINING and DRAINED mode - hostResult, err := monitor.HostMaintenance( + hostResult, err := r.HostMaintenanceMonitor( hosts, []aurora.MaintenanceMode{aurora.MaintenanceMode_DRAINED, aurora.MaintenanceMode_DRAINING}, - 5, - 10) + 5*time.Second, + 10*time.Second) if err != nil { for host, ok := range hostResult { if !ok { @@ -552,8 +534,6 @@ func main() { log.Fatalf("error: %+v\n", err.Error()) } - fmt.Print(result.String()) - case "SLADrainHosts": fmt.Println("Setting hosts to DRAINING using SLA aware draining") if hostList == "" { @@ -563,17 +543,17 @@ func main() { policy := aurora.SlaPolicy{PercentageSlaPolicy: &aurora.PercentageSlaPolicy{Percentage: 50.0}} - result, err := r.SLADrainHosts(&policy, 30, hosts...) + _, err := r.SLADrainHosts(&policy, 30, hosts...) if err != nil { log.Fatalf("error: %+v\n", err.Error()) } // Monitor change to DRAINING and DRAINED mode - hostResult, err := monitor.HostMaintenance( + hostResult, err := r.HostMaintenanceMonitor( hosts, []aurora.MaintenanceMode{aurora.MaintenanceMode_DRAINED, aurora.MaintenanceMode_DRAINING}, - 5, - 10) + 5*time.Second, + 10*time.Second) if err != nil { for host, ok := range hostResult { if !ok { @@ -583,25 +563,23 @@ func main() { log.Fatalf("error: %+v\n", err.Error()) } - fmt.Print(result.String()) - case "endMaintenance": fmt.Println("Setting hosts to ACTIVE") if hostList == "" { log.Fatal("No hosts specified to drain") } hosts := strings.Split(hostList, ",") - _, result, err := r.EndMaintenance(hosts...) + _, err := r.EndMaintenance(hosts...) if err != nil { log.Fatalf("error: %+v\n", err.Error()) } // Monitor change to DRAINING and DRAINED mode - hostResult, err := monitor.HostMaintenance( + hostResult, err := r.HostMaintenanceMonitor( hosts, []aurora.MaintenanceMode{aurora.MaintenanceMode_NONE}, - 5, - 10) + 5*time.Second, + 10*time.Second) if err != nil { for host, ok := range hostResult { if !ok { @@ -611,14 +589,13 @@ func main() { log.Fatalf("error: %+v\n", err.Error()) } - fmt.Print(result.String()) - case "getPendingReasons": fmt.Println("Getting pending reasons") + key := job.JobKey() taskQ := &aurora.TaskQuery{ - Role: &job.JobKey().Role, - Environment: &job.JobKey().Environment, - JobName: &job.JobKey().Name, + Role: &key.Role, + Environment: &key.Environment, + JobName: &key.Name, } reasons, err := r.GetPendingReason(taskQ) if err != nil { @@ -630,7 +607,7 @@ func main() { case "getJobs": fmt.Println("GetJobs...role: ", role) - _, result, err := r.GetJobs(role) + result, err := r.GetJobs(role) if err != nil { log.Fatalf("error: %+v\n", err.Error()) } diff --git a/vendor/github.com/paypal/gorealis/examples/jsonClient.go b/vendor/github.com/paypal/gorealis/examples/jsonClient.go index 0989671..907b0d0 100644 --- a/vendor/github.com/paypal/gorealis/examples/jsonClient.go +++ b/vendor/github.com/paypal/gorealis/examples/jsonClient.go @@ -23,7 +23,7 @@ import ( "os" "time" - "github.com/paypal/gorealis" + realis "github.com/paypal/gorealis" "github.com/paypal/gorealis/gen-go/apache/aurora" "github.com/pkg/errors" ) @@ -125,7 +125,7 @@ func init() { } } -func CreateRealisClient(config *Config) (realis.Realis, error) { +func CreateRealisClient(config *Config) (*realis.Client, error) { var transportOption realis.ClientOption // Configuring transport protocol. If not transport is provided, then using JSON as the // default transport protocol. @@ -157,7 +157,7 @@ func CreateRealisClient(config *Config) (realis.Realis, error) { clientOptions = append(clientOptions, realis.Debug()) } - return realis.NewRealisClient(clientOptions...) + return realis.NewClient(clientOptions...) } func main() { @@ -165,7 +165,6 @@ func main() { fmt.Println(clientCreationErr) os.Exit(1) } else { - monitor := &realis.Monitor{Client: r} defer r.Close() uris := job.URIs labels := job.Labels @@ -205,20 +204,18 @@ func main() { } fmt.Println("Creating Job...") - if resp, jobCreationErr := r.CreateJob(auroraJob); jobCreationErr != nil { + if jobCreationErr := r.CreateJob(auroraJob); jobCreationErr != nil { fmt.Println("Error creating Aurora job: ", jobCreationErr) os.Exit(1) } else { - if resp.ResponseCode == aurora.ResponseCode_OK { - if ok, monitorErr := monitor.Instances(auroraJob.JobKey(), auroraJob.GetInstanceCount(), 5, 50); !ok || monitorErr != nil { - if _, jobErr := r.KillJob(auroraJob.JobKey()); jobErr != - nil { - fmt.Println(jobErr) - os.Exit(1) - } else { - fmt.Println("ok: ", ok) - fmt.Println("jobErr: ", jobErr) - } + if ok, monitorErr := r.InstancesMonitor(auroraJob.JobKey(), auroraJob.GetInstanceCount(), 5, 50); !ok || monitorErr != nil { + if jobErr := r.KillJob(auroraJob.JobKey()); jobErr != + nil { + fmt.Println(jobErr) + os.Exit(1) + } else { + fmt.Println("ok: ", ok) + fmt.Println("jobErr: ", jobErr) } } } diff --git a/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/GoUnusedProtection__.go b/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/GoUnusedProtection__.go new file mode 100644 index 0000000..0854061 --- /dev/null +++ b/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/GoUnusedProtection__.go @@ -0,0 +1,7 @@ +// Autogenerated by Thrift Compiler (1.0.0-dev) +// Autogenerated by Thrift Compiler (0.12.0) +// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING + +package aurora + +var GoUnusedProtection__ int diff --git a/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/auroraAPI-consts.go b/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/auroraAPI-consts.go new file mode 100644 index 0000000..da41b93 --- /dev/null +++ b/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/auroraAPI-consts.go @@ -0,0 +1,58 @@ +// Autogenerated by Thrift Compiler (0.12.0) +// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING + +package aurora + +import ( + "bytes" + "context" + "fmt" + "reflect" + + "git.apache.org/thrift.git/lib/go/thrift" +) + +// (needed to ensure safety because of naive import list construction.) +var _ = thrift.ZERO +var _ = fmt.Printf +var _ = context.Background +var _ = reflect.DeepEqual +var _ = bytes.Equal + +const AURORA_EXECUTOR_NAME = "AuroraExecutor" + +var ACTIVE_STATES []ScheduleStatus +var SLAVE_ASSIGNED_STATES []ScheduleStatus +var LIVE_STATES []ScheduleStatus +var TERMINAL_STATES []ScheduleStatus + +const GOOD_IDENTIFIER_PATTERN = "^[\\w\\-\\.]+$" +const GOOD_IDENTIFIER_PATTERN_JVM = "^[\\w\\-\\.]+$" +const GOOD_IDENTIFIER_PATTERN_PYTHON = "^[\\w\\-\\.]+$" + +var ACTIVE_JOB_UPDATE_STATES []JobUpdateStatus +var AWAITNG_PULSE_JOB_UPDATE_STATES []JobUpdateStatus + +const BYPASS_LEADER_REDIRECT_HEADER_NAME = "Bypass-Leader-Redirect" +const TASK_FILESYSTEM_MOUNT_POINT = "taskfs" + +func init() { + ACTIVE_STATES = []ScheduleStatus{ + 9, 17, 6, 0, 13, 12, 2, 1, 18, 16} + + SLAVE_ASSIGNED_STATES = []ScheduleStatus{ + 9, 17, 6, 13, 12, 2, 18, 1} + + LIVE_STATES = []ScheduleStatus{ + 6, 13, 12, 17, 18, 2} + + TERMINAL_STATES = []ScheduleStatus{ + 4, 3, 5, 7} + + ACTIVE_JOB_UPDATE_STATES = []JobUpdateStatus{ + 0, 1, 2, 3, 9, 10} + + AWAITNG_PULSE_JOB_UPDATE_STATES = []JobUpdateStatus{ + 9, 10} + +} diff --git a/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/auroraAPI.go b/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/auroraAPI.go new file mode 100644 index 0000000..2c6bb79 --- /dev/null +++ b/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/auroraAPI.go @@ -0,0 +1,31576 @@ +// Autogenerated by Thrift Compiler (0.12.0) +// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING + +package aurora + +import ( + "bytes" + "context" + "database/sql/driver" + "errors" + "fmt" + "reflect" + + "git.apache.org/thrift.git/lib/go/thrift" +) + +// (needed to ensure safety because of naive import list construction.) +var _ = thrift.ZERO +var _ = fmt.Printf +var _ = context.Background +var _ = reflect.DeepEqual +var _ = bytes.Equal + +type ResponseCode int64 + +const ( + ResponseCode_INVALID_REQUEST ResponseCode = 0 + ResponseCode_OK ResponseCode = 1 + ResponseCode_ERROR ResponseCode = 2 + ResponseCode_WARNING ResponseCode = 3 + ResponseCode_AUTH_FAILED ResponseCode = 4 + ResponseCode_JOB_UPDATING_ERROR ResponseCode = 5 + ResponseCode_ERROR_TRANSIENT ResponseCode = 6 +) + +func (p ResponseCode) String() string { + switch p { + case ResponseCode_INVALID_REQUEST: + return "INVALID_REQUEST" + case ResponseCode_OK: + return "OK" + case ResponseCode_ERROR: + return "ERROR" + case ResponseCode_WARNING: + return "WARNING" + case ResponseCode_AUTH_FAILED: + return "AUTH_FAILED" + case ResponseCode_JOB_UPDATING_ERROR: + return "JOB_UPDATING_ERROR" + case ResponseCode_ERROR_TRANSIENT: + return "ERROR_TRANSIENT" + } + return "" +} + +func ResponseCodeFromString(s string) (ResponseCode, error) { + switch s { + case "INVALID_REQUEST": + return ResponseCode_INVALID_REQUEST, nil + case "OK": + return ResponseCode_OK, nil + case "ERROR": + return ResponseCode_ERROR, nil + case "WARNING": + return ResponseCode_WARNING, nil + case "AUTH_FAILED": + return ResponseCode_AUTH_FAILED, nil + case "JOB_UPDATING_ERROR": + return ResponseCode_JOB_UPDATING_ERROR, nil + case "ERROR_TRANSIENT": + return ResponseCode_ERROR_TRANSIENT, nil + } + return ResponseCode(0), fmt.Errorf("not a valid ResponseCode string") +} + +func ResponseCodePtr(v ResponseCode) *ResponseCode { return &v } + +func (p ResponseCode) MarshalText() ([]byte, error) { + return []byte(p.String()), nil +} + +func (p *ResponseCode) UnmarshalText(text []byte) error { + q, err := ResponseCodeFromString(string(text)) + if err != nil { + return err + } + *p = q + return nil +} + +func (p *ResponseCode) Scan(value interface{}) error { + v, ok := value.(int64) + if !ok { + return errors.New("Scan value is not int64") + } + *p = ResponseCode(v) + return nil +} + +func (p *ResponseCode) Value() (driver.Value, error) { + if p == nil { + return nil, nil + } + return int64(*p), nil +} + +type MaintenanceMode int64 + +const ( + MaintenanceMode_NONE MaintenanceMode = 1 + MaintenanceMode_SCHEDULED MaintenanceMode = 2 + MaintenanceMode_DRAINING MaintenanceMode = 3 + MaintenanceMode_DRAINED MaintenanceMode = 4 +) + +func (p MaintenanceMode) String() string { + switch p { + case MaintenanceMode_NONE: + return "NONE" + case MaintenanceMode_SCHEDULED: + return "SCHEDULED" + case MaintenanceMode_DRAINING: + return "DRAINING" + case MaintenanceMode_DRAINED: + return "DRAINED" + } + return "" +} + +func MaintenanceModeFromString(s string) (MaintenanceMode, error) { + switch s { + case "NONE": + return MaintenanceMode_NONE, nil + case "SCHEDULED": + return MaintenanceMode_SCHEDULED, nil + case "DRAINING": + return MaintenanceMode_DRAINING, nil + case "DRAINED": + return MaintenanceMode_DRAINED, nil + } + return MaintenanceMode(0), fmt.Errorf("not a valid MaintenanceMode string") +} + +func MaintenanceModePtr(v MaintenanceMode) *MaintenanceMode { return &v } + +func (p MaintenanceMode) MarshalText() ([]byte, error) { + return []byte(p.String()), nil +} + +func (p *MaintenanceMode) UnmarshalText(text []byte) error { + q, err := MaintenanceModeFromString(string(text)) + if err != nil { + return err + } + *p = q + return nil +} + +func (p *MaintenanceMode) Scan(value interface{}) error { + v, ok := value.(int64) + if !ok { + return errors.New("Scan value is not int64") + } + *p = MaintenanceMode(v) + return nil +} + +func (p *MaintenanceMode) Value() (driver.Value, error) { + if p == nil { + return nil, nil + } + return int64(*p), nil +} + +//The mode for a volume mount +type Mode int64 + +const ( + Mode_RW Mode = 1 + Mode_RO Mode = 2 +) + +func (p Mode) String() string { + switch p { + case Mode_RW: + return "RW" + case Mode_RO: + return "RO" + } + return "" +} + +func ModeFromString(s string) (Mode, error) { + switch s { + case "RW": + return Mode_RW, nil + case "RO": + return Mode_RO, nil + } + return Mode(0), fmt.Errorf("not a valid Mode string") +} + +func ModePtr(v Mode) *Mode { return &v } + +func (p Mode) MarshalText() ([]byte, error) { + return []byte(p.String()), nil +} + +func (p *Mode) UnmarshalText(text []byte) error { + q, err := ModeFromString(string(text)) + if err != nil { + return err + } + *p = q + return nil +} + +func (p *Mode) Scan(value interface{}) error { + v, ok := value.(int64) + if !ok { + return errors.New("Scan value is not int64") + } + *p = Mode(v) + return nil +} + +func (p *Mode) Value() (driver.Value, error) { + if p == nil { + return nil, nil + } + return int64(*p), nil +} + +//Defines the policy for launching a new cron job when one is already running. +type CronCollisionPolicy int64 + +const ( + CronCollisionPolicy_KILL_EXISTING CronCollisionPolicy = 0 + CronCollisionPolicy_CANCEL_NEW CronCollisionPolicy = 1 + CronCollisionPolicy_RUN_OVERLAP CronCollisionPolicy = 2 +) + +func (p CronCollisionPolicy) String() string { + switch p { + case CronCollisionPolicy_KILL_EXISTING: + return "KILL_EXISTING" + case CronCollisionPolicy_CANCEL_NEW: + return "CANCEL_NEW" + case CronCollisionPolicy_RUN_OVERLAP: + return "RUN_OVERLAP" + } + return "" +} + +func CronCollisionPolicyFromString(s string) (CronCollisionPolicy, error) { + switch s { + case "KILL_EXISTING": + return CronCollisionPolicy_KILL_EXISTING, nil + case "CANCEL_NEW": + return CronCollisionPolicy_CANCEL_NEW, nil + case "RUN_OVERLAP": + return CronCollisionPolicy_RUN_OVERLAP, nil + } + return CronCollisionPolicy(0), fmt.Errorf("not a valid CronCollisionPolicy string") +} + +func CronCollisionPolicyPtr(v CronCollisionPolicy) *CronCollisionPolicy { return &v } + +func (p CronCollisionPolicy) MarshalText() ([]byte, error) { + return []byte(p.String()), nil +} + +func (p *CronCollisionPolicy) UnmarshalText(text []byte) error { + q, err := CronCollisionPolicyFromString(string(text)) + if err != nil { + return err + } + *p = q + return nil +} + +func (p *CronCollisionPolicy) Scan(value interface{}) error { + v, ok := value.(int64) + if !ok { + return errors.New("Scan value is not int64") + } + *p = CronCollisionPolicy(v) + return nil +} + +func (p *CronCollisionPolicy) Value() (driver.Value, error) { + if p == nil { + return nil, nil + } + return int64(*p), nil +} + +//States that a task may be in. +type ScheduleStatus int64 + +const ( + ScheduleStatus_INIT ScheduleStatus = 11 + ScheduleStatus_THROTTLED ScheduleStatus = 16 + ScheduleStatus_PENDING ScheduleStatus = 0 + ScheduleStatus_ASSIGNED ScheduleStatus = 9 + ScheduleStatus_STARTING ScheduleStatus = 1 + ScheduleStatus_RUNNING ScheduleStatus = 2 + ScheduleStatus_FINISHED ScheduleStatus = 3 + ScheduleStatus_PREEMPTING ScheduleStatus = 13 + ScheduleStatus_RESTARTING ScheduleStatus = 12 + ScheduleStatus_DRAINING ScheduleStatus = 17 + ScheduleStatus_FAILED ScheduleStatus = 4 + ScheduleStatus_KILLED ScheduleStatus = 5 + ScheduleStatus_KILLING ScheduleStatus = 6 + ScheduleStatus_LOST ScheduleStatus = 7 + ScheduleStatus_PARTITIONED ScheduleStatus = 18 +) + +func (p ScheduleStatus) String() string { + switch p { + case ScheduleStatus_INIT: + return "INIT" + case ScheduleStatus_THROTTLED: + return "THROTTLED" + case ScheduleStatus_PENDING: + return "PENDING" + case ScheduleStatus_ASSIGNED: + return "ASSIGNED" + case ScheduleStatus_STARTING: + return "STARTING" + case ScheduleStatus_RUNNING: + return "RUNNING" + case ScheduleStatus_FINISHED: + return "FINISHED" + case ScheduleStatus_PREEMPTING: + return "PREEMPTING" + case ScheduleStatus_RESTARTING: + return "RESTARTING" + case ScheduleStatus_DRAINING: + return "DRAINING" + case ScheduleStatus_FAILED: + return "FAILED" + case ScheduleStatus_KILLED: + return "KILLED" + case ScheduleStatus_KILLING: + return "KILLING" + case ScheduleStatus_LOST: + return "LOST" + case ScheduleStatus_PARTITIONED: + return "PARTITIONED" + } + return "" +} + +func ScheduleStatusFromString(s string) (ScheduleStatus, error) { + switch s { + case "INIT": + return ScheduleStatus_INIT, nil + case "THROTTLED": + return ScheduleStatus_THROTTLED, nil + case "PENDING": + return ScheduleStatus_PENDING, nil + case "ASSIGNED": + return ScheduleStatus_ASSIGNED, nil + case "STARTING": + return ScheduleStatus_STARTING, nil + case "RUNNING": + return ScheduleStatus_RUNNING, nil + case "FINISHED": + return ScheduleStatus_FINISHED, nil + case "PREEMPTING": + return ScheduleStatus_PREEMPTING, nil + case "RESTARTING": + return ScheduleStatus_RESTARTING, nil + case "DRAINING": + return ScheduleStatus_DRAINING, nil + case "FAILED": + return ScheduleStatus_FAILED, nil + case "KILLED": + return ScheduleStatus_KILLED, nil + case "KILLING": + return ScheduleStatus_KILLING, nil + case "LOST": + return ScheduleStatus_LOST, nil + case "PARTITIONED": + return ScheduleStatus_PARTITIONED, nil + } + return ScheduleStatus(0), fmt.Errorf("not a valid ScheduleStatus string") +} + +func ScheduleStatusPtr(v ScheduleStatus) *ScheduleStatus { return &v } + +func (p ScheduleStatus) MarshalText() ([]byte, error) { + return []byte(p.String()), nil +} + +func (p *ScheduleStatus) UnmarshalText(text []byte) error { + q, err := ScheduleStatusFromString(string(text)) + if err != nil { + return err + } + *p = q + return nil +} + +func (p *ScheduleStatus) Scan(value interface{}) error { + v, ok := value.(int64) + if !ok { + return errors.New("Scan value is not int64") + } + *p = ScheduleStatus(v) + return nil +} + +func (p *ScheduleStatus) Value() (driver.Value, error) { + if p == nil { + return nil, nil + } + return int64(*p), nil +} + +//States that a job update may be in. +type JobUpdateStatus int64 + +const ( + JobUpdateStatus_ROLLING_FORWARD JobUpdateStatus = 0 + JobUpdateStatus_ROLLING_BACK JobUpdateStatus = 1 + JobUpdateStatus_ROLL_FORWARD_PAUSED JobUpdateStatus = 2 + JobUpdateStatus_ROLL_BACK_PAUSED JobUpdateStatus = 3 + JobUpdateStatus_ROLLED_FORWARD JobUpdateStatus = 4 + JobUpdateStatus_ROLLED_BACK JobUpdateStatus = 5 + JobUpdateStatus_ABORTED JobUpdateStatus = 6 + JobUpdateStatus_ERROR JobUpdateStatus = 7 + JobUpdateStatus_FAILED JobUpdateStatus = 8 + JobUpdateStatus_ROLL_FORWARD_AWAITING_PULSE JobUpdateStatus = 9 + JobUpdateStatus_ROLL_BACK_AWAITING_PULSE JobUpdateStatus = 10 +) + +func (p JobUpdateStatus) String() string { + switch p { + case JobUpdateStatus_ROLLING_FORWARD: + return "ROLLING_FORWARD" + case JobUpdateStatus_ROLLING_BACK: + return "ROLLING_BACK" + case JobUpdateStatus_ROLL_FORWARD_PAUSED: + return "ROLL_FORWARD_PAUSED" + case JobUpdateStatus_ROLL_BACK_PAUSED: + return "ROLL_BACK_PAUSED" + case JobUpdateStatus_ROLLED_FORWARD: + return "ROLLED_FORWARD" + case JobUpdateStatus_ROLLED_BACK: + return "ROLLED_BACK" + case JobUpdateStatus_ABORTED: + return "ABORTED" + case JobUpdateStatus_ERROR: + return "ERROR" + case JobUpdateStatus_FAILED: + return "FAILED" + case JobUpdateStatus_ROLL_FORWARD_AWAITING_PULSE: + return "ROLL_FORWARD_AWAITING_PULSE" + case JobUpdateStatus_ROLL_BACK_AWAITING_PULSE: + return "ROLL_BACK_AWAITING_PULSE" + } + return "" +} + +func JobUpdateStatusFromString(s string) (JobUpdateStatus, error) { + switch s { + case "ROLLING_FORWARD": + return JobUpdateStatus_ROLLING_FORWARD, nil + case "ROLLING_BACK": + return JobUpdateStatus_ROLLING_BACK, nil + case "ROLL_FORWARD_PAUSED": + return JobUpdateStatus_ROLL_FORWARD_PAUSED, nil + case "ROLL_BACK_PAUSED": + return JobUpdateStatus_ROLL_BACK_PAUSED, nil + case "ROLLED_FORWARD": + return JobUpdateStatus_ROLLED_FORWARD, nil + case "ROLLED_BACK": + return JobUpdateStatus_ROLLED_BACK, nil + case "ABORTED": + return JobUpdateStatus_ABORTED, nil + case "ERROR": + return JobUpdateStatus_ERROR, nil + case "FAILED": + return JobUpdateStatus_FAILED, nil + case "ROLL_FORWARD_AWAITING_PULSE": + return JobUpdateStatus_ROLL_FORWARD_AWAITING_PULSE, nil + case "ROLL_BACK_AWAITING_PULSE": + return JobUpdateStatus_ROLL_BACK_AWAITING_PULSE, nil + } + return JobUpdateStatus(0), fmt.Errorf("not a valid JobUpdateStatus string") +} + +func JobUpdateStatusPtr(v JobUpdateStatus) *JobUpdateStatus { return &v } + +func (p JobUpdateStatus) MarshalText() ([]byte, error) { + return []byte(p.String()), nil +} + +func (p *JobUpdateStatus) UnmarshalText(text []byte) error { + q, err := JobUpdateStatusFromString(string(text)) + if err != nil { + return err + } + *p = q + return nil +} + +func (p *JobUpdateStatus) Scan(value interface{}) error { + v, ok := value.(int64) + if !ok { + return errors.New("Scan value is not int64") + } + *p = JobUpdateStatus(v) + return nil +} + +func (p *JobUpdateStatus) Value() (driver.Value, error) { + if p == nil { + return nil, nil + } + return int64(*p), nil +} + +//Job update actions that can be applied to job instances. +type JobUpdateAction int64 + +const ( + JobUpdateAction_INSTANCE_UPDATED JobUpdateAction = 1 + JobUpdateAction_INSTANCE_ROLLED_BACK JobUpdateAction = 2 + JobUpdateAction_INSTANCE_UPDATING JobUpdateAction = 3 + JobUpdateAction_INSTANCE_ROLLING_BACK JobUpdateAction = 4 + JobUpdateAction_INSTANCE_UPDATE_FAILED JobUpdateAction = 5 + JobUpdateAction_INSTANCE_ROLLBACK_FAILED JobUpdateAction = 6 +) + +func (p JobUpdateAction) String() string { + switch p { + case JobUpdateAction_INSTANCE_UPDATED: + return "INSTANCE_UPDATED" + case JobUpdateAction_INSTANCE_ROLLED_BACK: + return "INSTANCE_ROLLED_BACK" + case JobUpdateAction_INSTANCE_UPDATING: + return "INSTANCE_UPDATING" + case JobUpdateAction_INSTANCE_ROLLING_BACK: + return "INSTANCE_ROLLING_BACK" + case JobUpdateAction_INSTANCE_UPDATE_FAILED: + return "INSTANCE_UPDATE_FAILED" + case JobUpdateAction_INSTANCE_ROLLBACK_FAILED: + return "INSTANCE_ROLLBACK_FAILED" + } + return "" +} + +func JobUpdateActionFromString(s string) (JobUpdateAction, error) { + switch s { + case "INSTANCE_UPDATED": + return JobUpdateAction_INSTANCE_UPDATED, nil + case "INSTANCE_ROLLED_BACK": + return JobUpdateAction_INSTANCE_ROLLED_BACK, nil + case "INSTANCE_UPDATING": + return JobUpdateAction_INSTANCE_UPDATING, nil + case "INSTANCE_ROLLING_BACK": + return JobUpdateAction_INSTANCE_ROLLING_BACK, nil + case "INSTANCE_UPDATE_FAILED": + return JobUpdateAction_INSTANCE_UPDATE_FAILED, nil + case "INSTANCE_ROLLBACK_FAILED": + return JobUpdateAction_INSTANCE_ROLLBACK_FAILED, nil + } + return JobUpdateAction(0), fmt.Errorf("not a valid JobUpdateAction string") +} + +func JobUpdateActionPtr(v JobUpdateAction) *JobUpdateAction { return &v } + +func (p JobUpdateAction) MarshalText() ([]byte, error) { + return []byte(p.String()), nil +} + +func (p *JobUpdateAction) UnmarshalText(text []byte) error { + q, err := JobUpdateActionFromString(string(text)) + if err != nil { + return err + } + *p = q + return nil +} + +func (p *JobUpdateAction) Scan(value interface{}) error { + v, ok := value.(int64) + if !ok { + return errors.New("Scan value is not int64") + } + *p = JobUpdateAction(v) + return nil +} + +func (p *JobUpdateAction) Value() (driver.Value, error) { + if p == nil { + return nil, nil + } + return int64(*p), nil +} + +//Status of the coordinated update. Intended as a response to pulseJobUpdate RPC. +type JobUpdatePulseStatus int64 + +const ( + JobUpdatePulseStatus_OK JobUpdatePulseStatus = 1 + JobUpdatePulseStatus_FINISHED JobUpdatePulseStatus = 2 +) + +func (p JobUpdatePulseStatus) String() string { + switch p { + case JobUpdatePulseStatus_OK: + return "OK" + case JobUpdatePulseStatus_FINISHED: + return "FINISHED" + } + return "" +} + +func JobUpdatePulseStatusFromString(s string) (JobUpdatePulseStatus, error) { + switch s { + case "OK": + return JobUpdatePulseStatus_OK, nil + case "FINISHED": + return JobUpdatePulseStatus_FINISHED, nil + } + return JobUpdatePulseStatus(0), fmt.Errorf("not a valid JobUpdatePulseStatus string") +} + +func JobUpdatePulseStatusPtr(v JobUpdatePulseStatus) *JobUpdatePulseStatus { return &v } + +func (p JobUpdatePulseStatus) MarshalText() ([]byte, error) { + return []byte(p.String()), nil +} + +func (p *JobUpdatePulseStatus) UnmarshalText(text []byte) error { + q, err := JobUpdatePulseStatusFromString(string(text)) + if err != nil { + return err + } + *p = q + return nil +} + +func (p *JobUpdatePulseStatus) Scan(value interface{}) error { + v, ok := value.(int64) + if !ok { + return errors.New("Scan value is not int64") + } + *p = JobUpdatePulseStatus(v) + return nil +} + +func (p *JobUpdatePulseStatus) Value() (driver.Value, error) { + if p == nil { + return nil, nil + } + return int64(*p), nil +} + +// Attributes: +// - User +type Identity struct { + // unused field # 1 + User string `thrift:"user,2" db:"user" json:"user"` +} + +func NewIdentity() *Identity { + return &Identity{} +} + +func (p *Identity) GetUser() string { + return p.User +} +func (p *Identity) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 2: + if fieldTypeId == thrift.STRING { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *Identity) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.User = v + } + return nil +} + +func (p *Identity) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("Identity"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *Identity) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("user", thrift.STRING, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:user: ", p), err) + } + if err := oprot.WriteString(string(p.User)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.user (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:user: ", p), err) + } + return err +} + +func (p *Identity) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("Identity(%+v)", *p) +} + +// A single host attribute. +// +// Attributes: +// - Name +// - Values +type Attribute struct { + Name string `thrift:"name,1" db:"name" json:"name"` + Values []string `thrift:"values,2" db:"values" json:"values"` +} + +func NewAttribute() *Attribute { + return &Attribute{} +} + +func (p *Attribute) GetName() string { + return p.Name +} + +func (p *Attribute) GetValues() []string { + return p.Values +} +func (p *Attribute) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.SET { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *Attribute) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Name = v + } + return nil +} + +func (p *Attribute) ReadField2(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]string, 0, size) + p.Values = tSet + for i := 0; i < size; i++ { + var _elem0 string + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 0: ", err) + } else { + _elem0 = v + } + p.Values = append(p.Values, _elem0) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *Attribute) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("Attribute"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *Attribute) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("name", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:name: ", p), err) + } + if err := oprot.WriteString(string(p.Name)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.name (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:name: ", p), err) + } + return err +} + +func (p *Attribute) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("values", thrift.SET, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:values: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRING, len(p.Values)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Values); i++ { + for j := i + 1; j < len(p.Values); j++ { + if reflect.DeepEqual(p.Values[i], p.Values[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Values[i])) + } + } + } + for _, v := range p.Values { + if err := oprot.WriteString(string(v)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:values: ", p), err) + } + return err +} + +func (p *Attribute) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("Attribute(%+v)", *p) +} + +// The attributes assigned to a host. +// +// Attributes: +// - Host +// - Attributes +// - Mode +// - SlaveId +type HostAttributes struct { + Host string `thrift:"host,1" db:"host" json:"host"` + Attributes []*Attribute `thrift:"attributes,2" db:"attributes" json:"attributes"` + Mode *MaintenanceMode `thrift:"mode,3" db:"mode" json:"mode,omitempty"` + SlaveId *string `thrift:"slaveId,4" db:"slaveId" json:"slaveId,omitempty"` +} + +func NewHostAttributes() *HostAttributes { + return &HostAttributes{} +} + +func (p *HostAttributes) GetHost() string { + return p.Host +} + +func (p *HostAttributes) GetAttributes() []*Attribute { + return p.Attributes +} + +var HostAttributes_Mode_DEFAULT MaintenanceMode + +func (p *HostAttributes) GetMode() MaintenanceMode { + if !p.IsSetMode() { + return HostAttributes_Mode_DEFAULT + } + return *p.Mode +} + +var HostAttributes_SlaveId_DEFAULT string + +func (p *HostAttributes) GetSlaveId() string { + if !p.IsSetSlaveId() { + return HostAttributes_SlaveId_DEFAULT + } + return *p.SlaveId +} +func (p *HostAttributes) IsSetMode() bool { + return p.Mode != nil +} + +func (p *HostAttributes) IsSetSlaveId() bool { + return p.SlaveId != nil +} + +func (p *HostAttributes) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.SET { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.I32 { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 4: + if fieldTypeId == thrift.STRING { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *HostAttributes) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Host = v + } + return nil +} + +func (p *HostAttributes) ReadField2(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*Attribute, 0, size) + p.Attributes = tSet + for i := 0; i < size; i++ { + _elem1 := &Attribute{} + if err := _elem1.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem1), err) + } + p.Attributes = append(p.Attributes, _elem1) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *HostAttributes) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + temp := MaintenanceMode(v) + p.Mode = &temp + } + return nil +} + +func (p *HostAttributes) ReadField4(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 4: ", err) + } else { + p.SlaveId = &v + } + return nil +} + +func (p *HostAttributes) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("HostAttributes"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + if err := p.writeField4(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *HostAttributes) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("host", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:host: ", p), err) + } + if err := oprot.WriteString(string(p.Host)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.host (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:host: ", p), err) + } + return err +} + +func (p *HostAttributes) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("attributes", thrift.SET, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:attributes: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Attributes)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Attributes); i++ { + for j := i + 1; j < len(p.Attributes); j++ { + if reflect.DeepEqual(p.Attributes[i], p.Attributes[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Attributes[i])) + } + } + } + for _, v := range p.Attributes { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:attributes: ", p), err) + } + return err +} + +func (p *HostAttributes) writeField3(oprot thrift.TProtocol) (err error) { + if p.IsSetMode() { + if err := oprot.WriteFieldBegin("mode", thrift.I32, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:mode: ", p), err) + } + if err := oprot.WriteI32(int32(*p.Mode)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.mode (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:mode: ", p), err) + } + } + return err +} + +func (p *HostAttributes) writeField4(oprot thrift.TProtocol) (err error) { + if p.IsSetSlaveId() { + if err := oprot.WriteFieldBegin("slaveId", thrift.STRING, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:slaveId: ", p), err) + } + if err := oprot.WriteString(string(*p.SlaveId)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.slaveId (4) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:slaveId: ", p), err) + } + } + return err +} + +func (p *HostAttributes) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("HostAttributes(%+v)", *p) +} + +// A constraint that specifies an explicit set of values, at least one of which must be present +// on a host for a task to be scheduled there. +// +// Attributes: +// - Negated: If true, treat this as a 'not' - to avoid specific values. +// - Values +type ValueConstraint struct { + Negated bool `thrift:"negated,1" db:"negated" json:"negated"` + Values []string `thrift:"values,2" db:"values" json:"values"` +} + +func NewValueConstraint() *ValueConstraint { + return &ValueConstraint{} +} + +func (p *ValueConstraint) GetNegated() bool { + return p.Negated +} + +func (p *ValueConstraint) GetValues() []string { + return p.Values +} +func (p *ValueConstraint) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.BOOL { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.SET { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ValueConstraint) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadBool(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Negated = v + } + return nil +} + +func (p *ValueConstraint) ReadField2(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]string, 0, size) + p.Values = tSet + for i := 0; i < size; i++ { + var _elem2 string + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 0: ", err) + } else { + _elem2 = v + } + p.Values = append(p.Values, _elem2) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *ValueConstraint) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("ValueConstraint"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ValueConstraint) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("negated", thrift.BOOL, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:negated: ", p), err) + } + if err := oprot.WriteBool(bool(p.Negated)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.negated (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:negated: ", p), err) + } + return err +} + +func (p *ValueConstraint) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("values", thrift.SET, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:values: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRING, len(p.Values)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Values); i++ { + for j := i + 1; j < len(p.Values); j++ { + if reflect.DeepEqual(p.Values[i], p.Values[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Values[i])) + } + } + } + for _, v := range p.Values { + if err := oprot.WriteString(string(v)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:values: ", p), err) + } + return err +} + +func (p *ValueConstraint) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ValueConstraint(%+v)", *p) +} + +// A constraint the specifies the maximum number of active tasks on a host with a matching +// attribute that may be scheduled simultaneously. +// +// Attributes: +// - Limit +type LimitConstraint struct { + Limit int32 `thrift:"limit,1" db:"limit" json:"limit"` +} + +func NewLimitConstraint() *LimitConstraint { + return &LimitConstraint{} +} + +func (p *LimitConstraint) GetLimit() int32 { + return p.Limit +} +func (p *LimitConstraint) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.I32 { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *LimitConstraint) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Limit = v + } + return nil +} + +func (p *LimitConstraint) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("LimitConstraint"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *LimitConstraint) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("limit", thrift.I32, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:limit: ", p), err) + } + if err := oprot.WriteI32(int32(p.Limit)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.limit (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:limit: ", p), err) + } + return err +} + +func (p *LimitConstraint) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("LimitConstraint(%+v)", *p) +} + +// Types of constraints that may be applied to a task. +// +// Attributes: +// - Value +// - Limit +type TaskConstraint struct { + Value *ValueConstraint `thrift:"value,1" db:"value" json:"value,omitempty"` + Limit *LimitConstraint `thrift:"limit,2" db:"limit" json:"limit,omitempty"` +} + +func NewTaskConstraint() *TaskConstraint { + return &TaskConstraint{} +} + +var TaskConstraint_Value_DEFAULT *ValueConstraint + +func (p *TaskConstraint) GetValue() *ValueConstraint { + if !p.IsSetValue() { + return TaskConstraint_Value_DEFAULT + } + return p.Value +} + +var TaskConstraint_Limit_DEFAULT *LimitConstraint + +func (p *TaskConstraint) GetLimit() *LimitConstraint { + if !p.IsSetLimit() { + return TaskConstraint_Limit_DEFAULT + } + return p.Limit +} +func (p *TaskConstraint) CountSetFieldsTaskConstraint() int { + count := 0 + if p.IsSetValue() { + count++ + } + if p.IsSetLimit() { + count++ + } + return count + +} + +func (p *TaskConstraint) IsSetValue() bool { + return p.Value != nil +} + +func (p *TaskConstraint) IsSetLimit() bool { + return p.Limit != nil +} + +func (p *TaskConstraint) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *TaskConstraint) ReadField1(iprot thrift.TProtocol) error { + p.Value = &ValueConstraint{} + if err := p.Value.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Value), err) + } + return nil +} + +func (p *TaskConstraint) ReadField2(iprot thrift.TProtocol) error { + p.Limit = &LimitConstraint{} + if err := p.Limit.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Limit), err) + } + return nil +} + +func (p *TaskConstraint) Write(oprot thrift.TProtocol) error { + if c := p.CountSetFieldsTaskConstraint(); c != 1 { + return fmt.Errorf("%T write union: exactly one field must be set (%d set).", p, c) + } + if err := oprot.WriteStructBegin("TaskConstraint"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *TaskConstraint) writeField1(oprot thrift.TProtocol) (err error) { + if p.IsSetValue() { + if err := oprot.WriteFieldBegin("value", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:value: ", p), err) + } + if err := p.Value.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Value), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:value: ", p), err) + } + } + return err +} + +func (p *TaskConstraint) writeField2(oprot thrift.TProtocol) (err error) { + if p.IsSetLimit() { + if err := oprot.WriteFieldBegin("limit", thrift.STRUCT, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:limit: ", p), err) + } + if err := p.Limit.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Limit), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:limit: ", p), err) + } + } + return err +} + +func (p *TaskConstraint) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("TaskConstraint(%+v)", *p) +} + +// A constraint that defines whether a task may be scheduled on a host. +// +// Attributes: +// - Name: Mesos slave attribute that the constraint is matched against. +// - Constraint +type Constraint struct { + Name string `thrift:"name,1" db:"name" json:"name"` + Constraint *TaskConstraint `thrift:"constraint,2" db:"constraint" json:"constraint"` +} + +func NewConstraint() *Constraint { + return &Constraint{} +} + +func (p *Constraint) GetName() string { + return p.Name +} + +var Constraint_Constraint_DEFAULT *TaskConstraint + +func (p *Constraint) GetConstraint() *TaskConstraint { + if !p.IsSetConstraint() { + return Constraint_Constraint_DEFAULT + } + return p.Constraint +} +func (p *Constraint) IsSetConstraint() bool { + return p.Constraint != nil +} + +func (p *Constraint) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *Constraint) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Name = v + } + return nil +} + +func (p *Constraint) ReadField2(iprot thrift.TProtocol) error { + p.Constraint = &TaskConstraint{} + if err := p.Constraint.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Constraint), err) + } + return nil +} + +func (p *Constraint) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("Constraint"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *Constraint) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("name", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:name: ", p), err) + } + if err := oprot.WriteString(string(p.Name)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.name (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:name: ", p), err) + } + return err +} + +func (p *Constraint) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("constraint", thrift.STRUCT, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:constraint: ", p), err) + } + if err := p.Constraint.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Constraint), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:constraint: ", p), err) + } + return err +} + +func (p *Constraint) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("Constraint(%+v)", *p) +} + +// Attributes: +// - Role +// - Name +// - Version +type Package struct { + Role string `thrift:"role,1" db:"role" json:"role"` + Name string `thrift:"name,2" db:"name" json:"name"` + Version int32 `thrift:"version,3" db:"version" json:"version"` +} + +func NewPackage() *Package { + return &Package{} +} + +func (p *Package) GetRole() string { + return p.Role +} + +func (p *Package) GetName() string { + return p.Name +} + +func (p *Package) GetVersion() int32 { + return p.Version +} +func (p *Package) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRING { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.I32 { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *Package) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Role = v + } + return nil +} + +func (p *Package) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.Name = v + } + return nil +} + +func (p *Package) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.Version = v + } + return nil +} + +func (p *Package) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("Package"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *Package) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("role", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:role: ", p), err) + } + if err := oprot.WriteString(string(p.Role)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.role (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:role: ", p), err) + } + return err +} + +func (p *Package) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("name", thrift.STRING, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:name: ", p), err) + } + if err := oprot.WriteString(string(p.Name)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.name (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:name: ", p), err) + } + return err +} + +func (p *Package) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("version", thrift.I32, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:version: ", p), err) + } + if err := oprot.WriteI32(int32(p.Version)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.version (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:version: ", p), err) + } + return err +} + +func (p *Package) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("Package(%+v)", *p) +} + +// Arbitrary key-value metadata to be included into TaskConfig. +// +// Attributes: +// - Key +// - Value +type Metadata struct { + Key string `thrift:"key,1" db:"key" json:"key"` + Value string `thrift:"value,2" db:"value" json:"value"` +} + +func NewMetadata() *Metadata { + return &Metadata{} +} + +func (p *Metadata) GetKey() string { + return p.Key +} + +func (p *Metadata) GetValue() string { + return p.Value +} +func (p *Metadata) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRING { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *Metadata) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Key = v + } + return nil +} + +func (p *Metadata) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.Value = v + } + return nil +} + +func (p *Metadata) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("Metadata"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *Metadata) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("key", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:key: ", p), err) + } + if err := oprot.WriteString(string(p.Key)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.key (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:key: ", p), err) + } + return err +} + +func (p *Metadata) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("value", thrift.STRING, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:value: ", p), err) + } + if err := oprot.WriteString(string(p.Value)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.value (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:value: ", p), err) + } + return err +} + +func (p *Metadata) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("Metadata(%+v)", *p) +} + +// A unique identifier for a Job. +// +// Attributes: +// - Role: User role (Unix service account), for example "mesos" +// - Environment: Environment, for example "devel" +// - Name: Name, for example "labrat" +type JobKey struct { + Role string `thrift:"role,1" db:"role" json:"role"` + Environment string `thrift:"environment,2" db:"environment" json:"environment"` + Name string `thrift:"name,3" db:"name" json:"name"` +} + +func NewJobKey() *JobKey { + return &JobKey{} +} + +func (p *JobKey) GetRole() string { + return p.Role +} + +func (p *JobKey) GetEnvironment() string { + return p.Environment +} + +func (p *JobKey) GetName() string { + return p.Name +} +func (p *JobKey) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRING { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.STRING { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *JobKey) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Role = v + } + return nil +} + +func (p *JobKey) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.Environment = v + } + return nil +} + +func (p *JobKey) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.Name = v + } + return nil +} + +func (p *JobKey) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("JobKey"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *JobKey) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("role", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:role: ", p), err) + } + if err := oprot.WriteString(string(p.Role)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.role (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:role: ", p), err) + } + return err +} + +func (p *JobKey) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("environment", thrift.STRING, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:environment: ", p), err) + } + if err := oprot.WriteString(string(p.Environment)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.environment (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:environment: ", p), err) + } + return err +} + +func (p *JobKey) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("name", thrift.STRING, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:name: ", p), err) + } + if err := oprot.WriteString(string(p.Name)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.name (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:name: ", p), err) + } + return err +} + +func (p *JobKey) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("JobKey(%+v)", *p) +} + +// A unique lock key. +// +// Attributes: +// - Job +type LockKey struct { + Job *JobKey `thrift:"job,1" db:"job" json:"job,omitempty"` +} + +func NewLockKey() *LockKey { + return &LockKey{} +} + +var LockKey_Job_DEFAULT *JobKey + +func (p *LockKey) GetJob() *JobKey { + if !p.IsSetJob() { + return LockKey_Job_DEFAULT + } + return p.Job +} +func (p *LockKey) CountSetFieldsLockKey() int { + count := 0 + if p.IsSetJob() { + count++ + } + return count + +} + +func (p *LockKey) IsSetJob() bool { + return p.Job != nil +} + +func (p *LockKey) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *LockKey) ReadField1(iprot thrift.TProtocol) error { + p.Job = &JobKey{} + if err := p.Job.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Job), err) + } + return nil +} + +func (p *LockKey) Write(oprot thrift.TProtocol) error { + if c := p.CountSetFieldsLockKey(); c != 1 { + return fmt.Errorf("%T write union: exactly one field must be set (%d set).", p, c) + } + if err := oprot.WriteStructBegin("LockKey"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *LockKey) writeField1(oprot thrift.TProtocol) (err error) { + if p.IsSetJob() { + if err := oprot.WriteFieldBegin("job", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:job: ", p), err) + } + if err := p.Job.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Job), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:job: ", p), err) + } + } + return err +} + +func (p *LockKey) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("LockKey(%+v)", *p) +} + +// A generic lock struct to facilitate context specific resource/operation serialization. +// +// Attributes: +// - Key: ID of the lock - unique per storage +// - Token: UUID - facilitating soft lock authorization +// - User: Lock creator +// - TimestampMs: Lock creation timestamp in milliseconds +// - Message: Optional message to record with the lock +type Lock struct { + Key *LockKey `thrift:"key,1" db:"key" json:"key"` + Token string `thrift:"token,2" db:"token" json:"token"` + User string `thrift:"user,3" db:"user" json:"user"` + TimestampMs int64 `thrift:"timestampMs,4" db:"timestampMs" json:"timestampMs"` + Message *string `thrift:"message,5" db:"message" json:"message,omitempty"` +} + +func NewLock() *Lock { + return &Lock{} +} + +var Lock_Key_DEFAULT *LockKey + +func (p *Lock) GetKey() *LockKey { + if !p.IsSetKey() { + return Lock_Key_DEFAULT + } + return p.Key +} + +func (p *Lock) GetToken() string { + return p.Token +} + +func (p *Lock) GetUser() string { + return p.User +} + +func (p *Lock) GetTimestampMs() int64 { + return p.TimestampMs +} + +var Lock_Message_DEFAULT string + +func (p *Lock) GetMessage() string { + if !p.IsSetMessage() { + return Lock_Message_DEFAULT + } + return *p.Message +} +func (p *Lock) IsSetKey() bool { + return p.Key != nil +} + +func (p *Lock) IsSetMessage() bool { + return p.Message != nil +} + +func (p *Lock) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRING { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.STRING { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 4: + if fieldTypeId == thrift.I64 { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 5: + if fieldTypeId == thrift.STRING { + if err := p.ReadField5(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *Lock) ReadField1(iprot thrift.TProtocol) error { + p.Key = &LockKey{} + if err := p.Key.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) + } + return nil +} + +func (p *Lock) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.Token = v + } + return nil +} + +func (p *Lock) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.User = v + } + return nil +} + +func (p *Lock) ReadField4(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI64(); err != nil { + return thrift.PrependError("error reading field 4: ", err) + } else { + p.TimestampMs = v + } + return nil +} + +func (p *Lock) ReadField5(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 5: ", err) + } else { + p.Message = &v + } + return nil +} + +func (p *Lock) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("Lock"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + if err := p.writeField4(oprot); err != nil { + return err + } + if err := p.writeField5(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *Lock) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:key: ", p), err) + } + if err := p.Key.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:key: ", p), err) + } + return err +} + +func (p *Lock) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("token", thrift.STRING, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:token: ", p), err) + } + if err := oprot.WriteString(string(p.Token)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.token (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:token: ", p), err) + } + return err +} + +func (p *Lock) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("user", thrift.STRING, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:user: ", p), err) + } + if err := oprot.WriteString(string(p.User)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.user (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:user: ", p), err) + } + return err +} + +func (p *Lock) writeField4(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("timestampMs", thrift.I64, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:timestampMs: ", p), err) + } + if err := oprot.WriteI64(int64(p.TimestampMs)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.timestampMs (4) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:timestampMs: ", p), err) + } + return err +} + +func (p *Lock) writeField5(oprot thrift.TProtocol) (err error) { + if p.IsSetMessage() { + if err := oprot.WriteFieldBegin("message", thrift.STRING, 5); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:message: ", p), err) + } + if err := oprot.WriteString(string(*p.Message)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.message (5) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 5:message: ", p), err) + } + } + return err +} + +func (p *Lock) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("Lock(%+v)", *p) +} + +// A unique identifier for the active task within a job. +// +// Attributes: +// - JobKey: Key identifying the job. +// - InstanceId: Unique instance ID for the active task in a job. +type InstanceKey struct { + JobKey *JobKey `thrift:"jobKey,1" db:"jobKey" json:"jobKey"` + InstanceId int32 `thrift:"instanceId,2" db:"instanceId" json:"instanceId"` +} + +func NewInstanceKey() *InstanceKey { + return &InstanceKey{} +} + +var InstanceKey_JobKey_DEFAULT *JobKey + +func (p *InstanceKey) GetJobKey() *JobKey { + if !p.IsSetJobKey() { + return InstanceKey_JobKey_DEFAULT + } + return p.JobKey +} + +func (p *InstanceKey) GetInstanceId() int32 { + return p.InstanceId +} +func (p *InstanceKey) IsSetJobKey() bool { + return p.JobKey != nil +} + +func (p *InstanceKey) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.I32 { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *InstanceKey) ReadField1(iprot thrift.TProtocol) error { + p.JobKey = &JobKey{} + if err := p.JobKey.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.JobKey), err) + } + return nil +} + +func (p *InstanceKey) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.InstanceId = v + } + return nil +} + +func (p *InstanceKey) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("InstanceKey"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *InstanceKey) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("jobKey", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:jobKey: ", p), err) + } + if err := p.JobKey.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.JobKey), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:jobKey: ", p), err) + } + return err +} + +func (p *InstanceKey) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("instanceId", thrift.I32, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:instanceId: ", p), err) + } + if err := oprot.WriteI32(int32(p.InstanceId)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.instanceId (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:instanceId: ", p), err) + } + return err +} + +func (p *InstanceKey) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("InstanceKey(%+v)", *p) +} + +// URI which mirrors CommandInfo.URI in the Mesos Protobuf +// +// Attributes: +// - Value: Where to get the resource from +// - Extract: Extract compressed archive after downloading +// - Cache: Cache value using Mesos Fetcher caching mechanism * +type MesosFetcherURI struct { + Value string `thrift:"value,1" db:"value" json:"value"` + Extract *bool `thrift:"extract,2" db:"extract" json:"extract,omitempty"` + Cache *bool `thrift:"cache,3" db:"cache" json:"cache,omitempty"` +} + +func NewMesosFetcherURI() *MesosFetcherURI { + return &MesosFetcherURI{} +} + +func (p *MesosFetcherURI) GetValue() string { + return p.Value +} + +var MesosFetcherURI_Extract_DEFAULT bool + +func (p *MesosFetcherURI) GetExtract() bool { + if !p.IsSetExtract() { + return MesosFetcherURI_Extract_DEFAULT + } + return *p.Extract +} + +var MesosFetcherURI_Cache_DEFAULT bool + +func (p *MesosFetcherURI) GetCache() bool { + if !p.IsSetCache() { + return MesosFetcherURI_Cache_DEFAULT + } + return *p.Cache +} +func (p *MesosFetcherURI) IsSetExtract() bool { + return p.Extract != nil +} + +func (p *MesosFetcherURI) IsSetCache() bool { + return p.Cache != nil +} + +func (p *MesosFetcherURI) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.BOOL { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.BOOL { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *MesosFetcherURI) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Value = v + } + return nil +} + +func (p *MesosFetcherURI) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadBool(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.Extract = &v + } + return nil +} + +func (p *MesosFetcherURI) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadBool(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.Cache = &v + } + return nil +} + +func (p *MesosFetcherURI) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("MesosFetcherURI"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *MesosFetcherURI) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("value", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:value: ", p), err) + } + if err := oprot.WriteString(string(p.Value)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.value (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:value: ", p), err) + } + return err +} + +func (p *MesosFetcherURI) writeField2(oprot thrift.TProtocol) (err error) { + if p.IsSetExtract() { + if err := oprot.WriteFieldBegin("extract", thrift.BOOL, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:extract: ", p), err) + } + if err := oprot.WriteBool(bool(*p.Extract)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.extract (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:extract: ", p), err) + } + } + return err +} + +func (p *MesosFetcherURI) writeField3(oprot thrift.TProtocol) (err error) { + if p.IsSetCache() { + if err := oprot.WriteFieldBegin("cache", thrift.BOOL, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:cache: ", p), err) + } + if err := oprot.WriteBool(bool(*p.Cache)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.cache (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:cache: ", p), err) + } + } + return err +} + +func (p *MesosFetcherURI) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("MesosFetcherURI(%+v)", *p) +} + +// Attributes: +// - Name: Name identifying the Executor. +// - Data: Executor configuration data. +type ExecutorConfig struct { + Name string `thrift:"name,1" db:"name" json:"name"` + Data string `thrift:"data,2" db:"data" json:"data"` +} + +func NewExecutorConfig() *ExecutorConfig { + return &ExecutorConfig{} +} + +func (p *ExecutorConfig) GetName() string { + return p.Name +} + +func (p *ExecutorConfig) GetData() string { + return p.Data +} +func (p *ExecutorConfig) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRING { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ExecutorConfig) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Name = v + } + return nil +} + +func (p *ExecutorConfig) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.Data = v + } + return nil +} + +func (p *ExecutorConfig) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("ExecutorConfig"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ExecutorConfig) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("name", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:name: ", p), err) + } + if err := oprot.WriteString(string(p.Name)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.name (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:name: ", p), err) + } + return err +} + +func (p *ExecutorConfig) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("data", thrift.STRING, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:data: ", p), err) + } + if err := oprot.WriteString(string(p.Data)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.data (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:data: ", p), err) + } + return err +} + +func (p *ExecutorConfig) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ExecutorConfig(%+v)", *p) +} + +// A volume mount point within a container +// +// Attributes: +// - ContainerPath: The path inside the container where the mount will be created. +// - HostPath: The path on the host that will serve as the source for the mount. +// - Mode: The access mode +type Volume struct { + ContainerPath string `thrift:"containerPath,1" db:"containerPath" json:"containerPath"` + HostPath string `thrift:"hostPath,2" db:"hostPath" json:"hostPath"` + Mode Mode `thrift:"mode,3" db:"mode" json:"mode"` +} + +func NewVolume() *Volume { + return &Volume{} +} + +func (p *Volume) GetContainerPath() string { + return p.ContainerPath +} + +func (p *Volume) GetHostPath() string { + return p.HostPath +} + +func (p *Volume) GetMode() Mode { + return p.Mode +} +func (p *Volume) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRING { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.I32 { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *Volume) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.ContainerPath = v + } + return nil +} + +func (p *Volume) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.HostPath = v + } + return nil +} + +func (p *Volume) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + temp := Mode(v) + p.Mode = temp + } + return nil +} + +func (p *Volume) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("Volume"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *Volume) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("containerPath", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:containerPath: ", p), err) + } + if err := oprot.WriteString(string(p.ContainerPath)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.containerPath (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:containerPath: ", p), err) + } + return err +} + +func (p *Volume) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("hostPath", thrift.STRING, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:hostPath: ", p), err) + } + if err := oprot.WriteString(string(p.HostPath)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.hostPath (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:hostPath: ", p), err) + } + return err +} + +func (p *Volume) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("mode", thrift.I32, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:mode: ", p), err) + } + if err := oprot.WriteI32(int32(p.Mode)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.mode (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:mode: ", p), err) + } + return err +} + +func (p *Volume) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("Volume(%+v)", *p) +} + +// Describes an image for use with the Mesos unified containerizer in the Docker format +// +// Attributes: +// - Name: The name of the image to run +// - Tag: The Docker tag identifying the image +type DockerImage struct { + Name string `thrift:"name,1" db:"name" json:"name"` + Tag string `thrift:"tag,2" db:"tag" json:"tag"` +} + +func NewDockerImage() *DockerImage { + return &DockerImage{} +} + +func (p *DockerImage) GetName() string { + return p.Name +} + +func (p *DockerImage) GetTag() string { + return p.Tag +} +func (p *DockerImage) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRING { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *DockerImage) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Name = v + } + return nil +} + +func (p *DockerImage) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.Tag = v + } + return nil +} + +func (p *DockerImage) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("DockerImage"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *DockerImage) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("name", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:name: ", p), err) + } + if err := oprot.WriteString(string(p.Name)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.name (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:name: ", p), err) + } + return err +} + +func (p *DockerImage) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("tag", thrift.STRING, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:tag: ", p), err) + } + if err := oprot.WriteString(string(p.Tag)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.tag (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:tag: ", p), err) + } + return err +} + +func (p *DockerImage) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("DockerImage(%+v)", *p) +} + +// Describes an image for use with the Mesos unified containerizer in the AppC format +// +// Attributes: +// - Name: The name of the image to run +// - ImageId: The appc image id identifying the image +type AppcImage struct { + Name string `thrift:"name,1" db:"name" json:"name"` + ImageId string `thrift:"imageId,2" db:"imageId" json:"imageId"` +} + +func NewAppcImage() *AppcImage { + return &AppcImage{} +} + +func (p *AppcImage) GetName() string { + return p.Name +} + +func (p *AppcImage) GetImageId() string { + return p.ImageId +} +func (p *AppcImage) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRING { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AppcImage) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Name = v + } + return nil +} + +func (p *AppcImage) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.ImageId = v + } + return nil +} + +func (p *AppcImage) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("AppcImage"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AppcImage) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("name", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:name: ", p), err) + } + if err := oprot.WriteString(string(p.Name)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.name (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:name: ", p), err) + } + return err +} + +func (p *AppcImage) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("imageId", thrift.STRING, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:imageId: ", p), err) + } + if err := oprot.WriteString(string(p.ImageId)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.imageId (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:imageId: ", p), err) + } + return err +} + +func (p *AppcImage) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AppcImage(%+v)", *p) +} + +// Describes an image to be used with the Mesos unified containerizer +// +// Attributes: +// - Docker +// - Appc +type Image struct { + Docker *DockerImage `thrift:"docker,1" db:"docker" json:"docker,omitempty"` + Appc *AppcImage `thrift:"appc,2" db:"appc" json:"appc,omitempty"` +} + +func NewImage() *Image { + return &Image{} +} + +var Image_Docker_DEFAULT *DockerImage + +func (p *Image) GetDocker() *DockerImage { + if !p.IsSetDocker() { + return Image_Docker_DEFAULT + } + return p.Docker +} + +var Image_Appc_DEFAULT *AppcImage + +func (p *Image) GetAppc() *AppcImage { + if !p.IsSetAppc() { + return Image_Appc_DEFAULT + } + return p.Appc +} +func (p *Image) CountSetFieldsImage() int { + count := 0 + if p.IsSetDocker() { + count++ + } + if p.IsSetAppc() { + count++ + } + return count + +} + +func (p *Image) IsSetDocker() bool { + return p.Docker != nil +} + +func (p *Image) IsSetAppc() bool { + return p.Appc != nil +} + +func (p *Image) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *Image) ReadField1(iprot thrift.TProtocol) error { + p.Docker = &DockerImage{} + if err := p.Docker.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Docker), err) + } + return nil +} + +func (p *Image) ReadField2(iprot thrift.TProtocol) error { + p.Appc = &AppcImage{} + if err := p.Appc.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Appc), err) + } + return nil +} + +func (p *Image) Write(oprot thrift.TProtocol) error { + if c := p.CountSetFieldsImage(); c != 1 { + return fmt.Errorf("%T write union: exactly one field must be set (%d set).", p, c) + } + if err := oprot.WriteStructBegin("Image"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *Image) writeField1(oprot thrift.TProtocol) (err error) { + if p.IsSetDocker() { + if err := oprot.WriteFieldBegin("docker", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:docker: ", p), err) + } + if err := p.Docker.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Docker), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:docker: ", p), err) + } + } + return err +} + +func (p *Image) writeField2(oprot thrift.TProtocol) (err error) { + if p.IsSetAppc() { + if err := oprot.WriteFieldBegin("appc", thrift.STRUCT, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:appc: ", p), err) + } + if err := p.Appc.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Appc), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:appc: ", p), err) + } + } + return err +} + +func (p *Image) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("Image(%+v)", *p) +} + +// Describes a mesos container, this is the default +// +// Attributes: +// - Image: the optional filesystem image to use when launching this task. +// - Volumes: the optional list of volumes to mount into the task. +type MesosContainer struct { + Image *Image `thrift:"image,1" db:"image" json:"image,omitempty"` + Volumes []*Volume `thrift:"volumes,2" db:"volumes" json:"volumes,omitempty"` +} + +func NewMesosContainer() *MesosContainer { + return &MesosContainer{} +} + +var MesosContainer_Image_DEFAULT *Image + +func (p *MesosContainer) GetImage() *Image { + if !p.IsSetImage() { + return MesosContainer_Image_DEFAULT + } + return p.Image +} + +var MesosContainer_Volumes_DEFAULT []*Volume + +func (p *MesosContainer) GetVolumes() []*Volume { + return p.Volumes +} +func (p *MesosContainer) IsSetImage() bool { + return p.Image != nil +} + +func (p *MesosContainer) IsSetVolumes() bool { + return p.Volumes != nil +} + +func (p *MesosContainer) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.LIST { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *MesosContainer) ReadField1(iprot thrift.TProtocol) error { + p.Image = &Image{} + if err := p.Image.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Image), err) + } + return nil +} + +func (p *MesosContainer) ReadField2(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadListBegin() + if err != nil { + return thrift.PrependError("error reading list begin: ", err) + } + tSlice := make([]*Volume, 0, size) + p.Volumes = tSlice + for i := 0; i < size; i++ { + _elem3 := &Volume{} + if err := _elem3.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem3), err) + } + p.Volumes = append(p.Volumes, _elem3) + } + if err := iprot.ReadListEnd(); err != nil { + return thrift.PrependError("error reading list end: ", err) + } + return nil +} + +func (p *MesosContainer) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("MesosContainer"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *MesosContainer) writeField1(oprot thrift.TProtocol) (err error) { + if p.IsSetImage() { + if err := oprot.WriteFieldBegin("image", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:image: ", p), err) + } + if err := p.Image.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Image), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:image: ", p), err) + } + } + return err +} + +func (p *MesosContainer) writeField2(oprot thrift.TProtocol) (err error) { + if p.IsSetVolumes() { + if err := oprot.WriteFieldBegin("volumes", thrift.LIST, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:volumes: ", p), err) + } + if err := oprot.WriteListBegin(thrift.STRUCT, len(p.Volumes)); err != nil { + return thrift.PrependError("error writing list begin: ", err) + } + for _, v := range p.Volumes { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteListEnd(); err != nil { + return thrift.PrependError("error writing list end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:volumes: ", p), err) + } + } + return err +} + +func (p *MesosContainer) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("MesosContainer(%+v)", *p) +} + +// Describes a parameter passed to docker cli +// +// Attributes: +// - Name: a parameter to pass to docker. (e.g. volume) +// - Value: the value to pass to a parameter (e.g. /src/webapp:/opt/webapp) +type DockerParameter struct { + Name string `thrift:"name,1" db:"name" json:"name"` + Value string `thrift:"value,2" db:"value" json:"value"` +} + +func NewDockerParameter() *DockerParameter { + return &DockerParameter{} +} + +func (p *DockerParameter) GetName() string { + return p.Name +} + +func (p *DockerParameter) GetValue() string { + return p.Value +} +func (p *DockerParameter) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRING { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *DockerParameter) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Name = v + } + return nil +} + +func (p *DockerParameter) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.Value = v + } + return nil +} + +func (p *DockerParameter) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("DockerParameter"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *DockerParameter) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("name", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:name: ", p), err) + } + if err := oprot.WriteString(string(p.Name)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.name (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:name: ", p), err) + } + return err +} + +func (p *DockerParameter) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("value", thrift.STRING, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:value: ", p), err) + } + if err := oprot.WriteString(string(p.Value)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.value (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:value: ", p), err) + } + return err +} + +func (p *DockerParameter) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("DockerParameter(%+v)", *p) +} + +// Describes a docker container +// +// Attributes: +// - Image: The container image to be run +// - Parameters: The arbitrary parameters to pass to container +type DockerContainer struct { + Image string `thrift:"image,1" db:"image" json:"image"` + Parameters []*DockerParameter `thrift:"parameters,2" db:"parameters" json:"parameters,omitempty"` +} + +func NewDockerContainer() *DockerContainer { + return &DockerContainer{} +} + +func (p *DockerContainer) GetImage() string { + return p.Image +} + +var DockerContainer_Parameters_DEFAULT []*DockerParameter + +func (p *DockerContainer) GetParameters() []*DockerParameter { + return p.Parameters +} +func (p *DockerContainer) IsSetParameters() bool { + return p.Parameters != nil +} + +func (p *DockerContainer) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.LIST { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *DockerContainer) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Image = v + } + return nil +} + +func (p *DockerContainer) ReadField2(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadListBegin() + if err != nil { + return thrift.PrependError("error reading list begin: ", err) + } + tSlice := make([]*DockerParameter, 0, size) + p.Parameters = tSlice + for i := 0; i < size; i++ { + _elem4 := &DockerParameter{} + if err := _elem4.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem4), err) + } + p.Parameters = append(p.Parameters, _elem4) + } + if err := iprot.ReadListEnd(); err != nil { + return thrift.PrependError("error reading list end: ", err) + } + return nil +} + +func (p *DockerContainer) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("DockerContainer"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *DockerContainer) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("image", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:image: ", p), err) + } + if err := oprot.WriteString(string(p.Image)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.image (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:image: ", p), err) + } + return err +} + +func (p *DockerContainer) writeField2(oprot thrift.TProtocol) (err error) { + if p.IsSetParameters() { + if err := oprot.WriteFieldBegin("parameters", thrift.LIST, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:parameters: ", p), err) + } + if err := oprot.WriteListBegin(thrift.STRUCT, len(p.Parameters)); err != nil { + return thrift.PrependError("error writing list begin: ", err) + } + for _, v := range p.Parameters { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteListEnd(); err != nil { + return thrift.PrependError("error writing list end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:parameters: ", p), err) + } + } + return err +} + +func (p *DockerContainer) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("DockerContainer(%+v)", *p) +} + +// Describes a container to be used in a task +// +// Attributes: +// - Mesos +// - Docker +type Container struct { + Mesos *MesosContainer `thrift:"mesos,1" db:"mesos" json:"mesos,omitempty"` + Docker *DockerContainer `thrift:"docker,2" db:"docker" json:"docker,omitempty"` +} + +func NewContainer() *Container { + return &Container{} +} + +var Container_Mesos_DEFAULT *MesosContainer + +func (p *Container) GetMesos() *MesosContainer { + if !p.IsSetMesos() { + return Container_Mesos_DEFAULT + } + return p.Mesos +} + +var Container_Docker_DEFAULT *DockerContainer + +func (p *Container) GetDocker() *DockerContainer { + if !p.IsSetDocker() { + return Container_Docker_DEFAULT + } + return p.Docker +} +func (p *Container) CountSetFieldsContainer() int { + count := 0 + if p.IsSetMesos() { + count++ + } + if p.IsSetDocker() { + count++ + } + return count + +} + +func (p *Container) IsSetMesos() bool { + return p.Mesos != nil +} + +func (p *Container) IsSetDocker() bool { + return p.Docker != nil +} + +func (p *Container) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *Container) ReadField1(iprot thrift.TProtocol) error { + p.Mesos = &MesosContainer{} + if err := p.Mesos.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Mesos), err) + } + return nil +} + +func (p *Container) ReadField2(iprot thrift.TProtocol) error { + p.Docker = &DockerContainer{} + if err := p.Docker.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Docker), err) + } + return nil +} + +func (p *Container) Write(oprot thrift.TProtocol) error { + if c := p.CountSetFieldsContainer(); c != 1 { + return fmt.Errorf("%T write union: exactly one field must be set (%d set).", p, c) + } + if err := oprot.WriteStructBegin("Container"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *Container) writeField1(oprot thrift.TProtocol) (err error) { + if p.IsSetMesos() { + if err := oprot.WriteFieldBegin("mesos", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:mesos: ", p), err) + } + if err := p.Mesos.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Mesos), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:mesos: ", p), err) + } + } + return err +} + +func (p *Container) writeField2(oprot thrift.TProtocol) (err error) { + if p.IsSetDocker() { + if err := oprot.WriteFieldBegin("docker", thrift.STRUCT, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:docker: ", p), err) + } + if err := p.Docker.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Docker), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:docker: ", p), err) + } + } + return err +} + +func (p *Container) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("Container(%+v)", *p) +} + +// Describes resource value required to run a task. +// +// Attributes: +// - NumCpus +// - RamMb +// - DiskMb +// - NamedPort +// - NumGpus +type Resource struct { + NumCpus *float64 `thrift:"numCpus,1" db:"numCpus" json:"numCpus,omitempty"` + RamMb *int64 `thrift:"ramMb,2" db:"ramMb" json:"ramMb,omitempty"` + DiskMb *int64 `thrift:"diskMb,3" db:"diskMb" json:"diskMb,omitempty"` + NamedPort *string `thrift:"namedPort,4" db:"namedPort" json:"namedPort,omitempty"` + NumGpus *int64 `thrift:"numGpus,5" db:"numGpus" json:"numGpus,omitempty"` +} + +func NewResource() *Resource { + return &Resource{} +} + +var Resource_NumCpus_DEFAULT float64 + +func (p *Resource) GetNumCpus() float64 { + if !p.IsSetNumCpus() { + return Resource_NumCpus_DEFAULT + } + return *p.NumCpus +} + +var Resource_RamMb_DEFAULT int64 + +func (p *Resource) GetRamMb() int64 { + if !p.IsSetRamMb() { + return Resource_RamMb_DEFAULT + } + return *p.RamMb +} + +var Resource_DiskMb_DEFAULT int64 + +func (p *Resource) GetDiskMb() int64 { + if !p.IsSetDiskMb() { + return Resource_DiskMb_DEFAULT + } + return *p.DiskMb +} + +var Resource_NamedPort_DEFAULT string + +func (p *Resource) GetNamedPort() string { + if !p.IsSetNamedPort() { + return Resource_NamedPort_DEFAULT + } + return *p.NamedPort +} + +var Resource_NumGpus_DEFAULT int64 + +func (p *Resource) GetNumGpus() int64 { + if !p.IsSetNumGpus() { + return Resource_NumGpus_DEFAULT + } + return *p.NumGpus +} +func (p *Resource) CountSetFieldsResource() int { + count := 0 + if p.IsSetNumCpus() { + count++ + } + if p.IsSetRamMb() { + count++ + } + if p.IsSetDiskMb() { + count++ + } + if p.IsSetNamedPort() { + count++ + } + if p.IsSetNumGpus() { + count++ + } + return count + +} + +func (p *Resource) IsSetNumCpus() bool { + return p.NumCpus != nil +} + +func (p *Resource) IsSetRamMb() bool { + return p.RamMb != nil +} + +func (p *Resource) IsSetDiskMb() bool { + return p.DiskMb != nil +} + +func (p *Resource) IsSetNamedPort() bool { + return p.NamedPort != nil +} + +func (p *Resource) IsSetNumGpus() bool { + return p.NumGpus != nil +} + +func (p *Resource) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.DOUBLE { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.I64 { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.I64 { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 4: + if fieldTypeId == thrift.STRING { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 5: + if fieldTypeId == thrift.I64 { + if err := p.ReadField5(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *Resource) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadDouble(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.NumCpus = &v + } + return nil +} + +func (p *Resource) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI64(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.RamMb = &v + } + return nil +} + +func (p *Resource) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI64(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.DiskMb = &v + } + return nil +} + +func (p *Resource) ReadField4(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 4: ", err) + } else { + p.NamedPort = &v + } + return nil +} + +func (p *Resource) ReadField5(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI64(); err != nil { + return thrift.PrependError("error reading field 5: ", err) + } else { + p.NumGpus = &v + } + return nil +} + +func (p *Resource) Write(oprot thrift.TProtocol) error { + if c := p.CountSetFieldsResource(); c != 1 { + return fmt.Errorf("%T write union: exactly one field must be set (%d set).", p, c) + } + if err := oprot.WriteStructBegin("Resource"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + if err := p.writeField4(oprot); err != nil { + return err + } + if err := p.writeField5(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *Resource) writeField1(oprot thrift.TProtocol) (err error) { + if p.IsSetNumCpus() { + if err := oprot.WriteFieldBegin("numCpus", thrift.DOUBLE, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:numCpus: ", p), err) + } + if err := oprot.WriteDouble(float64(*p.NumCpus)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.numCpus (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:numCpus: ", p), err) + } + } + return err +} + +func (p *Resource) writeField2(oprot thrift.TProtocol) (err error) { + if p.IsSetRamMb() { + if err := oprot.WriteFieldBegin("ramMb", thrift.I64, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:ramMb: ", p), err) + } + if err := oprot.WriteI64(int64(*p.RamMb)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.ramMb (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:ramMb: ", p), err) + } + } + return err +} + +func (p *Resource) writeField3(oprot thrift.TProtocol) (err error) { + if p.IsSetDiskMb() { + if err := oprot.WriteFieldBegin("diskMb", thrift.I64, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:diskMb: ", p), err) + } + if err := oprot.WriteI64(int64(*p.DiskMb)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.diskMb (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:diskMb: ", p), err) + } + } + return err +} + +func (p *Resource) writeField4(oprot thrift.TProtocol) (err error) { + if p.IsSetNamedPort() { + if err := oprot.WriteFieldBegin("namedPort", thrift.STRING, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:namedPort: ", p), err) + } + if err := oprot.WriteString(string(*p.NamedPort)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.namedPort (4) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:namedPort: ", p), err) + } + } + return err +} + +func (p *Resource) writeField5(oprot thrift.TProtocol) (err error) { + if p.IsSetNumGpus() { + if err := oprot.WriteFieldBegin("numGpus", thrift.I64, 5); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:numGpus: ", p), err) + } + if err := oprot.WriteI64(int64(*p.NumGpus)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.numGpus (5) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 5:numGpus: ", p), err) + } + } + return err +} + +func (p *Resource) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("Resource(%+v)", *p) +} + +// Attributes: +// - Reschedule +// - DelaySecs +type PartitionPolicy struct { + Reschedule bool `thrift:"reschedule,1" db:"reschedule" json:"reschedule"` + DelaySecs *int64 `thrift:"delaySecs,2" db:"delaySecs" json:"delaySecs,omitempty"` +} + +func NewPartitionPolicy() *PartitionPolicy { + return &PartitionPolicy{} +} + +func (p *PartitionPolicy) GetReschedule() bool { + return p.Reschedule +} + +var PartitionPolicy_DelaySecs_DEFAULT int64 + +func (p *PartitionPolicy) GetDelaySecs() int64 { + if !p.IsSetDelaySecs() { + return PartitionPolicy_DelaySecs_DEFAULT + } + return *p.DelaySecs +} +func (p *PartitionPolicy) IsSetDelaySecs() bool { + return p.DelaySecs != nil +} + +func (p *PartitionPolicy) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.BOOL { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.I64 { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *PartitionPolicy) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadBool(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Reschedule = v + } + return nil +} + +func (p *PartitionPolicy) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI64(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.DelaySecs = &v + } + return nil +} + +func (p *PartitionPolicy) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("PartitionPolicy"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *PartitionPolicy) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("reschedule", thrift.BOOL, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:reschedule: ", p), err) + } + if err := oprot.WriteBool(bool(p.Reschedule)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.reschedule (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:reschedule: ", p), err) + } + return err +} + +func (p *PartitionPolicy) writeField2(oprot thrift.TProtocol) (err error) { + if p.IsSetDelaySecs() { + if err := oprot.WriteFieldBegin("delaySecs", thrift.I64, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:delaySecs: ", p), err) + } + if err := oprot.WriteI64(int64(*p.DelaySecs)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.delaySecs (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:delaySecs: ", p), err) + } + } + return err +} + +func (p *PartitionPolicy) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("PartitionPolicy(%+v)", *p) +} + +// SLA requirements expressed as the percentage of instances to be RUNNING every durationSecs +// +// Attributes: +// - Percentage +// - DurationSecs: Minimum time duration a task needs to be `RUNNING` to be treated as active +type PercentageSlaPolicy struct { + Percentage float64 `thrift:"percentage,1" db:"percentage" json:"percentage"` + DurationSecs int64 `thrift:"durationSecs,2" db:"durationSecs" json:"durationSecs"` +} + +func NewPercentageSlaPolicy() *PercentageSlaPolicy { + return &PercentageSlaPolicy{} +} + +func (p *PercentageSlaPolicy) GetPercentage() float64 { + return p.Percentage +} + +func (p *PercentageSlaPolicy) GetDurationSecs() int64 { + return p.DurationSecs +} +func (p *PercentageSlaPolicy) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.DOUBLE { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.I64 { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *PercentageSlaPolicy) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadDouble(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Percentage = v + } + return nil +} + +func (p *PercentageSlaPolicy) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI64(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.DurationSecs = v + } + return nil +} + +func (p *PercentageSlaPolicy) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("PercentageSlaPolicy"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *PercentageSlaPolicy) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("percentage", thrift.DOUBLE, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:percentage: ", p), err) + } + if err := oprot.WriteDouble(float64(p.Percentage)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.percentage (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:percentage: ", p), err) + } + return err +} + +func (p *PercentageSlaPolicy) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("durationSecs", thrift.I64, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:durationSecs: ", p), err) + } + if err := oprot.WriteI64(int64(p.DurationSecs)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.durationSecs (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:durationSecs: ", p), err) + } + return err +} + +func (p *PercentageSlaPolicy) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("PercentageSlaPolicy(%+v)", *p) +} + +// SLA requirements expressed as the number of instances to be RUNNING every durationSecs +// +// Attributes: +// - Count: The number of active instances required every `durationSecs` +// - DurationSecs: Minimum time duration a task needs to be `RUNNING` to be treated as active +type CountSlaPolicy struct { + Count int64 `thrift:"count,1" db:"count" json:"count"` + DurationSecs int64 `thrift:"durationSecs,2" db:"durationSecs" json:"durationSecs"` +} + +func NewCountSlaPolicy() *CountSlaPolicy { + return &CountSlaPolicy{} +} + +func (p *CountSlaPolicy) GetCount() int64 { + return p.Count +} + +func (p *CountSlaPolicy) GetDurationSecs() int64 { + return p.DurationSecs +} +func (p *CountSlaPolicy) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.I64 { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.I64 { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *CountSlaPolicy) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI64(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Count = v + } + return nil +} + +func (p *CountSlaPolicy) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI64(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.DurationSecs = v + } + return nil +} + +func (p *CountSlaPolicy) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("CountSlaPolicy"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *CountSlaPolicy) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("count", thrift.I64, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:count: ", p), err) + } + if err := oprot.WriteI64(int64(p.Count)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.count (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:count: ", p), err) + } + return err +} + +func (p *CountSlaPolicy) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("durationSecs", thrift.I64, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:durationSecs: ", p), err) + } + if err := oprot.WriteI64(int64(p.DurationSecs)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.durationSecs (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:durationSecs: ", p), err) + } + return err +} + +func (p *CountSlaPolicy) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("CountSlaPolicy(%+v)", *p) +} + +// SLA requirements to be delegated to an external coordinator +// +// Attributes: +// - CoordinatorUrl: URL for the coordinator service that needs to be contacted for SLA checks +// - StatusKey: Field in the Coordinator response json indicating if the action is allowed or not +type CoordinatorSlaPolicy struct { + CoordinatorUrl string `thrift:"coordinatorUrl,1" db:"coordinatorUrl" json:"coordinatorUrl"` + StatusKey string `thrift:"statusKey,2" db:"statusKey" json:"statusKey"` +} + +func NewCoordinatorSlaPolicy() *CoordinatorSlaPolicy { + return &CoordinatorSlaPolicy{} +} + +func (p *CoordinatorSlaPolicy) GetCoordinatorUrl() string { + return p.CoordinatorUrl +} + +func (p *CoordinatorSlaPolicy) GetStatusKey() string { + return p.StatusKey +} +func (p *CoordinatorSlaPolicy) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRING { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *CoordinatorSlaPolicy) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.CoordinatorUrl = v + } + return nil +} + +func (p *CoordinatorSlaPolicy) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.StatusKey = v + } + return nil +} + +func (p *CoordinatorSlaPolicy) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("CoordinatorSlaPolicy"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *CoordinatorSlaPolicy) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("coordinatorUrl", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:coordinatorUrl: ", p), err) + } + if err := oprot.WriteString(string(p.CoordinatorUrl)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.coordinatorUrl (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:coordinatorUrl: ", p), err) + } + return err +} + +func (p *CoordinatorSlaPolicy) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("statusKey", thrift.STRING, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:statusKey: ", p), err) + } + if err := oprot.WriteString(string(p.StatusKey)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.statusKey (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:statusKey: ", p), err) + } + return err +} + +func (p *CoordinatorSlaPolicy) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("CoordinatorSlaPolicy(%+v)", *p) +} + +// SLA requirements expressed in one of the many types +// +// Attributes: +// - PercentageSlaPolicy +// - CountSlaPolicy +// - CoordinatorSlaPolicy +type SlaPolicy struct { + PercentageSlaPolicy *PercentageSlaPolicy `thrift:"percentageSlaPolicy,1" db:"percentageSlaPolicy" json:"percentageSlaPolicy,omitempty"` + CountSlaPolicy *CountSlaPolicy `thrift:"countSlaPolicy,2" db:"countSlaPolicy" json:"countSlaPolicy,omitempty"` + CoordinatorSlaPolicy *CoordinatorSlaPolicy `thrift:"coordinatorSlaPolicy,3" db:"coordinatorSlaPolicy" json:"coordinatorSlaPolicy,omitempty"` +} + +func NewSlaPolicy() *SlaPolicy { + return &SlaPolicy{} +} + +var SlaPolicy_PercentageSlaPolicy_DEFAULT *PercentageSlaPolicy + +func (p *SlaPolicy) GetPercentageSlaPolicy() *PercentageSlaPolicy { + if !p.IsSetPercentageSlaPolicy() { + return SlaPolicy_PercentageSlaPolicy_DEFAULT + } + return p.PercentageSlaPolicy +} + +var SlaPolicy_CountSlaPolicy_DEFAULT *CountSlaPolicy + +func (p *SlaPolicy) GetCountSlaPolicy() *CountSlaPolicy { + if !p.IsSetCountSlaPolicy() { + return SlaPolicy_CountSlaPolicy_DEFAULT + } + return p.CountSlaPolicy +} + +var SlaPolicy_CoordinatorSlaPolicy_DEFAULT *CoordinatorSlaPolicy + +func (p *SlaPolicy) GetCoordinatorSlaPolicy() *CoordinatorSlaPolicy { + if !p.IsSetCoordinatorSlaPolicy() { + return SlaPolicy_CoordinatorSlaPolicy_DEFAULT + } + return p.CoordinatorSlaPolicy +} +func (p *SlaPolicy) CountSetFieldsSlaPolicy() int { + count := 0 + if p.IsSetPercentageSlaPolicy() { + count++ + } + if p.IsSetCountSlaPolicy() { + count++ + } + if p.IsSetCoordinatorSlaPolicy() { + count++ + } + return count + +} + +func (p *SlaPolicy) IsSetPercentageSlaPolicy() bool { + return p.PercentageSlaPolicy != nil +} + +func (p *SlaPolicy) IsSetCountSlaPolicy() bool { + return p.CountSlaPolicy != nil +} + +func (p *SlaPolicy) IsSetCoordinatorSlaPolicy() bool { + return p.CoordinatorSlaPolicy != nil +} + +func (p *SlaPolicy) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *SlaPolicy) ReadField1(iprot thrift.TProtocol) error { + p.PercentageSlaPolicy = &PercentageSlaPolicy{} + if err := p.PercentageSlaPolicy.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.PercentageSlaPolicy), err) + } + return nil +} + +func (p *SlaPolicy) ReadField2(iprot thrift.TProtocol) error { + p.CountSlaPolicy = &CountSlaPolicy{} + if err := p.CountSlaPolicy.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.CountSlaPolicy), err) + } + return nil +} + +func (p *SlaPolicy) ReadField3(iprot thrift.TProtocol) error { + p.CoordinatorSlaPolicy = &CoordinatorSlaPolicy{} + if err := p.CoordinatorSlaPolicy.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.CoordinatorSlaPolicy), err) + } + return nil +} + +func (p *SlaPolicy) Write(oprot thrift.TProtocol) error { + if c := p.CountSetFieldsSlaPolicy(); c != 1 { + return fmt.Errorf("%T write union: exactly one field must be set (%d set).", p, c) + } + if err := oprot.WriteStructBegin("SlaPolicy"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *SlaPolicy) writeField1(oprot thrift.TProtocol) (err error) { + if p.IsSetPercentageSlaPolicy() { + if err := oprot.WriteFieldBegin("percentageSlaPolicy", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:percentageSlaPolicy: ", p), err) + } + if err := p.PercentageSlaPolicy.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.PercentageSlaPolicy), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:percentageSlaPolicy: ", p), err) + } + } + return err +} + +func (p *SlaPolicy) writeField2(oprot thrift.TProtocol) (err error) { + if p.IsSetCountSlaPolicy() { + if err := oprot.WriteFieldBegin("countSlaPolicy", thrift.STRUCT, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:countSlaPolicy: ", p), err) + } + if err := p.CountSlaPolicy.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.CountSlaPolicy), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:countSlaPolicy: ", p), err) + } + } + return err +} + +func (p *SlaPolicy) writeField3(oprot thrift.TProtocol) (err error) { + if p.IsSetCoordinatorSlaPolicy() { + if err := oprot.WriteFieldBegin("coordinatorSlaPolicy", thrift.STRUCT, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:coordinatorSlaPolicy: ", p), err) + } + if err := p.CoordinatorSlaPolicy.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.CoordinatorSlaPolicy), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:coordinatorSlaPolicy: ", p), err) + } + } + return err +} + +func (p *SlaPolicy) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("SlaPolicy(%+v)", *p) +} + +// Description of the tasks contained within a job. +// +// Attributes: +// - Job: Job task belongs to. +// - Owner: contains the role component of JobKey +// - IsService +// - Priority +// - MaxTaskFailures +// - Production: Whether this is a production task, which can preempt. +// - Tier: Task tier type. +// - Resources: All resources required to run a task. +// - Constraints +// - MesosFetcherUris: Resources to retrieve with Mesos Fetcher +// - TaskLinks: Custom links to include when displaying this task on the scheduler dashboard. Keys are anchor +// text, values are URLs. Wildcards are supported for dynamic link crafting based on host, ports, +// instance, etc. +// - ContactEmail +// - ExecutorConfig: Executor configuration +// - Metadata: Used to display additional details in the UI. +// - PartitionPolicy: Policy for how to deal with task partitions +// - SlaPolicy: SLA requirements to be met during maintenance +// - Container: the container the task should use to execute +type TaskConfig struct { + // unused fields # 1 to 6 + IsService bool `thrift:"isService,7" db:"isService" json:"isService"` + // unused fields # 8 to 10 + Priority int32 `thrift:"priority,11" db:"priority" json:"priority"` + // unused field # 12 + MaxTaskFailures int32 `thrift:"maxTaskFailures,13" db:"maxTaskFailures" json:"maxTaskFailures"` + // unused fields # 14 to 16 + Owner *Identity `thrift:"owner,17" db:"owner" json:"owner"` + Production *bool `thrift:"production,18" db:"production" json:"production,omitempty"` + // unused field # 19 + Constraints []*Constraint `thrift:"constraints,20" db:"constraints" json:"constraints"` + // unused field # 21 + TaskLinks map[string]string `thrift:"taskLinks,22" db:"taskLinks" json:"taskLinks,omitempty"` + ContactEmail *string `thrift:"contactEmail,23" db:"contactEmail" json:"contactEmail,omitempty"` + // unused field # 24 + ExecutorConfig *ExecutorConfig `thrift:"executorConfig,25" db:"executorConfig" json:"executorConfig,omitempty"` + // unused field # 26 + Metadata []*Metadata `thrift:"metadata,27" db:"metadata" json:"metadata,omitempty"` + Job *JobKey `thrift:"job,28" db:"job" json:"job"` + Container *Container `thrift:"container,29" db:"container" json:"container"` + Tier *string `thrift:"tier,30" db:"tier" json:"tier,omitempty"` + // unused field # 31 + Resources []*Resource `thrift:"resources,32" db:"resources" json:"resources"` + MesosFetcherUris []*MesosFetcherURI `thrift:"mesosFetcherUris,33" db:"mesosFetcherUris" json:"mesosFetcherUris,omitempty"` + PartitionPolicy *PartitionPolicy `thrift:"partitionPolicy,34" db:"partitionPolicy" json:"partitionPolicy,omitempty"` + SlaPolicy *SlaPolicy `thrift:"slaPolicy,35" db:"slaPolicy" json:"slaPolicy,omitempty"` +} + +func NewTaskConfig() *TaskConfig { + return &TaskConfig{} +} + +var TaskConfig_Job_DEFAULT *JobKey + +func (p *TaskConfig) GetJob() *JobKey { + if !p.IsSetJob() { + return TaskConfig_Job_DEFAULT + } + return p.Job +} + +var TaskConfig_Owner_DEFAULT *Identity + +func (p *TaskConfig) GetOwner() *Identity { + if !p.IsSetOwner() { + return TaskConfig_Owner_DEFAULT + } + return p.Owner +} + +func (p *TaskConfig) GetIsService() bool { + return p.IsService +} + +func (p *TaskConfig) GetPriority() int32 { + return p.Priority +} + +func (p *TaskConfig) GetMaxTaskFailures() int32 { + return p.MaxTaskFailures +} + +var TaskConfig_Production_DEFAULT bool + +func (p *TaskConfig) GetProduction() bool { + if !p.IsSetProduction() { + return TaskConfig_Production_DEFAULT + } + return *p.Production +} + +var TaskConfig_Tier_DEFAULT string + +func (p *TaskConfig) GetTier() string { + if !p.IsSetTier() { + return TaskConfig_Tier_DEFAULT + } + return *p.Tier +} + +func (p *TaskConfig) GetResources() []*Resource { + return p.Resources +} + +func (p *TaskConfig) GetConstraints() []*Constraint { + return p.Constraints +} + +var TaskConfig_MesosFetcherUris_DEFAULT []*MesosFetcherURI + +func (p *TaskConfig) GetMesosFetcherUris() []*MesosFetcherURI { + return p.MesosFetcherUris +} + +var TaskConfig_TaskLinks_DEFAULT map[string]string + +func (p *TaskConfig) GetTaskLinks() map[string]string { + return p.TaskLinks +} + +var TaskConfig_ContactEmail_DEFAULT string + +func (p *TaskConfig) GetContactEmail() string { + if !p.IsSetContactEmail() { + return TaskConfig_ContactEmail_DEFAULT + } + return *p.ContactEmail +} + +var TaskConfig_ExecutorConfig_DEFAULT *ExecutorConfig + +func (p *TaskConfig) GetExecutorConfig() *ExecutorConfig { + if !p.IsSetExecutorConfig() { + return TaskConfig_ExecutorConfig_DEFAULT + } + return p.ExecutorConfig +} + +var TaskConfig_Metadata_DEFAULT []*Metadata + +func (p *TaskConfig) GetMetadata() []*Metadata { + return p.Metadata +} + +var TaskConfig_PartitionPolicy_DEFAULT *PartitionPolicy + +func (p *TaskConfig) GetPartitionPolicy() *PartitionPolicy { + if !p.IsSetPartitionPolicy() { + return TaskConfig_PartitionPolicy_DEFAULT + } + return p.PartitionPolicy +} + +var TaskConfig_SlaPolicy_DEFAULT *SlaPolicy + +func (p *TaskConfig) GetSlaPolicy() *SlaPolicy { + if !p.IsSetSlaPolicy() { + return TaskConfig_SlaPolicy_DEFAULT + } + return p.SlaPolicy +} + +var TaskConfig_Container_DEFAULT *Container = &Container{ + Mesos: &MesosContainer{}, +} + +func (p *TaskConfig) GetContainer() *Container { + if !p.IsSetContainer() { + return TaskConfig_Container_DEFAULT + } + return p.Container +} +func (p *TaskConfig) IsSetJob() bool { + return p.Job != nil +} + +func (p *TaskConfig) IsSetOwner() bool { + return p.Owner != nil +} + +func (p *TaskConfig) IsSetProduction() bool { + return p.Production != nil +} + +func (p *TaskConfig) IsSetTier() bool { + return p.Tier != nil +} + +func (p *TaskConfig) IsSetMesosFetcherUris() bool { + return p.MesosFetcherUris != nil +} + +func (p *TaskConfig) IsSetTaskLinks() bool { + return p.TaskLinks != nil +} + +func (p *TaskConfig) IsSetContactEmail() bool { + return p.ContactEmail != nil +} + +func (p *TaskConfig) IsSetExecutorConfig() bool { + return p.ExecutorConfig != nil +} + +func (p *TaskConfig) IsSetMetadata() bool { + return p.Metadata != nil +} + +func (p *TaskConfig) IsSetPartitionPolicy() bool { + return p.PartitionPolicy != nil +} + +func (p *TaskConfig) IsSetSlaPolicy() bool { + return p.SlaPolicy != nil +} + +func (p *TaskConfig) IsSetContainer() bool { + return p.Container != nil +} + +func (p *TaskConfig) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 28: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField28(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 17: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField17(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 7: + if fieldTypeId == thrift.BOOL { + if err := p.ReadField7(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 11: + if fieldTypeId == thrift.I32 { + if err := p.ReadField11(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 13: + if fieldTypeId == thrift.I32 { + if err := p.ReadField13(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 18: + if fieldTypeId == thrift.BOOL { + if err := p.ReadField18(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 30: + if fieldTypeId == thrift.STRING { + if err := p.ReadField30(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 32: + if fieldTypeId == thrift.SET { + if err := p.ReadField32(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 20: + if fieldTypeId == thrift.SET { + if err := p.ReadField20(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 33: + if fieldTypeId == thrift.SET { + if err := p.ReadField33(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 22: + if fieldTypeId == thrift.MAP { + if err := p.ReadField22(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 23: + if fieldTypeId == thrift.STRING { + if err := p.ReadField23(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 25: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField25(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 27: + if fieldTypeId == thrift.SET { + if err := p.ReadField27(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 34: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField34(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 35: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField35(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 29: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField29(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *TaskConfig) ReadField28(iprot thrift.TProtocol) error { + p.Job = &JobKey{} + if err := p.Job.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Job), err) + } + return nil +} + +func (p *TaskConfig) ReadField17(iprot thrift.TProtocol) error { + p.Owner = &Identity{} + if err := p.Owner.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Owner), err) + } + return nil +} + +func (p *TaskConfig) ReadField7(iprot thrift.TProtocol) error { + if v, err := iprot.ReadBool(); err != nil { + return thrift.PrependError("error reading field 7: ", err) + } else { + p.IsService = v + } + return nil +} + +func (p *TaskConfig) ReadField11(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 11: ", err) + } else { + p.Priority = v + } + return nil +} + +func (p *TaskConfig) ReadField13(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 13: ", err) + } else { + p.MaxTaskFailures = v + } + return nil +} + +func (p *TaskConfig) ReadField18(iprot thrift.TProtocol) error { + if v, err := iprot.ReadBool(); err != nil { + return thrift.PrependError("error reading field 18: ", err) + } else { + p.Production = &v + } + return nil +} + +func (p *TaskConfig) ReadField30(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 30: ", err) + } else { + p.Tier = &v + } + return nil +} + +func (p *TaskConfig) ReadField32(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*Resource, 0, size) + p.Resources = tSet + for i := 0; i < size; i++ { + _elem5 := &Resource{} + if err := _elem5.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem5), err) + } + p.Resources = append(p.Resources, _elem5) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *TaskConfig) ReadField20(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*Constraint, 0, size) + p.Constraints = tSet + for i := 0; i < size; i++ { + _elem6 := &Constraint{} + if err := _elem6.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem6), err) + } + p.Constraints = append(p.Constraints, _elem6) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *TaskConfig) ReadField33(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*MesosFetcherURI, 0, size) + p.MesosFetcherUris = tSet + for i := 0; i < size; i++ { + _elem7 := &MesosFetcherURI{} + if err := _elem7.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem7), err) + } + p.MesosFetcherUris = append(p.MesosFetcherUris, _elem7) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *TaskConfig) ReadField22(iprot thrift.TProtocol) error { + _, _, size, err := iprot.ReadMapBegin() + if err != nil { + return thrift.PrependError("error reading map begin: ", err) + } + tMap := make(map[string]string, size) + p.TaskLinks = tMap + for i := 0; i < size; i++ { + var _key8 string + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 0: ", err) + } else { + _key8 = v + } + var _val9 string + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 0: ", err) + } else { + _val9 = v + } + p.TaskLinks[_key8] = _val9 + } + if err := iprot.ReadMapEnd(); err != nil { + return thrift.PrependError("error reading map end: ", err) + } + return nil +} + +func (p *TaskConfig) ReadField23(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 23: ", err) + } else { + p.ContactEmail = &v + } + return nil +} + +func (p *TaskConfig) ReadField25(iprot thrift.TProtocol) error { + p.ExecutorConfig = &ExecutorConfig{} + if err := p.ExecutorConfig.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.ExecutorConfig), err) + } + return nil +} + +func (p *TaskConfig) ReadField27(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*Metadata, 0, size) + p.Metadata = tSet + for i := 0; i < size; i++ { + _elem10 := &Metadata{} + if err := _elem10.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem10), err) + } + p.Metadata = append(p.Metadata, _elem10) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *TaskConfig) ReadField34(iprot thrift.TProtocol) error { + p.PartitionPolicy = &PartitionPolicy{} + if err := p.PartitionPolicy.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.PartitionPolicy), err) + } + return nil +} + +func (p *TaskConfig) ReadField35(iprot thrift.TProtocol) error { + p.SlaPolicy = &SlaPolicy{} + if err := p.SlaPolicy.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.SlaPolicy), err) + } + return nil +} + +func (p *TaskConfig) ReadField29(iprot thrift.TProtocol) error { + p.Container = &Container{} + if err := p.Container.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Container), err) + } + return nil +} + +func (p *TaskConfig) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("TaskConfig"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField7(oprot); err != nil { + return err + } + if err := p.writeField11(oprot); err != nil { + return err + } + if err := p.writeField13(oprot); err != nil { + return err + } + if err := p.writeField17(oprot); err != nil { + return err + } + if err := p.writeField18(oprot); err != nil { + return err + } + if err := p.writeField20(oprot); err != nil { + return err + } + if err := p.writeField22(oprot); err != nil { + return err + } + if err := p.writeField23(oprot); err != nil { + return err + } + if err := p.writeField25(oprot); err != nil { + return err + } + if err := p.writeField27(oprot); err != nil { + return err + } + if err := p.writeField28(oprot); err != nil { + return err + } + if err := p.writeField29(oprot); err != nil { + return err + } + if err := p.writeField30(oprot); err != nil { + return err + } + if err := p.writeField32(oprot); err != nil { + return err + } + if err := p.writeField33(oprot); err != nil { + return err + } + if err := p.writeField34(oprot); err != nil { + return err + } + if err := p.writeField35(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *TaskConfig) writeField7(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("isService", thrift.BOOL, 7); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 7:isService: ", p), err) + } + if err := oprot.WriteBool(bool(p.IsService)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.isService (7) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 7:isService: ", p), err) + } + return err +} + +func (p *TaskConfig) writeField11(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("priority", thrift.I32, 11); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 11:priority: ", p), err) + } + if err := oprot.WriteI32(int32(p.Priority)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.priority (11) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 11:priority: ", p), err) + } + return err +} + +func (p *TaskConfig) writeField13(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("maxTaskFailures", thrift.I32, 13); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 13:maxTaskFailures: ", p), err) + } + if err := oprot.WriteI32(int32(p.MaxTaskFailures)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.maxTaskFailures (13) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 13:maxTaskFailures: ", p), err) + } + return err +} + +func (p *TaskConfig) writeField17(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("owner", thrift.STRUCT, 17); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 17:owner: ", p), err) + } + if err := p.Owner.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Owner), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 17:owner: ", p), err) + } + return err +} + +func (p *TaskConfig) writeField18(oprot thrift.TProtocol) (err error) { + if p.IsSetProduction() { + if err := oprot.WriteFieldBegin("production", thrift.BOOL, 18); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 18:production: ", p), err) + } + if err := oprot.WriteBool(bool(*p.Production)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.production (18) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 18:production: ", p), err) + } + } + return err +} + +func (p *TaskConfig) writeField20(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("constraints", thrift.SET, 20); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 20:constraints: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Constraints)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Constraints); i++ { + for j := i + 1; j < len(p.Constraints); j++ { + if reflect.DeepEqual(p.Constraints[i], p.Constraints[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Constraints[i])) + } + } + } + for _, v := range p.Constraints { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 20:constraints: ", p), err) + } + return err +} + +func (p *TaskConfig) writeField22(oprot thrift.TProtocol) (err error) { + if p.IsSetTaskLinks() { + if err := oprot.WriteFieldBegin("taskLinks", thrift.MAP, 22); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 22:taskLinks: ", p), err) + } + if err := oprot.WriteMapBegin(thrift.STRING, thrift.STRING, len(p.TaskLinks)); err != nil { + return thrift.PrependError("error writing map begin: ", err) + } + for k, v := range p.TaskLinks { + if err := oprot.WriteString(string(k)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) + } + if err := oprot.WriteString(string(v)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) + } + } + if err := oprot.WriteMapEnd(); err != nil { + return thrift.PrependError("error writing map end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 22:taskLinks: ", p), err) + } + } + return err +} + +func (p *TaskConfig) writeField23(oprot thrift.TProtocol) (err error) { + if p.IsSetContactEmail() { + if err := oprot.WriteFieldBegin("contactEmail", thrift.STRING, 23); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 23:contactEmail: ", p), err) + } + if err := oprot.WriteString(string(*p.ContactEmail)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.contactEmail (23) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 23:contactEmail: ", p), err) + } + } + return err +} + +func (p *TaskConfig) writeField25(oprot thrift.TProtocol) (err error) { + if p.IsSetExecutorConfig() { + if err := oprot.WriteFieldBegin("executorConfig", thrift.STRUCT, 25); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 25:executorConfig: ", p), err) + } + if err := p.ExecutorConfig.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.ExecutorConfig), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 25:executorConfig: ", p), err) + } + } + return err +} + +func (p *TaskConfig) writeField27(oprot thrift.TProtocol) (err error) { + if p.IsSetMetadata() { + if err := oprot.WriteFieldBegin("metadata", thrift.SET, 27); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 27:metadata: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Metadata)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Metadata); i++ { + for j := i + 1; j < len(p.Metadata); j++ { + if reflect.DeepEqual(p.Metadata[i], p.Metadata[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Metadata[i])) + } + } + } + for _, v := range p.Metadata { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 27:metadata: ", p), err) + } + } + return err +} + +func (p *TaskConfig) writeField28(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("job", thrift.STRUCT, 28); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 28:job: ", p), err) + } + if err := p.Job.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Job), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 28:job: ", p), err) + } + return err +} + +func (p *TaskConfig) writeField29(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("container", thrift.STRUCT, 29); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 29:container: ", p), err) + } + if err := p.Container.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Container), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 29:container: ", p), err) + } + return err +} + +func (p *TaskConfig) writeField30(oprot thrift.TProtocol) (err error) { + if p.IsSetTier() { + if err := oprot.WriteFieldBegin("tier", thrift.STRING, 30); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 30:tier: ", p), err) + } + if err := oprot.WriteString(string(*p.Tier)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.tier (30) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 30:tier: ", p), err) + } + } + return err +} + +func (p *TaskConfig) writeField32(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("resources", thrift.SET, 32); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 32:resources: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Resources)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Resources); i++ { + for j := i + 1; j < len(p.Resources); j++ { + if reflect.DeepEqual(p.Resources[i], p.Resources[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Resources[i])) + } + } + } + for _, v := range p.Resources { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 32:resources: ", p), err) + } + return err +} + +func (p *TaskConfig) writeField33(oprot thrift.TProtocol) (err error) { + if p.IsSetMesosFetcherUris() { + if err := oprot.WriteFieldBegin("mesosFetcherUris", thrift.SET, 33); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 33:mesosFetcherUris: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.MesosFetcherUris)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.MesosFetcherUris); i++ { + for j := i + 1; j < len(p.MesosFetcherUris); j++ { + if reflect.DeepEqual(p.MesosFetcherUris[i], p.MesosFetcherUris[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.MesosFetcherUris[i])) + } + } + } + for _, v := range p.MesosFetcherUris { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 33:mesosFetcherUris: ", p), err) + } + } + return err +} + +func (p *TaskConfig) writeField34(oprot thrift.TProtocol) (err error) { + if p.IsSetPartitionPolicy() { + if err := oprot.WriteFieldBegin("partitionPolicy", thrift.STRUCT, 34); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 34:partitionPolicy: ", p), err) + } + if err := p.PartitionPolicy.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.PartitionPolicy), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 34:partitionPolicy: ", p), err) + } + } + return err +} + +func (p *TaskConfig) writeField35(oprot thrift.TProtocol) (err error) { + if p.IsSetSlaPolicy() { + if err := oprot.WriteFieldBegin("slaPolicy", thrift.STRUCT, 35); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 35:slaPolicy: ", p), err) + } + if err := p.SlaPolicy.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.SlaPolicy), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 35:slaPolicy: ", p), err) + } + } + return err +} + +func (p *TaskConfig) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("TaskConfig(%+v)", *p) +} + +// Attributes: +// - Resources: Aggregated resource values. +type ResourceAggregate struct { + // unused fields # 1 to 3 + Resources []*Resource `thrift:"resources,4" db:"resources" json:"resources"` +} + +func NewResourceAggregate() *ResourceAggregate { + return &ResourceAggregate{} +} + +func (p *ResourceAggregate) GetResources() []*Resource { + return p.Resources +} +func (p *ResourceAggregate) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 4: + if fieldTypeId == thrift.SET { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ResourceAggregate) ReadField4(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*Resource, 0, size) + p.Resources = tSet + for i := 0; i < size; i++ { + _elem11 := &Resource{} + if err := _elem11.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem11), err) + } + p.Resources = append(p.Resources, _elem11) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *ResourceAggregate) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("ResourceAggregate"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField4(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ResourceAggregate) writeField4(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("resources", thrift.SET, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:resources: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Resources)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Resources); i++ { + for j := i + 1; j < len(p.Resources); j++ { + if reflect.DeepEqual(p.Resources[i], p.Resources[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Resources[i])) + } + } + } + for _, v := range p.Resources { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:resources: ", p), err) + } + return err +} + +func (p *ResourceAggregate) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ResourceAggregate(%+v)", *p) +} + +// Description of an Aurora job. One task will be scheduled for each instance within the job. +// +// Attributes: +// - Key: Key for this job. If not specified name, owner.role, and a reasonable default environment are +// used to construct it server-side. +// - Owner: Owner of this job. +// - CronSchedule: If present, the job will be handled as a cron job with this crontab-syntax schedule. +// - CronCollisionPolicy: Collision policy to use when handling overlapping cron runs. Default is KILL_EXISTING. +// - TaskConfig: Task configuration for this job. +// - InstanceCount: The number of instances in the job. Generated instance IDs for tasks will be in the range +// [0, instances). +type JobConfiguration struct { + // unused fields # 1 to 3 + CronSchedule *string `thrift:"cronSchedule,4" db:"cronSchedule" json:"cronSchedule,omitempty"` + CronCollisionPolicy CronCollisionPolicy `thrift:"cronCollisionPolicy,5" db:"cronCollisionPolicy" json:"cronCollisionPolicy"` + TaskConfig *TaskConfig `thrift:"taskConfig,6" db:"taskConfig" json:"taskConfig"` + Owner *Identity `thrift:"owner,7" db:"owner" json:"owner"` + InstanceCount int32 `thrift:"instanceCount,8" db:"instanceCount" json:"instanceCount"` + Key *JobKey `thrift:"key,9" db:"key" json:"key"` +} + +func NewJobConfiguration() *JobConfiguration { + return &JobConfiguration{} +} + +var JobConfiguration_Key_DEFAULT *JobKey + +func (p *JobConfiguration) GetKey() *JobKey { + if !p.IsSetKey() { + return JobConfiguration_Key_DEFAULT + } + return p.Key +} + +var JobConfiguration_Owner_DEFAULT *Identity + +func (p *JobConfiguration) GetOwner() *Identity { + if !p.IsSetOwner() { + return JobConfiguration_Owner_DEFAULT + } + return p.Owner +} + +var JobConfiguration_CronSchedule_DEFAULT string + +func (p *JobConfiguration) GetCronSchedule() string { + if !p.IsSetCronSchedule() { + return JobConfiguration_CronSchedule_DEFAULT + } + return *p.CronSchedule +} + +func (p *JobConfiguration) GetCronCollisionPolicy() CronCollisionPolicy { + return p.CronCollisionPolicy +} + +var JobConfiguration_TaskConfig_DEFAULT *TaskConfig + +func (p *JobConfiguration) GetTaskConfig() *TaskConfig { + if !p.IsSetTaskConfig() { + return JobConfiguration_TaskConfig_DEFAULT + } + return p.TaskConfig +} + +func (p *JobConfiguration) GetInstanceCount() int32 { + return p.InstanceCount +} +func (p *JobConfiguration) IsSetKey() bool { + return p.Key != nil +} + +func (p *JobConfiguration) IsSetOwner() bool { + return p.Owner != nil +} + +func (p *JobConfiguration) IsSetCronSchedule() bool { + return p.CronSchedule != nil +} + +func (p *JobConfiguration) IsSetTaskConfig() bool { + return p.TaskConfig != nil +} + +func (p *JobConfiguration) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 9: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField9(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 7: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField7(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 4: + if fieldTypeId == thrift.STRING { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 5: + if fieldTypeId == thrift.I32 { + if err := p.ReadField5(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 6: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField6(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 8: + if fieldTypeId == thrift.I32 { + if err := p.ReadField8(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *JobConfiguration) ReadField9(iprot thrift.TProtocol) error { + p.Key = &JobKey{} + if err := p.Key.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) + } + return nil +} + +func (p *JobConfiguration) ReadField7(iprot thrift.TProtocol) error { + p.Owner = &Identity{} + if err := p.Owner.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Owner), err) + } + return nil +} + +func (p *JobConfiguration) ReadField4(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 4: ", err) + } else { + p.CronSchedule = &v + } + return nil +} + +func (p *JobConfiguration) ReadField5(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 5: ", err) + } else { + temp := CronCollisionPolicy(v) + p.CronCollisionPolicy = temp + } + return nil +} + +func (p *JobConfiguration) ReadField6(iprot thrift.TProtocol) error { + p.TaskConfig = &TaskConfig{} + if err := p.TaskConfig.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.TaskConfig), err) + } + return nil +} + +func (p *JobConfiguration) ReadField8(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 8: ", err) + } else { + p.InstanceCount = v + } + return nil +} + +func (p *JobConfiguration) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("JobConfiguration"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField4(oprot); err != nil { + return err + } + if err := p.writeField5(oprot); err != nil { + return err + } + if err := p.writeField6(oprot); err != nil { + return err + } + if err := p.writeField7(oprot); err != nil { + return err + } + if err := p.writeField8(oprot); err != nil { + return err + } + if err := p.writeField9(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *JobConfiguration) writeField4(oprot thrift.TProtocol) (err error) { + if p.IsSetCronSchedule() { + if err := oprot.WriteFieldBegin("cronSchedule", thrift.STRING, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:cronSchedule: ", p), err) + } + if err := oprot.WriteString(string(*p.CronSchedule)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.cronSchedule (4) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:cronSchedule: ", p), err) + } + } + return err +} + +func (p *JobConfiguration) writeField5(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("cronCollisionPolicy", thrift.I32, 5); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:cronCollisionPolicy: ", p), err) + } + if err := oprot.WriteI32(int32(p.CronCollisionPolicy)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.cronCollisionPolicy (5) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 5:cronCollisionPolicy: ", p), err) + } + return err +} + +func (p *JobConfiguration) writeField6(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("taskConfig", thrift.STRUCT, 6); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 6:taskConfig: ", p), err) + } + if err := p.TaskConfig.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.TaskConfig), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 6:taskConfig: ", p), err) + } + return err +} + +func (p *JobConfiguration) writeField7(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("owner", thrift.STRUCT, 7); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 7:owner: ", p), err) + } + if err := p.Owner.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Owner), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 7:owner: ", p), err) + } + return err +} + +func (p *JobConfiguration) writeField8(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("instanceCount", thrift.I32, 8); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 8:instanceCount: ", p), err) + } + if err := oprot.WriteI32(int32(p.InstanceCount)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.instanceCount (8) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 8:instanceCount: ", p), err) + } + return err +} + +func (p *JobConfiguration) writeField9(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 9); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 9:key: ", p), err) + } + if err := p.Key.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 9:key: ", p), err) + } + return err +} + +func (p *JobConfiguration) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("JobConfiguration(%+v)", *p) +} + +// Attributes: +// - ActiveTaskCount: Number of tasks in active state for this job. +// - FinishedTaskCount: Number of tasks in finished state for this job. +// - FailedTaskCount: Number of failed tasks for this job. +// - PendingTaskCount: Number of tasks in pending state for this job. +type JobStats struct { + ActiveTaskCount int32 `thrift:"activeTaskCount,1" db:"activeTaskCount" json:"activeTaskCount"` + FinishedTaskCount int32 `thrift:"finishedTaskCount,2" db:"finishedTaskCount" json:"finishedTaskCount"` + FailedTaskCount int32 `thrift:"failedTaskCount,3" db:"failedTaskCount" json:"failedTaskCount"` + PendingTaskCount int32 `thrift:"pendingTaskCount,4" db:"pendingTaskCount" json:"pendingTaskCount"` +} + +func NewJobStats() *JobStats { + return &JobStats{} +} + +func (p *JobStats) GetActiveTaskCount() int32 { + return p.ActiveTaskCount +} + +func (p *JobStats) GetFinishedTaskCount() int32 { + return p.FinishedTaskCount +} + +func (p *JobStats) GetFailedTaskCount() int32 { + return p.FailedTaskCount +} + +func (p *JobStats) GetPendingTaskCount() int32 { + return p.PendingTaskCount +} +func (p *JobStats) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.I32 { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.I32 { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.I32 { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 4: + if fieldTypeId == thrift.I32 { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *JobStats) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.ActiveTaskCount = v + } + return nil +} + +func (p *JobStats) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.FinishedTaskCount = v + } + return nil +} + +func (p *JobStats) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.FailedTaskCount = v + } + return nil +} + +func (p *JobStats) ReadField4(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 4: ", err) + } else { + p.PendingTaskCount = v + } + return nil +} + +func (p *JobStats) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("JobStats"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + if err := p.writeField4(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *JobStats) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("activeTaskCount", thrift.I32, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:activeTaskCount: ", p), err) + } + if err := oprot.WriteI32(int32(p.ActiveTaskCount)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.activeTaskCount (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:activeTaskCount: ", p), err) + } + return err +} + +func (p *JobStats) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("finishedTaskCount", thrift.I32, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:finishedTaskCount: ", p), err) + } + if err := oprot.WriteI32(int32(p.FinishedTaskCount)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.finishedTaskCount (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:finishedTaskCount: ", p), err) + } + return err +} + +func (p *JobStats) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("failedTaskCount", thrift.I32, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:failedTaskCount: ", p), err) + } + if err := oprot.WriteI32(int32(p.FailedTaskCount)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.failedTaskCount (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:failedTaskCount: ", p), err) + } + return err +} + +func (p *JobStats) writeField4(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("pendingTaskCount", thrift.I32, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:pendingTaskCount: ", p), err) + } + if err := oprot.WriteI32(int32(p.PendingTaskCount)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.pendingTaskCount (4) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:pendingTaskCount: ", p), err) + } + return err +} + +func (p *JobStats) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("JobStats(%+v)", *p) +} + +// Attributes: +// - Job +// - Stats +// - NextCronRunMs: Timestamp of next cron run in ms since epoch, for a cron job +type JobSummary struct { + Job *JobConfiguration `thrift:"job,1" db:"job" json:"job"` + Stats *JobStats `thrift:"stats,2" db:"stats" json:"stats"` + NextCronRunMs *int64 `thrift:"nextCronRunMs,3" db:"nextCronRunMs" json:"nextCronRunMs,omitempty"` +} + +func NewJobSummary() *JobSummary { + return &JobSummary{} +} + +var JobSummary_Job_DEFAULT *JobConfiguration + +func (p *JobSummary) GetJob() *JobConfiguration { + if !p.IsSetJob() { + return JobSummary_Job_DEFAULT + } + return p.Job +} + +var JobSummary_Stats_DEFAULT *JobStats + +func (p *JobSummary) GetStats() *JobStats { + if !p.IsSetStats() { + return JobSummary_Stats_DEFAULT + } + return p.Stats +} + +var JobSummary_NextCronRunMs_DEFAULT int64 + +func (p *JobSummary) GetNextCronRunMs() int64 { + if !p.IsSetNextCronRunMs() { + return JobSummary_NextCronRunMs_DEFAULT + } + return *p.NextCronRunMs +} +func (p *JobSummary) IsSetJob() bool { + return p.Job != nil +} + +func (p *JobSummary) IsSetStats() bool { + return p.Stats != nil +} + +func (p *JobSummary) IsSetNextCronRunMs() bool { + return p.NextCronRunMs != nil +} + +func (p *JobSummary) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.I64 { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *JobSummary) ReadField1(iprot thrift.TProtocol) error { + p.Job = &JobConfiguration{} + if err := p.Job.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Job), err) + } + return nil +} + +func (p *JobSummary) ReadField2(iprot thrift.TProtocol) error { + p.Stats = &JobStats{} + if err := p.Stats.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Stats), err) + } + return nil +} + +func (p *JobSummary) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI64(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.NextCronRunMs = &v + } + return nil +} + +func (p *JobSummary) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("JobSummary"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *JobSummary) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("job", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:job: ", p), err) + } + if err := p.Job.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Job), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:job: ", p), err) + } + return err +} + +func (p *JobSummary) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("stats", thrift.STRUCT, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:stats: ", p), err) + } + if err := p.Stats.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Stats), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:stats: ", p), err) + } + return err +} + +func (p *JobSummary) writeField3(oprot thrift.TProtocol) (err error) { + if p.IsSetNextCronRunMs() { + if err := oprot.WriteFieldBegin("nextCronRunMs", thrift.I64, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:nextCronRunMs: ", p), err) + } + if err := oprot.WriteI64(int64(*p.NextCronRunMs)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.nextCronRunMs (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:nextCronRunMs: ", p), err) + } + } + return err +} + +func (p *JobSummary) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("JobSummary(%+v)", *p) +} + +// Closed range of integers. +// +// Attributes: +// - First +// - Last +type Range struct { + First int32 `thrift:"first,1" db:"first" json:"first"` + Last int32 `thrift:"last,2" db:"last" json:"last"` +} + +func NewRange() *Range { + return &Range{} +} + +func (p *Range) GetFirst() int32 { + return p.First +} + +func (p *Range) GetLast() int32 { + return p.Last +} +func (p *Range) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.I32 { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.I32 { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *Range) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.First = v + } + return nil +} + +func (p *Range) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.Last = v + } + return nil +} + +func (p *Range) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("Range"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *Range) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("first", thrift.I32, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:first: ", p), err) + } + if err := oprot.WriteI32(int32(p.First)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.first (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:first: ", p), err) + } + return err +} + +func (p *Range) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("last", thrift.I32, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:last: ", p), err) + } + if err := oprot.WriteI32(int32(p.Last)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.last (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:last: ", p), err) + } + return err +} + +func (p *Range) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("Range(%+v)", *p) +} + +// Attributes: +// - Config +// - Instances +type ConfigGroup struct { + Config *TaskConfig `thrift:"config,1" db:"config" json:"config"` + // unused field # 2 + Instances []*Range `thrift:"instances,3" db:"instances" json:"instances"` +} + +func NewConfigGroup() *ConfigGroup { + return &ConfigGroup{} +} + +var ConfigGroup_Config_DEFAULT *TaskConfig + +func (p *ConfigGroup) GetConfig() *TaskConfig { + if !p.IsSetConfig() { + return ConfigGroup_Config_DEFAULT + } + return p.Config +} + +func (p *ConfigGroup) GetInstances() []*Range { + return p.Instances +} +func (p *ConfigGroup) IsSetConfig() bool { + return p.Config != nil +} + +func (p *ConfigGroup) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.SET { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ConfigGroup) ReadField1(iprot thrift.TProtocol) error { + p.Config = &TaskConfig{} + if err := p.Config.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Config), err) + } + return nil +} + +func (p *ConfigGroup) ReadField3(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*Range, 0, size) + p.Instances = tSet + for i := 0; i < size; i++ { + _elem12 := &Range{} + if err := _elem12.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem12), err) + } + p.Instances = append(p.Instances, _elem12) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *ConfigGroup) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("ConfigGroup"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ConfigGroup) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("config", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:config: ", p), err) + } + if err := p.Config.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Config), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:config: ", p), err) + } + return err +} + +func (p *ConfigGroup) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("instances", thrift.SET, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:instances: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Instances)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Instances); i++ { + for j := i + 1; j < len(p.Instances); j++ { + if reflect.DeepEqual(p.Instances[i], p.Instances[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Instances[i])) + } + } + } + for _, v := range p.Instances { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:instances: ", p), err) + } + return err +} + +func (p *ConfigGroup) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ConfigGroup(%+v)", *p) +} + +// Attributes: +// - Key +// - Groups +type ConfigSummary struct { + Key *JobKey `thrift:"key,1" db:"key" json:"key"` + Groups []*ConfigGroup `thrift:"groups,2" db:"groups" json:"groups"` +} + +func NewConfigSummary() *ConfigSummary { + return &ConfigSummary{} +} + +var ConfigSummary_Key_DEFAULT *JobKey + +func (p *ConfigSummary) GetKey() *JobKey { + if !p.IsSetKey() { + return ConfigSummary_Key_DEFAULT + } + return p.Key +} + +func (p *ConfigSummary) GetGroups() []*ConfigGroup { + return p.Groups +} +func (p *ConfigSummary) IsSetKey() bool { + return p.Key != nil +} + +func (p *ConfigSummary) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.SET { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ConfigSummary) ReadField1(iprot thrift.TProtocol) error { + p.Key = &JobKey{} + if err := p.Key.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) + } + return nil +} + +func (p *ConfigSummary) ReadField2(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*ConfigGroup, 0, size) + p.Groups = tSet + for i := 0; i < size; i++ { + _elem13 := &ConfigGroup{} + if err := _elem13.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem13), err) + } + p.Groups = append(p.Groups, _elem13) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *ConfigSummary) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("ConfigSummary"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ConfigSummary) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:key: ", p), err) + } + if err := p.Key.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:key: ", p), err) + } + return err +} + +func (p *ConfigSummary) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("groups", thrift.SET, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:groups: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Groups)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Groups); i++ { + for j := i + 1; j < len(p.Groups); j++ { + if reflect.DeepEqual(p.Groups[i], p.Groups[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Groups[i])) + } + } + } + for _, v := range p.Groups { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:groups: ", p), err) + } + return err +} + +func (p *ConfigSummary) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ConfigSummary(%+v)", *p) +} + +// Attributes: +// - TaskConfig +type PopulateJobResult_ struct { + // unused field # 1 + TaskConfig *TaskConfig `thrift:"taskConfig,2" db:"taskConfig" json:"taskConfig"` +} + +func NewPopulateJobResult_() *PopulateJobResult_ { + return &PopulateJobResult_{} +} + +var PopulateJobResult__TaskConfig_DEFAULT *TaskConfig + +func (p *PopulateJobResult_) GetTaskConfig() *TaskConfig { + if !p.IsSetTaskConfig() { + return PopulateJobResult__TaskConfig_DEFAULT + } + return p.TaskConfig +} +func (p *PopulateJobResult_) IsSetTaskConfig() bool { + return p.TaskConfig != nil +} + +func (p *PopulateJobResult_) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 2: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *PopulateJobResult_) ReadField2(iprot thrift.TProtocol) error { + p.TaskConfig = &TaskConfig{} + if err := p.TaskConfig.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.TaskConfig), err) + } + return nil +} + +func (p *PopulateJobResult_) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("PopulateJobResult"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *PopulateJobResult_) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("taskConfig", thrift.STRUCT, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:taskConfig: ", p), err) + } + if err := p.TaskConfig.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.TaskConfig), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:taskConfig: ", p), err) + } + return err +} + +func (p *PopulateJobResult_) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("PopulateJobResult_(%+v)", *p) +} + +// Attributes: +// - Quota: Total allocated resource quota. +// - ProdSharedConsumption: Resources consumed by production jobs from a shared resource pool. +// - NonProdSharedConsumption: Resources consumed by non-production jobs from a shared resource pool. +// - ProdDedicatedConsumption: Resources consumed by production jobs from a dedicated resource pool. +// - NonProdDedicatedConsumption: Resources consumed by non-production jobs from a dedicated resource pool. +type GetQuotaResult_ struct { + Quota *ResourceAggregate `thrift:"quota,1" db:"quota" json:"quota"` + ProdSharedConsumption *ResourceAggregate `thrift:"prodSharedConsumption,2" db:"prodSharedConsumption" json:"prodSharedConsumption,omitempty"` + NonProdSharedConsumption *ResourceAggregate `thrift:"nonProdSharedConsumption,3" db:"nonProdSharedConsumption" json:"nonProdSharedConsumption,omitempty"` + ProdDedicatedConsumption *ResourceAggregate `thrift:"prodDedicatedConsumption,4" db:"prodDedicatedConsumption" json:"prodDedicatedConsumption,omitempty"` + NonProdDedicatedConsumption *ResourceAggregate `thrift:"nonProdDedicatedConsumption,5" db:"nonProdDedicatedConsumption" json:"nonProdDedicatedConsumption,omitempty"` +} + +func NewGetQuotaResult_() *GetQuotaResult_ { + return &GetQuotaResult_{} +} + +var GetQuotaResult__Quota_DEFAULT *ResourceAggregate + +func (p *GetQuotaResult_) GetQuota() *ResourceAggregate { + if !p.IsSetQuota() { + return GetQuotaResult__Quota_DEFAULT + } + return p.Quota +} + +var GetQuotaResult__ProdSharedConsumption_DEFAULT *ResourceAggregate + +func (p *GetQuotaResult_) GetProdSharedConsumption() *ResourceAggregate { + if !p.IsSetProdSharedConsumption() { + return GetQuotaResult__ProdSharedConsumption_DEFAULT + } + return p.ProdSharedConsumption +} + +var GetQuotaResult__NonProdSharedConsumption_DEFAULT *ResourceAggregate + +func (p *GetQuotaResult_) GetNonProdSharedConsumption() *ResourceAggregate { + if !p.IsSetNonProdSharedConsumption() { + return GetQuotaResult__NonProdSharedConsumption_DEFAULT + } + return p.NonProdSharedConsumption +} + +var GetQuotaResult__ProdDedicatedConsumption_DEFAULT *ResourceAggregate + +func (p *GetQuotaResult_) GetProdDedicatedConsumption() *ResourceAggregate { + if !p.IsSetProdDedicatedConsumption() { + return GetQuotaResult__ProdDedicatedConsumption_DEFAULT + } + return p.ProdDedicatedConsumption +} + +var GetQuotaResult__NonProdDedicatedConsumption_DEFAULT *ResourceAggregate + +func (p *GetQuotaResult_) GetNonProdDedicatedConsumption() *ResourceAggregate { + if !p.IsSetNonProdDedicatedConsumption() { + return GetQuotaResult__NonProdDedicatedConsumption_DEFAULT + } + return p.NonProdDedicatedConsumption +} +func (p *GetQuotaResult_) IsSetQuota() bool { + return p.Quota != nil +} + +func (p *GetQuotaResult_) IsSetProdSharedConsumption() bool { + return p.ProdSharedConsumption != nil +} + +func (p *GetQuotaResult_) IsSetNonProdSharedConsumption() bool { + return p.NonProdSharedConsumption != nil +} + +func (p *GetQuotaResult_) IsSetProdDedicatedConsumption() bool { + return p.ProdDedicatedConsumption != nil +} + +func (p *GetQuotaResult_) IsSetNonProdDedicatedConsumption() bool { + return p.NonProdDedicatedConsumption != nil +} + +func (p *GetQuotaResult_) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 4: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 5: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField5(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *GetQuotaResult_) ReadField1(iprot thrift.TProtocol) error { + p.Quota = &ResourceAggregate{} + if err := p.Quota.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Quota), err) + } + return nil +} + +func (p *GetQuotaResult_) ReadField2(iprot thrift.TProtocol) error { + p.ProdSharedConsumption = &ResourceAggregate{} + if err := p.ProdSharedConsumption.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.ProdSharedConsumption), err) + } + return nil +} + +func (p *GetQuotaResult_) ReadField3(iprot thrift.TProtocol) error { + p.NonProdSharedConsumption = &ResourceAggregate{} + if err := p.NonProdSharedConsumption.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.NonProdSharedConsumption), err) + } + return nil +} + +func (p *GetQuotaResult_) ReadField4(iprot thrift.TProtocol) error { + p.ProdDedicatedConsumption = &ResourceAggregate{} + if err := p.ProdDedicatedConsumption.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.ProdDedicatedConsumption), err) + } + return nil +} + +func (p *GetQuotaResult_) ReadField5(iprot thrift.TProtocol) error { + p.NonProdDedicatedConsumption = &ResourceAggregate{} + if err := p.NonProdDedicatedConsumption.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.NonProdDedicatedConsumption), err) + } + return nil +} + +func (p *GetQuotaResult_) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("GetQuotaResult"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + if err := p.writeField4(oprot); err != nil { + return err + } + if err := p.writeField5(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *GetQuotaResult_) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("quota", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:quota: ", p), err) + } + if err := p.Quota.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Quota), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:quota: ", p), err) + } + return err +} + +func (p *GetQuotaResult_) writeField2(oprot thrift.TProtocol) (err error) { + if p.IsSetProdSharedConsumption() { + if err := oprot.WriteFieldBegin("prodSharedConsumption", thrift.STRUCT, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:prodSharedConsumption: ", p), err) + } + if err := p.ProdSharedConsumption.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.ProdSharedConsumption), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:prodSharedConsumption: ", p), err) + } + } + return err +} + +func (p *GetQuotaResult_) writeField3(oprot thrift.TProtocol) (err error) { + if p.IsSetNonProdSharedConsumption() { + if err := oprot.WriteFieldBegin("nonProdSharedConsumption", thrift.STRUCT, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:nonProdSharedConsumption: ", p), err) + } + if err := p.NonProdSharedConsumption.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.NonProdSharedConsumption), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:nonProdSharedConsumption: ", p), err) + } + } + return err +} + +func (p *GetQuotaResult_) writeField4(oprot thrift.TProtocol) (err error) { + if p.IsSetProdDedicatedConsumption() { + if err := oprot.WriteFieldBegin("prodDedicatedConsumption", thrift.STRUCT, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:prodDedicatedConsumption: ", p), err) + } + if err := p.ProdDedicatedConsumption.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.ProdDedicatedConsumption), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:prodDedicatedConsumption: ", p), err) + } + } + return err +} + +func (p *GetQuotaResult_) writeField5(oprot thrift.TProtocol) (err error) { + if p.IsSetNonProdDedicatedConsumption() { + if err := oprot.WriteFieldBegin("nonProdDedicatedConsumption", thrift.STRUCT, 5); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:nonProdDedicatedConsumption: ", p), err) + } + if err := p.NonProdDedicatedConsumption.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.NonProdDedicatedConsumption), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 5:nonProdDedicatedConsumption: ", p), err) + } + } + return err +} + +func (p *GetQuotaResult_) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("GetQuotaResult_(%+v)", *p) +} + +// Event marking a state transition within a task's lifecycle. +// +// Attributes: +// - Timestamp: Epoch timestamp in milliseconds. +// - Status: New status of the task. +// - Message: Audit message that explains why a transition occurred. +// - Scheduler: Hostname of the scheduler machine that performed the event. +type TaskEvent struct { + Timestamp int64 `thrift:"timestamp,1" db:"timestamp" json:"timestamp"` + Status ScheduleStatus `thrift:"status,2" db:"status" json:"status"` + Message *string `thrift:"message,3" db:"message" json:"message,omitempty"` + Scheduler *string `thrift:"scheduler,4" db:"scheduler" json:"scheduler,omitempty"` +} + +func NewTaskEvent() *TaskEvent { + return &TaskEvent{} +} + +func (p *TaskEvent) GetTimestamp() int64 { + return p.Timestamp +} + +func (p *TaskEvent) GetStatus() ScheduleStatus { + return p.Status +} + +var TaskEvent_Message_DEFAULT string + +func (p *TaskEvent) GetMessage() string { + if !p.IsSetMessage() { + return TaskEvent_Message_DEFAULT + } + return *p.Message +} + +var TaskEvent_Scheduler_DEFAULT string + +func (p *TaskEvent) GetScheduler() string { + if !p.IsSetScheduler() { + return TaskEvent_Scheduler_DEFAULT + } + return *p.Scheduler +} +func (p *TaskEvent) IsSetMessage() bool { + return p.Message != nil +} + +func (p *TaskEvent) IsSetScheduler() bool { + return p.Scheduler != nil +} + +func (p *TaskEvent) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.I64 { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.I32 { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.STRING { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 4: + if fieldTypeId == thrift.STRING { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *TaskEvent) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI64(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Timestamp = v + } + return nil +} + +func (p *TaskEvent) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + temp := ScheduleStatus(v) + p.Status = temp + } + return nil +} + +func (p *TaskEvent) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.Message = &v + } + return nil +} + +func (p *TaskEvent) ReadField4(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 4: ", err) + } else { + p.Scheduler = &v + } + return nil +} + +func (p *TaskEvent) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("TaskEvent"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + if err := p.writeField4(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *TaskEvent) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("timestamp", thrift.I64, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:timestamp: ", p), err) + } + if err := oprot.WriteI64(int64(p.Timestamp)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.timestamp (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:timestamp: ", p), err) + } + return err +} + +func (p *TaskEvent) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("status", thrift.I32, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:status: ", p), err) + } + if err := oprot.WriteI32(int32(p.Status)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.status (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:status: ", p), err) + } + return err +} + +func (p *TaskEvent) writeField3(oprot thrift.TProtocol) (err error) { + if p.IsSetMessage() { + if err := oprot.WriteFieldBegin("message", thrift.STRING, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:message: ", p), err) + } + if err := oprot.WriteString(string(*p.Message)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.message (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:message: ", p), err) + } + } + return err +} + +func (p *TaskEvent) writeField4(oprot thrift.TProtocol) (err error) { + if p.IsSetScheduler() { + if err := oprot.WriteFieldBegin("scheduler", thrift.STRING, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:scheduler: ", p), err) + } + if err := oprot.WriteString(string(*p.Scheduler)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.scheduler (4) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:scheduler: ", p), err) + } + } + return err +} + +func (p *TaskEvent) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("TaskEvent(%+v)", *p) +} + +// A task assignment that is provided to an executor. +// +// Attributes: +// - TaskId: The mesos task ID for this task. Guaranteed to be globally unique +// - SlaveId: The mesos slave ID that this task has been assigned to. +// This will not be populated for a PENDING task. +// - SlaveHost: The name of the machine that this task has been assigned to. +// This will not be populated for a PENDING task. +// - Task: Information about how to run this task. +// - AssignedPorts: Ports reserved on the machine while this task is running. +// - InstanceId: The instance ID assigned to this task. Instance IDs must be unique and contiguous within a +// job, and will be in the range [0, N-1] (inclusive) for a job that has N instances. +type AssignedTask struct { + TaskId string `thrift:"taskId,1" db:"taskId" json:"taskId"` + SlaveId string `thrift:"slaveId,2" db:"slaveId" json:"slaveId"` + SlaveHost string `thrift:"slaveHost,3" db:"slaveHost" json:"slaveHost"` + Task *TaskConfig `thrift:"task,4" db:"task" json:"task"` + AssignedPorts map[string]int32 `thrift:"assignedPorts,5" db:"assignedPorts" json:"assignedPorts"` + InstanceId int32 `thrift:"instanceId,6" db:"instanceId" json:"instanceId"` +} + +func NewAssignedTask() *AssignedTask { + return &AssignedTask{} +} + +func (p *AssignedTask) GetTaskId() string { + return p.TaskId +} + +func (p *AssignedTask) GetSlaveId() string { + return p.SlaveId +} + +func (p *AssignedTask) GetSlaveHost() string { + return p.SlaveHost +} + +var AssignedTask_Task_DEFAULT *TaskConfig + +func (p *AssignedTask) GetTask() *TaskConfig { + if !p.IsSetTask() { + return AssignedTask_Task_DEFAULT + } + return p.Task +} + +func (p *AssignedTask) GetAssignedPorts() map[string]int32 { + return p.AssignedPorts +} + +func (p *AssignedTask) GetInstanceId() int32 { + return p.InstanceId +} +func (p *AssignedTask) IsSetTask() bool { + return p.Task != nil +} + +func (p *AssignedTask) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRING { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.STRING { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 4: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 5: + if fieldTypeId == thrift.MAP { + if err := p.ReadField5(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 6: + if fieldTypeId == thrift.I32 { + if err := p.ReadField6(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AssignedTask) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.TaskId = v + } + return nil +} + +func (p *AssignedTask) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.SlaveId = v + } + return nil +} + +func (p *AssignedTask) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.SlaveHost = v + } + return nil +} + +func (p *AssignedTask) ReadField4(iprot thrift.TProtocol) error { + p.Task = &TaskConfig{} + if err := p.Task.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Task), err) + } + return nil +} + +func (p *AssignedTask) ReadField5(iprot thrift.TProtocol) error { + _, _, size, err := iprot.ReadMapBegin() + if err != nil { + return thrift.PrependError("error reading map begin: ", err) + } + tMap := make(map[string]int32, size) + p.AssignedPorts = tMap + for i := 0; i < size; i++ { + var _key14 string + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 0: ", err) + } else { + _key14 = v + } + var _val15 int32 + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 0: ", err) + } else { + _val15 = v + } + p.AssignedPorts[_key14] = _val15 + } + if err := iprot.ReadMapEnd(); err != nil { + return thrift.PrependError("error reading map end: ", err) + } + return nil +} + +func (p *AssignedTask) ReadField6(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 6: ", err) + } else { + p.InstanceId = v + } + return nil +} + +func (p *AssignedTask) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("AssignedTask"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + if err := p.writeField4(oprot); err != nil { + return err + } + if err := p.writeField5(oprot); err != nil { + return err + } + if err := p.writeField6(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AssignedTask) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("taskId", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:taskId: ", p), err) + } + if err := oprot.WriteString(string(p.TaskId)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.taskId (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:taskId: ", p), err) + } + return err +} + +func (p *AssignedTask) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("slaveId", thrift.STRING, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:slaveId: ", p), err) + } + if err := oprot.WriteString(string(p.SlaveId)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.slaveId (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:slaveId: ", p), err) + } + return err +} + +func (p *AssignedTask) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("slaveHost", thrift.STRING, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:slaveHost: ", p), err) + } + if err := oprot.WriteString(string(p.SlaveHost)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.slaveHost (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:slaveHost: ", p), err) + } + return err +} + +func (p *AssignedTask) writeField4(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("task", thrift.STRUCT, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:task: ", p), err) + } + if err := p.Task.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Task), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:task: ", p), err) + } + return err +} + +func (p *AssignedTask) writeField5(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("assignedPorts", thrift.MAP, 5); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:assignedPorts: ", p), err) + } + if err := oprot.WriteMapBegin(thrift.STRING, thrift.I32, len(p.AssignedPorts)); err != nil { + return thrift.PrependError("error writing map begin: ", err) + } + for k, v := range p.AssignedPorts { + if err := oprot.WriteString(string(k)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) + } + if err := oprot.WriteI32(int32(v)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) + } + } + if err := oprot.WriteMapEnd(); err != nil { + return thrift.PrependError("error writing map end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 5:assignedPorts: ", p), err) + } + return err +} + +func (p *AssignedTask) writeField6(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("instanceId", thrift.I32, 6); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 6:instanceId: ", p), err) + } + if err := oprot.WriteI32(int32(p.InstanceId)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.instanceId (6) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 6:instanceId: ", p), err) + } + return err +} + +func (p *AssignedTask) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AssignedTask(%+v)", *p) +} + +// A task that has been scheduled. +// +// Attributes: +// - AssignedTask: The task that was scheduled. +// - Status: The current status of this task. +// - FailureCount: The number of failures that this task has accumulated over the multi-generational history of +// this task. +// - TimesPartitioned: The number of partitions this task has accumulated over its lifetime. +// - TaskEvents: State change history for this task. +// - AncestorId: The task ID of the previous generation of this task. When a task is automatically rescheduled, +// a copy of the task is created and ancestor ID of the previous task's task ID. +type ScheduledTask struct { + AssignedTask *AssignedTask `thrift:"assignedTask,1" db:"assignedTask" json:"assignedTask"` + Status ScheduleStatus `thrift:"status,2" db:"status" json:"status"` + FailureCount int32 `thrift:"failureCount,3" db:"failureCount" json:"failureCount"` + TaskEvents []*TaskEvent `thrift:"taskEvents,4" db:"taskEvents" json:"taskEvents"` + AncestorId string `thrift:"ancestorId,5" db:"ancestorId" json:"ancestorId"` + TimesPartitioned int32 `thrift:"timesPartitioned,6" db:"timesPartitioned" json:"timesPartitioned"` +} + +func NewScheduledTask() *ScheduledTask { + return &ScheduledTask{} +} + +var ScheduledTask_AssignedTask_DEFAULT *AssignedTask + +func (p *ScheduledTask) GetAssignedTask() *AssignedTask { + if !p.IsSetAssignedTask() { + return ScheduledTask_AssignedTask_DEFAULT + } + return p.AssignedTask +} + +func (p *ScheduledTask) GetStatus() ScheduleStatus { + return p.Status +} + +func (p *ScheduledTask) GetFailureCount() int32 { + return p.FailureCount +} + +func (p *ScheduledTask) GetTimesPartitioned() int32 { + return p.TimesPartitioned +} + +func (p *ScheduledTask) GetTaskEvents() []*TaskEvent { + return p.TaskEvents +} + +func (p *ScheduledTask) GetAncestorId() string { + return p.AncestorId +} +func (p *ScheduledTask) IsSetAssignedTask() bool { + return p.AssignedTask != nil +} + +func (p *ScheduledTask) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.I32 { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.I32 { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 6: + if fieldTypeId == thrift.I32 { + if err := p.ReadField6(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 4: + if fieldTypeId == thrift.LIST { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 5: + if fieldTypeId == thrift.STRING { + if err := p.ReadField5(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ScheduledTask) ReadField1(iprot thrift.TProtocol) error { + p.AssignedTask = &AssignedTask{} + if err := p.AssignedTask.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.AssignedTask), err) + } + return nil +} + +func (p *ScheduledTask) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + temp := ScheduleStatus(v) + p.Status = temp + } + return nil +} + +func (p *ScheduledTask) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.FailureCount = v + } + return nil +} + +func (p *ScheduledTask) ReadField6(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 6: ", err) + } else { + p.TimesPartitioned = v + } + return nil +} + +func (p *ScheduledTask) ReadField4(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadListBegin() + if err != nil { + return thrift.PrependError("error reading list begin: ", err) + } + tSlice := make([]*TaskEvent, 0, size) + p.TaskEvents = tSlice + for i := 0; i < size; i++ { + _elem16 := &TaskEvent{} + if err := _elem16.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem16), err) + } + p.TaskEvents = append(p.TaskEvents, _elem16) + } + if err := iprot.ReadListEnd(); err != nil { + return thrift.PrependError("error reading list end: ", err) + } + return nil +} + +func (p *ScheduledTask) ReadField5(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 5: ", err) + } else { + p.AncestorId = v + } + return nil +} + +func (p *ScheduledTask) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("ScheduledTask"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + if err := p.writeField4(oprot); err != nil { + return err + } + if err := p.writeField5(oprot); err != nil { + return err + } + if err := p.writeField6(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ScheduledTask) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("assignedTask", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:assignedTask: ", p), err) + } + if err := p.AssignedTask.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.AssignedTask), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:assignedTask: ", p), err) + } + return err +} + +func (p *ScheduledTask) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("status", thrift.I32, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:status: ", p), err) + } + if err := oprot.WriteI32(int32(p.Status)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.status (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:status: ", p), err) + } + return err +} + +func (p *ScheduledTask) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("failureCount", thrift.I32, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:failureCount: ", p), err) + } + if err := oprot.WriteI32(int32(p.FailureCount)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.failureCount (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:failureCount: ", p), err) + } + return err +} + +func (p *ScheduledTask) writeField4(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("taskEvents", thrift.LIST, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:taskEvents: ", p), err) + } + if err := oprot.WriteListBegin(thrift.STRUCT, len(p.TaskEvents)); err != nil { + return thrift.PrependError("error writing list begin: ", err) + } + for _, v := range p.TaskEvents { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteListEnd(); err != nil { + return thrift.PrependError("error writing list end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:taskEvents: ", p), err) + } + return err +} + +func (p *ScheduledTask) writeField5(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("ancestorId", thrift.STRING, 5); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:ancestorId: ", p), err) + } + if err := oprot.WriteString(string(p.AncestorId)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.ancestorId (5) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 5:ancestorId: ", p), err) + } + return err +} + +func (p *ScheduledTask) writeField6(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("timesPartitioned", thrift.I32, 6); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 6:timesPartitioned: ", p), err) + } + if err := oprot.WriteI32(int32(p.TimesPartitioned)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.timesPartitioned (6) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 6:timesPartitioned: ", p), err) + } + return err +} + +func (p *ScheduledTask) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ScheduledTask(%+v)", *p) +} + +// Attributes: +// - Tasks +type ScheduleStatusResult_ struct { + Tasks []*ScheduledTask `thrift:"tasks,1" db:"tasks" json:"tasks"` +} + +func NewScheduleStatusResult_() *ScheduleStatusResult_ { + return &ScheduleStatusResult_{} +} + +func (p *ScheduleStatusResult_) GetTasks() []*ScheduledTask { + return p.Tasks +} +func (p *ScheduleStatusResult_) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.LIST { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ScheduleStatusResult_) ReadField1(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadListBegin() + if err != nil { + return thrift.PrependError("error reading list begin: ", err) + } + tSlice := make([]*ScheduledTask, 0, size) + p.Tasks = tSlice + for i := 0; i < size; i++ { + _elem17 := &ScheduledTask{} + if err := _elem17.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem17), err) + } + p.Tasks = append(p.Tasks, _elem17) + } + if err := iprot.ReadListEnd(); err != nil { + return thrift.PrependError("error reading list end: ", err) + } + return nil +} + +func (p *ScheduleStatusResult_) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("ScheduleStatusResult"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ScheduleStatusResult_) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("tasks", thrift.LIST, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:tasks: ", p), err) + } + if err := oprot.WriteListBegin(thrift.STRUCT, len(p.Tasks)); err != nil { + return thrift.PrependError("error writing list begin: ", err) + } + for _, v := range p.Tasks { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteListEnd(); err != nil { + return thrift.PrependError("error writing list end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:tasks: ", p), err) + } + return err +} + +func (p *ScheduleStatusResult_) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ScheduleStatusResult_(%+v)", *p) +} + +// Attributes: +// - Configs +type GetJobsResult_ struct { + Configs []*JobConfiguration `thrift:"configs,1" db:"configs" json:"configs"` +} + +func NewGetJobsResult_() *GetJobsResult_ { + return &GetJobsResult_{} +} + +func (p *GetJobsResult_) GetConfigs() []*JobConfiguration { + return p.Configs +} +func (p *GetJobsResult_) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.SET { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *GetJobsResult_) ReadField1(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*JobConfiguration, 0, size) + p.Configs = tSet + for i := 0; i < size; i++ { + _elem18 := &JobConfiguration{} + if err := _elem18.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem18), err) + } + p.Configs = append(p.Configs, _elem18) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *GetJobsResult_) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("GetJobsResult"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *GetJobsResult_) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("configs", thrift.SET, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:configs: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Configs)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Configs); i++ { + for j := i + 1; j < len(p.Configs); j++ { + if reflect.DeepEqual(p.Configs[i], p.Configs[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Configs[i])) + } + } + } + for _, v := range p.Configs { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:configs: ", p), err) + } + return err +} + +func (p *GetJobsResult_) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("GetJobsResult_(%+v)", *p) +} + +// Contains a set of restrictions on matching tasks where all restrictions must be met +// (terms are AND'ed together). +// +// Attributes: +// - Role +// - Environment +// - JobName +// - TaskIds +// - Statuses +// - InstanceIds +// - SlaveHosts +// - JobKeys +// - Offset +// - Limit +type TaskQuery struct { + // unused field # 1 + JobName *string `thrift:"jobName,2" db:"jobName" json:"jobName,omitempty"` + // unused field # 3 + TaskIds []string `thrift:"taskIds,4" db:"taskIds" json:"taskIds,omitempty"` + Statuses []ScheduleStatus `thrift:"statuses,5" db:"statuses" json:"statuses,omitempty"` + // unused field # 6 + InstanceIds []int32 `thrift:"instanceIds,7" db:"instanceIds" json:"instanceIds,omitempty"` + // unused field # 8 + Environment *string `thrift:"environment,9" db:"environment" json:"environment,omitempty"` + SlaveHosts []string `thrift:"slaveHosts,10" db:"slaveHosts" json:"slaveHosts,omitempty"` + JobKeys []*JobKey `thrift:"jobKeys,11" db:"jobKeys" json:"jobKeys,omitempty"` + Offset *int32 `thrift:"offset,12" db:"offset" json:"offset,omitempty"` + Limit *int32 `thrift:"limit,13" db:"limit" json:"limit,omitempty"` + Role *string `thrift:"role,14" db:"role" json:"role,omitempty"` +} + +func NewTaskQuery() *TaskQuery { + return &TaskQuery{} +} + +var TaskQuery_Role_DEFAULT string + +func (p *TaskQuery) GetRole() string { + if !p.IsSetRole() { + return TaskQuery_Role_DEFAULT + } + return *p.Role +} + +var TaskQuery_Environment_DEFAULT string + +func (p *TaskQuery) GetEnvironment() string { + if !p.IsSetEnvironment() { + return TaskQuery_Environment_DEFAULT + } + return *p.Environment +} + +var TaskQuery_JobName_DEFAULT string + +func (p *TaskQuery) GetJobName() string { + if !p.IsSetJobName() { + return TaskQuery_JobName_DEFAULT + } + return *p.JobName +} + +var TaskQuery_TaskIds_DEFAULT []string + +func (p *TaskQuery) GetTaskIds() []string { + return p.TaskIds +} + +var TaskQuery_Statuses_DEFAULT []ScheduleStatus + +func (p *TaskQuery) GetStatuses() []ScheduleStatus { + return p.Statuses +} + +var TaskQuery_InstanceIds_DEFAULT []int32 + +func (p *TaskQuery) GetInstanceIds() []int32 { + return p.InstanceIds +} + +var TaskQuery_SlaveHosts_DEFAULT []string + +func (p *TaskQuery) GetSlaveHosts() []string { + return p.SlaveHosts +} + +var TaskQuery_JobKeys_DEFAULT []*JobKey + +func (p *TaskQuery) GetJobKeys() []*JobKey { + return p.JobKeys +} + +var TaskQuery_Offset_DEFAULT int32 + +func (p *TaskQuery) GetOffset() int32 { + if !p.IsSetOffset() { + return TaskQuery_Offset_DEFAULT + } + return *p.Offset +} + +var TaskQuery_Limit_DEFAULT int32 + +func (p *TaskQuery) GetLimit() int32 { + if !p.IsSetLimit() { + return TaskQuery_Limit_DEFAULT + } + return *p.Limit +} +func (p *TaskQuery) IsSetRole() bool { + return p.Role != nil +} + +func (p *TaskQuery) IsSetEnvironment() bool { + return p.Environment != nil +} + +func (p *TaskQuery) IsSetJobName() bool { + return p.JobName != nil +} + +func (p *TaskQuery) IsSetTaskIds() bool { + return p.TaskIds != nil +} + +func (p *TaskQuery) IsSetStatuses() bool { + return p.Statuses != nil +} + +func (p *TaskQuery) IsSetInstanceIds() bool { + return p.InstanceIds != nil +} + +func (p *TaskQuery) IsSetSlaveHosts() bool { + return p.SlaveHosts != nil +} + +func (p *TaskQuery) IsSetJobKeys() bool { + return p.JobKeys != nil +} + +func (p *TaskQuery) IsSetOffset() bool { + return p.Offset != nil +} + +func (p *TaskQuery) IsSetLimit() bool { + return p.Limit != nil +} + +func (p *TaskQuery) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 14: + if fieldTypeId == thrift.STRING { + if err := p.ReadField14(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 9: + if fieldTypeId == thrift.STRING { + if err := p.ReadField9(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRING { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 4: + if fieldTypeId == thrift.SET { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 5: + if fieldTypeId == thrift.SET { + if err := p.ReadField5(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 7: + if fieldTypeId == thrift.SET { + if err := p.ReadField7(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 10: + if fieldTypeId == thrift.SET { + if err := p.ReadField10(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 11: + if fieldTypeId == thrift.SET { + if err := p.ReadField11(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 12: + if fieldTypeId == thrift.I32 { + if err := p.ReadField12(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 13: + if fieldTypeId == thrift.I32 { + if err := p.ReadField13(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *TaskQuery) ReadField14(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 14: ", err) + } else { + p.Role = &v + } + return nil +} + +func (p *TaskQuery) ReadField9(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 9: ", err) + } else { + p.Environment = &v + } + return nil +} + +func (p *TaskQuery) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.JobName = &v + } + return nil +} + +func (p *TaskQuery) ReadField4(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]string, 0, size) + p.TaskIds = tSet + for i := 0; i < size; i++ { + var _elem19 string + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 0: ", err) + } else { + _elem19 = v + } + p.TaskIds = append(p.TaskIds, _elem19) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *TaskQuery) ReadField5(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]ScheduleStatus, 0, size) + p.Statuses = tSet + for i := 0; i < size; i++ { + var _elem20 ScheduleStatus + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 0: ", err) + } else { + temp := ScheduleStatus(v) + _elem20 = temp + } + p.Statuses = append(p.Statuses, _elem20) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *TaskQuery) ReadField7(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]int32, 0, size) + p.InstanceIds = tSet + for i := 0; i < size; i++ { + var _elem21 int32 + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 0: ", err) + } else { + _elem21 = v + } + p.InstanceIds = append(p.InstanceIds, _elem21) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *TaskQuery) ReadField10(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]string, 0, size) + p.SlaveHosts = tSet + for i := 0; i < size; i++ { + var _elem22 string + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 0: ", err) + } else { + _elem22 = v + } + p.SlaveHosts = append(p.SlaveHosts, _elem22) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *TaskQuery) ReadField11(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*JobKey, 0, size) + p.JobKeys = tSet + for i := 0; i < size; i++ { + _elem23 := &JobKey{} + if err := _elem23.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem23), err) + } + p.JobKeys = append(p.JobKeys, _elem23) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *TaskQuery) ReadField12(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 12: ", err) + } else { + p.Offset = &v + } + return nil +} + +func (p *TaskQuery) ReadField13(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 13: ", err) + } else { + p.Limit = &v + } + return nil +} + +func (p *TaskQuery) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("TaskQuery"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField4(oprot); err != nil { + return err + } + if err := p.writeField5(oprot); err != nil { + return err + } + if err := p.writeField7(oprot); err != nil { + return err + } + if err := p.writeField9(oprot); err != nil { + return err + } + if err := p.writeField10(oprot); err != nil { + return err + } + if err := p.writeField11(oprot); err != nil { + return err + } + if err := p.writeField12(oprot); err != nil { + return err + } + if err := p.writeField13(oprot); err != nil { + return err + } + if err := p.writeField14(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *TaskQuery) writeField2(oprot thrift.TProtocol) (err error) { + if p.IsSetJobName() { + if err := oprot.WriteFieldBegin("jobName", thrift.STRING, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:jobName: ", p), err) + } + if err := oprot.WriteString(string(*p.JobName)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.jobName (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:jobName: ", p), err) + } + } + return err +} + +func (p *TaskQuery) writeField4(oprot thrift.TProtocol) (err error) { + if p.IsSetTaskIds() { + if err := oprot.WriteFieldBegin("taskIds", thrift.SET, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:taskIds: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRING, len(p.TaskIds)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.TaskIds); i++ { + for j := i + 1; j < len(p.TaskIds); j++ { + if reflect.DeepEqual(p.TaskIds[i], p.TaskIds[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.TaskIds[i])) + } + } + } + for _, v := range p.TaskIds { + if err := oprot.WriteString(string(v)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:taskIds: ", p), err) + } + } + return err +} + +func (p *TaskQuery) writeField5(oprot thrift.TProtocol) (err error) { + if p.IsSetStatuses() { + if err := oprot.WriteFieldBegin("statuses", thrift.SET, 5); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:statuses: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.I32, len(p.Statuses)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Statuses); i++ { + for j := i + 1; j < len(p.Statuses); j++ { + if reflect.DeepEqual(p.Statuses[i], p.Statuses[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Statuses[i])) + } + } + } + for _, v := range p.Statuses { + if err := oprot.WriteI32(int32(v)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 5:statuses: ", p), err) + } + } + return err +} + +func (p *TaskQuery) writeField7(oprot thrift.TProtocol) (err error) { + if p.IsSetInstanceIds() { + if err := oprot.WriteFieldBegin("instanceIds", thrift.SET, 7); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 7:instanceIds: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.I32, len(p.InstanceIds)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.InstanceIds); i++ { + for j := i + 1; j < len(p.InstanceIds); j++ { + if reflect.DeepEqual(p.InstanceIds[i], p.InstanceIds[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.InstanceIds[i])) + } + } + } + for _, v := range p.InstanceIds { + if err := oprot.WriteI32(int32(v)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 7:instanceIds: ", p), err) + } + } + return err +} + +func (p *TaskQuery) writeField9(oprot thrift.TProtocol) (err error) { + if p.IsSetEnvironment() { + if err := oprot.WriteFieldBegin("environment", thrift.STRING, 9); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 9:environment: ", p), err) + } + if err := oprot.WriteString(string(*p.Environment)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.environment (9) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 9:environment: ", p), err) + } + } + return err +} + +func (p *TaskQuery) writeField10(oprot thrift.TProtocol) (err error) { + if p.IsSetSlaveHosts() { + if err := oprot.WriteFieldBegin("slaveHosts", thrift.SET, 10); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 10:slaveHosts: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRING, len(p.SlaveHosts)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.SlaveHosts); i++ { + for j := i + 1; j < len(p.SlaveHosts); j++ { + if reflect.DeepEqual(p.SlaveHosts[i], p.SlaveHosts[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.SlaveHosts[i])) + } + } + } + for _, v := range p.SlaveHosts { + if err := oprot.WriteString(string(v)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 10:slaveHosts: ", p), err) + } + } + return err +} + +func (p *TaskQuery) writeField11(oprot thrift.TProtocol) (err error) { + if p.IsSetJobKeys() { + if err := oprot.WriteFieldBegin("jobKeys", thrift.SET, 11); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 11:jobKeys: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.JobKeys)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.JobKeys); i++ { + for j := i + 1; j < len(p.JobKeys); j++ { + if reflect.DeepEqual(p.JobKeys[i], p.JobKeys[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.JobKeys[i])) + } + } + } + for _, v := range p.JobKeys { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 11:jobKeys: ", p), err) + } + } + return err +} + +func (p *TaskQuery) writeField12(oprot thrift.TProtocol) (err error) { + if p.IsSetOffset() { + if err := oprot.WriteFieldBegin("offset", thrift.I32, 12); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 12:offset: ", p), err) + } + if err := oprot.WriteI32(int32(*p.Offset)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.offset (12) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 12:offset: ", p), err) + } + } + return err +} + +func (p *TaskQuery) writeField13(oprot thrift.TProtocol) (err error) { + if p.IsSetLimit() { + if err := oprot.WriteFieldBegin("limit", thrift.I32, 13); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 13:limit: ", p), err) + } + if err := oprot.WriteI32(int32(*p.Limit)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.limit (13) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 13:limit: ", p), err) + } + } + return err +} + +func (p *TaskQuery) writeField14(oprot thrift.TProtocol) (err error) { + if p.IsSetRole() { + if err := oprot.WriteFieldBegin("role", thrift.STRING, 14); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 14:role: ", p), err) + } + if err := oprot.WriteString(string(*p.Role)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.role (14) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 14:role: ", p), err) + } + } + return err +} + +func (p *TaskQuery) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("TaskQuery(%+v)", *p) +} + +// Attributes: +// - Host +// - Mode +type HostStatus struct { + Host string `thrift:"host,1" db:"host" json:"host"` + Mode MaintenanceMode `thrift:"mode,2" db:"mode" json:"mode"` +} + +func NewHostStatus() *HostStatus { + return &HostStatus{} +} + +func (p *HostStatus) GetHost() string { + return p.Host +} + +func (p *HostStatus) GetMode() MaintenanceMode { + return p.Mode +} +func (p *HostStatus) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.I32 { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *HostStatus) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Host = v + } + return nil +} + +func (p *HostStatus) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + temp := MaintenanceMode(v) + p.Mode = temp + } + return nil +} + +func (p *HostStatus) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("HostStatus"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *HostStatus) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("host", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:host: ", p), err) + } + if err := oprot.WriteString(string(p.Host)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.host (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:host: ", p), err) + } + return err +} + +func (p *HostStatus) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("mode", thrift.I32, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:mode: ", p), err) + } + if err := oprot.WriteI32(int32(p.Mode)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.mode (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:mode: ", p), err) + } + return err +} + +func (p *HostStatus) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("HostStatus(%+v)", *p) +} + +// Attributes: +// - Role +// - JobCount +// - CronJobCount +type RoleSummary struct { + Role string `thrift:"role,1" db:"role" json:"role"` + JobCount int32 `thrift:"jobCount,2" db:"jobCount" json:"jobCount"` + CronJobCount int32 `thrift:"cronJobCount,3" db:"cronJobCount" json:"cronJobCount"` +} + +func NewRoleSummary() *RoleSummary { + return &RoleSummary{} +} + +func (p *RoleSummary) GetRole() string { + return p.Role +} + +func (p *RoleSummary) GetJobCount() int32 { + return p.JobCount +} + +func (p *RoleSummary) GetCronJobCount() int32 { + return p.CronJobCount +} +func (p *RoleSummary) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.I32 { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.I32 { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *RoleSummary) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Role = v + } + return nil +} + +func (p *RoleSummary) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.JobCount = v + } + return nil +} + +func (p *RoleSummary) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.CronJobCount = v + } + return nil +} + +func (p *RoleSummary) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("RoleSummary"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *RoleSummary) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("role", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:role: ", p), err) + } + if err := oprot.WriteString(string(p.Role)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.role (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:role: ", p), err) + } + return err +} + +func (p *RoleSummary) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("jobCount", thrift.I32, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:jobCount: ", p), err) + } + if err := oprot.WriteI32(int32(p.JobCount)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.jobCount (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:jobCount: ", p), err) + } + return err +} + +func (p *RoleSummary) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("cronJobCount", thrift.I32, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:cronJobCount: ", p), err) + } + if err := oprot.WriteI32(int32(p.CronJobCount)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.cronJobCount (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:cronJobCount: ", p), err) + } + return err +} + +func (p *RoleSummary) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("RoleSummary(%+v)", *p) +} + +// Attributes: +// - HostNames +type Hosts struct { + HostNames []string `thrift:"hostNames,1" db:"hostNames" json:"hostNames"` +} + +func NewHosts() *Hosts { + return &Hosts{} +} + +func (p *Hosts) GetHostNames() []string { + return p.HostNames +} +func (p *Hosts) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.SET { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *Hosts) ReadField1(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]string, 0, size) + p.HostNames = tSet + for i := 0; i < size; i++ { + var _elem24 string + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 0: ", err) + } else { + _elem24 = v + } + p.HostNames = append(p.HostNames, _elem24) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *Hosts) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("Hosts"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *Hosts) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("hostNames", thrift.SET, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:hostNames: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRING, len(p.HostNames)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.HostNames); i++ { + for j := i + 1; j < len(p.HostNames); j++ { + if reflect.DeepEqual(p.HostNames[i], p.HostNames[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.HostNames[i])) + } + } + } + for _, v := range p.HostNames { + if err := oprot.WriteString(string(v)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:hostNames: ", p), err) + } + return err +} + +func (p *Hosts) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("Hosts(%+v)", *p) +} + +// Attributes: +// - TaskId +// - Reason +type PendingReason struct { + TaskId string `thrift:"taskId,1" db:"taskId" json:"taskId"` + Reason string `thrift:"reason,2" db:"reason" json:"reason"` +} + +func NewPendingReason() *PendingReason { + return &PendingReason{} +} + +func (p *PendingReason) GetTaskId() string { + return p.TaskId +} + +func (p *PendingReason) GetReason() string { + return p.Reason +} +func (p *PendingReason) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRING { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *PendingReason) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.TaskId = v + } + return nil +} + +func (p *PendingReason) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.Reason = v + } + return nil +} + +func (p *PendingReason) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("PendingReason"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *PendingReason) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("taskId", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:taskId: ", p), err) + } + if err := oprot.WriteString(string(p.TaskId)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.taskId (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:taskId: ", p), err) + } + return err +} + +func (p *PendingReason) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("reason", thrift.STRING, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:reason: ", p), err) + } + if err := oprot.WriteString(string(p.Reason)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.reason (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:reason: ", p), err) + } + return err +} + +func (p *PendingReason) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("PendingReason(%+v)", *p) +} + +// Job update key. +// +// Attributes: +// - Job: Job being updated +// - ID: Update ID. +type JobUpdateKey struct { + Job *JobKey `thrift:"job,1" db:"job" json:"job"` + ID string `thrift:"id,2" db:"id" json:"id"` +} + +func NewJobUpdateKey() *JobUpdateKey { + return &JobUpdateKey{} +} + +var JobUpdateKey_Job_DEFAULT *JobKey + +func (p *JobUpdateKey) GetJob() *JobKey { + if !p.IsSetJob() { + return JobUpdateKey_Job_DEFAULT + } + return p.Job +} + +func (p *JobUpdateKey) GetID() string { + return p.ID +} +func (p *JobUpdateKey) IsSetJob() bool { + return p.Job != nil +} + +func (p *JobUpdateKey) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRING { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *JobUpdateKey) ReadField1(iprot thrift.TProtocol) error { + p.Job = &JobKey{} + if err := p.Job.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Job), err) + } + return nil +} + +func (p *JobUpdateKey) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.ID = v + } + return nil +} + +func (p *JobUpdateKey) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("JobUpdateKey"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *JobUpdateKey) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("job", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:job: ", p), err) + } + if err := p.Job.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Job), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:job: ", p), err) + } + return err +} + +func (p *JobUpdateKey) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("id", thrift.STRING, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:id: ", p), err) + } + if err := oprot.WriteString(string(p.ID)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.id (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:id: ", p), err) + } + return err +} + +func (p *JobUpdateKey) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("JobUpdateKey(%+v)", *p) +} + +// Job update thresholds and limits. +// +// Attributes: +// - UpdateGroupSize: Max number of instances being updated at any given moment. +// - MaxPerInstanceFailures: Max number of instance failures to tolerate before marking instance as FAILED. +// - MaxFailedInstances: Max number of FAILED instances to tolerate before terminating the update. +// - MinWaitInInstanceRunningMs: Min time to watch a RUNNING instance. +// - RollbackOnFailure: If true, enables failed update rollback. +// - UpdateOnlyTheseInstances: Instance IDs to act on. All instances will be affected if this is not set. +// - WaitForBatchCompletion: If true, use updateGroupSize as strict batching boundaries, and avoid proceeding to another +// batch until the preceding batch finishes updating. +// - BlockIfNoPulsesAfterMs: If set, requires external calls to pulseJobUpdate RPC within the specified rate for the +// update to make progress. If no pulses received within specified interval the update will +// block. A blocked update is unable to continue but retains its current status. It may only get +// unblocked by a fresh pulseJobUpdate call. +// - SlaAware: If true, updates will obey the SLA requirements of the tasks being updated. If the SLA policy +// differs between the old and new task configurations, updates will use the newest configuration. +type JobUpdateSettings struct { + UpdateGroupSize int32 `thrift:"updateGroupSize,1" db:"updateGroupSize" json:"updateGroupSize"` + MaxPerInstanceFailures int32 `thrift:"maxPerInstanceFailures,2" db:"maxPerInstanceFailures" json:"maxPerInstanceFailures"` + MaxFailedInstances int32 `thrift:"maxFailedInstances,3" db:"maxFailedInstances" json:"maxFailedInstances"` + // unused field # 4 + MinWaitInInstanceRunningMs int32 `thrift:"minWaitInInstanceRunningMs,5" db:"minWaitInInstanceRunningMs" json:"minWaitInInstanceRunningMs"` + RollbackOnFailure bool `thrift:"rollbackOnFailure,6" db:"rollbackOnFailure" json:"rollbackOnFailure"` + UpdateOnlyTheseInstances []*Range `thrift:"updateOnlyTheseInstances,7" db:"updateOnlyTheseInstances" json:"updateOnlyTheseInstances"` + WaitForBatchCompletion bool `thrift:"waitForBatchCompletion,8" db:"waitForBatchCompletion" json:"waitForBatchCompletion"` + BlockIfNoPulsesAfterMs *int32 `thrift:"blockIfNoPulsesAfterMs,9" db:"blockIfNoPulsesAfterMs" json:"blockIfNoPulsesAfterMs,omitempty"` + SlaAware *bool `thrift:"slaAware,10" db:"slaAware" json:"slaAware,omitempty"` +} + +func NewJobUpdateSettings() *JobUpdateSettings { + return &JobUpdateSettings{} +} + +func (p *JobUpdateSettings) GetUpdateGroupSize() int32 { + return p.UpdateGroupSize +} + +func (p *JobUpdateSettings) GetMaxPerInstanceFailures() int32 { + return p.MaxPerInstanceFailures +} + +func (p *JobUpdateSettings) GetMaxFailedInstances() int32 { + return p.MaxFailedInstances +} + +func (p *JobUpdateSettings) GetMinWaitInInstanceRunningMs() int32 { + return p.MinWaitInInstanceRunningMs +} + +func (p *JobUpdateSettings) GetRollbackOnFailure() bool { + return p.RollbackOnFailure +} + +func (p *JobUpdateSettings) GetUpdateOnlyTheseInstances() []*Range { + return p.UpdateOnlyTheseInstances +} + +func (p *JobUpdateSettings) GetWaitForBatchCompletion() bool { + return p.WaitForBatchCompletion +} + +var JobUpdateSettings_BlockIfNoPulsesAfterMs_DEFAULT int32 + +func (p *JobUpdateSettings) GetBlockIfNoPulsesAfterMs() int32 { + if !p.IsSetBlockIfNoPulsesAfterMs() { + return JobUpdateSettings_BlockIfNoPulsesAfterMs_DEFAULT + } + return *p.BlockIfNoPulsesAfterMs +} + +var JobUpdateSettings_SlaAware_DEFAULT bool + +func (p *JobUpdateSettings) GetSlaAware() bool { + if !p.IsSetSlaAware() { + return JobUpdateSettings_SlaAware_DEFAULT + } + return *p.SlaAware +} +func (p *JobUpdateSettings) IsSetBlockIfNoPulsesAfterMs() bool { + return p.BlockIfNoPulsesAfterMs != nil +} + +func (p *JobUpdateSettings) IsSetSlaAware() bool { + return p.SlaAware != nil +} + +func (p *JobUpdateSettings) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.I32 { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.I32 { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.I32 { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 5: + if fieldTypeId == thrift.I32 { + if err := p.ReadField5(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 6: + if fieldTypeId == thrift.BOOL { + if err := p.ReadField6(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 7: + if fieldTypeId == thrift.SET { + if err := p.ReadField7(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 8: + if fieldTypeId == thrift.BOOL { + if err := p.ReadField8(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 9: + if fieldTypeId == thrift.I32 { + if err := p.ReadField9(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 10: + if fieldTypeId == thrift.BOOL { + if err := p.ReadField10(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *JobUpdateSettings) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.UpdateGroupSize = v + } + return nil +} + +func (p *JobUpdateSettings) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.MaxPerInstanceFailures = v + } + return nil +} + +func (p *JobUpdateSettings) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.MaxFailedInstances = v + } + return nil +} + +func (p *JobUpdateSettings) ReadField5(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 5: ", err) + } else { + p.MinWaitInInstanceRunningMs = v + } + return nil +} + +func (p *JobUpdateSettings) ReadField6(iprot thrift.TProtocol) error { + if v, err := iprot.ReadBool(); err != nil { + return thrift.PrependError("error reading field 6: ", err) + } else { + p.RollbackOnFailure = v + } + return nil +} + +func (p *JobUpdateSettings) ReadField7(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*Range, 0, size) + p.UpdateOnlyTheseInstances = tSet + for i := 0; i < size; i++ { + _elem25 := &Range{} + if err := _elem25.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem25), err) + } + p.UpdateOnlyTheseInstances = append(p.UpdateOnlyTheseInstances, _elem25) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *JobUpdateSettings) ReadField8(iprot thrift.TProtocol) error { + if v, err := iprot.ReadBool(); err != nil { + return thrift.PrependError("error reading field 8: ", err) + } else { + p.WaitForBatchCompletion = v + } + return nil +} + +func (p *JobUpdateSettings) ReadField9(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 9: ", err) + } else { + p.BlockIfNoPulsesAfterMs = &v + } + return nil +} + +func (p *JobUpdateSettings) ReadField10(iprot thrift.TProtocol) error { + if v, err := iprot.ReadBool(); err != nil { + return thrift.PrependError("error reading field 10: ", err) + } else { + p.SlaAware = &v + } + return nil +} + +func (p *JobUpdateSettings) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("JobUpdateSettings"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + if err := p.writeField5(oprot); err != nil { + return err + } + if err := p.writeField6(oprot); err != nil { + return err + } + if err := p.writeField7(oprot); err != nil { + return err + } + if err := p.writeField8(oprot); err != nil { + return err + } + if err := p.writeField9(oprot); err != nil { + return err + } + if err := p.writeField10(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *JobUpdateSettings) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("updateGroupSize", thrift.I32, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:updateGroupSize: ", p), err) + } + if err := oprot.WriteI32(int32(p.UpdateGroupSize)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.updateGroupSize (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:updateGroupSize: ", p), err) + } + return err +} + +func (p *JobUpdateSettings) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("maxPerInstanceFailures", thrift.I32, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:maxPerInstanceFailures: ", p), err) + } + if err := oprot.WriteI32(int32(p.MaxPerInstanceFailures)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.maxPerInstanceFailures (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:maxPerInstanceFailures: ", p), err) + } + return err +} + +func (p *JobUpdateSettings) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("maxFailedInstances", thrift.I32, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:maxFailedInstances: ", p), err) + } + if err := oprot.WriteI32(int32(p.MaxFailedInstances)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.maxFailedInstances (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:maxFailedInstances: ", p), err) + } + return err +} + +func (p *JobUpdateSettings) writeField5(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("minWaitInInstanceRunningMs", thrift.I32, 5); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:minWaitInInstanceRunningMs: ", p), err) + } + if err := oprot.WriteI32(int32(p.MinWaitInInstanceRunningMs)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.minWaitInInstanceRunningMs (5) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 5:minWaitInInstanceRunningMs: ", p), err) + } + return err +} + +func (p *JobUpdateSettings) writeField6(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("rollbackOnFailure", thrift.BOOL, 6); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 6:rollbackOnFailure: ", p), err) + } + if err := oprot.WriteBool(bool(p.RollbackOnFailure)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.rollbackOnFailure (6) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 6:rollbackOnFailure: ", p), err) + } + return err +} + +func (p *JobUpdateSettings) writeField7(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("updateOnlyTheseInstances", thrift.SET, 7); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 7:updateOnlyTheseInstances: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.UpdateOnlyTheseInstances)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.UpdateOnlyTheseInstances); i++ { + for j := i + 1; j < len(p.UpdateOnlyTheseInstances); j++ { + if reflect.DeepEqual(p.UpdateOnlyTheseInstances[i], p.UpdateOnlyTheseInstances[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.UpdateOnlyTheseInstances[i])) + } + } + } + for _, v := range p.UpdateOnlyTheseInstances { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 7:updateOnlyTheseInstances: ", p), err) + } + return err +} + +func (p *JobUpdateSettings) writeField8(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("waitForBatchCompletion", thrift.BOOL, 8); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 8:waitForBatchCompletion: ", p), err) + } + if err := oprot.WriteBool(bool(p.WaitForBatchCompletion)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.waitForBatchCompletion (8) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 8:waitForBatchCompletion: ", p), err) + } + return err +} + +func (p *JobUpdateSettings) writeField9(oprot thrift.TProtocol) (err error) { + if p.IsSetBlockIfNoPulsesAfterMs() { + if err := oprot.WriteFieldBegin("blockIfNoPulsesAfterMs", thrift.I32, 9); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 9:blockIfNoPulsesAfterMs: ", p), err) + } + if err := oprot.WriteI32(int32(*p.BlockIfNoPulsesAfterMs)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.blockIfNoPulsesAfterMs (9) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 9:blockIfNoPulsesAfterMs: ", p), err) + } + } + return err +} + +func (p *JobUpdateSettings) writeField10(oprot thrift.TProtocol) (err error) { + if p.IsSetSlaAware() { + if err := oprot.WriteFieldBegin("slaAware", thrift.BOOL, 10); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 10:slaAware: ", p), err) + } + if err := oprot.WriteBool(bool(*p.SlaAware)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.slaAware (10) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 10:slaAware: ", p), err) + } + } + return err +} + +func (p *JobUpdateSettings) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("JobUpdateSettings(%+v)", *p) +} + +// Event marking a state transition in job update lifecycle. +// +// Attributes: +// - Status: Update status. +// - TimestampMs: Epoch timestamp in milliseconds. +// - User: User who performed this event (if user-initiated). +// - Message: Message from the user (for user-initiated transitions) or the scheduler about why the state was +// changed. +type JobUpdateEvent struct { + Status JobUpdateStatus `thrift:"status,1" db:"status" json:"status"` + TimestampMs int64 `thrift:"timestampMs,2" db:"timestampMs" json:"timestampMs"` + User *string `thrift:"user,3" db:"user" json:"user,omitempty"` + Message *string `thrift:"message,4" db:"message" json:"message,omitempty"` +} + +func NewJobUpdateEvent() *JobUpdateEvent { + return &JobUpdateEvent{} +} + +func (p *JobUpdateEvent) GetStatus() JobUpdateStatus { + return p.Status +} + +func (p *JobUpdateEvent) GetTimestampMs() int64 { + return p.TimestampMs +} + +var JobUpdateEvent_User_DEFAULT string + +func (p *JobUpdateEvent) GetUser() string { + if !p.IsSetUser() { + return JobUpdateEvent_User_DEFAULT + } + return *p.User +} + +var JobUpdateEvent_Message_DEFAULT string + +func (p *JobUpdateEvent) GetMessage() string { + if !p.IsSetMessage() { + return JobUpdateEvent_Message_DEFAULT + } + return *p.Message +} +func (p *JobUpdateEvent) IsSetUser() bool { + return p.User != nil +} + +func (p *JobUpdateEvent) IsSetMessage() bool { + return p.Message != nil +} + +func (p *JobUpdateEvent) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.I32 { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.I64 { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.STRING { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 4: + if fieldTypeId == thrift.STRING { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *JobUpdateEvent) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + temp := JobUpdateStatus(v) + p.Status = temp + } + return nil +} + +func (p *JobUpdateEvent) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI64(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.TimestampMs = v + } + return nil +} + +func (p *JobUpdateEvent) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.User = &v + } + return nil +} + +func (p *JobUpdateEvent) ReadField4(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 4: ", err) + } else { + p.Message = &v + } + return nil +} + +func (p *JobUpdateEvent) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("JobUpdateEvent"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + if err := p.writeField4(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *JobUpdateEvent) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("status", thrift.I32, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:status: ", p), err) + } + if err := oprot.WriteI32(int32(p.Status)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.status (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:status: ", p), err) + } + return err +} + +func (p *JobUpdateEvent) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("timestampMs", thrift.I64, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:timestampMs: ", p), err) + } + if err := oprot.WriteI64(int64(p.TimestampMs)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.timestampMs (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:timestampMs: ", p), err) + } + return err +} + +func (p *JobUpdateEvent) writeField3(oprot thrift.TProtocol) (err error) { + if p.IsSetUser() { + if err := oprot.WriteFieldBegin("user", thrift.STRING, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:user: ", p), err) + } + if err := oprot.WriteString(string(*p.User)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.user (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:user: ", p), err) + } + } + return err +} + +func (p *JobUpdateEvent) writeField4(oprot thrift.TProtocol) (err error) { + if p.IsSetMessage() { + if err := oprot.WriteFieldBegin("message", thrift.STRING, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:message: ", p), err) + } + if err := oprot.WriteString(string(*p.Message)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.message (4) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:message: ", p), err) + } + } + return err +} + +func (p *JobUpdateEvent) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("JobUpdateEvent(%+v)", *p) +} + +// Event marking a state transition in job instance update lifecycle. +// +// Attributes: +// - InstanceId: Job instance ID. +// - TimestampMs: Epoch timestamp in milliseconds. +// - Action: Job update action taken on the instance. +// - Message: Optional message explaining the instance update event. +type JobInstanceUpdateEvent struct { + InstanceId int32 `thrift:"instanceId,1" db:"instanceId" json:"instanceId"` + TimestampMs int64 `thrift:"timestampMs,2" db:"timestampMs" json:"timestampMs"` + Action JobUpdateAction `thrift:"action,3" db:"action" json:"action"` + Message *string `thrift:"message,4" db:"message" json:"message,omitempty"` +} + +func NewJobInstanceUpdateEvent() *JobInstanceUpdateEvent { + return &JobInstanceUpdateEvent{} +} + +func (p *JobInstanceUpdateEvent) GetInstanceId() int32 { + return p.InstanceId +} + +func (p *JobInstanceUpdateEvent) GetTimestampMs() int64 { + return p.TimestampMs +} + +func (p *JobInstanceUpdateEvent) GetAction() JobUpdateAction { + return p.Action +} + +var JobInstanceUpdateEvent_Message_DEFAULT string + +func (p *JobInstanceUpdateEvent) GetMessage() string { + if !p.IsSetMessage() { + return JobInstanceUpdateEvent_Message_DEFAULT + } + return *p.Message +} +func (p *JobInstanceUpdateEvent) IsSetMessage() bool { + return p.Message != nil +} + +func (p *JobInstanceUpdateEvent) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.I32 { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.I64 { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.I32 { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 4: + if fieldTypeId == thrift.STRING { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *JobInstanceUpdateEvent) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.InstanceId = v + } + return nil +} + +func (p *JobInstanceUpdateEvent) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI64(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.TimestampMs = v + } + return nil +} + +func (p *JobInstanceUpdateEvent) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + temp := JobUpdateAction(v) + p.Action = temp + } + return nil +} + +func (p *JobInstanceUpdateEvent) ReadField4(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 4: ", err) + } else { + p.Message = &v + } + return nil +} + +func (p *JobInstanceUpdateEvent) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("JobInstanceUpdateEvent"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + if err := p.writeField4(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *JobInstanceUpdateEvent) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("instanceId", thrift.I32, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:instanceId: ", p), err) + } + if err := oprot.WriteI32(int32(p.InstanceId)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.instanceId (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:instanceId: ", p), err) + } + return err +} + +func (p *JobInstanceUpdateEvent) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("timestampMs", thrift.I64, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:timestampMs: ", p), err) + } + if err := oprot.WriteI64(int64(p.TimestampMs)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.timestampMs (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:timestampMs: ", p), err) + } + return err +} + +func (p *JobInstanceUpdateEvent) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("action", thrift.I32, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:action: ", p), err) + } + if err := oprot.WriteI32(int32(p.Action)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.action (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:action: ", p), err) + } + return err +} + +func (p *JobInstanceUpdateEvent) writeField4(oprot thrift.TProtocol) (err error) { + if p.IsSetMessage() { + if err := oprot.WriteFieldBegin("message", thrift.STRING, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:message: ", p), err) + } + if err := oprot.WriteString(string(*p.Message)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.message (4) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:message: ", p), err) + } + } + return err +} + +func (p *JobInstanceUpdateEvent) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("JobInstanceUpdateEvent(%+v)", *p) +} + +// Maps instance IDs to TaskConfigs it. +// +// Attributes: +// - Task: A TaskConfig associated with instances. +// - Instances: Instances associated with the TaskConfig. +type InstanceTaskConfig struct { + Task *TaskConfig `thrift:"task,1" db:"task" json:"task"` + Instances []*Range `thrift:"instances,2" db:"instances" json:"instances"` +} + +func NewInstanceTaskConfig() *InstanceTaskConfig { + return &InstanceTaskConfig{} +} + +var InstanceTaskConfig_Task_DEFAULT *TaskConfig + +func (p *InstanceTaskConfig) GetTask() *TaskConfig { + if !p.IsSetTask() { + return InstanceTaskConfig_Task_DEFAULT + } + return p.Task +} + +func (p *InstanceTaskConfig) GetInstances() []*Range { + return p.Instances +} +func (p *InstanceTaskConfig) IsSetTask() bool { + return p.Task != nil +} + +func (p *InstanceTaskConfig) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.SET { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *InstanceTaskConfig) ReadField1(iprot thrift.TProtocol) error { + p.Task = &TaskConfig{} + if err := p.Task.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Task), err) + } + return nil +} + +func (p *InstanceTaskConfig) ReadField2(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*Range, 0, size) + p.Instances = tSet + for i := 0; i < size; i++ { + _elem26 := &Range{} + if err := _elem26.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem26), err) + } + p.Instances = append(p.Instances, _elem26) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *InstanceTaskConfig) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("InstanceTaskConfig"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *InstanceTaskConfig) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("task", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:task: ", p), err) + } + if err := p.Task.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Task), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:task: ", p), err) + } + return err +} + +func (p *InstanceTaskConfig) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("instances", thrift.SET, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:instances: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Instances)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Instances); i++ { + for j := i + 1; j < len(p.Instances); j++ { + if reflect.DeepEqual(p.Instances[i], p.Instances[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Instances[i])) + } + } + } + for _, v := range p.Instances { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:instances: ", p), err) + } + return err +} + +func (p *InstanceTaskConfig) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("InstanceTaskConfig(%+v)", *p) +} + +// Current job update state including status and created/modified timestamps. +// +// Attributes: +// - Status: Current status of the update. +// - CreatedTimestampMs: Created timestamp in milliseconds. +// - LastModifiedTimestampMs: Last modified timestamp in milliseconds. +type JobUpdateState struct { + Status JobUpdateStatus `thrift:"status,1" db:"status" json:"status"` + CreatedTimestampMs int64 `thrift:"createdTimestampMs,2" db:"createdTimestampMs" json:"createdTimestampMs"` + LastModifiedTimestampMs int64 `thrift:"lastModifiedTimestampMs,3" db:"lastModifiedTimestampMs" json:"lastModifiedTimestampMs"` +} + +func NewJobUpdateState() *JobUpdateState { + return &JobUpdateState{} +} + +func (p *JobUpdateState) GetStatus() JobUpdateStatus { + return p.Status +} + +func (p *JobUpdateState) GetCreatedTimestampMs() int64 { + return p.CreatedTimestampMs +} + +func (p *JobUpdateState) GetLastModifiedTimestampMs() int64 { + return p.LastModifiedTimestampMs +} +func (p *JobUpdateState) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.I32 { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.I64 { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.I64 { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *JobUpdateState) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + temp := JobUpdateStatus(v) + p.Status = temp + } + return nil +} + +func (p *JobUpdateState) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI64(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.CreatedTimestampMs = v + } + return nil +} + +func (p *JobUpdateState) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI64(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.LastModifiedTimestampMs = v + } + return nil +} + +func (p *JobUpdateState) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("JobUpdateState"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *JobUpdateState) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("status", thrift.I32, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:status: ", p), err) + } + if err := oprot.WriteI32(int32(p.Status)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.status (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:status: ", p), err) + } + return err +} + +func (p *JobUpdateState) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("createdTimestampMs", thrift.I64, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:createdTimestampMs: ", p), err) + } + if err := oprot.WriteI64(int64(p.CreatedTimestampMs)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.createdTimestampMs (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:createdTimestampMs: ", p), err) + } + return err +} + +func (p *JobUpdateState) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("lastModifiedTimestampMs", thrift.I64, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:lastModifiedTimestampMs: ", p), err) + } + if err := oprot.WriteI64(int64(p.LastModifiedTimestampMs)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.lastModifiedTimestampMs (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:lastModifiedTimestampMs: ", p), err) + } + return err +} + +func (p *JobUpdateState) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("JobUpdateState(%+v)", *p) +} + +// Summary of the job update including job key, user and current state. +// +// Attributes: +// - Key: Unique identifier for the update. +// - User: User initiated an update. +// - State: Current job update state. +// - Metadata: Update metadata supplied by the client. +type JobUpdateSummary struct { + // unused fields # 1 to 2 + User string `thrift:"user,3" db:"user" json:"user"` + State *JobUpdateState `thrift:"state,4" db:"state" json:"state"` + Key *JobUpdateKey `thrift:"key,5" db:"key" json:"key"` + Metadata []*Metadata `thrift:"metadata,6" db:"metadata" json:"metadata,omitempty"` +} + +func NewJobUpdateSummary() *JobUpdateSummary { + return &JobUpdateSummary{} +} + +var JobUpdateSummary_Key_DEFAULT *JobUpdateKey + +func (p *JobUpdateSummary) GetKey() *JobUpdateKey { + if !p.IsSetKey() { + return JobUpdateSummary_Key_DEFAULT + } + return p.Key +} + +func (p *JobUpdateSummary) GetUser() string { + return p.User +} + +var JobUpdateSummary_State_DEFAULT *JobUpdateState + +func (p *JobUpdateSummary) GetState() *JobUpdateState { + if !p.IsSetState() { + return JobUpdateSummary_State_DEFAULT + } + return p.State +} + +var JobUpdateSummary_Metadata_DEFAULT []*Metadata + +func (p *JobUpdateSummary) GetMetadata() []*Metadata { + return p.Metadata +} +func (p *JobUpdateSummary) IsSetKey() bool { + return p.Key != nil +} + +func (p *JobUpdateSummary) IsSetState() bool { + return p.State != nil +} + +func (p *JobUpdateSummary) IsSetMetadata() bool { + return p.Metadata != nil +} + +func (p *JobUpdateSummary) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 5: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField5(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.STRING { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 4: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 6: + if fieldTypeId == thrift.SET { + if err := p.ReadField6(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *JobUpdateSummary) ReadField5(iprot thrift.TProtocol) error { + p.Key = &JobUpdateKey{} + if err := p.Key.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) + } + return nil +} + +func (p *JobUpdateSummary) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.User = v + } + return nil +} + +func (p *JobUpdateSummary) ReadField4(iprot thrift.TProtocol) error { + p.State = &JobUpdateState{} + if err := p.State.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.State), err) + } + return nil +} + +func (p *JobUpdateSummary) ReadField6(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*Metadata, 0, size) + p.Metadata = tSet + for i := 0; i < size; i++ { + _elem27 := &Metadata{} + if err := _elem27.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem27), err) + } + p.Metadata = append(p.Metadata, _elem27) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *JobUpdateSummary) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("JobUpdateSummary"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField3(oprot); err != nil { + return err + } + if err := p.writeField4(oprot); err != nil { + return err + } + if err := p.writeField5(oprot); err != nil { + return err + } + if err := p.writeField6(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *JobUpdateSummary) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("user", thrift.STRING, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:user: ", p), err) + } + if err := oprot.WriteString(string(p.User)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.user (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:user: ", p), err) + } + return err +} + +func (p *JobUpdateSummary) writeField4(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("state", thrift.STRUCT, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:state: ", p), err) + } + if err := p.State.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.State), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:state: ", p), err) + } + return err +} + +func (p *JobUpdateSummary) writeField5(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 5); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:key: ", p), err) + } + if err := p.Key.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 5:key: ", p), err) + } + return err +} + +func (p *JobUpdateSummary) writeField6(oprot thrift.TProtocol) (err error) { + if p.IsSetMetadata() { + if err := oprot.WriteFieldBegin("metadata", thrift.SET, 6); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 6:metadata: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Metadata)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Metadata); i++ { + for j := i + 1; j < len(p.Metadata); j++ { + if reflect.DeepEqual(p.Metadata[i], p.Metadata[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Metadata[i])) + } + } + } + for _, v := range p.Metadata { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 6:metadata: ", p), err) + } + } + return err +} + +func (p *JobUpdateSummary) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("JobUpdateSummary(%+v)", *p) +} + +// Update configuration and setting details. +// +// Attributes: +// - InitialState: Actual InstanceId -> TaskConfig mapping when the update was requested. +// - DesiredState: Desired configuration when the update completes. +// - Settings: Update specific settings. +type JobUpdateInstructions struct { + InitialState []*InstanceTaskConfig `thrift:"initialState,1" db:"initialState" json:"initialState"` + DesiredState *InstanceTaskConfig `thrift:"desiredState,2" db:"desiredState" json:"desiredState"` + Settings *JobUpdateSettings `thrift:"settings,3" db:"settings" json:"settings"` +} + +func NewJobUpdateInstructions() *JobUpdateInstructions { + return &JobUpdateInstructions{} +} + +func (p *JobUpdateInstructions) GetInitialState() []*InstanceTaskConfig { + return p.InitialState +} + +var JobUpdateInstructions_DesiredState_DEFAULT *InstanceTaskConfig + +func (p *JobUpdateInstructions) GetDesiredState() *InstanceTaskConfig { + if !p.IsSetDesiredState() { + return JobUpdateInstructions_DesiredState_DEFAULT + } + return p.DesiredState +} + +var JobUpdateInstructions_Settings_DEFAULT *JobUpdateSettings + +func (p *JobUpdateInstructions) GetSettings() *JobUpdateSettings { + if !p.IsSetSettings() { + return JobUpdateInstructions_Settings_DEFAULT + } + return p.Settings +} +func (p *JobUpdateInstructions) IsSetDesiredState() bool { + return p.DesiredState != nil +} + +func (p *JobUpdateInstructions) IsSetSettings() bool { + return p.Settings != nil +} + +func (p *JobUpdateInstructions) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.SET { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *JobUpdateInstructions) ReadField1(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*InstanceTaskConfig, 0, size) + p.InitialState = tSet + for i := 0; i < size; i++ { + _elem28 := &InstanceTaskConfig{} + if err := _elem28.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem28), err) + } + p.InitialState = append(p.InitialState, _elem28) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *JobUpdateInstructions) ReadField2(iprot thrift.TProtocol) error { + p.DesiredState = &InstanceTaskConfig{} + if err := p.DesiredState.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.DesiredState), err) + } + return nil +} + +func (p *JobUpdateInstructions) ReadField3(iprot thrift.TProtocol) error { + p.Settings = &JobUpdateSettings{} + if err := p.Settings.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Settings), err) + } + return nil +} + +func (p *JobUpdateInstructions) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("JobUpdateInstructions"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *JobUpdateInstructions) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("initialState", thrift.SET, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:initialState: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.InitialState)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.InitialState); i++ { + for j := i + 1; j < len(p.InitialState); j++ { + if reflect.DeepEqual(p.InitialState[i], p.InitialState[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.InitialState[i])) + } + } + } + for _, v := range p.InitialState { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:initialState: ", p), err) + } + return err +} + +func (p *JobUpdateInstructions) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("desiredState", thrift.STRUCT, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:desiredState: ", p), err) + } + if err := p.DesiredState.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.DesiredState), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:desiredState: ", p), err) + } + return err +} + +func (p *JobUpdateInstructions) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("settings", thrift.STRUCT, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:settings: ", p), err) + } + if err := p.Settings.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Settings), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:settings: ", p), err) + } + return err +} + +func (p *JobUpdateInstructions) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("JobUpdateInstructions(%+v)", *p) +} + +// Full definition of the job update. +// +// Attributes: +// - Summary: Update summary. +// - Instructions: Update configuration. +type JobUpdate struct { + Summary *JobUpdateSummary `thrift:"summary,1" db:"summary" json:"summary"` + Instructions *JobUpdateInstructions `thrift:"instructions,2" db:"instructions" json:"instructions"` +} + +func NewJobUpdate() *JobUpdate { + return &JobUpdate{} +} + +var JobUpdate_Summary_DEFAULT *JobUpdateSummary + +func (p *JobUpdate) GetSummary() *JobUpdateSummary { + if !p.IsSetSummary() { + return JobUpdate_Summary_DEFAULT + } + return p.Summary +} + +var JobUpdate_Instructions_DEFAULT *JobUpdateInstructions + +func (p *JobUpdate) GetInstructions() *JobUpdateInstructions { + if !p.IsSetInstructions() { + return JobUpdate_Instructions_DEFAULT + } + return p.Instructions +} +func (p *JobUpdate) IsSetSummary() bool { + return p.Summary != nil +} + +func (p *JobUpdate) IsSetInstructions() bool { + return p.Instructions != nil +} + +func (p *JobUpdate) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *JobUpdate) ReadField1(iprot thrift.TProtocol) error { + p.Summary = &JobUpdateSummary{} + if err := p.Summary.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Summary), err) + } + return nil +} + +func (p *JobUpdate) ReadField2(iprot thrift.TProtocol) error { + p.Instructions = &JobUpdateInstructions{} + if err := p.Instructions.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Instructions), err) + } + return nil +} + +func (p *JobUpdate) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("JobUpdate"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *JobUpdate) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("summary", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:summary: ", p), err) + } + if err := p.Summary.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Summary), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:summary: ", p), err) + } + return err +} + +func (p *JobUpdate) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("instructions", thrift.STRUCT, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:instructions: ", p), err) + } + if err := p.Instructions.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Instructions), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:instructions: ", p), err) + } + return err +} + +func (p *JobUpdate) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("JobUpdate(%+v)", *p) +} + +// Attributes: +// - Update: Update definition. +// - UpdateEvents: History for this update. +// - InstanceEvents: History for the individual instances updated. +type JobUpdateDetails struct { + Update *JobUpdate `thrift:"update,1" db:"update" json:"update"` + UpdateEvents []*JobUpdateEvent `thrift:"updateEvents,2" db:"updateEvents" json:"updateEvents"` + InstanceEvents []*JobInstanceUpdateEvent `thrift:"instanceEvents,3" db:"instanceEvents" json:"instanceEvents"` +} + +func NewJobUpdateDetails() *JobUpdateDetails { + return &JobUpdateDetails{} +} + +var JobUpdateDetails_Update_DEFAULT *JobUpdate + +func (p *JobUpdateDetails) GetUpdate() *JobUpdate { + if !p.IsSetUpdate() { + return JobUpdateDetails_Update_DEFAULT + } + return p.Update +} + +func (p *JobUpdateDetails) GetUpdateEvents() []*JobUpdateEvent { + return p.UpdateEvents +} + +func (p *JobUpdateDetails) GetInstanceEvents() []*JobInstanceUpdateEvent { + return p.InstanceEvents +} +func (p *JobUpdateDetails) IsSetUpdate() bool { + return p.Update != nil +} + +func (p *JobUpdateDetails) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.LIST { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.LIST { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *JobUpdateDetails) ReadField1(iprot thrift.TProtocol) error { + p.Update = &JobUpdate{} + if err := p.Update.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Update), err) + } + return nil +} + +func (p *JobUpdateDetails) ReadField2(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadListBegin() + if err != nil { + return thrift.PrependError("error reading list begin: ", err) + } + tSlice := make([]*JobUpdateEvent, 0, size) + p.UpdateEvents = tSlice + for i := 0; i < size; i++ { + _elem29 := &JobUpdateEvent{} + if err := _elem29.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem29), err) + } + p.UpdateEvents = append(p.UpdateEvents, _elem29) + } + if err := iprot.ReadListEnd(); err != nil { + return thrift.PrependError("error reading list end: ", err) + } + return nil +} + +func (p *JobUpdateDetails) ReadField3(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadListBegin() + if err != nil { + return thrift.PrependError("error reading list begin: ", err) + } + tSlice := make([]*JobInstanceUpdateEvent, 0, size) + p.InstanceEvents = tSlice + for i := 0; i < size; i++ { + _elem30 := &JobInstanceUpdateEvent{} + if err := _elem30.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem30), err) + } + p.InstanceEvents = append(p.InstanceEvents, _elem30) + } + if err := iprot.ReadListEnd(); err != nil { + return thrift.PrependError("error reading list end: ", err) + } + return nil +} + +func (p *JobUpdateDetails) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("JobUpdateDetails"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *JobUpdateDetails) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("update", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:update: ", p), err) + } + if err := p.Update.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Update), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:update: ", p), err) + } + return err +} + +func (p *JobUpdateDetails) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("updateEvents", thrift.LIST, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:updateEvents: ", p), err) + } + if err := oprot.WriteListBegin(thrift.STRUCT, len(p.UpdateEvents)); err != nil { + return thrift.PrependError("error writing list begin: ", err) + } + for _, v := range p.UpdateEvents { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteListEnd(); err != nil { + return thrift.PrependError("error writing list end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:updateEvents: ", p), err) + } + return err +} + +func (p *JobUpdateDetails) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("instanceEvents", thrift.LIST, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:instanceEvents: ", p), err) + } + if err := oprot.WriteListBegin(thrift.STRUCT, len(p.InstanceEvents)); err != nil { + return thrift.PrependError("error writing list begin: ", err) + } + for _, v := range p.InstanceEvents { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteListEnd(); err != nil { + return thrift.PrependError("error writing list end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:instanceEvents: ", p), err) + } + return err +} + +func (p *JobUpdateDetails) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("JobUpdateDetails(%+v)", *p) +} + +// A request to update the following instances of an existing job. Used by startUpdate. +// +// Attributes: +// - TaskConfig: Desired TaskConfig to apply. +// - InstanceCount: Desired number of instances of the task config. +// - Settings: Update settings and limits. +// - Metadata: Update metadata supplied by the client issuing the JobUpdateRequest. +type JobUpdateRequest struct { + TaskConfig *TaskConfig `thrift:"taskConfig,1" db:"taskConfig" json:"taskConfig"` + InstanceCount int32 `thrift:"instanceCount,2" db:"instanceCount" json:"instanceCount"` + Settings *JobUpdateSettings `thrift:"settings,3" db:"settings" json:"settings"` + Metadata []*Metadata `thrift:"metadata,4" db:"metadata" json:"metadata,omitempty"` +} + +func NewJobUpdateRequest() *JobUpdateRequest { + return &JobUpdateRequest{} +} + +var JobUpdateRequest_TaskConfig_DEFAULT *TaskConfig + +func (p *JobUpdateRequest) GetTaskConfig() *TaskConfig { + if !p.IsSetTaskConfig() { + return JobUpdateRequest_TaskConfig_DEFAULT + } + return p.TaskConfig +} + +func (p *JobUpdateRequest) GetInstanceCount() int32 { + return p.InstanceCount +} + +var JobUpdateRequest_Settings_DEFAULT *JobUpdateSettings + +func (p *JobUpdateRequest) GetSettings() *JobUpdateSettings { + if !p.IsSetSettings() { + return JobUpdateRequest_Settings_DEFAULT + } + return p.Settings +} + +var JobUpdateRequest_Metadata_DEFAULT []*Metadata + +func (p *JobUpdateRequest) GetMetadata() []*Metadata { + return p.Metadata +} +func (p *JobUpdateRequest) IsSetTaskConfig() bool { + return p.TaskConfig != nil +} + +func (p *JobUpdateRequest) IsSetSettings() bool { + return p.Settings != nil +} + +func (p *JobUpdateRequest) IsSetMetadata() bool { + return p.Metadata != nil +} + +func (p *JobUpdateRequest) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.I32 { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 4: + if fieldTypeId == thrift.SET { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *JobUpdateRequest) ReadField1(iprot thrift.TProtocol) error { + p.TaskConfig = &TaskConfig{} + if err := p.TaskConfig.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.TaskConfig), err) + } + return nil +} + +func (p *JobUpdateRequest) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.InstanceCount = v + } + return nil +} + +func (p *JobUpdateRequest) ReadField3(iprot thrift.TProtocol) error { + p.Settings = &JobUpdateSettings{} + if err := p.Settings.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Settings), err) + } + return nil +} + +func (p *JobUpdateRequest) ReadField4(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*Metadata, 0, size) + p.Metadata = tSet + for i := 0; i < size; i++ { + _elem31 := &Metadata{} + if err := _elem31.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem31), err) + } + p.Metadata = append(p.Metadata, _elem31) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *JobUpdateRequest) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("JobUpdateRequest"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + if err := p.writeField4(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *JobUpdateRequest) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("taskConfig", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:taskConfig: ", p), err) + } + if err := p.TaskConfig.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.TaskConfig), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:taskConfig: ", p), err) + } + return err +} + +func (p *JobUpdateRequest) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("instanceCount", thrift.I32, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:instanceCount: ", p), err) + } + if err := oprot.WriteI32(int32(p.InstanceCount)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.instanceCount (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:instanceCount: ", p), err) + } + return err +} + +func (p *JobUpdateRequest) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("settings", thrift.STRUCT, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:settings: ", p), err) + } + if err := p.Settings.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Settings), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:settings: ", p), err) + } + return err +} + +func (p *JobUpdateRequest) writeField4(oprot thrift.TProtocol) (err error) { + if p.IsSetMetadata() { + if err := oprot.WriteFieldBegin("metadata", thrift.SET, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:metadata: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Metadata)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Metadata); i++ { + for j := i + 1; j < len(p.Metadata); j++ { + if reflect.DeepEqual(p.Metadata[i], p.Metadata[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Metadata[i])) + } + } + } + for _, v := range p.Metadata { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:metadata: ", p), err) + } + } + return err +} + +func (p *JobUpdateRequest) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("JobUpdateRequest(%+v)", *p) +} + +// Contains a set of restrictions on matching job updates where all restrictions must be met +// (terms are AND'ed together). +// +// Attributes: +// - Role: Job role. +// - Key: Unique identifier for a job update. +// - JobKey: Job key. +// - User: User who created the update. +// - UpdateStatuses: Set of update statuses. +// - Offset: Offset to serve data from. Used by pagination. +// - Limit: Number or records to serve. Used by pagination. +type JobUpdateQuery struct { + // unused field # 1 + Role *string `thrift:"role,2" db:"role" json:"role,omitempty"` + JobKey *JobKey `thrift:"jobKey,3" db:"jobKey" json:"jobKey,omitempty"` + User *string `thrift:"user,4" db:"user" json:"user,omitempty"` + UpdateStatuses []JobUpdateStatus `thrift:"updateStatuses,5" db:"updateStatuses" json:"updateStatuses,omitempty"` + Offset int32 `thrift:"offset,6" db:"offset" json:"offset"` + Limit int32 `thrift:"limit,7" db:"limit" json:"limit"` + Key *JobUpdateKey `thrift:"key,8" db:"key" json:"key,omitempty"` +} + +func NewJobUpdateQuery() *JobUpdateQuery { + return &JobUpdateQuery{} +} + +var JobUpdateQuery_Role_DEFAULT string + +func (p *JobUpdateQuery) GetRole() string { + if !p.IsSetRole() { + return JobUpdateQuery_Role_DEFAULT + } + return *p.Role +} + +var JobUpdateQuery_Key_DEFAULT *JobUpdateKey + +func (p *JobUpdateQuery) GetKey() *JobUpdateKey { + if !p.IsSetKey() { + return JobUpdateQuery_Key_DEFAULT + } + return p.Key +} + +var JobUpdateQuery_JobKey_DEFAULT *JobKey + +func (p *JobUpdateQuery) GetJobKey() *JobKey { + if !p.IsSetJobKey() { + return JobUpdateQuery_JobKey_DEFAULT + } + return p.JobKey +} + +var JobUpdateQuery_User_DEFAULT string + +func (p *JobUpdateQuery) GetUser() string { + if !p.IsSetUser() { + return JobUpdateQuery_User_DEFAULT + } + return *p.User +} + +var JobUpdateQuery_UpdateStatuses_DEFAULT []JobUpdateStatus + +func (p *JobUpdateQuery) GetUpdateStatuses() []JobUpdateStatus { + return p.UpdateStatuses +} + +func (p *JobUpdateQuery) GetOffset() int32 { + return p.Offset +} + +func (p *JobUpdateQuery) GetLimit() int32 { + return p.Limit +} +func (p *JobUpdateQuery) IsSetRole() bool { + return p.Role != nil +} + +func (p *JobUpdateQuery) IsSetKey() bool { + return p.Key != nil +} + +func (p *JobUpdateQuery) IsSetJobKey() bool { + return p.JobKey != nil +} + +func (p *JobUpdateQuery) IsSetUser() bool { + return p.User != nil +} + +func (p *JobUpdateQuery) IsSetUpdateStatuses() bool { + return p.UpdateStatuses != nil +} + +func (p *JobUpdateQuery) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 2: + if fieldTypeId == thrift.STRING { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 8: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField8(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 4: + if fieldTypeId == thrift.STRING { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 5: + if fieldTypeId == thrift.SET { + if err := p.ReadField5(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 6: + if fieldTypeId == thrift.I32 { + if err := p.ReadField6(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 7: + if fieldTypeId == thrift.I32 { + if err := p.ReadField7(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *JobUpdateQuery) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.Role = &v + } + return nil +} + +func (p *JobUpdateQuery) ReadField8(iprot thrift.TProtocol) error { + p.Key = &JobUpdateKey{} + if err := p.Key.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) + } + return nil +} + +func (p *JobUpdateQuery) ReadField3(iprot thrift.TProtocol) error { + p.JobKey = &JobKey{} + if err := p.JobKey.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.JobKey), err) + } + return nil +} + +func (p *JobUpdateQuery) ReadField4(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 4: ", err) + } else { + p.User = &v + } + return nil +} + +func (p *JobUpdateQuery) ReadField5(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]JobUpdateStatus, 0, size) + p.UpdateStatuses = tSet + for i := 0; i < size; i++ { + var _elem32 JobUpdateStatus + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 0: ", err) + } else { + temp := JobUpdateStatus(v) + _elem32 = temp + } + p.UpdateStatuses = append(p.UpdateStatuses, _elem32) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *JobUpdateQuery) ReadField6(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 6: ", err) + } else { + p.Offset = v + } + return nil +} + +func (p *JobUpdateQuery) ReadField7(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 7: ", err) + } else { + p.Limit = v + } + return nil +} + +func (p *JobUpdateQuery) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("JobUpdateQuery"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + if err := p.writeField4(oprot); err != nil { + return err + } + if err := p.writeField5(oprot); err != nil { + return err + } + if err := p.writeField6(oprot); err != nil { + return err + } + if err := p.writeField7(oprot); err != nil { + return err + } + if err := p.writeField8(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *JobUpdateQuery) writeField2(oprot thrift.TProtocol) (err error) { + if p.IsSetRole() { + if err := oprot.WriteFieldBegin("role", thrift.STRING, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:role: ", p), err) + } + if err := oprot.WriteString(string(*p.Role)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.role (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:role: ", p), err) + } + } + return err +} + +func (p *JobUpdateQuery) writeField3(oprot thrift.TProtocol) (err error) { + if p.IsSetJobKey() { + if err := oprot.WriteFieldBegin("jobKey", thrift.STRUCT, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:jobKey: ", p), err) + } + if err := p.JobKey.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.JobKey), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:jobKey: ", p), err) + } + } + return err +} + +func (p *JobUpdateQuery) writeField4(oprot thrift.TProtocol) (err error) { + if p.IsSetUser() { + if err := oprot.WriteFieldBegin("user", thrift.STRING, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:user: ", p), err) + } + if err := oprot.WriteString(string(*p.User)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.user (4) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:user: ", p), err) + } + } + return err +} + +func (p *JobUpdateQuery) writeField5(oprot thrift.TProtocol) (err error) { + if p.IsSetUpdateStatuses() { + if err := oprot.WriteFieldBegin("updateStatuses", thrift.SET, 5); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:updateStatuses: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.I32, len(p.UpdateStatuses)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.UpdateStatuses); i++ { + for j := i + 1; j < len(p.UpdateStatuses); j++ { + if reflect.DeepEqual(p.UpdateStatuses[i], p.UpdateStatuses[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.UpdateStatuses[i])) + } + } + } + for _, v := range p.UpdateStatuses { + if err := oprot.WriteI32(int32(v)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 5:updateStatuses: ", p), err) + } + } + return err +} + +func (p *JobUpdateQuery) writeField6(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("offset", thrift.I32, 6); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 6:offset: ", p), err) + } + if err := oprot.WriteI32(int32(p.Offset)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.offset (6) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 6:offset: ", p), err) + } + return err +} + +func (p *JobUpdateQuery) writeField7(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("limit", thrift.I32, 7); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 7:limit: ", p), err) + } + if err := oprot.WriteI32(int32(p.Limit)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.limit (7) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 7:limit: ", p), err) + } + return err +} + +func (p *JobUpdateQuery) writeField8(oprot thrift.TProtocol) (err error) { + if p.IsSetKey() { + if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 8); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 8:key: ", p), err) + } + if err := p.Key.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 8:key: ", p), err) + } + } + return err +} + +func (p *JobUpdateQuery) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("JobUpdateQuery(%+v)", *p) +} + +// Attributes: +// - Host +// - DefaultSlaPolicy +// - TimeoutSecs +// - CreatedTimestampMs +type HostMaintenanceRequest struct { + Host string `thrift:"host,1" db:"host" json:"host"` + DefaultSlaPolicy *SlaPolicy `thrift:"defaultSlaPolicy,2" db:"defaultSlaPolicy" json:"defaultSlaPolicy"` + TimeoutSecs int64 `thrift:"timeoutSecs,3" db:"timeoutSecs" json:"timeoutSecs"` + CreatedTimestampMs int64 `thrift:"createdTimestampMs,4" db:"createdTimestampMs" json:"createdTimestampMs"` +} + +func NewHostMaintenanceRequest() *HostMaintenanceRequest { + return &HostMaintenanceRequest{} +} + +func (p *HostMaintenanceRequest) GetHost() string { + return p.Host +} + +var HostMaintenanceRequest_DefaultSlaPolicy_DEFAULT *SlaPolicy + +func (p *HostMaintenanceRequest) GetDefaultSlaPolicy() *SlaPolicy { + if !p.IsSetDefaultSlaPolicy() { + return HostMaintenanceRequest_DefaultSlaPolicy_DEFAULT + } + return p.DefaultSlaPolicy +} + +func (p *HostMaintenanceRequest) GetTimeoutSecs() int64 { + return p.TimeoutSecs +} + +func (p *HostMaintenanceRequest) GetCreatedTimestampMs() int64 { + return p.CreatedTimestampMs +} +func (p *HostMaintenanceRequest) IsSetDefaultSlaPolicy() bool { + return p.DefaultSlaPolicy != nil +} + +func (p *HostMaintenanceRequest) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.I64 { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 4: + if fieldTypeId == thrift.I64 { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *HostMaintenanceRequest) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Host = v + } + return nil +} + +func (p *HostMaintenanceRequest) ReadField2(iprot thrift.TProtocol) error { + p.DefaultSlaPolicy = &SlaPolicy{} + if err := p.DefaultSlaPolicy.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.DefaultSlaPolicy), err) + } + return nil +} + +func (p *HostMaintenanceRequest) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI64(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.TimeoutSecs = v + } + return nil +} + +func (p *HostMaintenanceRequest) ReadField4(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI64(); err != nil { + return thrift.PrependError("error reading field 4: ", err) + } else { + p.CreatedTimestampMs = v + } + return nil +} + +func (p *HostMaintenanceRequest) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("HostMaintenanceRequest"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + if err := p.writeField4(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *HostMaintenanceRequest) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("host", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:host: ", p), err) + } + if err := oprot.WriteString(string(p.Host)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.host (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:host: ", p), err) + } + return err +} + +func (p *HostMaintenanceRequest) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("defaultSlaPolicy", thrift.STRUCT, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:defaultSlaPolicy: ", p), err) + } + if err := p.DefaultSlaPolicy.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.DefaultSlaPolicy), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:defaultSlaPolicy: ", p), err) + } + return err +} + +func (p *HostMaintenanceRequest) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("timeoutSecs", thrift.I64, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:timeoutSecs: ", p), err) + } + if err := oprot.WriteI64(int64(p.TimeoutSecs)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.timeoutSecs (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:timeoutSecs: ", p), err) + } + return err +} + +func (p *HostMaintenanceRequest) writeField4(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("createdTimestampMs", thrift.I64, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:createdTimestampMs: ", p), err) + } + if err := oprot.WriteI64(int64(p.CreatedTimestampMs)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.createdTimestampMs (4) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:createdTimestampMs: ", p), err) + } + return err +} + +func (p *HostMaintenanceRequest) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("HostMaintenanceRequest(%+v)", *p) +} + +// Attributes: +// - Backups +type ListBackupsResult_ struct { + Backups []string `thrift:"backups,1" db:"backups" json:"backups"` +} + +func NewListBackupsResult_() *ListBackupsResult_ { + return &ListBackupsResult_{} +} + +func (p *ListBackupsResult_) GetBackups() []string { + return p.Backups +} +func (p *ListBackupsResult_) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.SET { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ListBackupsResult_) ReadField1(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]string, 0, size) + p.Backups = tSet + for i := 0; i < size; i++ { + var _elem33 string + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 0: ", err) + } else { + _elem33 = v + } + p.Backups = append(p.Backups, _elem33) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *ListBackupsResult_) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("ListBackupsResult"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ListBackupsResult_) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("backups", thrift.SET, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:backups: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRING, len(p.Backups)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Backups); i++ { + for j := i + 1; j < len(p.Backups); j++ { + if reflect.DeepEqual(p.Backups[i], p.Backups[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Backups[i])) + } + } + } + for _, v := range p.Backups { + if err := oprot.WriteString(string(v)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:backups: ", p), err) + } + return err +} + +func (p *ListBackupsResult_) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ListBackupsResult_(%+v)", *p) +} + +// Attributes: +// - Statuses +type StartMaintenanceResult_ struct { + Statuses []*HostStatus `thrift:"statuses,1" db:"statuses" json:"statuses"` +} + +func NewStartMaintenanceResult_() *StartMaintenanceResult_ { + return &StartMaintenanceResult_{} +} + +func (p *StartMaintenanceResult_) GetStatuses() []*HostStatus { + return p.Statuses +} +func (p *StartMaintenanceResult_) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.SET { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *StartMaintenanceResult_) ReadField1(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*HostStatus, 0, size) + p.Statuses = tSet + for i := 0; i < size; i++ { + _elem34 := &HostStatus{} + if err := _elem34.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem34), err) + } + p.Statuses = append(p.Statuses, _elem34) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *StartMaintenanceResult_) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("StartMaintenanceResult"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *StartMaintenanceResult_) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("statuses", thrift.SET, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:statuses: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Statuses)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Statuses); i++ { + for j := i + 1; j < len(p.Statuses); j++ { + if reflect.DeepEqual(p.Statuses[i], p.Statuses[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Statuses[i])) + } + } + } + for _, v := range p.Statuses { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:statuses: ", p), err) + } + return err +} + +func (p *StartMaintenanceResult_) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("StartMaintenanceResult_(%+v)", *p) +} + +// Attributes: +// - Statuses +type DrainHostsResult_ struct { + Statuses []*HostStatus `thrift:"statuses,1" db:"statuses" json:"statuses"` +} + +func NewDrainHostsResult_() *DrainHostsResult_ { + return &DrainHostsResult_{} +} + +func (p *DrainHostsResult_) GetStatuses() []*HostStatus { + return p.Statuses +} +func (p *DrainHostsResult_) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.SET { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *DrainHostsResult_) ReadField1(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*HostStatus, 0, size) + p.Statuses = tSet + for i := 0; i < size; i++ { + _elem35 := &HostStatus{} + if err := _elem35.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem35), err) + } + p.Statuses = append(p.Statuses, _elem35) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *DrainHostsResult_) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("DrainHostsResult"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *DrainHostsResult_) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("statuses", thrift.SET, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:statuses: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Statuses)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Statuses); i++ { + for j := i + 1; j < len(p.Statuses); j++ { + if reflect.DeepEqual(p.Statuses[i], p.Statuses[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Statuses[i])) + } + } + } + for _, v := range p.Statuses { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:statuses: ", p), err) + } + return err +} + +func (p *DrainHostsResult_) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("DrainHostsResult_(%+v)", *p) +} + +// Attributes: +// - Tasks +type QueryRecoveryResult_ struct { + Tasks []*ScheduledTask `thrift:"tasks,1" db:"tasks" json:"tasks"` +} + +func NewQueryRecoveryResult_() *QueryRecoveryResult_ { + return &QueryRecoveryResult_{} +} + +func (p *QueryRecoveryResult_) GetTasks() []*ScheduledTask { + return p.Tasks +} +func (p *QueryRecoveryResult_) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.SET { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *QueryRecoveryResult_) ReadField1(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*ScheduledTask, 0, size) + p.Tasks = tSet + for i := 0; i < size; i++ { + _elem36 := &ScheduledTask{} + if err := _elem36.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem36), err) + } + p.Tasks = append(p.Tasks, _elem36) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *QueryRecoveryResult_) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("QueryRecoveryResult"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *QueryRecoveryResult_) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("tasks", thrift.SET, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:tasks: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Tasks)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Tasks); i++ { + for j := i + 1; j < len(p.Tasks); j++ { + if reflect.DeepEqual(p.Tasks[i], p.Tasks[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Tasks[i])) + } + } + } + for _, v := range p.Tasks { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:tasks: ", p), err) + } + return err +} + +func (p *QueryRecoveryResult_) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("QueryRecoveryResult_(%+v)", *p) +} + +// Attributes: +// - Statuses +type MaintenanceStatusResult_ struct { + Statuses []*HostStatus `thrift:"statuses,1" db:"statuses" json:"statuses"` +} + +func NewMaintenanceStatusResult_() *MaintenanceStatusResult_ { + return &MaintenanceStatusResult_{} +} + +func (p *MaintenanceStatusResult_) GetStatuses() []*HostStatus { + return p.Statuses +} +func (p *MaintenanceStatusResult_) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.SET { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *MaintenanceStatusResult_) ReadField1(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*HostStatus, 0, size) + p.Statuses = tSet + for i := 0; i < size; i++ { + _elem37 := &HostStatus{} + if err := _elem37.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem37), err) + } + p.Statuses = append(p.Statuses, _elem37) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *MaintenanceStatusResult_) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("MaintenanceStatusResult"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *MaintenanceStatusResult_) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("statuses", thrift.SET, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:statuses: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Statuses)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Statuses); i++ { + for j := i + 1; j < len(p.Statuses); j++ { + if reflect.DeepEqual(p.Statuses[i], p.Statuses[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Statuses[i])) + } + } + } + for _, v := range p.Statuses { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:statuses: ", p), err) + } + return err +} + +func (p *MaintenanceStatusResult_) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("MaintenanceStatusResult_(%+v)", *p) +} + +// Attributes: +// - Statuses +type EndMaintenanceResult_ struct { + Statuses []*HostStatus `thrift:"statuses,1" db:"statuses" json:"statuses"` +} + +func NewEndMaintenanceResult_() *EndMaintenanceResult_ { + return &EndMaintenanceResult_{} +} + +func (p *EndMaintenanceResult_) GetStatuses() []*HostStatus { + return p.Statuses +} +func (p *EndMaintenanceResult_) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.SET { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *EndMaintenanceResult_) ReadField1(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*HostStatus, 0, size) + p.Statuses = tSet + for i := 0; i < size; i++ { + _elem38 := &HostStatus{} + if err := _elem38.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem38), err) + } + p.Statuses = append(p.Statuses, _elem38) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *EndMaintenanceResult_) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("EndMaintenanceResult"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *EndMaintenanceResult_) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("statuses", thrift.SET, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:statuses: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Statuses)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Statuses); i++ { + for j := i + 1; j < len(p.Statuses); j++ { + if reflect.DeepEqual(p.Statuses[i], p.Statuses[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Statuses[i])) + } + } + } + for _, v := range p.Statuses { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:statuses: ", p), err) + } + return err +} + +func (p *EndMaintenanceResult_) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("EndMaintenanceResult_(%+v)", *p) +} + +// Attributes: +// - Summaries +type RoleSummaryResult_ struct { + Summaries []*RoleSummary `thrift:"summaries,1" db:"summaries" json:"summaries"` +} + +func NewRoleSummaryResult_() *RoleSummaryResult_ { + return &RoleSummaryResult_{} +} + +func (p *RoleSummaryResult_) GetSummaries() []*RoleSummary { + return p.Summaries +} +func (p *RoleSummaryResult_) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.SET { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *RoleSummaryResult_) ReadField1(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*RoleSummary, 0, size) + p.Summaries = tSet + for i := 0; i < size; i++ { + _elem39 := &RoleSummary{} + if err := _elem39.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem39), err) + } + p.Summaries = append(p.Summaries, _elem39) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *RoleSummaryResult_) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("RoleSummaryResult"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *RoleSummaryResult_) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("summaries", thrift.SET, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:summaries: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Summaries)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Summaries); i++ { + for j := i + 1; j < len(p.Summaries); j++ { + if reflect.DeepEqual(p.Summaries[i], p.Summaries[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Summaries[i])) + } + } + } + for _, v := range p.Summaries { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:summaries: ", p), err) + } + return err +} + +func (p *RoleSummaryResult_) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("RoleSummaryResult_(%+v)", *p) +} + +// Attributes: +// - Summaries +type JobSummaryResult_ struct { + Summaries []*JobSummary `thrift:"summaries,1" db:"summaries" json:"summaries"` +} + +func NewJobSummaryResult_() *JobSummaryResult_ { + return &JobSummaryResult_{} +} + +func (p *JobSummaryResult_) GetSummaries() []*JobSummary { + return p.Summaries +} +func (p *JobSummaryResult_) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.SET { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *JobSummaryResult_) ReadField1(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*JobSummary, 0, size) + p.Summaries = tSet + for i := 0; i < size; i++ { + _elem40 := &JobSummary{} + if err := _elem40.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem40), err) + } + p.Summaries = append(p.Summaries, _elem40) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *JobSummaryResult_) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("JobSummaryResult"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *JobSummaryResult_) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("summaries", thrift.SET, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:summaries: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Summaries)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Summaries); i++ { + for j := i + 1; j < len(p.Summaries); j++ { + if reflect.DeepEqual(p.Summaries[i], p.Summaries[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Summaries[i])) + } + } + } + for _, v := range p.Summaries { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:summaries: ", p), err) + } + return err +} + +func (p *JobSummaryResult_) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("JobSummaryResult_(%+v)", *p) +} + +// Attributes: +// - Summary +type ConfigSummaryResult_ struct { + Summary *ConfigSummary `thrift:"summary,1" db:"summary" json:"summary"` +} + +func NewConfigSummaryResult_() *ConfigSummaryResult_ { + return &ConfigSummaryResult_{} +} + +var ConfigSummaryResult__Summary_DEFAULT *ConfigSummary + +func (p *ConfigSummaryResult_) GetSummary() *ConfigSummary { + if !p.IsSetSummary() { + return ConfigSummaryResult__Summary_DEFAULT + } + return p.Summary +} +func (p *ConfigSummaryResult_) IsSetSummary() bool { + return p.Summary != nil +} + +func (p *ConfigSummaryResult_) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ConfigSummaryResult_) ReadField1(iprot thrift.TProtocol) error { + p.Summary = &ConfigSummary{} + if err := p.Summary.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Summary), err) + } + return nil +} + +func (p *ConfigSummaryResult_) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("ConfigSummaryResult"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ConfigSummaryResult_) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("summary", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:summary: ", p), err) + } + if err := p.Summary.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Summary), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:summary: ", p), err) + } + return err +} + +func (p *ConfigSummaryResult_) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ConfigSummaryResult_(%+v)", *p) +} + +// Attributes: +// - Reasons +type GetPendingReasonResult_ struct { + Reasons []*PendingReason `thrift:"reasons,1" db:"reasons" json:"reasons"` +} + +func NewGetPendingReasonResult_() *GetPendingReasonResult_ { + return &GetPendingReasonResult_{} +} + +func (p *GetPendingReasonResult_) GetReasons() []*PendingReason { + return p.Reasons +} +func (p *GetPendingReasonResult_) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.SET { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *GetPendingReasonResult_) ReadField1(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*PendingReason, 0, size) + p.Reasons = tSet + for i := 0; i < size; i++ { + _elem41 := &PendingReason{} + if err := _elem41.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem41), err) + } + p.Reasons = append(p.Reasons, _elem41) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *GetPendingReasonResult_) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("GetPendingReasonResult"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *GetPendingReasonResult_) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("reasons", thrift.SET, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:reasons: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Reasons)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Reasons); i++ { + for j := i + 1; j < len(p.Reasons); j++ { + if reflect.DeepEqual(p.Reasons[i], p.Reasons[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Reasons[i])) + } + } + } + for _, v := range p.Reasons { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:reasons: ", p), err) + } + return err +} + +func (p *GetPendingReasonResult_) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("GetPendingReasonResult_(%+v)", *p) +} + +// Result of the startUpdate call. +// +// Attributes: +// - Key: Unique identifier for the job update. +// - UpdateSummary: Summary of the update that is in progress for the given JobKey. +type StartJobUpdateResult_ struct { + Key *JobUpdateKey `thrift:"key,1" db:"key" json:"key"` + UpdateSummary *JobUpdateSummary `thrift:"updateSummary,2" db:"updateSummary" json:"updateSummary,omitempty"` +} + +func NewStartJobUpdateResult_() *StartJobUpdateResult_ { + return &StartJobUpdateResult_{} +} + +var StartJobUpdateResult__Key_DEFAULT *JobUpdateKey + +func (p *StartJobUpdateResult_) GetKey() *JobUpdateKey { + if !p.IsSetKey() { + return StartJobUpdateResult__Key_DEFAULT + } + return p.Key +} + +var StartJobUpdateResult__UpdateSummary_DEFAULT *JobUpdateSummary + +func (p *StartJobUpdateResult_) GetUpdateSummary() *JobUpdateSummary { + if !p.IsSetUpdateSummary() { + return StartJobUpdateResult__UpdateSummary_DEFAULT + } + return p.UpdateSummary +} +func (p *StartJobUpdateResult_) IsSetKey() bool { + return p.Key != nil +} + +func (p *StartJobUpdateResult_) IsSetUpdateSummary() bool { + return p.UpdateSummary != nil +} + +func (p *StartJobUpdateResult_) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *StartJobUpdateResult_) ReadField1(iprot thrift.TProtocol) error { + p.Key = &JobUpdateKey{} + if err := p.Key.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) + } + return nil +} + +func (p *StartJobUpdateResult_) ReadField2(iprot thrift.TProtocol) error { + p.UpdateSummary = &JobUpdateSummary{} + if err := p.UpdateSummary.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.UpdateSummary), err) + } + return nil +} + +func (p *StartJobUpdateResult_) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("StartJobUpdateResult"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *StartJobUpdateResult_) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:key: ", p), err) + } + if err := p.Key.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:key: ", p), err) + } + return err +} + +func (p *StartJobUpdateResult_) writeField2(oprot thrift.TProtocol) (err error) { + if p.IsSetUpdateSummary() { + if err := oprot.WriteFieldBegin("updateSummary", thrift.STRUCT, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:updateSummary: ", p), err) + } + if err := p.UpdateSummary.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.UpdateSummary), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:updateSummary: ", p), err) + } + } + return err +} + +func (p *StartJobUpdateResult_) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("StartJobUpdateResult_(%+v)", *p) +} + +// Result of the getJobUpdateSummaries call. +// +// Attributes: +// - UpdateSummaries +type GetJobUpdateSummariesResult_ struct { + UpdateSummaries []*JobUpdateSummary `thrift:"updateSummaries,1" db:"updateSummaries" json:"updateSummaries"` +} + +func NewGetJobUpdateSummariesResult_() *GetJobUpdateSummariesResult_ { + return &GetJobUpdateSummariesResult_{} +} + +func (p *GetJobUpdateSummariesResult_) GetUpdateSummaries() []*JobUpdateSummary { + return p.UpdateSummaries +} +func (p *GetJobUpdateSummariesResult_) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.LIST { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *GetJobUpdateSummariesResult_) ReadField1(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadListBegin() + if err != nil { + return thrift.PrependError("error reading list begin: ", err) + } + tSlice := make([]*JobUpdateSummary, 0, size) + p.UpdateSummaries = tSlice + for i := 0; i < size; i++ { + _elem42 := &JobUpdateSummary{} + if err := _elem42.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem42), err) + } + p.UpdateSummaries = append(p.UpdateSummaries, _elem42) + } + if err := iprot.ReadListEnd(); err != nil { + return thrift.PrependError("error reading list end: ", err) + } + return nil +} + +func (p *GetJobUpdateSummariesResult_) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("GetJobUpdateSummariesResult"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *GetJobUpdateSummariesResult_) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("updateSummaries", thrift.LIST, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:updateSummaries: ", p), err) + } + if err := oprot.WriteListBegin(thrift.STRUCT, len(p.UpdateSummaries)); err != nil { + return thrift.PrependError("error writing list begin: ", err) + } + for _, v := range p.UpdateSummaries { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteListEnd(); err != nil { + return thrift.PrependError("error writing list end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:updateSummaries: ", p), err) + } + return err +} + +func (p *GetJobUpdateSummariesResult_) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("GetJobUpdateSummariesResult_(%+v)", *p) +} + +// Result of the getJobUpdateDetails call. +// +// Attributes: +// - Details +// - DetailsList +type GetJobUpdateDetailsResult_ struct { + Details *JobUpdateDetails `thrift:"details,1" db:"details" json:"details"` + DetailsList []*JobUpdateDetails `thrift:"detailsList,2" db:"detailsList" json:"detailsList"` +} + +func NewGetJobUpdateDetailsResult_() *GetJobUpdateDetailsResult_ { + return &GetJobUpdateDetailsResult_{} +} + +var GetJobUpdateDetailsResult__Details_DEFAULT *JobUpdateDetails + +func (p *GetJobUpdateDetailsResult_) GetDetails() *JobUpdateDetails { + if !p.IsSetDetails() { + return GetJobUpdateDetailsResult__Details_DEFAULT + } + return p.Details +} + +func (p *GetJobUpdateDetailsResult_) GetDetailsList() []*JobUpdateDetails { + return p.DetailsList +} +func (p *GetJobUpdateDetailsResult_) IsSetDetails() bool { + return p.Details != nil +} + +func (p *GetJobUpdateDetailsResult_) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.LIST { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *GetJobUpdateDetailsResult_) ReadField1(iprot thrift.TProtocol) error { + p.Details = &JobUpdateDetails{} + if err := p.Details.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Details), err) + } + return nil +} + +func (p *GetJobUpdateDetailsResult_) ReadField2(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadListBegin() + if err != nil { + return thrift.PrependError("error reading list begin: ", err) + } + tSlice := make([]*JobUpdateDetails, 0, size) + p.DetailsList = tSlice + for i := 0; i < size; i++ { + _elem43 := &JobUpdateDetails{} + if err := _elem43.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem43), err) + } + p.DetailsList = append(p.DetailsList, _elem43) + } + if err := iprot.ReadListEnd(); err != nil { + return thrift.PrependError("error reading list end: ", err) + } + return nil +} + +func (p *GetJobUpdateDetailsResult_) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("GetJobUpdateDetailsResult"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *GetJobUpdateDetailsResult_) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("details", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:details: ", p), err) + } + if err := p.Details.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Details), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:details: ", p), err) + } + return err +} + +func (p *GetJobUpdateDetailsResult_) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("detailsList", thrift.LIST, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:detailsList: ", p), err) + } + if err := oprot.WriteListBegin(thrift.STRUCT, len(p.DetailsList)); err != nil { + return thrift.PrependError("error writing list begin: ", err) + } + for _, v := range p.DetailsList { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteListEnd(); err != nil { + return thrift.PrependError("error writing list end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:detailsList: ", p), err) + } + return err +} + +func (p *GetJobUpdateDetailsResult_) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("GetJobUpdateDetailsResult_(%+v)", *p) +} + +// Result of the pulseJobUpdate call. +// +// Attributes: +// - Status +type PulseJobUpdateResult_ struct { + Status JobUpdatePulseStatus `thrift:"status,1" db:"status" json:"status"` +} + +func NewPulseJobUpdateResult_() *PulseJobUpdateResult_ { + return &PulseJobUpdateResult_{} +} + +func (p *PulseJobUpdateResult_) GetStatus() JobUpdatePulseStatus { + return p.Status +} +func (p *PulseJobUpdateResult_) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.I32 { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *PulseJobUpdateResult_) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + temp := JobUpdatePulseStatus(v) + p.Status = temp + } + return nil +} + +func (p *PulseJobUpdateResult_) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("PulseJobUpdateResult"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *PulseJobUpdateResult_) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("status", thrift.I32, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:status: ", p), err) + } + if err := oprot.WriteI32(int32(p.Status)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.status (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:status: ", p), err) + } + return err +} + +func (p *PulseJobUpdateResult_) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("PulseJobUpdateResult_(%+v)", *p) +} + +// Attributes: +// - Add: Instance addition diff details. +// - Remove: Instance removal diff details. +// - Update: Instance update diff details. +// - Unchanged: Instances unchanged by the update. +type GetJobUpdateDiffResult_ struct { + Add []*ConfigGroup `thrift:"add,1" db:"add" json:"add"` + Remove []*ConfigGroup `thrift:"remove,2" db:"remove" json:"remove"` + Update []*ConfigGroup `thrift:"update,3" db:"update" json:"update"` + Unchanged []*ConfigGroup `thrift:"unchanged,4" db:"unchanged" json:"unchanged"` +} + +func NewGetJobUpdateDiffResult_() *GetJobUpdateDiffResult_ { + return &GetJobUpdateDiffResult_{} +} + +func (p *GetJobUpdateDiffResult_) GetAdd() []*ConfigGroup { + return p.Add +} + +func (p *GetJobUpdateDiffResult_) GetRemove() []*ConfigGroup { + return p.Remove +} + +func (p *GetJobUpdateDiffResult_) GetUpdate() []*ConfigGroup { + return p.Update +} + +func (p *GetJobUpdateDiffResult_) GetUnchanged() []*ConfigGroup { + return p.Unchanged +} +func (p *GetJobUpdateDiffResult_) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.SET { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.SET { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.SET { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 4: + if fieldTypeId == thrift.SET { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *GetJobUpdateDiffResult_) ReadField1(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*ConfigGroup, 0, size) + p.Add = tSet + for i := 0; i < size; i++ { + _elem44 := &ConfigGroup{} + if err := _elem44.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem44), err) + } + p.Add = append(p.Add, _elem44) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *GetJobUpdateDiffResult_) ReadField2(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*ConfigGroup, 0, size) + p.Remove = tSet + for i := 0; i < size; i++ { + _elem45 := &ConfigGroup{} + if err := _elem45.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem45), err) + } + p.Remove = append(p.Remove, _elem45) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *GetJobUpdateDiffResult_) ReadField3(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*ConfigGroup, 0, size) + p.Update = tSet + for i := 0; i < size; i++ { + _elem46 := &ConfigGroup{} + if err := _elem46.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem46), err) + } + p.Update = append(p.Update, _elem46) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *GetJobUpdateDiffResult_) ReadField4(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*ConfigGroup, 0, size) + p.Unchanged = tSet + for i := 0; i < size; i++ { + _elem47 := &ConfigGroup{} + if err := _elem47.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem47), err) + } + p.Unchanged = append(p.Unchanged, _elem47) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *GetJobUpdateDiffResult_) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("GetJobUpdateDiffResult"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + if err := p.writeField4(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *GetJobUpdateDiffResult_) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("add", thrift.SET, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:add: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Add)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Add); i++ { + for j := i + 1; j < len(p.Add); j++ { + if reflect.DeepEqual(p.Add[i], p.Add[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Add[i])) + } + } + } + for _, v := range p.Add { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:add: ", p), err) + } + return err +} + +func (p *GetJobUpdateDiffResult_) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("remove", thrift.SET, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:remove: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Remove)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Remove); i++ { + for j := i + 1; j < len(p.Remove); j++ { + if reflect.DeepEqual(p.Remove[i], p.Remove[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Remove[i])) + } + } + } + for _, v := range p.Remove { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:remove: ", p), err) + } + return err +} + +func (p *GetJobUpdateDiffResult_) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("update", thrift.SET, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:update: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Update)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Update); i++ { + for j := i + 1; j < len(p.Update); j++ { + if reflect.DeepEqual(p.Update[i], p.Update[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Update[i])) + } + } + } + for _, v := range p.Update { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:update: ", p), err) + } + return err +} + +func (p *GetJobUpdateDiffResult_) writeField4(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("unchanged", thrift.SET, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:unchanged: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Unchanged)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Unchanged); i++ { + for j := i + 1; j < len(p.Unchanged); j++ { + if reflect.DeepEqual(p.Unchanged[i], p.Unchanged[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Unchanged[i])) + } + } + } + for _, v := range p.Unchanged { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:unchanged: ", p), err) + } + return err +} + +func (p *GetJobUpdateDiffResult_) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("GetJobUpdateDiffResult_(%+v)", *p) +} + +// Tier information. +// +// Attributes: +// - Name: Name of tier. +// - Settings: Tier attributes. +type TierConfig struct { + Name string `thrift:"name,1" db:"name" json:"name"` + Settings map[string]string `thrift:"settings,2" db:"settings" json:"settings"` +} + +func NewTierConfig() *TierConfig { + return &TierConfig{} +} + +func (p *TierConfig) GetName() string { + return p.Name +} + +func (p *TierConfig) GetSettings() map[string]string { + return p.Settings +} +func (p *TierConfig) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.MAP { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *TierConfig) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Name = v + } + return nil +} + +func (p *TierConfig) ReadField2(iprot thrift.TProtocol) error { + _, _, size, err := iprot.ReadMapBegin() + if err != nil { + return thrift.PrependError("error reading map begin: ", err) + } + tMap := make(map[string]string, size) + p.Settings = tMap + for i := 0; i < size; i++ { + var _key48 string + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 0: ", err) + } else { + _key48 = v + } + var _val49 string + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 0: ", err) + } else { + _val49 = v + } + p.Settings[_key48] = _val49 + } + if err := iprot.ReadMapEnd(); err != nil { + return thrift.PrependError("error reading map end: ", err) + } + return nil +} + +func (p *TierConfig) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("TierConfig"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *TierConfig) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("name", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:name: ", p), err) + } + if err := oprot.WriteString(string(p.Name)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.name (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:name: ", p), err) + } + return err +} + +func (p *TierConfig) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("settings", thrift.MAP, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:settings: ", p), err) + } + if err := oprot.WriteMapBegin(thrift.STRING, thrift.STRING, len(p.Settings)); err != nil { + return thrift.PrependError("error writing map begin: ", err) + } + for k, v := range p.Settings { + if err := oprot.WriteString(string(k)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) + } + if err := oprot.WriteString(string(v)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) + } + } + if err := oprot.WriteMapEnd(); err != nil { + return thrift.PrependError("error writing map end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:settings: ", p), err) + } + return err +} + +func (p *TierConfig) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("TierConfig(%+v)", *p) +} + +// Result of the getTierConfigResult call. +// +// Attributes: +// - DefaultTierName: Name of the default tier. +// - Tiers: Set of tier configurations. +type GetTierConfigResult_ struct { + DefaultTierName string `thrift:"defaultTierName,1" db:"defaultTierName" json:"defaultTierName"` + Tiers []*TierConfig `thrift:"tiers,2" db:"tiers" json:"tiers"` +} + +func NewGetTierConfigResult_() *GetTierConfigResult_ { + return &GetTierConfigResult_{} +} + +func (p *GetTierConfigResult_) GetDefaultTierName() string { + return p.DefaultTierName +} + +func (p *GetTierConfigResult_) GetTiers() []*TierConfig { + return p.Tiers +} +func (p *GetTierConfigResult_) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.SET { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *GetTierConfigResult_) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.DefaultTierName = v + } + return nil +} + +func (p *GetTierConfigResult_) ReadField2(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]*TierConfig, 0, size) + p.Tiers = tSet + for i := 0; i < size; i++ { + _elem50 := &TierConfig{} + if err := _elem50.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem50), err) + } + p.Tiers = append(p.Tiers, _elem50) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *GetTierConfigResult_) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("GetTierConfigResult"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *GetTierConfigResult_) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("defaultTierName", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:defaultTierName: ", p), err) + } + if err := oprot.WriteString(string(p.DefaultTierName)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.defaultTierName (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:defaultTierName: ", p), err) + } + return err +} + +func (p *GetTierConfigResult_) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("tiers", thrift.SET, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:tiers: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Tiers)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Tiers); i++ { + for j := i + 1; j < len(p.Tiers); j++ { + if reflect.DeepEqual(p.Tiers[i], p.Tiers[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Tiers[i])) + } + } + } + for _, v := range p.Tiers { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:tiers: ", p), err) + } + return err +} + +func (p *GetTierConfigResult_) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("GetTierConfigResult_(%+v)", *p) +} + +// Information about the scheduler. +// +// Attributes: +// - ClusterName +// - StatsUrlPrefix: A url prefix for job container stats. +type ServerInfo struct { + ClusterName string `thrift:"clusterName,1" db:"clusterName" json:"clusterName"` + // unused field # 2 + StatsUrlPrefix string `thrift:"statsUrlPrefix,3" db:"statsUrlPrefix" json:"statsUrlPrefix"` +} + +func NewServerInfo() *ServerInfo { + return &ServerInfo{} +} + +func (p *ServerInfo) GetClusterName() string { + return p.ClusterName +} + +func (p *ServerInfo) GetStatsUrlPrefix() string { + return p.StatsUrlPrefix +} +func (p *ServerInfo) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.STRING { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ServerInfo) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.ClusterName = v + } + return nil +} + +func (p *ServerInfo) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.StatsUrlPrefix = v + } + return nil +} + +func (p *ServerInfo) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("ServerInfo"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ServerInfo) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("clusterName", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:clusterName: ", p), err) + } + if err := oprot.WriteString(string(p.ClusterName)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.clusterName (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:clusterName: ", p), err) + } + return err +} + +func (p *ServerInfo) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("statsUrlPrefix", thrift.STRING, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:statsUrlPrefix: ", p), err) + } + if err := oprot.WriteString(string(p.StatsUrlPrefix)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.statsUrlPrefix (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:statsUrlPrefix: ", p), err) + } + return err +} + +func (p *ServerInfo) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ServerInfo(%+v)", *p) +} + +// Attributes: +// - PopulateJobResult_ +// - ScheduleStatusResult_ +// - GetJobsResult_ +// - GetQuotaResult_ +// - ListBackupsResult_ +// - StartMaintenanceResult_ +// - DrainHostsResult_ +// - QueryRecoveryResult_ +// - MaintenanceStatusResult_ +// - EndMaintenanceResult_ +// - RoleSummaryResult_ +// - JobSummaryResult_ +// - ConfigSummaryResult_ +// - GetPendingReasonResult_ +// - StartJobUpdateResult_ +// - GetJobUpdateSummariesResult_ +// - GetJobUpdateDetailsResult_ +// - PulseJobUpdateResult_ +// - GetJobUpdateDiffResult_ +// - GetTierConfigResult_ +type Result_ struct { + PopulateJobResult_ *PopulateJobResult_ `thrift:"populateJobResult,1" db:"populateJobResult" json:"populateJobResult,omitempty"` + // unused field # 2 + ScheduleStatusResult_ *ScheduleStatusResult_ `thrift:"scheduleStatusResult,3" db:"scheduleStatusResult" json:"scheduleStatusResult,omitempty"` + GetJobsResult_ *GetJobsResult_ `thrift:"getJobsResult,4" db:"getJobsResult" json:"getJobsResult,omitempty"` + GetQuotaResult_ *GetQuotaResult_ `thrift:"getQuotaResult,5" db:"getQuotaResult" json:"getQuotaResult,omitempty"` + ListBackupsResult_ *ListBackupsResult_ `thrift:"listBackupsResult,6" db:"listBackupsResult" json:"listBackupsResult,omitempty"` + StartMaintenanceResult_ *StartMaintenanceResult_ `thrift:"startMaintenanceResult,7" db:"startMaintenanceResult" json:"startMaintenanceResult,omitempty"` + DrainHostsResult_ *DrainHostsResult_ `thrift:"drainHostsResult,8" db:"drainHostsResult" json:"drainHostsResult,omitempty"` + QueryRecoveryResult_ *QueryRecoveryResult_ `thrift:"queryRecoveryResult,9" db:"queryRecoveryResult" json:"queryRecoveryResult,omitempty"` + MaintenanceStatusResult_ *MaintenanceStatusResult_ `thrift:"maintenanceStatusResult,10" db:"maintenanceStatusResult" json:"maintenanceStatusResult,omitempty"` + EndMaintenanceResult_ *EndMaintenanceResult_ `thrift:"endMaintenanceResult,11" db:"endMaintenanceResult" json:"endMaintenanceResult,omitempty"` + // unused fields # 12 to 16 + RoleSummaryResult_ *RoleSummaryResult_ `thrift:"roleSummaryResult,17" db:"roleSummaryResult" json:"roleSummaryResult,omitempty"` + JobSummaryResult_ *JobSummaryResult_ `thrift:"jobSummaryResult,18" db:"jobSummaryResult" json:"jobSummaryResult,omitempty"` + // unused field # 19 + ConfigSummaryResult_ *ConfigSummaryResult_ `thrift:"configSummaryResult,20" db:"configSummaryResult" json:"configSummaryResult,omitempty"` + GetPendingReasonResult_ *GetPendingReasonResult_ `thrift:"getPendingReasonResult,21" db:"getPendingReasonResult" json:"getPendingReasonResult,omitempty"` + StartJobUpdateResult_ *StartJobUpdateResult_ `thrift:"startJobUpdateResult,22" db:"startJobUpdateResult" json:"startJobUpdateResult,omitempty"` + GetJobUpdateSummariesResult_ *GetJobUpdateSummariesResult_ `thrift:"getJobUpdateSummariesResult,23" db:"getJobUpdateSummariesResult" json:"getJobUpdateSummariesResult,omitempty"` + GetJobUpdateDetailsResult_ *GetJobUpdateDetailsResult_ `thrift:"getJobUpdateDetailsResult,24" db:"getJobUpdateDetailsResult" json:"getJobUpdateDetailsResult,omitempty"` + PulseJobUpdateResult_ *PulseJobUpdateResult_ `thrift:"pulseJobUpdateResult,25" db:"pulseJobUpdateResult" json:"pulseJobUpdateResult,omitempty"` + GetJobUpdateDiffResult_ *GetJobUpdateDiffResult_ `thrift:"getJobUpdateDiffResult,26" db:"getJobUpdateDiffResult" json:"getJobUpdateDiffResult,omitempty"` + GetTierConfigResult_ *GetTierConfigResult_ `thrift:"getTierConfigResult,27" db:"getTierConfigResult" json:"getTierConfigResult,omitempty"` +} + +func NewResult_() *Result_ { + return &Result_{} +} + +var Result__PopulateJobResult__DEFAULT *PopulateJobResult_ + +func (p *Result_) GetPopulateJobResult_() *PopulateJobResult_ { + if !p.IsSetPopulateJobResult_() { + return Result__PopulateJobResult__DEFAULT + } + return p.PopulateJobResult_ +} + +var Result__ScheduleStatusResult__DEFAULT *ScheduleStatusResult_ + +func (p *Result_) GetScheduleStatusResult_() *ScheduleStatusResult_ { + if !p.IsSetScheduleStatusResult_() { + return Result__ScheduleStatusResult__DEFAULT + } + return p.ScheduleStatusResult_ +} + +var Result__GetJobsResult__DEFAULT *GetJobsResult_ + +func (p *Result_) GetGetJobsResult_() *GetJobsResult_ { + if !p.IsSetGetJobsResult_() { + return Result__GetJobsResult__DEFAULT + } + return p.GetJobsResult_ +} + +var Result__GetQuotaResult__DEFAULT *GetQuotaResult_ + +func (p *Result_) GetGetQuotaResult_() *GetQuotaResult_ { + if !p.IsSetGetQuotaResult_() { + return Result__GetQuotaResult__DEFAULT + } + return p.GetQuotaResult_ +} + +var Result__ListBackupsResult__DEFAULT *ListBackupsResult_ + +func (p *Result_) GetListBackupsResult_() *ListBackupsResult_ { + if !p.IsSetListBackupsResult_() { + return Result__ListBackupsResult__DEFAULT + } + return p.ListBackupsResult_ +} + +var Result__StartMaintenanceResult__DEFAULT *StartMaintenanceResult_ + +func (p *Result_) GetStartMaintenanceResult_() *StartMaintenanceResult_ { + if !p.IsSetStartMaintenanceResult_() { + return Result__StartMaintenanceResult__DEFAULT + } + return p.StartMaintenanceResult_ +} + +var Result__DrainHostsResult__DEFAULT *DrainHostsResult_ + +func (p *Result_) GetDrainHostsResult_() *DrainHostsResult_ { + if !p.IsSetDrainHostsResult_() { + return Result__DrainHostsResult__DEFAULT + } + return p.DrainHostsResult_ +} + +var Result__QueryRecoveryResult__DEFAULT *QueryRecoveryResult_ + +func (p *Result_) GetQueryRecoveryResult_() *QueryRecoveryResult_ { + if !p.IsSetQueryRecoveryResult_() { + return Result__QueryRecoveryResult__DEFAULT + } + return p.QueryRecoveryResult_ +} + +var Result__MaintenanceStatusResult__DEFAULT *MaintenanceStatusResult_ + +func (p *Result_) GetMaintenanceStatusResult_() *MaintenanceStatusResult_ { + if !p.IsSetMaintenanceStatusResult_() { + return Result__MaintenanceStatusResult__DEFAULT + } + return p.MaintenanceStatusResult_ +} + +var Result__EndMaintenanceResult__DEFAULT *EndMaintenanceResult_ + +func (p *Result_) GetEndMaintenanceResult_() *EndMaintenanceResult_ { + if !p.IsSetEndMaintenanceResult_() { + return Result__EndMaintenanceResult__DEFAULT + } + return p.EndMaintenanceResult_ +} + +var Result__RoleSummaryResult__DEFAULT *RoleSummaryResult_ + +func (p *Result_) GetRoleSummaryResult_() *RoleSummaryResult_ { + if !p.IsSetRoleSummaryResult_() { + return Result__RoleSummaryResult__DEFAULT + } + return p.RoleSummaryResult_ +} + +var Result__JobSummaryResult__DEFAULT *JobSummaryResult_ + +func (p *Result_) GetJobSummaryResult_() *JobSummaryResult_ { + if !p.IsSetJobSummaryResult_() { + return Result__JobSummaryResult__DEFAULT + } + return p.JobSummaryResult_ +} + +var Result__ConfigSummaryResult__DEFAULT *ConfigSummaryResult_ + +func (p *Result_) GetConfigSummaryResult_() *ConfigSummaryResult_ { + if !p.IsSetConfigSummaryResult_() { + return Result__ConfigSummaryResult__DEFAULT + } + return p.ConfigSummaryResult_ +} + +var Result__GetPendingReasonResult__DEFAULT *GetPendingReasonResult_ + +func (p *Result_) GetGetPendingReasonResult_() *GetPendingReasonResult_ { + if !p.IsSetGetPendingReasonResult_() { + return Result__GetPendingReasonResult__DEFAULT + } + return p.GetPendingReasonResult_ +} + +var Result__StartJobUpdateResult__DEFAULT *StartJobUpdateResult_ + +func (p *Result_) GetStartJobUpdateResult_() *StartJobUpdateResult_ { + if !p.IsSetStartJobUpdateResult_() { + return Result__StartJobUpdateResult__DEFAULT + } + return p.StartJobUpdateResult_ +} + +var Result__GetJobUpdateSummariesResult__DEFAULT *GetJobUpdateSummariesResult_ + +func (p *Result_) GetGetJobUpdateSummariesResult_() *GetJobUpdateSummariesResult_ { + if !p.IsSetGetJobUpdateSummariesResult_() { + return Result__GetJobUpdateSummariesResult__DEFAULT + } + return p.GetJobUpdateSummariesResult_ +} + +var Result__GetJobUpdateDetailsResult__DEFAULT *GetJobUpdateDetailsResult_ + +func (p *Result_) GetGetJobUpdateDetailsResult_() *GetJobUpdateDetailsResult_ { + if !p.IsSetGetJobUpdateDetailsResult_() { + return Result__GetJobUpdateDetailsResult__DEFAULT + } + return p.GetJobUpdateDetailsResult_ +} + +var Result__PulseJobUpdateResult__DEFAULT *PulseJobUpdateResult_ + +func (p *Result_) GetPulseJobUpdateResult_() *PulseJobUpdateResult_ { + if !p.IsSetPulseJobUpdateResult_() { + return Result__PulseJobUpdateResult__DEFAULT + } + return p.PulseJobUpdateResult_ +} + +var Result__GetJobUpdateDiffResult__DEFAULT *GetJobUpdateDiffResult_ + +func (p *Result_) GetGetJobUpdateDiffResult_() *GetJobUpdateDiffResult_ { + if !p.IsSetGetJobUpdateDiffResult_() { + return Result__GetJobUpdateDiffResult__DEFAULT + } + return p.GetJobUpdateDiffResult_ +} + +var Result__GetTierConfigResult__DEFAULT *GetTierConfigResult_ + +func (p *Result_) GetGetTierConfigResult_() *GetTierConfigResult_ { + if !p.IsSetGetTierConfigResult_() { + return Result__GetTierConfigResult__DEFAULT + } + return p.GetTierConfigResult_ +} +func (p *Result_) CountSetFieldsResult_() int { + count := 0 + if p.IsSetPopulateJobResult_() { + count++ + } + if p.IsSetScheduleStatusResult_() { + count++ + } + if p.IsSetGetJobsResult_() { + count++ + } + if p.IsSetGetQuotaResult_() { + count++ + } + if p.IsSetListBackupsResult_() { + count++ + } + if p.IsSetStartMaintenanceResult_() { + count++ + } + if p.IsSetDrainHostsResult_() { + count++ + } + if p.IsSetQueryRecoveryResult_() { + count++ + } + if p.IsSetMaintenanceStatusResult_() { + count++ + } + if p.IsSetEndMaintenanceResult_() { + count++ + } + if p.IsSetRoleSummaryResult_() { + count++ + } + if p.IsSetJobSummaryResult_() { + count++ + } + if p.IsSetConfigSummaryResult_() { + count++ + } + if p.IsSetGetPendingReasonResult_() { + count++ + } + if p.IsSetStartJobUpdateResult_() { + count++ + } + if p.IsSetGetJobUpdateSummariesResult_() { + count++ + } + if p.IsSetGetJobUpdateDetailsResult_() { + count++ + } + if p.IsSetPulseJobUpdateResult_() { + count++ + } + if p.IsSetGetJobUpdateDiffResult_() { + count++ + } + if p.IsSetGetTierConfigResult_() { + count++ + } + return count + +} + +func (p *Result_) IsSetPopulateJobResult_() bool { + return p.PopulateJobResult_ != nil +} + +func (p *Result_) IsSetScheduleStatusResult_() bool { + return p.ScheduleStatusResult_ != nil +} + +func (p *Result_) IsSetGetJobsResult_() bool { + return p.GetJobsResult_ != nil +} + +func (p *Result_) IsSetGetQuotaResult_() bool { + return p.GetQuotaResult_ != nil +} + +func (p *Result_) IsSetListBackupsResult_() bool { + return p.ListBackupsResult_ != nil +} + +func (p *Result_) IsSetStartMaintenanceResult_() bool { + return p.StartMaintenanceResult_ != nil +} + +func (p *Result_) IsSetDrainHostsResult_() bool { + return p.DrainHostsResult_ != nil +} + +func (p *Result_) IsSetQueryRecoveryResult_() bool { + return p.QueryRecoveryResult_ != nil +} + +func (p *Result_) IsSetMaintenanceStatusResult_() bool { + return p.MaintenanceStatusResult_ != nil +} + +func (p *Result_) IsSetEndMaintenanceResult_() bool { + return p.EndMaintenanceResult_ != nil +} + +func (p *Result_) IsSetRoleSummaryResult_() bool { + return p.RoleSummaryResult_ != nil +} + +func (p *Result_) IsSetJobSummaryResult_() bool { + return p.JobSummaryResult_ != nil +} + +func (p *Result_) IsSetConfigSummaryResult_() bool { + return p.ConfigSummaryResult_ != nil +} + +func (p *Result_) IsSetGetPendingReasonResult_() bool { + return p.GetPendingReasonResult_ != nil +} + +func (p *Result_) IsSetStartJobUpdateResult_() bool { + return p.StartJobUpdateResult_ != nil +} + +func (p *Result_) IsSetGetJobUpdateSummariesResult_() bool { + return p.GetJobUpdateSummariesResult_ != nil +} + +func (p *Result_) IsSetGetJobUpdateDetailsResult_() bool { + return p.GetJobUpdateDetailsResult_ != nil +} + +func (p *Result_) IsSetPulseJobUpdateResult_() bool { + return p.PulseJobUpdateResult_ != nil +} + +func (p *Result_) IsSetGetJobUpdateDiffResult_() bool { + return p.GetJobUpdateDiffResult_ != nil +} + +func (p *Result_) IsSetGetTierConfigResult_() bool { + return p.GetTierConfigResult_ != nil +} + +func (p *Result_) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 4: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 5: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField5(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 6: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField6(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 7: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField7(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 8: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField8(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 9: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField9(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 10: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField10(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 11: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField11(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 17: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField17(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 18: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField18(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 20: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField20(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 21: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField21(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 22: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField22(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 23: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField23(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 24: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField24(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 25: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField25(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 26: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField26(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 27: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField27(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *Result_) ReadField1(iprot thrift.TProtocol) error { + p.PopulateJobResult_ = &PopulateJobResult_{} + if err := p.PopulateJobResult_.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.PopulateJobResult_), err) + } + return nil +} + +func (p *Result_) ReadField3(iprot thrift.TProtocol) error { + p.ScheduleStatusResult_ = &ScheduleStatusResult_{} + if err := p.ScheduleStatusResult_.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.ScheduleStatusResult_), err) + } + return nil +} + +func (p *Result_) ReadField4(iprot thrift.TProtocol) error { + p.GetJobsResult_ = &GetJobsResult_{} + if err := p.GetJobsResult_.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.GetJobsResult_), err) + } + return nil +} + +func (p *Result_) ReadField5(iprot thrift.TProtocol) error { + p.GetQuotaResult_ = &GetQuotaResult_{} + if err := p.GetQuotaResult_.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.GetQuotaResult_), err) + } + return nil +} + +func (p *Result_) ReadField6(iprot thrift.TProtocol) error { + p.ListBackupsResult_ = &ListBackupsResult_{} + if err := p.ListBackupsResult_.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.ListBackupsResult_), err) + } + return nil +} + +func (p *Result_) ReadField7(iprot thrift.TProtocol) error { + p.StartMaintenanceResult_ = &StartMaintenanceResult_{} + if err := p.StartMaintenanceResult_.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.StartMaintenanceResult_), err) + } + return nil +} + +func (p *Result_) ReadField8(iprot thrift.TProtocol) error { + p.DrainHostsResult_ = &DrainHostsResult_{} + if err := p.DrainHostsResult_.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.DrainHostsResult_), err) + } + return nil +} + +func (p *Result_) ReadField9(iprot thrift.TProtocol) error { + p.QueryRecoveryResult_ = &QueryRecoveryResult_{} + if err := p.QueryRecoveryResult_.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.QueryRecoveryResult_), err) + } + return nil +} + +func (p *Result_) ReadField10(iprot thrift.TProtocol) error { + p.MaintenanceStatusResult_ = &MaintenanceStatusResult_{} + if err := p.MaintenanceStatusResult_.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.MaintenanceStatusResult_), err) + } + return nil +} + +func (p *Result_) ReadField11(iprot thrift.TProtocol) error { + p.EndMaintenanceResult_ = &EndMaintenanceResult_{} + if err := p.EndMaintenanceResult_.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.EndMaintenanceResult_), err) + } + return nil +} + +func (p *Result_) ReadField17(iprot thrift.TProtocol) error { + p.RoleSummaryResult_ = &RoleSummaryResult_{} + if err := p.RoleSummaryResult_.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.RoleSummaryResult_), err) + } + return nil +} + +func (p *Result_) ReadField18(iprot thrift.TProtocol) error { + p.JobSummaryResult_ = &JobSummaryResult_{} + if err := p.JobSummaryResult_.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.JobSummaryResult_), err) + } + return nil +} + +func (p *Result_) ReadField20(iprot thrift.TProtocol) error { + p.ConfigSummaryResult_ = &ConfigSummaryResult_{} + if err := p.ConfigSummaryResult_.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.ConfigSummaryResult_), err) + } + return nil +} + +func (p *Result_) ReadField21(iprot thrift.TProtocol) error { + p.GetPendingReasonResult_ = &GetPendingReasonResult_{} + if err := p.GetPendingReasonResult_.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.GetPendingReasonResult_), err) + } + return nil +} + +func (p *Result_) ReadField22(iprot thrift.TProtocol) error { + p.StartJobUpdateResult_ = &StartJobUpdateResult_{} + if err := p.StartJobUpdateResult_.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.StartJobUpdateResult_), err) + } + return nil +} + +func (p *Result_) ReadField23(iprot thrift.TProtocol) error { + p.GetJobUpdateSummariesResult_ = &GetJobUpdateSummariesResult_{} + if err := p.GetJobUpdateSummariesResult_.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.GetJobUpdateSummariesResult_), err) + } + return nil +} + +func (p *Result_) ReadField24(iprot thrift.TProtocol) error { + p.GetJobUpdateDetailsResult_ = &GetJobUpdateDetailsResult_{} + if err := p.GetJobUpdateDetailsResult_.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.GetJobUpdateDetailsResult_), err) + } + return nil +} + +func (p *Result_) ReadField25(iprot thrift.TProtocol) error { + p.PulseJobUpdateResult_ = &PulseJobUpdateResult_{} + if err := p.PulseJobUpdateResult_.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.PulseJobUpdateResult_), err) + } + return nil +} + +func (p *Result_) ReadField26(iprot thrift.TProtocol) error { + p.GetJobUpdateDiffResult_ = &GetJobUpdateDiffResult_{} + if err := p.GetJobUpdateDiffResult_.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.GetJobUpdateDiffResult_), err) + } + return nil +} + +func (p *Result_) ReadField27(iprot thrift.TProtocol) error { + p.GetTierConfigResult_ = &GetTierConfigResult_{} + if err := p.GetTierConfigResult_.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.GetTierConfigResult_), err) + } + return nil +} + +func (p *Result_) Write(oprot thrift.TProtocol) error { + if c := p.CountSetFieldsResult_(); c != 1 { + return fmt.Errorf("%T write union: exactly one field must be set (%d set).", p, c) + } + if err := oprot.WriteStructBegin("Result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + if err := p.writeField4(oprot); err != nil { + return err + } + if err := p.writeField5(oprot); err != nil { + return err + } + if err := p.writeField6(oprot); err != nil { + return err + } + if err := p.writeField7(oprot); err != nil { + return err + } + if err := p.writeField8(oprot); err != nil { + return err + } + if err := p.writeField9(oprot); err != nil { + return err + } + if err := p.writeField10(oprot); err != nil { + return err + } + if err := p.writeField11(oprot); err != nil { + return err + } + if err := p.writeField17(oprot); err != nil { + return err + } + if err := p.writeField18(oprot); err != nil { + return err + } + if err := p.writeField20(oprot); err != nil { + return err + } + if err := p.writeField21(oprot); err != nil { + return err + } + if err := p.writeField22(oprot); err != nil { + return err + } + if err := p.writeField23(oprot); err != nil { + return err + } + if err := p.writeField24(oprot); err != nil { + return err + } + if err := p.writeField25(oprot); err != nil { + return err + } + if err := p.writeField26(oprot); err != nil { + return err + } + if err := p.writeField27(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *Result_) writeField1(oprot thrift.TProtocol) (err error) { + if p.IsSetPopulateJobResult_() { + if err := oprot.WriteFieldBegin("populateJobResult", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:populateJobResult: ", p), err) + } + if err := p.PopulateJobResult_.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.PopulateJobResult_), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:populateJobResult: ", p), err) + } + } + return err +} + +func (p *Result_) writeField3(oprot thrift.TProtocol) (err error) { + if p.IsSetScheduleStatusResult_() { + if err := oprot.WriteFieldBegin("scheduleStatusResult", thrift.STRUCT, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:scheduleStatusResult: ", p), err) + } + if err := p.ScheduleStatusResult_.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.ScheduleStatusResult_), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:scheduleStatusResult: ", p), err) + } + } + return err +} + +func (p *Result_) writeField4(oprot thrift.TProtocol) (err error) { + if p.IsSetGetJobsResult_() { + if err := oprot.WriteFieldBegin("getJobsResult", thrift.STRUCT, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:getJobsResult: ", p), err) + } + if err := p.GetJobsResult_.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.GetJobsResult_), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:getJobsResult: ", p), err) + } + } + return err +} + +func (p *Result_) writeField5(oprot thrift.TProtocol) (err error) { + if p.IsSetGetQuotaResult_() { + if err := oprot.WriteFieldBegin("getQuotaResult", thrift.STRUCT, 5); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:getQuotaResult: ", p), err) + } + if err := p.GetQuotaResult_.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.GetQuotaResult_), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 5:getQuotaResult: ", p), err) + } + } + return err +} + +func (p *Result_) writeField6(oprot thrift.TProtocol) (err error) { + if p.IsSetListBackupsResult_() { + if err := oprot.WriteFieldBegin("listBackupsResult", thrift.STRUCT, 6); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 6:listBackupsResult: ", p), err) + } + if err := p.ListBackupsResult_.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.ListBackupsResult_), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 6:listBackupsResult: ", p), err) + } + } + return err +} + +func (p *Result_) writeField7(oprot thrift.TProtocol) (err error) { + if p.IsSetStartMaintenanceResult_() { + if err := oprot.WriteFieldBegin("startMaintenanceResult", thrift.STRUCT, 7); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 7:startMaintenanceResult: ", p), err) + } + if err := p.StartMaintenanceResult_.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.StartMaintenanceResult_), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 7:startMaintenanceResult: ", p), err) + } + } + return err +} + +func (p *Result_) writeField8(oprot thrift.TProtocol) (err error) { + if p.IsSetDrainHostsResult_() { + if err := oprot.WriteFieldBegin("drainHostsResult", thrift.STRUCT, 8); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 8:drainHostsResult: ", p), err) + } + if err := p.DrainHostsResult_.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.DrainHostsResult_), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 8:drainHostsResult: ", p), err) + } + } + return err +} + +func (p *Result_) writeField9(oprot thrift.TProtocol) (err error) { + if p.IsSetQueryRecoveryResult_() { + if err := oprot.WriteFieldBegin("queryRecoveryResult", thrift.STRUCT, 9); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 9:queryRecoveryResult: ", p), err) + } + if err := p.QueryRecoveryResult_.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.QueryRecoveryResult_), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 9:queryRecoveryResult: ", p), err) + } + } + return err +} + +func (p *Result_) writeField10(oprot thrift.TProtocol) (err error) { + if p.IsSetMaintenanceStatusResult_() { + if err := oprot.WriteFieldBegin("maintenanceStatusResult", thrift.STRUCT, 10); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 10:maintenanceStatusResult: ", p), err) + } + if err := p.MaintenanceStatusResult_.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.MaintenanceStatusResult_), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 10:maintenanceStatusResult: ", p), err) + } + } + return err +} + +func (p *Result_) writeField11(oprot thrift.TProtocol) (err error) { + if p.IsSetEndMaintenanceResult_() { + if err := oprot.WriteFieldBegin("endMaintenanceResult", thrift.STRUCT, 11); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 11:endMaintenanceResult: ", p), err) + } + if err := p.EndMaintenanceResult_.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.EndMaintenanceResult_), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 11:endMaintenanceResult: ", p), err) + } + } + return err +} + +func (p *Result_) writeField17(oprot thrift.TProtocol) (err error) { + if p.IsSetRoleSummaryResult_() { + if err := oprot.WriteFieldBegin("roleSummaryResult", thrift.STRUCT, 17); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 17:roleSummaryResult: ", p), err) + } + if err := p.RoleSummaryResult_.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.RoleSummaryResult_), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 17:roleSummaryResult: ", p), err) + } + } + return err +} + +func (p *Result_) writeField18(oprot thrift.TProtocol) (err error) { + if p.IsSetJobSummaryResult_() { + if err := oprot.WriteFieldBegin("jobSummaryResult", thrift.STRUCT, 18); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 18:jobSummaryResult: ", p), err) + } + if err := p.JobSummaryResult_.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.JobSummaryResult_), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 18:jobSummaryResult: ", p), err) + } + } + return err +} + +func (p *Result_) writeField20(oprot thrift.TProtocol) (err error) { + if p.IsSetConfigSummaryResult_() { + if err := oprot.WriteFieldBegin("configSummaryResult", thrift.STRUCT, 20); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 20:configSummaryResult: ", p), err) + } + if err := p.ConfigSummaryResult_.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.ConfigSummaryResult_), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 20:configSummaryResult: ", p), err) + } + } + return err +} + +func (p *Result_) writeField21(oprot thrift.TProtocol) (err error) { + if p.IsSetGetPendingReasonResult_() { + if err := oprot.WriteFieldBegin("getPendingReasonResult", thrift.STRUCT, 21); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 21:getPendingReasonResult: ", p), err) + } + if err := p.GetPendingReasonResult_.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.GetPendingReasonResult_), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 21:getPendingReasonResult: ", p), err) + } + } + return err +} + +func (p *Result_) writeField22(oprot thrift.TProtocol) (err error) { + if p.IsSetStartJobUpdateResult_() { + if err := oprot.WriteFieldBegin("startJobUpdateResult", thrift.STRUCT, 22); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 22:startJobUpdateResult: ", p), err) + } + if err := p.StartJobUpdateResult_.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.StartJobUpdateResult_), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 22:startJobUpdateResult: ", p), err) + } + } + return err +} + +func (p *Result_) writeField23(oprot thrift.TProtocol) (err error) { + if p.IsSetGetJobUpdateSummariesResult_() { + if err := oprot.WriteFieldBegin("getJobUpdateSummariesResult", thrift.STRUCT, 23); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 23:getJobUpdateSummariesResult: ", p), err) + } + if err := p.GetJobUpdateSummariesResult_.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.GetJobUpdateSummariesResult_), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 23:getJobUpdateSummariesResult: ", p), err) + } + } + return err +} + +func (p *Result_) writeField24(oprot thrift.TProtocol) (err error) { + if p.IsSetGetJobUpdateDetailsResult_() { + if err := oprot.WriteFieldBegin("getJobUpdateDetailsResult", thrift.STRUCT, 24); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 24:getJobUpdateDetailsResult: ", p), err) + } + if err := p.GetJobUpdateDetailsResult_.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.GetJobUpdateDetailsResult_), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 24:getJobUpdateDetailsResult: ", p), err) + } + } + return err +} + +func (p *Result_) writeField25(oprot thrift.TProtocol) (err error) { + if p.IsSetPulseJobUpdateResult_() { + if err := oprot.WriteFieldBegin("pulseJobUpdateResult", thrift.STRUCT, 25); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 25:pulseJobUpdateResult: ", p), err) + } + if err := p.PulseJobUpdateResult_.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.PulseJobUpdateResult_), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 25:pulseJobUpdateResult: ", p), err) + } + } + return err +} + +func (p *Result_) writeField26(oprot thrift.TProtocol) (err error) { + if p.IsSetGetJobUpdateDiffResult_() { + if err := oprot.WriteFieldBegin("getJobUpdateDiffResult", thrift.STRUCT, 26); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 26:getJobUpdateDiffResult: ", p), err) + } + if err := p.GetJobUpdateDiffResult_.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.GetJobUpdateDiffResult_), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 26:getJobUpdateDiffResult: ", p), err) + } + } + return err +} + +func (p *Result_) writeField27(oprot thrift.TProtocol) (err error) { + if p.IsSetGetTierConfigResult_() { + if err := oprot.WriteFieldBegin("getTierConfigResult", thrift.STRUCT, 27); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 27:getTierConfigResult: ", p), err) + } + if err := p.GetTierConfigResult_.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.GetTierConfigResult_), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 27:getTierConfigResult: ", p), err) + } + } + return err +} + +func (p *Result_) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("Result_(%+v)", *p) +} + +// Attributes: +// - Message +type ResponseDetail struct { + Message string `thrift:"message,1" db:"message" json:"message"` +} + +func NewResponseDetail() *ResponseDetail { + return &ResponseDetail{} +} + +func (p *ResponseDetail) GetMessage() string { + return p.Message +} +func (p *ResponseDetail) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ResponseDetail) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Message = v + } + return nil +} + +func (p *ResponseDetail) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("ResponseDetail"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ResponseDetail) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("message", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:message: ", p), err) + } + if err := oprot.WriteString(string(p.Message)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.message (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:message: ", p), err) + } + return err +} + +func (p *ResponseDetail) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ResponseDetail(%+v)", *p) +} + +// Attributes: +// - ResponseCode +// - ServerInfo +// - Result_: Payload from the invoked RPC. +// - Details: Messages from the server relevant to the request, such as warnings or use of deprecated +// features. +type Response struct { + ResponseCode ResponseCode `thrift:"responseCode,1" db:"responseCode" json:"responseCode"` + // unused field # 2 + Result_ *Result_ `thrift:"result,3" db:"result" json:"result,omitempty"` + // unused field # 4 + ServerInfo *ServerInfo `thrift:"serverInfo,5" db:"serverInfo" json:"serverInfo"` + Details []*ResponseDetail `thrift:"details,6" db:"details" json:"details"` +} + +func NewResponse() *Response { + return &Response{} +} + +func (p *Response) GetResponseCode() ResponseCode { + return p.ResponseCode +} + +var Response_ServerInfo_DEFAULT *ServerInfo + +func (p *Response) GetServerInfo() *ServerInfo { + if !p.IsSetServerInfo() { + return Response_ServerInfo_DEFAULT + } + return p.ServerInfo +} + +var Response_Result__DEFAULT *Result_ + +func (p *Response) GetResult_() *Result_ { + if !p.IsSetResult_() { + return Response_Result__DEFAULT + } + return p.Result_ +} + +func (p *Response) GetDetails() []*ResponseDetail { + return p.Details +} +func (p *Response) IsSetServerInfo() bool { + return p.ServerInfo != nil +} + +func (p *Response) IsSetResult_() bool { + return p.Result_ != nil +} + +func (p *Response) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.I32 { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 5: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField5(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 6: + if fieldTypeId == thrift.LIST { + if err := p.ReadField6(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *Response) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + temp := ResponseCode(v) + p.ResponseCode = temp + } + return nil +} + +func (p *Response) ReadField5(iprot thrift.TProtocol) error { + p.ServerInfo = &ServerInfo{} + if err := p.ServerInfo.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.ServerInfo), err) + } + return nil +} + +func (p *Response) ReadField3(iprot thrift.TProtocol) error { + p.Result_ = &Result_{} + if err := p.Result_.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Result_), err) + } + return nil +} + +func (p *Response) ReadField6(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadListBegin() + if err != nil { + return thrift.PrependError("error reading list begin: ", err) + } + tSlice := make([]*ResponseDetail, 0, size) + p.Details = tSlice + for i := 0; i < size; i++ { + _elem51 := &ResponseDetail{} + if err := _elem51.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem51), err) + } + p.Details = append(p.Details, _elem51) + } + if err := iprot.ReadListEnd(); err != nil { + return thrift.PrependError("error reading list end: ", err) + } + return nil +} + +func (p *Response) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("Response"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + if err := p.writeField5(oprot); err != nil { + return err + } + if err := p.writeField6(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *Response) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("responseCode", thrift.I32, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:responseCode: ", p), err) + } + if err := oprot.WriteI32(int32(p.ResponseCode)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.responseCode (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:responseCode: ", p), err) + } + return err +} + +func (p *Response) writeField3(oprot thrift.TProtocol) (err error) { + if p.IsSetResult_() { + if err := oprot.WriteFieldBegin("result", thrift.STRUCT, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:result: ", p), err) + } + if err := p.Result_.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Result_), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:result: ", p), err) + } + } + return err +} + +func (p *Response) writeField5(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("serverInfo", thrift.STRUCT, 5); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:serverInfo: ", p), err) + } + if err := p.ServerInfo.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.ServerInfo), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 5:serverInfo: ", p), err) + } + return err +} + +func (p *Response) writeField6(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("details", thrift.LIST, 6); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 6:details: ", p), err) + } + if err := oprot.WriteListBegin(thrift.STRUCT, len(p.Details)); err != nil { + return thrift.PrependError("error writing list begin: ", err) + } + for _, v := range p.Details { + if err := v.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) + } + } + if err := oprot.WriteListEnd(); err != nil { + return thrift.PrependError("error writing list end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 6:details: ", p), err) + } + return err +} + +func (p *Response) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("Response(%+v)", *p) +} + +// Attributes: +// - BatchSize +type ExplicitReconciliationSettings struct { + BatchSize *int32 `thrift:"batchSize,1" db:"batchSize" json:"batchSize,omitempty"` +} + +func NewExplicitReconciliationSettings() *ExplicitReconciliationSettings { + return &ExplicitReconciliationSettings{} +} + +var ExplicitReconciliationSettings_BatchSize_DEFAULT int32 + +func (p *ExplicitReconciliationSettings) GetBatchSize() int32 { + if !p.IsSetBatchSize() { + return ExplicitReconciliationSettings_BatchSize_DEFAULT + } + return *p.BatchSize +} +func (p *ExplicitReconciliationSettings) IsSetBatchSize() bool { + return p.BatchSize != nil +} + +func (p *ExplicitReconciliationSettings) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.I32 { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ExplicitReconciliationSettings) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.BatchSize = &v + } + return nil +} + +func (p *ExplicitReconciliationSettings) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("ExplicitReconciliationSettings"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ExplicitReconciliationSettings) writeField1(oprot thrift.TProtocol) (err error) { + if p.IsSetBatchSize() { + if err := oprot.WriteFieldBegin("batchSize", thrift.I32, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:batchSize: ", p), err) + } + if err := oprot.WriteI32(int32(*p.BatchSize)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.batchSize (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:batchSize: ", p), err) + } + } + return err +} + +func (p *ExplicitReconciliationSettings) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ExplicitReconciliationSettings(%+v)", *p) +} + +type ReadOnlyScheduler interface { + // Returns a summary of the jobs grouped by role. + GetRoleSummary(ctx context.Context) (r *Response, err error) + // Returns a summary of jobs, optionally only those owned by a specific role. + // + // Parameters: + // - Role + GetJobSummary(ctx context.Context, role string) (r *Response, err error) + // Fetches the status of tasks. + // + // Parameters: + // - Query + GetTasksStatus(ctx context.Context, query *TaskQuery) (r *Response, err error) + // Same as getTaskStatus but without the TaskConfig.ExecutorConfig data set. + // This is an interim solution until we have a better way to query TaskConfigs (AURORA-541). + // + // Parameters: + // - Query + GetTasksWithoutConfigs(ctx context.Context, query *TaskQuery) (r *Response, err error) + // Returns user-friendly reasons (if available) for tasks retained in PENDING state. + // + // Parameters: + // - Query + GetPendingReason(ctx context.Context, query *TaskQuery) (r *Response, err error) + // Fetches the configuration summary of active tasks for the specified job. + // + // Parameters: + // - Job + GetConfigSummary(ctx context.Context, job *JobKey) (r *Response, err error) + // Fetches the status of jobs. + // ownerRole is optional, in which case all jobs are returned. + // + // Parameters: + // - OwnerRole + GetJobs(ctx context.Context, ownerRole string) (r *Response, err error) + // Fetches the quota allocated for a user. + // + // Parameters: + // - OwnerRole + GetQuota(ctx context.Context, ownerRole string) (r *Response, err error) + // Populates fields in a job configuration as though it were about to be run. + // This can be used to diff a configuration running tasks. + // + // Parameters: + // - Description + PopulateJobConfig(ctx context.Context, description *JobConfiguration) (r *Response, err error) + // Gets job update summaries. + // + // Parameters: + // - JobUpdateQuery + GetJobUpdateSummaries(ctx context.Context, jobUpdateQuery *JobUpdateQuery) (r *Response, err error) + // Gets job update details. + // + // Parameters: + // - Query + GetJobUpdateDetails(ctx context.Context, query *JobUpdateQuery) (r *Response, err error) + // Gets the diff between client (desired) and server (current) job states. + // + // Parameters: + // - Request + GetJobUpdateDiff(ctx context.Context, request *JobUpdateRequest) (r *Response, err error) + // Gets tier configurations. + GetTierConfigs(ctx context.Context) (r *Response, err error) +} + +type ReadOnlySchedulerClient struct { + c thrift.TClient +} + +func NewReadOnlySchedulerClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *ReadOnlySchedulerClient { + return &ReadOnlySchedulerClient{ + c: thrift.NewTStandardClient(f.GetProtocol(t), f.GetProtocol(t)), + } +} + +func NewReadOnlySchedulerClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *ReadOnlySchedulerClient { + return &ReadOnlySchedulerClient{ + c: thrift.NewTStandardClient(iprot, oprot), + } +} + +func NewReadOnlySchedulerClient(c thrift.TClient) *ReadOnlySchedulerClient { + return &ReadOnlySchedulerClient{ + c: c, + } +} + +func (p *ReadOnlySchedulerClient) Client_() thrift.TClient { + return p.c +} + +// Returns a summary of the jobs grouped by role. +func (p *ReadOnlySchedulerClient) GetRoleSummary(ctx context.Context) (r *Response, err error) { + var _args52 ReadOnlySchedulerGetRoleSummaryArgs + var _result53 ReadOnlySchedulerGetRoleSummaryResult + if err = p.Client_().Call(ctx, "getRoleSummary", &_args52, &_result53); err != nil { + return + } + return _result53.GetSuccess(), nil +} + +// Returns a summary of jobs, optionally only those owned by a specific role. +// +// Parameters: +// - Role +func (p *ReadOnlySchedulerClient) GetJobSummary(ctx context.Context, role string) (r *Response, err error) { + var _args54 ReadOnlySchedulerGetJobSummaryArgs + _args54.Role = role + var _result55 ReadOnlySchedulerGetJobSummaryResult + if err = p.Client_().Call(ctx, "getJobSummary", &_args54, &_result55); err != nil { + return + } + return _result55.GetSuccess(), nil +} + +// Fetches the status of tasks. +// +// Parameters: +// - Query +func (p *ReadOnlySchedulerClient) GetTasksStatus(ctx context.Context, query *TaskQuery) (r *Response, err error) { + var _args56 ReadOnlySchedulerGetTasksStatusArgs + _args56.Query = query + var _result57 ReadOnlySchedulerGetTasksStatusResult + if err = p.Client_().Call(ctx, "getTasksStatus", &_args56, &_result57); err != nil { + return + } + return _result57.GetSuccess(), nil +} + +// Same as getTaskStatus but without the TaskConfig.ExecutorConfig data set. +// This is an interim solution until we have a better way to query TaskConfigs (AURORA-541). +// +// Parameters: +// - Query +func (p *ReadOnlySchedulerClient) GetTasksWithoutConfigs(ctx context.Context, query *TaskQuery) (r *Response, err error) { + var _args58 ReadOnlySchedulerGetTasksWithoutConfigsArgs + _args58.Query = query + var _result59 ReadOnlySchedulerGetTasksWithoutConfigsResult + if err = p.Client_().Call(ctx, "getTasksWithoutConfigs", &_args58, &_result59); err != nil { + return + } + return _result59.GetSuccess(), nil +} + +// Returns user-friendly reasons (if available) for tasks retained in PENDING state. +// +// Parameters: +// - Query +func (p *ReadOnlySchedulerClient) GetPendingReason(ctx context.Context, query *TaskQuery) (r *Response, err error) { + var _args60 ReadOnlySchedulerGetPendingReasonArgs + _args60.Query = query + var _result61 ReadOnlySchedulerGetPendingReasonResult + if err = p.Client_().Call(ctx, "getPendingReason", &_args60, &_result61); err != nil { + return + } + return _result61.GetSuccess(), nil +} + +// Fetches the configuration summary of active tasks for the specified job. +// +// Parameters: +// - Job +func (p *ReadOnlySchedulerClient) GetConfigSummary(ctx context.Context, job *JobKey) (r *Response, err error) { + var _args62 ReadOnlySchedulerGetConfigSummaryArgs + _args62.Job = job + var _result63 ReadOnlySchedulerGetConfigSummaryResult + if err = p.Client_().Call(ctx, "getConfigSummary", &_args62, &_result63); err != nil { + return + } + return _result63.GetSuccess(), nil +} + +// Fetches the status of jobs. +// ownerRole is optional, in which case all jobs are returned. +// +// Parameters: +// - OwnerRole +func (p *ReadOnlySchedulerClient) GetJobs(ctx context.Context, ownerRole string) (r *Response, err error) { + var _args64 ReadOnlySchedulerGetJobsArgs + _args64.OwnerRole = ownerRole + var _result65 ReadOnlySchedulerGetJobsResult + if err = p.Client_().Call(ctx, "getJobs", &_args64, &_result65); err != nil { + return + } + return _result65.GetSuccess(), nil +} + +// Fetches the quota allocated for a user. +// +// Parameters: +// - OwnerRole +func (p *ReadOnlySchedulerClient) GetQuota(ctx context.Context, ownerRole string) (r *Response, err error) { + var _args66 ReadOnlySchedulerGetQuotaArgs + _args66.OwnerRole = ownerRole + var _result67 ReadOnlySchedulerGetQuotaResult + if err = p.Client_().Call(ctx, "getQuota", &_args66, &_result67); err != nil { + return + } + return _result67.GetSuccess(), nil +} + +// Populates fields in a job configuration as though it were about to be run. +// This can be used to diff a configuration running tasks. +// +// Parameters: +// - Description +func (p *ReadOnlySchedulerClient) PopulateJobConfig(ctx context.Context, description *JobConfiguration) (r *Response, err error) { + var _args68 ReadOnlySchedulerPopulateJobConfigArgs + _args68.Description = description + var _result69 ReadOnlySchedulerPopulateJobConfigResult + if err = p.Client_().Call(ctx, "populateJobConfig", &_args68, &_result69); err != nil { + return + } + return _result69.GetSuccess(), nil +} + +// Gets job update summaries. +// +// Parameters: +// - JobUpdateQuery +func (p *ReadOnlySchedulerClient) GetJobUpdateSummaries(ctx context.Context, jobUpdateQuery *JobUpdateQuery) (r *Response, err error) { + var _args70 ReadOnlySchedulerGetJobUpdateSummariesArgs + _args70.JobUpdateQuery = jobUpdateQuery + var _result71 ReadOnlySchedulerGetJobUpdateSummariesResult + if err = p.Client_().Call(ctx, "getJobUpdateSummaries", &_args70, &_result71); err != nil { + return + } + return _result71.GetSuccess(), nil +} + +// Gets job update details. +// +// Parameters: +// - Query +func (p *ReadOnlySchedulerClient) GetJobUpdateDetails(ctx context.Context, query *JobUpdateQuery) (r *Response, err error) { + var _args72 ReadOnlySchedulerGetJobUpdateDetailsArgs + _args72.Query = query + var _result73 ReadOnlySchedulerGetJobUpdateDetailsResult + if err = p.Client_().Call(ctx, "getJobUpdateDetails", &_args72, &_result73); err != nil { + return + } + return _result73.GetSuccess(), nil +} + +// Gets the diff between client (desired) and server (current) job states. +// +// Parameters: +// - Request +func (p *ReadOnlySchedulerClient) GetJobUpdateDiff(ctx context.Context, request *JobUpdateRequest) (r *Response, err error) { + var _args74 ReadOnlySchedulerGetJobUpdateDiffArgs + _args74.Request = request + var _result75 ReadOnlySchedulerGetJobUpdateDiffResult + if err = p.Client_().Call(ctx, "getJobUpdateDiff", &_args74, &_result75); err != nil { + return + } + return _result75.GetSuccess(), nil +} + +// Gets tier configurations. +func (p *ReadOnlySchedulerClient) GetTierConfigs(ctx context.Context) (r *Response, err error) { + var _args76 ReadOnlySchedulerGetTierConfigsArgs + var _result77 ReadOnlySchedulerGetTierConfigsResult + if err = p.Client_().Call(ctx, "getTierConfigs", &_args76, &_result77); err != nil { + return + } + return _result77.GetSuccess(), nil +} + +type ReadOnlySchedulerProcessor struct { + processorMap map[string]thrift.TProcessorFunction + handler ReadOnlyScheduler +} + +func (p *ReadOnlySchedulerProcessor) AddToProcessorMap(key string, processor thrift.TProcessorFunction) { + p.processorMap[key] = processor +} + +func (p *ReadOnlySchedulerProcessor) GetProcessorFunction(key string) (processor thrift.TProcessorFunction, ok bool) { + processor, ok = p.processorMap[key] + return processor, ok +} + +func (p *ReadOnlySchedulerProcessor) ProcessorMap() map[string]thrift.TProcessorFunction { + return p.processorMap +} + +func NewReadOnlySchedulerProcessor(handler ReadOnlyScheduler) *ReadOnlySchedulerProcessor { + + self78 := &ReadOnlySchedulerProcessor{handler: handler, processorMap: make(map[string]thrift.TProcessorFunction)} + self78.processorMap["getRoleSummary"] = &readOnlySchedulerProcessorGetRoleSummary{handler: handler} + self78.processorMap["getJobSummary"] = &readOnlySchedulerProcessorGetJobSummary{handler: handler} + self78.processorMap["getTasksStatus"] = &readOnlySchedulerProcessorGetTasksStatus{handler: handler} + self78.processorMap["getTasksWithoutConfigs"] = &readOnlySchedulerProcessorGetTasksWithoutConfigs{handler: handler} + self78.processorMap["getPendingReason"] = &readOnlySchedulerProcessorGetPendingReason{handler: handler} + self78.processorMap["getConfigSummary"] = &readOnlySchedulerProcessorGetConfigSummary{handler: handler} + self78.processorMap["getJobs"] = &readOnlySchedulerProcessorGetJobs{handler: handler} + self78.processorMap["getQuota"] = &readOnlySchedulerProcessorGetQuota{handler: handler} + self78.processorMap["populateJobConfig"] = &readOnlySchedulerProcessorPopulateJobConfig{handler: handler} + self78.processorMap["getJobUpdateSummaries"] = &readOnlySchedulerProcessorGetJobUpdateSummaries{handler: handler} + self78.processorMap["getJobUpdateDetails"] = &readOnlySchedulerProcessorGetJobUpdateDetails{handler: handler} + self78.processorMap["getJobUpdateDiff"] = &readOnlySchedulerProcessorGetJobUpdateDiff{handler: handler} + self78.processorMap["getTierConfigs"] = &readOnlySchedulerProcessorGetTierConfigs{handler: handler} + return self78 +} + +func (p *ReadOnlySchedulerProcessor) Process(ctx context.Context, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + name, _, seqId, err := iprot.ReadMessageBegin() + if err != nil { + return false, err + } + if processor, ok := p.GetProcessorFunction(name); ok { + return processor.Process(ctx, seqId, iprot, oprot) + } + iprot.Skip(thrift.STRUCT) + iprot.ReadMessageEnd() + x79 := thrift.NewTApplicationException(thrift.UNKNOWN_METHOD, "Unknown function "+name) + oprot.WriteMessageBegin(name, thrift.EXCEPTION, seqId) + x79.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, x79 + +} + +type readOnlySchedulerProcessorGetRoleSummary struct { + handler ReadOnlyScheduler +} + +func (p *readOnlySchedulerProcessorGetRoleSummary) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := ReadOnlySchedulerGetRoleSummaryArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("getRoleSummary", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := ReadOnlySchedulerGetRoleSummaryResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.GetRoleSummary(ctx); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getRoleSummary: "+err2.Error()) + oprot.WriteMessageBegin("getRoleSummary", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("getRoleSummary", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type readOnlySchedulerProcessorGetJobSummary struct { + handler ReadOnlyScheduler +} + +func (p *readOnlySchedulerProcessorGetJobSummary) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := ReadOnlySchedulerGetJobSummaryArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("getJobSummary", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := ReadOnlySchedulerGetJobSummaryResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.GetJobSummary(ctx, args.Role); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getJobSummary: "+err2.Error()) + oprot.WriteMessageBegin("getJobSummary", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("getJobSummary", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type readOnlySchedulerProcessorGetTasksStatus struct { + handler ReadOnlyScheduler +} + +func (p *readOnlySchedulerProcessorGetTasksStatus) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := ReadOnlySchedulerGetTasksStatusArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("getTasksStatus", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := ReadOnlySchedulerGetTasksStatusResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.GetTasksStatus(ctx, args.Query); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getTasksStatus: "+err2.Error()) + oprot.WriteMessageBegin("getTasksStatus", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("getTasksStatus", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type readOnlySchedulerProcessorGetTasksWithoutConfigs struct { + handler ReadOnlyScheduler +} + +func (p *readOnlySchedulerProcessorGetTasksWithoutConfigs) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := ReadOnlySchedulerGetTasksWithoutConfigsArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("getTasksWithoutConfigs", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := ReadOnlySchedulerGetTasksWithoutConfigsResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.GetTasksWithoutConfigs(ctx, args.Query); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getTasksWithoutConfigs: "+err2.Error()) + oprot.WriteMessageBegin("getTasksWithoutConfigs", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("getTasksWithoutConfigs", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type readOnlySchedulerProcessorGetPendingReason struct { + handler ReadOnlyScheduler +} + +func (p *readOnlySchedulerProcessorGetPendingReason) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := ReadOnlySchedulerGetPendingReasonArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("getPendingReason", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := ReadOnlySchedulerGetPendingReasonResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.GetPendingReason(ctx, args.Query); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getPendingReason: "+err2.Error()) + oprot.WriteMessageBegin("getPendingReason", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("getPendingReason", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type readOnlySchedulerProcessorGetConfigSummary struct { + handler ReadOnlyScheduler +} + +func (p *readOnlySchedulerProcessorGetConfigSummary) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := ReadOnlySchedulerGetConfigSummaryArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("getConfigSummary", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := ReadOnlySchedulerGetConfigSummaryResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.GetConfigSummary(ctx, args.Job); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getConfigSummary: "+err2.Error()) + oprot.WriteMessageBegin("getConfigSummary", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("getConfigSummary", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type readOnlySchedulerProcessorGetJobs struct { + handler ReadOnlyScheduler +} + +func (p *readOnlySchedulerProcessorGetJobs) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := ReadOnlySchedulerGetJobsArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("getJobs", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := ReadOnlySchedulerGetJobsResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.GetJobs(ctx, args.OwnerRole); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getJobs: "+err2.Error()) + oprot.WriteMessageBegin("getJobs", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("getJobs", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type readOnlySchedulerProcessorGetQuota struct { + handler ReadOnlyScheduler +} + +func (p *readOnlySchedulerProcessorGetQuota) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := ReadOnlySchedulerGetQuotaArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("getQuota", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := ReadOnlySchedulerGetQuotaResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.GetQuota(ctx, args.OwnerRole); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getQuota: "+err2.Error()) + oprot.WriteMessageBegin("getQuota", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("getQuota", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type readOnlySchedulerProcessorPopulateJobConfig struct { + handler ReadOnlyScheduler +} + +func (p *readOnlySchedulerProcessorPopulateJobConfig) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := ReadOnlySchedulerPopulateJobConfigArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("populateJobConfig", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := ReadOnlySchedulerPopulateJobConfigResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.PopulateJobConfig(ctx, args.Description); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing populateJobConfig: "+err2.Error()) + oprot.WriteMessageBegin("populateJobConfig", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("populateJobConfig", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type readOnlySchedulerProcessorGetJobUpdateSummaries struct { + handler ReadOnlyScheduler +} + +func (p *readOnlySchedulerProcessorGetJobUpdateSummaries) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := ReadOnlySchedulerGetJobUpdateSummariesArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("getJobUpdateSummaries", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := ReadOnlySchedulerGetJobUpdateSummariesResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.GetJobUpdateSummaries(ctx, args.JobUpdateQuery); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getJobUpdateSummaries: "+err2.Error()) + oprot.WriteMessageBegin("getJobUpdateSummaries", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("getJobUpdateSummaries", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type readOnlySchedulerProcessorGetJobUpdateDetails struct { + handler ReadOnlyScheduler +} + +func (p *readOnlySchedulerProcessorGetJobUpdateDetails) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := ReadOnlySchedulerGetJobUpdateDetailsArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("getJobUpdateDetails", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := ReadOnlySchedulerGetJobUpdateDetailsResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.GetJobUpdateDetails(ctx, args.Query); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getJobUpdateDetails: "+err2.Error()) + oprot.WriteMessageBegin("getJobUpdateDetails", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("getJobUpdateDetails", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type readOnlySchedulerProcessorGetJobUpdateDiff struct { + handler ReadOnlyScheduler +} + +func (p *readOnlySchedulerProcessorGetJobUpdateDiff) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := ReadOnlySchedulerGetJobUpdateDiffArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("getJobUpdateDiff", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := ReadOnlySchedulerGetJobUpdateDiffResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.GetJobUpdateDiff(ctx, args.Request); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getJobUpdateDiff: "+err2.Error()) + oprot.WriteMessageBegin("getJobUpdateDiff", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("getJobUpdateDiff", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type readOnlySchedulerProcessorGetTierConfigs struct { + handler ReadOnlyScheduler +} + +func (p *readOnlySchedulerProcessorGetTierConfigs) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := ReadOnlySchedulerGetTierConfigsArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("getTierConfigs", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := ReadOnlySchedulerGetTierConfigsResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.GetTierConfigs(ctx); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getTierConfigs: "+err2.Error()) + oprot.WriteMessageBegin("getTierConfigs", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("getTierConfigs", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +// HELPER FUNCTIONS AND STRUCTURES + +type ReadOnlySchedulerGetRoleSummaryArgs struct { +} + +func NewReadOnlySchedulerGetRoleSummaryArgs() *ReadOnlySchedulerGetRoleSummaryArgs { + return &ReadOnlySchedulerGetRoleSummaryArgs{} +} + +func (p *ReadOnlySchedulerGetRoleSummaryArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetRoleSummaryArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getRoleSummary_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetRoleSummaryArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetRoleSummaryArgs(%+v)", *p) +} + +// Attributes: +// - Success +type ReadOnlySchedulerGetRoleSummaryResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewReadOnlySchedulerGetRoleSummaryResult() *ReadOnlySchedulerGetRoleSummaryResult { + return &ReadOnlySchedulerGetRoleSummaryResult{} +} + +var ReadOnlySchedulerGetRoleSummaryResult_Success_DEFAULT *Response + +func (p *ReadOnlySchedulerGetRoleSummaryResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return ReadOnlySchedulerGetRoleSummaryResult_Success_DEFAULT + } + return p.Success +} +func (p *ReadOnlySchedulerGetRoleSummaryResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *ReadOnlySchedulerGetRoleSummaryResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetRoleSummaryResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetRoleSummaryResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getRoleSummary_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetRoleSummaryResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *ReadOnlySchedulerGetRoleSummaryResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetRoleSummaryResult(%+v)", *p) +} + +// Attributes: +// - Role +type ReadOnlySchedulerGetJobSummaryArgs struct { + Role string `thrift:"role,1" db:"role" json:"role"` +} + +func NewReadOnlySchedulerGetJobSummaryArgs() *ReadOnlySchedulerGetJobSummaryArgs { + return &ReadOnlySchedulerGetJobSummaryArgs{} +} + +func (p *ReadOnlySchedulerGetJobSummaryArgs) GetRole() string { + return p.Role +} +func (p *ReadOnlySchedulerGetJobSummaryArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobSummaryArgs) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.Role = v + } + return nil +} + +func (p *ReadOnlySchedulerGetJobSummaryArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getJobSummary_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobSummaryArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("role", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:role: ", p), err) + } + if err := oprot.WriteString(string(p.Role)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.role (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:role: ", p), err) + } + return err +} + +func (p *ReadOnlySchedulerGetJobSummaryArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetJobSummaryArgs(%+v)", *p) +} + +// Attributes: +// - Success +type ReadOnlySchedulerGetJobSummaryResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewReadOnlySchedulerGetJobSummaryResult() *ReadOnlySchedulerGetJobSummaryResult { + return &ReadOnlySchedulerGetJobSummaryResult{} +} + +var ReadOnlySchedulerGetJobSummaryResult_Success_DEFAULT *Response + +func (p *ReadOnlySchedulerGetJobSummaryResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return ReadOnlySchedulerGetJobSummaryResult_Success_DEFAULT + } + return p.Success +} +func (p *ReadOnlySchedulerGetJobSummaryResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *ReadOnlySchedulerGetJobSummaryResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobSummaryResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobSummaryResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getJobSummary_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobSummaryResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *ReadOnlySchedulerGetJobSummaryResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetJobSummaryResult(%+v)", *p) +} + +// Attributes: +// - Query +type ReadOnlySchedulerGetTasksStatusArgs struct { + Query *TaskQuery `thrift:"query,1" db:"query" json:"query"` +} + +func NewReadOnlySchedulerGetTasksStatusArgs() *ReadOnlySchedulerGetTasksStatusArgs { + return &ReadOnlySchedulerGetTasksStatusArgs{} +} + +var ReadOnlySchedulerGetTasksStatusArgs_Query_DEFAULT *TaskQuery + +func (p *ReadOnlySchedulerGetTasksStatusArgs) GetQuery() *TaskQuery { + if !p.IsSetQuery() { + return ReadOnlySchedulerGetTasksStatusArgs_Query_DEFAULT + } + return p.Query +} +func (p *ReadOnlySchedulerGetTasksStatusArgs) IsSetQuery() bool { + return p.Query != nil +} + +func (p *ReadOnlySchedulerGetTasksStatusArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetTasksStatusArgs) ReadField1(iprot thrift.TProtocol) error { + p.Query = &TaskQuery{} + if err := p.Query.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Query), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetTasksStatusArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getTasksStatus_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetTasksStatusArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("query", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:query: ", p), err) + } + if err := p.Query.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Query), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:query: ", p), err) + } + return err +} + +func (p *ReadOnlySchedulerGetTasksStatusArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetTasksStatusArgs(%+v)", *p) +} + +// Attributes: +// - Success +type ReadOnlySchedulerGetTasksStatusResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewReadOnlySchedulerGetTasksStatusResult() *ReadOnlySchedulerGetTasksStatusResult { + return &ReadOnlySchedulerGetTasksStatusResult{} +} + +var ReadOnlySchedulerGetTasksStatusResult_Success_DEFAULT *Response + +func (p *ReadOnlySchedulerGetTasksStatusResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return ReadOnlySchedulerGetTasksStatusResult_Success_DEFAULT + } + return p.Success +} +func (p *ReadOnlySchedulerGetTasksStatusResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *ReadOnlySchedulerGetTasksStatusResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetTasksStatusResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetTasksStatusResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getTasksStatus_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetTasksStatusResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *ReadOnlySchedulerGetTasksStatusResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetTasksStatusResult(%+v)", *p) +} + +// Attributes: +// - Query +type ReadOnlySchedulerGetTasksWithoutConfigsArgs struct { + Query *TaskQuery `thrift:"query,1" db:"query" json:"query"` +} + +func NewReadOnlySchedulerGetTasksWithoutConfigsArgs() *ReadOnlySchedulerGetTasksWithoutConfigsArgs { + return &ReadOnlySchedulerGetTasksWithoutConfigsArgs{} +} + +var ReadOnlySchedulerGetTasksWithoutConfigsArgs_Query_DEFAULT *TaskQuery + +func (p *ReadOnlySchedulerGetTasksWithoutConfigsArgs) GetQuery() *TaskQuery { + if !p.IsSetQuery() { + return ReadOnlySchedulerGetTasksWithoutConfigsArgs_Query_DEFAULT + } + return p.Query +} +func (p *ReadOnlySchedulerGetTasksWithoutConfigsArgs) IsSetQuery() bool { + return p.Query != nil +} + +func (p *ReadOnlySchedulerGetTasksWithoutConfigsArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetTasksWithoutConfigsArgs) ReadField1(iprot thrift.TProtocol) error { + p.Query = &TaskQuery{} + if err := p.Query.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Query), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetTasksWithoutConfigsArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getTasksWithoutConfigs_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetTasksWithoutConfigsArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("query", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:query: ", p), err) + } + if err := p.Query.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Query), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:query: ", p), err) + } + return err +} + +func (p *ReadOnlySchedulerGetTasksWithoutConfigsArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetTasksWithoutConfigsArgs(%+v)", *p) +} + +// Attributes: +// - Success +type ReadOnlySchedulerGetTasksWithoutConfigsResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewReadOnlySchedulerGetTasksWithoutConfigsResult() *ReadOnlySchedulerGetTasksWithoutConfigsResult { + return &ReadOnlySchedulerGetTasksWithoutConfigsResult{} +} + +var ReadOnlySchedulerGetTasksWithoutConfigsResult_Success_DEFAULT *Response + +func (p *ReadOnlySchedulerGetTasksWithoutConfigsResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return ReadOnlySchedulerGetTasksWithoutConfigsResult_Success_DEFAULT + } + return p.Success +} +func (p *ReadOnlySchedulerGetTasksWithoutConfigsResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *ReadOnlySchedulerGetTasksWithoutConfigsResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetTasksWithoutConfigsResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetTasksWithoutConfigsResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getTasksWithoutConfigs_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetTasksWithoutConfigsResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *ReadOnlySchedulerGetTasksWithoutConfigsResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetTasksWithoutConfigsResult(%+v)", *p) +} + +// Attributes: +// - Query +type ReadOnlySchedulerGetPendingReasonArgs struct { + Query *TaskQuery `thrift:"query,1" db:"query" json:"query"` +} + +func NewReadOnlySchedulerGetPendingReasonArgs() *ReadOnlySchedulerGetPendingReasonArgs { + return &ReadOnlySchedulerGetPendingReasonArgs{} +} + +var ReadOnlySchedulerGetPendingReasonArgs_Query_DEFAULT *TaskQuery + +func (p *ReadOnlySchedulerGetPendingReasonArgs) GetQuery() *TaskQuery { + if !p.IsSetQuery() { + return ReadOnlySchedulerGetPendingReasonArgs_Query_DEFAULT + } + return p.Query +} +func (p *ReadOnlySchedulerGetPendingReasonArgs) IsSetQuery() bool { + return p.Query != nil +} + +func (p *ReadOnlySchedulerGetPendingReasonArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetPendingReasonArgs) ReadField1(iprot thrift.TProtocol) error { + p.Query = &TaskQuery{} + if err := p.Query.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Query), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetPendingReasonArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getPendingReason_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetPendingReasonArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("query", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:query: ", p), err) + } + if err := p.Query.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Query), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:query: ", p), err) + } + return err +} + +func (p *ReadOnlySchedulerGetPendingReasonArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetPendingReasonArgs(%+v)", *p) +} + +// Attributes: +// - Success +type ReadOnlySchedulerGetPendingReasonResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewReadOnlySchedulerGetPendingReasonResult() *ReadOnlySchedulerGetPendingReasonResult { + return &ReadOnlySchedulerGetPendingReasonResult{} +} + +var ReadOnlySchedulerGetPendingReasonResult_Success_DEFAULT *Response + +func (p *ReadOnlySchedulerGetPendingReasonResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return ReadOnlySchedulerGetPendingReasonResult_Success_DEFAULT + } + return p.Success +} +func (p *ReadOnlySchedulerGetPendingReasonResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *ReadOnlySchedulerGetPendingReasonResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetPendingReasonResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetPendingReasonResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getPendingReason_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetPendingReasonResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *ReadOnlySchedulerGetPendingReasonResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetPendingReasonResult(%+v)", *p) +} + +// Attributes: +// - Job +type ReadOnlySchedulerGetConfigSummaryArgs struct { + Job *JobKey `thrift:"job,1" db:"job" json:"job"` +} + +func NewReadOnlySchedulerGetConfigSummaryArgs() *ReadOnlySchedulerGetConfigSummaryArgs { + return &ReadOnlySchedulerGetConfigSummaryArgs{} +} + +var ReadOnlySchedulerGetConfigSummaryArgs_Job_DEFAULT *JobKey + +func (p *ReadOnlySchedulerGetConfigSummaryArgs) GetJob() *JobKey { + if !p.IsSetJob() { + return ReadOnlySchedulerGetConfigSummaryArgs_Job_DEFAULT + } + return p.Job +} +func (p *ReadOnlySchedulerGetConfigSummaryArgs) IsSetJob() bool { + return p.Job != nil +} + +func (p *ReadOnlySchedulerGetConfigSummaryArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetConfigSummaryArgs) ReadField1(iprot thrift.TProtocol) error { + p.Job = &JobKey{} + if err := p.Job.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Job), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetConfigSummaryArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getConfigSummary_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetConfigSummaryArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("job", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:job: ", p), err) + } + if err := p.Job.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Job), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:job: ", p), err) + } + return err +} + +func (p *ReadOnlySchedulerGetConfigSummaryArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetConfigSummaryArgs(%+v)", *p) +} + +// Attributes: +// - Success +type ReadOnlySchedulerGetConfigSummaryResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewReadOnlySchedulerGetConfigSummaryResult() *ReadOnlySchedulerGetConfigSummaryResult { + return &ReadOnlySchedulerGetConfigSummaryResult{} +} + +var ReadOnlySchedulerGetConfigSummaryResult_Success_DEFAULT *Response + +func (p *ReadOnlySchedulerGetConfigSummaryResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return ReadOnlySchedulerGetConfigSummaryResult_Success_DEFAULT + } + return p.Success +} +func (p *ReadOnlySchedulerGetConfigSummaryResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *ReadOnlySchedulerGetConfigSummaryResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetConfigSummaryResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetConfigSummaryResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getConfigSummary_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetConfigSummaryResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *ReadOnlySchedulerGetConfigSummaryResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetConfigSummaryResult(%+v)", *p) +} + +// Attributes: +// - OwnerRole +type ReadOnlySchedulerGetJobsArgs struct { + OwnerRole string `thrift:"ownerRole,1" db:"ownerRole" json:"ownerRole"` +} + +func NewReadOnlySchedulerGetJobsArgs() *ReadOnlySchedulerGetJobsArgs { + return &ReadOnlySchedulerGetJobsArgs{} +} + +func (p *ReadOnlySchedulerGetJobsArgs) GetOwnerRole() string { + return p.OwnerRole +} +func (p *ReadOnlySchedulerGetJobsArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobsArgs) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.OwnerRole = v + } + return nil +} + +func (p *ReadOnlySchedulerGetJobsArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getJobs_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobsArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("ownerRole", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:ownerRole: ", p), err) + } + if err := oprot.WriteString(string(p.OwnerRole)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.ownerRole (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:ownerRole: ", p), err) + } + return err +} + +func (p *ReadOnlySchedulerGetJobsArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetJobsArgs(%+v)", *p) +} + +// Attributes: +// - Success +type ReadOnlySchedulerGetJobsResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewReadOnlySchedulerGetJobsResult() *ReadOnlySchedulerGetJobsResult { + return &ReadOnlySchedulerGetJobsResult{} +} + +var ReadOnlySchedulerGetJobsResult_Success_DEFAULT *Response + +func (p *ReadOnlySchedulerGetJobsResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return ReadOnlySchedulerGetJobsResult_Success_DEFAULT + } + return p.Success +} +func (p *ReadOnlySchedulerGetJobsResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *ReadOnlySchedulerGetJobsResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobsResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobsResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getJobs_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobsResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *ReadOnlySchedulerGetJobsResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetJobsResult(%+v)", *p) +} + +// Attributes: +// - OwnerRole +type ReadOnlySchedulerGetQuotaArgs struct { + OwnerRole string `thrift:"ownerRole,1" db:"ownerRole" json:"ownerRole"` +} + +func NewReadOnlySchedulerGetQuotaArgs() *ReadOnlySchedulerGetQuotaArgs { + return &ReadOnlySchedulerGetQuotaArgs{} +} + +func (p *ReadOnlySchedulerGetQuotaArgs) GetOwnerRole() string { + return p.OwnerRole +} +func (p *ReadOnlySchedulerGetQuotaArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetQuotaArgs) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.OwnerRole = v + } + return nil +} + +func (p *ReadOnlySchedulerGetQuotaArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getQuota_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetQuotaArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("ownerRole", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:ownerRole: ", p), err) + } + if err := oprot.WriteString(string(p.OwnerRole)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.ownerRole (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:ownerRole: ", p), err) + } + return err +} + +func (p *ReadOnlySchedulerGetQuotaArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetQuotaArgs(%+v)", *p) +} + +// Attributes: +// - Success +type ReadOnlySchedulerGetQuotaResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewReadOnlySchedulerGetQuotaResult() *ReadOnlySchedulerGetQuotaResult { + return &ReadOnlySchedulerGetQuotaResult{} +} + +var ReadOnlySchedulerGetQuotaResult_Success_DEFAULT *Response + +func (p *ReadOnlySchedulerGetQuotaResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return ReadOnlySchedulerGetQuotaResult_Success_DEFAULT + } + return p.Success +} +func (p *ReadOnlySchedulerGetQuotaResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *ReadOnlySchedulerGetQuotaResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetQuotaResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetQuotaResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getQuota_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetQuotaResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *ReadOnlySchedulerGetQuotaResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetQuotaResult(%+v)", *p) +} + +// Attributes: +// - Description +type ReadOnlySchedulerPopulateJobConfigArgs struct { + Description *JobConfiguration `thrift:"description,1" db:"description" json:"description"` +} + +func NewReadOnlySchedulerPopulateJobConfigArgs() *ReadOnlySchedulerPopulateJobConfigArgs { + return &ReadOnlySchedulerPopulateJobConfigArgs{} +} + +var ReadOnlySchedulerPopulateJobConfigArgs_Description_DEFAULT *JobConfiguration + +func (p *ReadOnlySchedulerPopulateJobConfigArgs) GetDescription() *JobConfiguration { + if !p.IsSetDescription() { + return ReadOnlySchedulerPopulateJobConfigArgs_Description_DEFAULT + } + return p.Description +} +func (p *ReadOnlySchedulerPopulateJobConfigArgs) IsSetDescription() bool { + return p.Description != nil +} + +func (p *ReadOnlySchedulerPopulateJobConfigArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerPopulateJobConfigArgs) ReadField1(iprot thrift.TProtocol) error { + p.Description = &JobConfiguration{} + if err := p.Description.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Description), err) + } + return nil +} + +func (p *ReadOnlySchedulerPopulateJobConfigArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("populateJobConfig_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerPopulateJobConfigArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("description", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:description: ", p), err) + } + if err := p.Description.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Description), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:description: ", p), err) + } + return err +} + +func (p *ReadOnlySchedulerPopulateJobConfigArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerPopulateJobConfigArgs(%+v)", *p) +} + +// Attributes: +// - Success +type ReadOnlySchedulerPopulateJobConfigResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewReadOnlySchedulerPopulateJobConfigResult() *ReadOnlySchedulerPopulateJobConfigResult { + return &ReadOnlySchedulerPopulateJobConfigResult{} +} + +var ReadOnlySchedulerPopulateJobConfigResult_Success_DEFAULT *Response + +func (p *ReadOnlySchedulerPopulateJobConfigResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return ReadOnlySchedulerPopulateJobConfigResult_Success_DEFAULT + } + return p.Success +} +func (p *ReadOnlySchedulerPopulateJobConfigResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *ReadOnlySchedulerPopulateJobConfigResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerPopulateJobConfigResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *ReadOnlySchedulerPopulateJobConfigResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("populateJobConfig_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerPopulateJobConfigResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *ReadOnlySchedulerPopulateJobConfigResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerPopulateJobConfigResult(%+v)", *p) +} + +// Attributes: +// - JobUpdateQuery +type ReadOnlySchedulerGetJobUpdateSummariesArgs struct { + JobUpdateQuery *JobUpdateQuery `thrift:"jobUpdateQuery,1" db:"jobUpdateQuery" json:"jobUpdateQuery"` +} + +func NewReadOnlySchedulerGetJobUpdateSummariesArgs() *ReadOnlySchedulerGetJobUpdateSummariesArgs { + return &ReadOnlySchedulerGetJobUpdateSummariesArgs{} +} + +var ReadOnlySchedulerGetJobUpdateSummariesArgs_JobUpdateQuery_DEFAULT *JobUpdateQuery + +func (p *ReadOnlySchedulerGetJobUpdateSummariesArgs) GetJobUpdateQuery() *JobUpdateQuery { + if !p.IsSetJobUpdateQuery() { + return ReadOnlySchedulerGetJobUpdateSummariesArgs_JobUpdateQuery_DEFAULT + } + return p.JobUpdateQuery +} +func (p *ReadOnlySchedulerGetJobUpdateSummariesArgs) IsSetJobUpdateQuery() bool { + return p.JobUpdateQuery != nil +} + +func (p *ReadOnlySchedulerGetJobUpdateSummariesArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobUpdateSummariesArgs) ReadField1(iprot thrift.TProtocol) error { + p.JobUpdateQuery = &JobUpdateQuery{} + if err := p.JobUpdateQuery.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.JobUpdateQuery), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobUpdateSummariesArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getJobUpdateSummaries_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobUpdateSummariesArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("jobUpdateQuery", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:jobUpdateQuery: ", p), err) + } + if err := p.JobUpdateQuery.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.JobUpdateQuery), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:jobUpdateQuery: ", p), err) + } + return err +} + +func (p *ReadOnlySchedulerGetJobUpdateSummariesArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetJobUpdateSummariesArgs(%+v)", *p) +} + +// Attributes: +// - Success +type ReadOnlySchedulerGetJobUpdateSummariesResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewReadOnlySchedulerGetJobUpdateSummariesResult() *ReadOnlySchedulerGetJobUpdateSummariesResult { + return &ReadOnlySchedulerGetJobUpdateSummariesResult{} +} + +var ReadOnlySchedulerGetJobUpdateSummariesResult_Success_DEFAULT *Response + +func (p *ReadOnlySchedulerGetJobUpdateSummariesResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return ReadOnlySchedulerGetJobUpdateSummariesResult_Success_DEFAULT + } + return p.Success +} +func (p *ReadOnlySchedulerGetJobUpdateSummariesResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *ReadOnlySchedulerGetJobUpdateSummariesResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobUpdateSummariesResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobUpdateSummariesResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getJobUpdateSummaries_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobUpdateSummariesResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *ReadOnlySchedulerGetJobUpdateSummariesResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetJobUpdateSummariesResult(%+v)", *p) +} + +// Attributes: +// - Query +type ReadOnlySchedulerGetJobUpdateDetailsArgs struct { + // unused field # 1 + Query *JobUpdateQuery `thrift:"query,2" db:"query" json:"query"` +} + +func NewReadOnlySchedulerGetJobUpdateDetailsArgs() *ReadOnlySchedulerGetJobUpdateDetailsArgs { + return &ReadOnlySchedulerGetJobUpdateDetailsArgs{} +} + +var ReadOnlySchedulerGetJobUpdateDetailsArgs_Query_DEFAULT *JobUpdateQuery + +func (p *ReadOnlySchedulerGetJobUpdateDetailsArgs) GetQuery() *JobUpdateQuery { + if !p.IsSetQuery() { + return ReadOnlySchedulerGetJobUpdateDetailsArgs_Query_DEFAULT + } + return p.Query +} +func (p *ReadOnlySchedulerGetJobUpdateDetailsArgs) IsSetQuery() bool { + return p.Query != nil +} + +func (p *ReadOnlySchedulerGetJobUpdateDetailsArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 2: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobUpdateDetailsArgs) ReadField2(iprot thrift.TProtocol) error { + p.Query = &JobUpdateQuery{} + if err := p.Query.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Query), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobUpdateDetailsArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getJobUpdateDetails_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobUpdateDetailsArgs) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("query", thrift.STRUCT, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:query: ", p), err) + } + if err := p.Query.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Query), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:query: ", p), err) + } + return err +} + +func (p *ReadOnlySchedulerGetJobUpdateDetailsArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetJobUpdateDetailsArgs(%+v)", *p) +} + +// Attributes: +// - Success +type ReadOnlySchedulerGetJobUpdateDetailsResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewReadOnlySchedulerGetJobUpdateDetailsResult() *ReadOnlySchedulerGetJobUpdateDetailsResult { + return &ReadOnlySchedulerGetJobUpdateDetailsResult{} +} + +var ReadOnlySchedulerGetJobUpdateDetailsResult_Success_DEFAULT *Response + +func (p *ReadOnlySchedulerGetJobUpdateDetailsResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return ReadOnlySchedulerGetJobUpdateDetailsResult_Success_DEFAULT + } + return p.Success +} +func (p *ReadOnlySchedulerGetJobUpdateDetailsResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *ReadOnlySchedulerGetJobUpdateDetailsResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobUpdateDetailsResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobUpdateDetailsResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getJobUpdateDetails_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobUpdateDetailsResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *ReadOnlySchedulerGetJobUpdateDetailsResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetJobUpdateDetailsResult(%+v)", *p) +} + +// Attributes: +// - Request +type ReadOnlySchedulerGetJobUpdateDiffArgs struct { + Request *JobUpdateRequest `thrift:"request,1" db:"request" json:"request"` +} + +func NewReadOnlySchedulerGetJobUpdateDiffArgs() *ReadOnlySchedulerGetJobUpdateDiffArgs { + return &ReadOnlySchedulerGetJobUpdateDiffArgs{} +} + +var ReadOnlySchedulerGetJobUpdateDiffArgs_Request_DEFAULT *JobUpdateRequest + +func (p *ReadOnlySchedulerGetJobUpdateDiffArgs) GetRequest() *JobUpdateRequest { + if !p.IsSetRequest() { + return ReadOnlySchedulerGetJobUpdateDiffArgs_Request_DEFAULT + } + return p.Request +} +func (p *ReadOnlySchedulerGetJobUpdateDiffArgs) IsSetRequest() bool { + return p.Request != nil +} + +func (p *ReadOnlySchedulerGetJobUpdateDiffArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobUpdateDiffArgs) ReadField1(iprot thrift.TProtocol) error { + p.Request = &JobUpdateRequest{} + if err := p.Request.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Request), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobUpdateDiffArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getJobUpdateDiff_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobUpdateDiffArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("request", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:request: ", p), err) + } + if err := p.Request.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Request), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:request: ", p), err) + } + return err +} + +func (p *ReadOnlySchedulerGetJobUpdateDiffArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetJobUpdateDiffArgs(%+v)", *p) +} + +// Attributes: +// - Success +type ReadOnlySchedulerGetJobUpdateDiffResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewReadOnlySchedulerGetJobUpdateDiffResult() *ReadOnlySchedulerGetJobUpdateDiffResult { + return &ReadOnlySchedulerGetJobUpdateDiffResult{} +} + +var ReadOnlySchedulerGetJobUpdateDiffResult_Success_DEFAULT *Response + +func (p *ReadOnlySchedulerGetJobUpdateDiffResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return ReadOnlySchedulerGetJobUpdateDiffResult_Success_DEFAULT + } + return p.Success +} +func (p *ReadOnlySchedulerGetJobUpdateDiffResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *ReadOnlySchedulerGetJobUpdateDiffResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobUpdateDiffResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobUpdateDiffResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getJobUpdateDiff_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetJobUpdateDiffResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *ReadOnlySchedulerGetJobUpdateDiffResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetJobUpdateDiffResult(%+v)", *p) +} + +type ReadOnlySchedulerGetTierConfigsArgs struct { +} + +func NewReadOnlySchedulerGetTierConfigsArgs() *ReadOnlySchedulerGetTierConfigsArgs { + return &ReadOnlySchedulerGetTierConfigsArgs{} +} + +func (p *ReadOnlySchedulerGetTierConfigsArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetTierConfigsArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getTierConfigs_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetTierConfigsArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetTierConfigsArgs(%+v)", *p) +} + +// Attributes: +// - Success +type ReadOnlySchedulerGetTierConfigsResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewReadOnlySchedulerGetTierConfigsResult() *ReadOnlySchedulerGetTierConfigsResult { + return &ReadOnlySchedulerGetTierConfigsResult{} +} + +var ReadOnlySchedulerGetTierConfigsResult_Success_DEFAULT *Response + +func (p *ReadOnlySchedulerGetTierConfigsResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return ReadOnlySchedulerGetTierConfigsResult_Success_DEFAULT + } + return p.Success +} +func (p *ReadOnlySchedulerGetTierConfigsResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *ReadOnlySchedulerGetTierConfigsResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetTierConfigsResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *ReadOnlySchedulerGetTierConfigsResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("getTierConfigs_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *ReadOnlySchedulerGetTierConfigsResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *ReadOnlySchedulerGetTierConfigsResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("ReadOnlySchedulerGetTierConfigsResult(%+v)", *p) +} + +type AuroraSchedulerManager interface { + ReadOnlyScheduler + + // Creates a new job. The request will be denied if a job with the provided name already exists + // in the cluster. + // + // Parameters: + // - Description + CreateJob(ctx context.Context, description *JobConfiguration) (r *Response, err error) + // Enters a job into the cron schedule, without actually starting the job. + // If the job is already present in the schedule, this will update the schedule entry with the new + // configuration. + // + // Parameters: + // - Description + ScheduleCronJob(ctx context.Context, description *JobConfiguration) (r *Response, err error) + // Removes a job from the cron schedule. The request will be denied if the job was not previously + // scheduled with scheduleCronJob. + // + // Parameters: + // - Job + DescheduleCronJob(ctx context.Context, job *JobKey) (r *Response, err error) + // Starts a cron job immediately. The request will be denied if the specified job does not + // exist for the role account, or the job is not a cron job. + // + // Parameters: + // - Job + StartCronJob(ctx context.Context, job *JobKey) (r *Response, err error) + // Restarts a batch of shards. + // + // Parameters: + // - Job + // - ShardIds + RestartShards(ctx context.Context, job *JobKey, shardIds []int32) (r *Response, err error) + // Initiates a kill on tasks. + // + // Parameters: + // - Job + // - Instances + // - Message + KillTasks(ctx context.Context, job *JobKey, instances []int32, message string) (r *Response, err error) + // Adds new instances with the TaskConfig of the existing instance pointed by the key. + // + // Parameters: + // - Key + // - Count + AddInstances(ctx context.Context, key *InstanceKey, count int32) (r *Response, err error) + // Replaces the template (configuration) for the existing cron job. + // The cron job template (configuration) must exist for the call to succeed. + // + // Parameters: + // - Config + ReplaceCronTemplate(ctx context.Context, config *JobConfiguration) (r *Response, err error) + // Starts update of the existing service job. + // + // Parameters: + // - Request: A description of how to change the job. + // - Message: A user-specified message to include with the induced job update state change. + StartJobUpdate(ctx context.Context, request *JobUpdateRequest, message string) (r *Response, err error) + // Pauses the specified job update. Can be resumed by resumeUpdate call. + // + // Parameters: + // - Key: The update to pause. + // - Message: A user-specified message to include with the induced job update state change. + PauseJobUpdate(ctx context.Context, key *JobUpdateKey, message string) (r *Response, err error) + // Resumes progress of a previously paused job update. + // + // Parameters: + // - Key: The update to resume. + // - Message: A user-specified message to include with the induced job update state change. + ResumeJobUpdate(ctx context.Context, key *JobUpdateKey, message string) (r *Response, err error) + // Permanently aborts the job update. Does not remove the update history. + // + // Parameters: + // - Key: The update to abort. + // - Message: A user-specified message to include with the induced job update state change. + AbortJobUpdate(ctx context.Context, key *JobUpdateKey, message string) (r *Response, err error) + // Rollbacks the specified active job update to the initial state. + // + // Parameters: + // - Key: The update to rollback. + // - Message: A user-specified message to include with the induced job update state change. + RollbackJobUpdate(ctx context.Context, key *JobUpdateKey, message string) (r *Response, err error) + // Allows progress of the job update in case blockIfNoPulsesAfterMs is specified in + // JobUpdateSettings. Unblocks progress if the update was previously blocked. + // Responds with ResponseCode.INVALID_REQUEST in case an unknown update key is specified. + // + // Parameters: + // - Key + PulseJobUpdate(ctx context.Context, key *JobUpdateKey) (r *Response, err error) +} + +type AuroraSchedulerManagerClient struct { + *ReadOnlySchedulerClient +} + +func NewAuroraSchedulerManagerClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *AuroraSchedulerManagerClient { + return &AuroraSchedulerManagerClient{ReadOnlySchedulerClient: NewReadOnlySchedulerClientFactory(t, f)} +} + +func NewAuroraSchedulerManagerClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *AuroraSchedulerManagerClient { + return &AuroraSchedulerManagerClient{ReadOnlySchedulerClient: NewReadOnlySchedulerClientProtocol(t, iprot, oprot)} +} + +func NewAuroraSchedulerManagerClient(c thrift.TClient) *AuroraSchedulerManagerClient { + return &AuroraSchedulerManagerClient{ + ReadOnlySchedulerClient: NewReadOnlySchedulerClient(c), + } +} + +// Creates a new job. The request will be denied if a job with the provided name already exists +// in the cluster. +// +// Parameters: +// - Description +func (p *AuroraSchedulerManagerClient) CreateJob(ctx context.Context, description *JobConfiguration) (r *Response, err error) { + var _args131 AuroraSchedulerManagerCreateJobArgs + _args131.Description = description + var _result132 AuroraSchedulerManagerCreateJobResult + if err = p.Client_().Call(ctx, "createJob", &_args131, &_result132); err != nil { + return + } + return _result132.GetSuccess(), nil +} + +// Enters a job into the cron schedule, without actually starting the job. +// If the job is already present in the schedule, this will update the schedule entry with the new +// configuration. +// +// Parameters: +// - Description +func (p *AuroraSchedulerManagerClient) ScheduleCronJob(ctx context.Context, description *JobConfiguration) (r *Response, err error) { + var _args133 AuroraSchedulerManagerScheduleCronJobArgs + _args133.Description = description + var _result134 AuroraSchedulerManagerScheduleCronJobResult + if err = p.Client_().Call(ctx, "scheduleCronJob", &_args133, &_result134); err != nil { + return + } + return _result134.GetSuccess(), nil +} + +// Removes a job from the cron schedule. The request will be denied if the job was not previously +// scheduled with scheduleCronJob. +// +// Parameters: +// - Job +func (p *AuroraSchedulerManagerClient) DescheduleCronJob(ctx context.Context, job *JobKey) (r *Response, err error) { + var _args135 AuroraSchedulerManagerDescheduleCronJobArgs + _args135.Job = job + var _result136 AuroraSchedulerManagerDescheduleCronJobResult + if err = p.Client_().Call(ctx, "descheduleCronJob", &_args135, &_result136); err != nil { + return + } + return _result136.GetSuccess(), nil +} + +// Starts a cron job immediately. The request will be denied if the specified job does not +// exist for the role account, or the job is not a cron job. +// +// Parameters: +// - Job +func (p *AuroraSchedulerManagerClient) StartCronJob(ctx context.Context, job *JobKey) (r *Response, err error) { + var _args137 AuroraSchedulerManagerStartCronJobArgs + _args137.Job = job + var _result138 AuroraSchedulerManagerStartCronJobResult + if err = p.Client_().Call(ctx, "startCronJob", &_args137, &_result138); err != nil { + return + } + return _result138.GetSuccess(), nil +} + +// Restarts a batch of shards. +// +// Parameters: +// - Job +// - ShardIds +func (p *AuroraSchedulerManagerClient) RestartShards(ctx context.Context, job *JobKey, shardIds []int32) (r *Response, err error) { + var _args139 AuroraSchedulerManagerRestartShardsArgs + _args139.Job = job + _args139.ShardIds = shardIds + var _result140 AuroraSchedulerManagerRestartShardsResult + if err = p.Client_().Call(ctx, "restartShards", &_args139, &_result140); err != nil { + return + } + return _result140.GetSuccess(), nil +} + +// Initiates a kill on tasks. +// +// Parameters: +// - Job +// - Instances +// - Message +func (p *AuroraSchedulerManagerClient) KillTasks(ctx context.Context, job *JobKey, instances []int32, message string) (r *Response, err error) { + var _args141 AuroraSchedulerManagerKillTasksArgs + _args141.Job = job + _args141.Instances = instances + _args141.Message = message + var _result142 AuroraSchedulerManagerKillTasksResult + if err = p.Client_().Call(ctx, "killTasks", &_args141, &_result142); err != nil { + return + } + return _result142.GetSuccess(), nil +} + +// Adds new instances with the TaskConfig of the existing instance pointed by the key. +// +// Parameters: +// - Key +// - Count +func (p *AuroraSchedulerManagerClient) AddInstances(ctx context.Context, key *InstanceKey, count int32) (r *Response, err error) { + var _args143 AuroraSchedulerManagerAddInstancesArgs + _args143.Key = key + _args143.Count = count + var _result144 AuroraSchedulerManagerAddInstancesResult + if err = p.Client_().Call(ctx, "addInstances", &_args143, &_result144); err != nil { + return + } + return _result144.GetSuccess(), nil +} + +// Replaces the template (configuration) for the existing cron job. +// The cron job template (configuration) must exist for the call to succeed. +// +// Parameters: +// - Config +func (p *AuroraSchedulerManagerClient) ReplaceCronTemplate(ctx context.Context, config *JobConfiguration) (r *Response, err error) { + var _args145 AuroraSchedulerManagerReplaceCronTemplateArgs + _args145.Config = config + var _result146 AuroraSchedulerManagerReplaceCronTemplateResult + if err = p.Client_().Call(ctx, "replaceCronTemplate", &_args145, &_result146); err != nil { + return + } + return _result146.GetSuccess(), nil +} + +// Starts update of the existing service job. +// +// Parameters: +// - Request: A description of how to change the job. +// - Message: A user-specified message to include with the induced job update state change. +func (p *AuroraSchedulerManagerClient) StartJobUpdate(ctx context.Context, request *JobUpdateRequest, message string) (r *Response, err error) { + var _args147 AuroraSchedulerManagerStartJobUpdateArgs + _args147.Request = request + _args147.Message = message + var _result148 AuroraSchedulerManagerStartJobUpdateResult + if err = p.Client_().Call(ctx, "startJobUpdate", &_args147, &_result148); err != nil { + return + } + return _result148.GetSuccess(), nil +} + +// Pauses the specified job update. Can be resumed by resumeUpdate call. +// +// Parameters: +// - Key: The update to pause. +// - Message: A user-specified message to include with the induced job update state change. +func (p *AuroraSchedulerManagerClient) PauseJobUpdate(ctx context.Context, key *JobUpdateKey, message string) (r *Response, err error) { + var _args149 AuroraSchedulerManagerPauseJobUpdateArgs + _args149.Key = key + _args149.Message = message + var _result150 AuroraSchedulerManagerPauseJobUpdateResult + if err = p.Client_().Call(ctx, "pauseJobUpdate", &_args149, &_result150); err != nil { + return + } + return _result150.GetSuccess(), nil +} + +// Resumes progress of a previously paused job update. +// +// Parameters: +// - Key: The update to resume. +// - Message: A user-specified message to include with the induced job update state change. +func (p *AuroraSchedulerManagerClient) ResumeJobUpdate(ctx context.Context, key *JobUpdateKey, message string) (r *Response, err error) { + var _args151 AuroraSchedulerManagerResumeJobUpdateArgs + _args151.Key = key + _args151.Message = message + var _result152 AuroraSchedulerManagerResumeJobUpdateResult + if err = p.Client_().Call(ctx, "resumeJobUpdate", &_args151, &_result152); err != nil { + return + } + return _result152.GetSuccess(), nil +} + +// Permanently aborts the job update. Does not remove the update history. +// +// Parameters: +// - Key: The update to abort. +// - Message: A user-specified message to include with the induced job update state change. +func (p *AuroraSchedulerManagerClient) AbortJobUpdate(ctx context.Context, key *JobUpdateKey, message string) (r *Response, err error) { + var _args153 AuroraSchedulerManagerAbortJobUpdateArgs + _args153.Key = key + _args153.Message = message + var _result154 AuroraSchedulerManagerAbortJobUpdateResult + if err = p.Client_().Call(ctx, "abortJobUpdate", &_args153, &_result154); err != nil { + return + } + return _result154.GetSuccess(), nil +} + +// Rollbacks the specified active job update to the initial state. +// +// Parameters: +// - Key: The update to rollback. +// - Message: A user-specified message to include with the induced job update state change. +func (p *AuroraSchedulerManagerClient) RollbackJobUpdate(ctx context.Context, key *JobUpdateKey, message string) (r *Response, err error) { + var _args155 AuroraSchedulerManagerRollbackJobUpdateArgs + _args155.Key = key + _args155.Message = message + var _result156 AuroraSchedulerManagerRollbackJobUpdateResult + if err = p.Client_().Call(ctx, "rollbackJobUpdate", &_args155, &_result156); err != nil { + return + } + return _result156.GetSuccess(), nil +} + +// Allows progress of the job update in case blockIfNoPulsesAfterMs is specified in +// JobUpdateSettings. Unblocks progress if the update was previously blocked. +// Responds with ResponseCode.INVALID_REQUEST in case an unknown update key is specified. +// +// Parameters: +// - Key +func (p *AuroraSchedulerManagerClient) PulseJobUpdate(ctx context.Context, key *JobUpdateKey) (r *Response, err error) { + var _args157 AuroraSchedulerManagerPulseJobUpdateArgs + _args157.Key = key + var _result158 AuroraSchedulerManagerPulseJobUpdateResult + if err = p.Client_().Call(ctx, "pulseJobUpdate", &_args157, &_result158); err != nil { + return + } + return _result158.GetSuccess(), nil +} + +type AuroraSchedulerManagerProcessor struct { + *ReadOnlySchedulerProcessor +} + +func NewAuroraSchedulerManagerProcessor(handler AuroraSchedulerManager) *AuroraSchedulerManagerProcessor { + self159 := &AuroraSchedulerManagerProcessor{NewReadOnlySchedulerProcessor(handler)} + self159.AddToProcessorMap("createJob", &auroraSchedulerManagerProcessorCreateJob{handler: handler}) + self159.AddToProcessorMap("scheduleCronJob", &auroraSchedulerManagerProcessorScheduleCronJob{handler: handler}) + self159.AddToProcessorMap("descheduleCronJob", &auroraSchedulerManagerProcessorDescheduleCronJob{handler: handler}) + self159.AddToProcessorMap("startCronJob", &auroraSchedulerManagerProcessorStartCronJob{handler: handler}) + self159.AddToProcessorMap("restartShards", &auroraSchedulerManagerProcessorRestartShards{handler: handler}) + self159.AddToProcessorMap("killTasks", &auroraSchedulerManagerProcessorKillTasks{handler: handler}) + self159.AddToProcessorMap("addInstances", &auroraSchedulerManagerProcessorAddInstances{handler: handler}) + self159.AddToProcessorMap("replaceCronTemplate", &auroraSchedulerManagerProcessorReplaceCronTemplate{handler: handler}) + self159.AddToProcessorMap("startJobUpdate", &auroraSchedulerManagerProcessorStartJobUpdate{handler: handler}) + self159.AddToProcessorMap("pauseJobUpdate", &auroraSchedulerManagerProcessorPauseJobUpdate{handler: handler}) + self159.AddToProcessorMap("resumeJobUpdate", &auroraSchedulerManagerProcessorResumeJobUpdate{handler: handler}) + self159.AddToProcessorMap("abortJobUpdate", &auroraSchedulerManagerProcessorAbortJobUpdate{handler: handler}) + self159.AddToProcessorMap("rollbackJobUpdate", &auroraSchedulerManagerProcessorRollbackJobUpdate{handler: handler}) + self159.AddToProcessorMap("pulseJobUpdate", &auroraSchedulerManagerProcessorPulseJobUpdate{handler: handler}) + return self159 +} + +type auroraSchedulerManagerProcessorCreateJob struct { + handler AuroraSchedulerManager +} + +func (p *auroraSchedulerManagerProcessorCreateJob) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraSchedulerManagerCreateJobArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("createJob", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraSchedulerManagerCreateJobResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.CreateJob(ctx, args.Description); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing createJob: "+err2.Error()) + oprot.WriteMessageBegin("createJob", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("createJob", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraSchedulerManagerProcessorScheduleCronJob struct { + handler AuroraSchedulerManager +} + +func (p *auroraSchedulerManagerProcessorScheduleCronJob) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraSchedulerManagerScheduleCronJobArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("scheduleCronJob", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraSchedulerManagerScheduleCronJobResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.ScheduleCronJob(ctx, args.Description); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing scheduleCronJob: "+err2.Error()) + oprot.WriteMessageBegin("scheduleCronJob", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("scheduleCronJob", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraSchedulerManagerProcessorDescheduleCronJob struct { + handler AuroraSchedulerManager +} + +func (p *auroraSchedulerManagerProcessorDescheduleCronJob) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraSchedulerManagerDescheduleCronJobArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("descheduleCronJob", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraSchedulerManagerDescheduleCronJobResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.DescheduleCronJob(ctx, args.Job); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing descheduleCronJob: "+err2.Error()) + oprot.WriteMessageBegin("descheduleCronJob", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("descheduleCronJob", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraSchedulerManagerProcessorStartCronJob struct { + handler AuroraSchedulerManager +} + +func (p *auroraSchedulerManagerProcessorStartCronJob) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraSchedulerManagerStartCronJobArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("startCronJob", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraSchedulerManagerStartCronJobResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.StartCronJob(ctx, args.Job); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing startCronJob: "+err2.Error()) + oprot.WriteMessageBegin("startCronJob", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("startCronJob", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraSchedulerManagerProcessorRestartShards struct { + handler AuroraSchedulerManager +} + +func (p *auroraSchedulerManagerProcessorRestartShards) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraSchedulerManagerRestartShardsArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("restartShards", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraSchedulerManagerRestartShardsResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.RestartShards(ctx, args.Job, args.ShardIds); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing restartShards: "+err2.Error()) + oprot.WriteMessageBegin("restartShards", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("restartShards", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraSchedulerManagerProcessorKillTasks struct { + handler AuroraSchedulerManager +} + +func (p *auroraSchedulerManagerProcessorKillTasks) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraSchedulerManagerKillTasksArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("killTasks", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraSchedulerManagerKillTasksResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.KillTasks(ctx, args.Job, args.Instances, args.Message); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing killTasks: "+err2.Error()) + oprot.WriteMessageBegin("killTasks", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("killTasks", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraSchedulerManagerProcessorAddInstances struct { + handler AuroraSchedulerManager +} + +func (p *auroraSchedulerManagerProcessorAddInstances) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraSchedulerManagerAddInstancesArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("addInstances", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraSchedulerManagerAddInstancesResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.AddInstances(ctx, args.Key, args.Count); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing addInstances: "+err2.Error()) + oprot.WriteMessageBegin("addInstances", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("addInstances", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraSchedulerManagerProcessorReplaceCronTemplate struct { + handler AuroraSchedulerManager +} + +func (p *auroraSchedulerManagerProcessorReplaceCronTemplate) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraSchedulerManagerReplaceCronTemplateArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("replaceCronTemplate", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraSchedulerManagerReplaceCronTemplateResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.ReplaceCronTemplate(ctx, args.Config); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing replaceCronTemplate: "+err2.Error()) + oprot.WriteMessageBegin("replaceCronTemplate", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("replaceCronTemplate", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraSchedulerManagerProcessorStartJobUpdate struct { + handler AuroraSchedulerManager +} + +func (p *auroraSchedulerManagerProcessorStartJobUpdate) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraSchedulerManagerStartJobUpdateArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("startJobUpdate", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraSchedulerManagerStartJobUpdateResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.StartJobUpdate(ctx, args.Request, args.Message); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing startJobUpdate: "+err2.Error()) + oprot.WriteMessageBegin("startJobUpdate", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("startJobUpdate", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraSchedulerManagerProcessorPauseJobUpdate struct { + handler AuroraSchedulerManager +} + +func (p *auroraSchedulerManagerProcessorPauseJobUpdate) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraSchedulerManagerPauseJobUpdateArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("pauseJobUpdate", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraSchedulerManagerPauseJobUpdateResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.PauseJobUpdate(ctx, args.Key, args.Message); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing pauseJobUpdate: "+err2.Error()) + oprot.WriteMessageBegin("pauseJobUpdate", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("pauseJobUpdate", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraSchedulerManagerProcessorResumeJobUpdate struct { + handler AuroraSchedulerManager +} + +func (p *auroraSchedulerManagerProcessorResumeJobUpdate) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraSchedulerManagerResumeJobUpdateArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("resumeJobUpdate", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraSchedulerManagerResumeJobUpdateResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.ResumeJobUpdate(ctx, args.Key, args.Message); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing resumeJobUpdate: "+err2.Error()) + oprot.WriteMessageBegin("resumeJobUpdate", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("resumeJobUpdate", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraSchedulerManagerProcessorAbortJobUpdate struct { + handler AuroraSchedulerManager +} + +func (p *auroraSchedulerManagerProcessorAbortJobUpdate) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraSchedulerManagerAbortJobUpdateArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("abortJobUpdate", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraSchedulerManagerAbortJobUpdateResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.AbortJobUpdate(ctx, args.Key, args.Message); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing abortJobUpdate: "+err2.Error()) + oprot.WriteMessageBegin("abortJobUpdate", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("abortJobUpdate", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraSchedulerManagerProcessorRollbackJobUpdate struct { + handler AuroraSchedulerManager +} + +func (p *auroraSchedulerManagerProcessorRollbackJobUpdate) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraSchedulerManagerRollbackJobUpdateArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("rollbackJobUpdate", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraSchedulerManagerRollbackJobUpdateResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.RollbackJobUpdate(ctx, args.Key, args.Message); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing rollbackJobUpdate: "+err2.Error()) + oprot.WriteMessageBegin("rollbackJobUpdate", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("rollbackJobUpdate", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraSchedulerManagerProcessorPulseJobUpdate struct { + handler AuroraSchedulerManager +} + +func (p *auroraSchedulerManagerProcessorPulseJobUpdate) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraSchedulerManagerPulseJobUpdateArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("pulseJobUpdate", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraSchedulerManagerPulseJobUpdateResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.PulseJobUpdate(ctx, args.Key); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing pulseJobUpdate: "+err2.Error()) + oprot.WriteMessageBegin("pulseJobUpdate", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("pulseJobUpdate", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +// HELPER FUNCTIONS AND STRUCTURES + +// Attributes: +// - Description +type AuroraSchedulerManagerCreateJobArgs struct { + Description *JobConfiguration `thrift:"description,1" db:"description" json:"description"` +} + +func NewAuroraSchedulerManagerCreateJobArgs() *AuroraSchedulerManagerCreateJobArgs { + return &AuroraSchedulerManagerCreateJobArgs{} +} + +var AuroraSchedulerManagerCreateJobArgs_Description_DEFAULT *JobConfiguration + +func (p *AuroraSchedulerManagerCreateJobArgs) GetDescription() *JobConfiguration { + if !p.IsSetDescription() { + return AuroraSchedulerManagerCreateJobArgs_Description_DEFAULT + } + return p.Description +} +func (p *AuroraSchedulerManagerCreateJobArgs) IsSetDescription() bool { + return p.Description != nil +} + +func (p *AuroraSchedulerManagerCreateJobArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerCreateJobArgs) ReadField1(iprot thrift.TProtocol) error { + p.Description = &JobConfiguration{} + if err := p.Description.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Description), err) + } + return nil +} + +func (p *AuroraSchedulerManagerCreateJobArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("createJob_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerCreateJobArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("description", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:description: ", p), err) + } + if err := p.Description.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Description), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:description: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerCreateJobArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerCreateJobArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraSchedulerManagerCreateJobResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraSchedulerManagerCreateJobResult() *AuroraSchedulerManagerCreateJobResult { + return &AuroraSchedulerManagerCreateJobResult{} +} + +var AuroraSchedulerManagerCreateJobResult_Success_DEFAULT *Response + +func (p *AuroraSchedulerManagerCreateJobResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraSchedulerManagerCreateJobResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraSchedulerManagerCreateJobResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraSchedulerManagerCreateJobResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerCreateJobResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraSchedulerManagerCreateJobResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("createJob_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerCreateJobResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraSchedulerManagerCreateJobResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerCreateJobResult(%+v)", *p) +} + +// Attributes: +// - Description +type AuroraSchedulerManagerScheduleCronJobArgs struct { + Description *JobConfiguration `thrift:"description,1" db:"description" json:"description"` +} + +func NewAuroraSchedulerManagerScheduleCronJobArgs() *AuroraSchedulerManagerScheduleCronJobArgs { + return &AuroraSchedulerManagerScheduleCronJobArgs{} +} + +var AuroraSchedulerManagerScheduleCronJobArgs_Description_DEFAULT *JobConfiguration + +func (p *AuroraSchedulerManagerScheduleCronJobArgs) GetDescription() *JobConfiguration { + if !p.IsSetDescription() { + return AuroraSchedulerManagerScheduleCronJobArgs_Description_DEFAULT + } + return p.Description +} +func (p *AuroraSchedulerManagerScheduleCronJobArgs) IsSetDescription() bool { + return p.Description != nil +} + +func (p *AuroraSchedulerManagerScheduleCronJobArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerScheduleCronJobArgs) ReadField1(iprot thrift.TProtocol) error { + p.Description = &JobConfiguration{} + if err := p.Description.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Description), err) + } + return nil +} + +func (p *AuroraSchedulerManagerScheduleCronJobArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("scheduleCronJob_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerScheduleCronJobArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("description", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:description: ", p), err) + } + if err := p.Description.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Description), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:description: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerScheduleCronJobArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerScheduleCronJobArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraSchedulerManagerScheduleCronJobResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraSchedulerManagerScheduleCronJobResult() *AuroraSchedulerManagerScheduleCronJobResult { + return &AuroraSchedulerManagerScheduleCronJobResult{} +} + +var AuroraSchedulerManagerScheduleCronJobResult_Success_DEFAULT *Response + +func (p *AuroraSchedulerManagerScheduleCronJobResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraSchedulerManagerScheduleCronJobResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraSchedulerManagerScheduleCronJobResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraSchedulerManagerScheduleCronJobResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerScheduleCronJobResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraSchedulerManagerScheduleCronJobResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("scheduleCronJob_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerScheduleCronJobResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraSchedulerManagerScheduleCronJobResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerScheduleCronJobResult(%+v)", *p) +} + +// Attributes: +// - Job +type AuroraSchedulerManagerDescheduleCronJobArgs struct { + // unused fields # 1 to 3 + Job *JobKey `thrift:"job,4" db:"job" json:"job"` +} + +func NewAuroraSchedulerManagerDescheduleCronJobArgs() *AuroraSchedulerManagerDescheduleCronJobArgs { + return &AuroraSchedulerManagerDescheduleCronJobArgs{} +} + +var AuroraSchedulerManagerDescheduleCronJobArgs_Job_DEFAULT *JobKey + +func (p *AuroraSchedulerManagerDescheduleCronJobArgs) GetJob() *JobKey { + if !p.IsSetJob() { + return AuroraSchedulerManagerDescheduleCronJobArgs_Job_DEFAULT + } + return p.Job +} +func (p *AuroraSchedulerManagerDescheduleCronJobArgs) IsSetJob() bool { + return p.Job != nil +} + +func (p *AuroraSchedulerManagerDescheduleCronJobArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 4: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerDescheduleCronJobArgs) ReadField4(iprot thrift.TProtocol) error { + p.Job = &JobKey{} + if err := p.Job.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Job), err) + } + return nil +} + +func (p *AuroraSchedulerManagerDescheduleCronJobArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("descheduleCronJob_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField4(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerDescheduleCronJobArgs) writeField4(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("job", thrift.STRUCT, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:job: ", p), err) + } + if err := p.Job.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Job), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:job: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerDescheduleCronJobArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerDescheduleCronJobArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraSchedulerManagerDescheduleCronJobResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraSchedulerManagerDescheduleCronJobResult() *AuroraSchedulerManagerDescheduleCronJobResult { + return &AuroraSchedulerManagerDescheduleCronJobResult{} +} + +var AuroraSchedulerManagerDescheduleCronJobResult_Success_DEFAULT *Response + +func (p *AuroraSchedulerManagerDescheduleCronJobResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraSchedulerManagerDescheduleCronJobResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraSchedulerManagerDescheduleCronJobResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraSchedulerManagerDescheduleCronJobResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerDescheduleCronJobResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraSchedulerManagerDescheduleCronJobResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("descheduleCronJob_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerDescheduleCronJobResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraSchedulerManagerDescheduleCronJobResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerDescheduleCronJobResult(%+v)", *p) +} + +// Attributes: +// - Job +type AuroraSchedulerManagerStartCronJobArgs struct { + // unused fields # 1 to 3 + Job *JobKey `thrift:"job,4" db:"job" json:"job"` +} + +func NewAuroraSchedulerManagerStartCronJobArgs() *AuroraSchedulerManagerStartCronJobArgs { + return &AuroraSchedulerManagerStartCronJobArgs{} +} + +var AuroraSchedulerManagerStartCronJobArgs_Job_DEFAULT *JobKey + +func (p *AuroraSchedulerManagerStartCronJobArgs) GetJob() *JobKey { + if !p.IsSetJob() { + return AuroraSchedulerManagerStartCronJobArgs_Job_DEFAULT + } + return p.Job +} +func (p *AuroraSchedulerManagerStartCronJobArgs) IsSetJob() bool { + return p.Job != nil +} + +func (p *AuroraSchedulerManagerStartCronJobArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 4: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerStartCronJobArgs) ReadField4(iprot thrift.TProtocol) error { + p.Job = &JobKey{} + if err := p.Job.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Job), err) + } + return nil +} + +func (p *AuroraSchedulerManagerStartCronJobArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("startCronJob_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField4(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerStartCronJobArgs) writeField4(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("job", thrift.STRUCT, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:job: ", p), err) + } + if err := p.Job.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Job), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:job: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerStartCronJobArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerStartCronJobArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraSchedulerManagerStartCronJobResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraSchedulerManagerStartCronJobResult() *AuroraSchedulerManagerStartCronJobResult { + return &AuroraSchedulerManagerStartCronJobResult{} +} + +var AuroraSchedulerManagerStartCronJobResult_Success_DEFAULT *Response + +func (p *AuroraSchedulerManagerStartCronJobResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraSchedulerManagerStartCronJobResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraSchedulerManagerStartCronJobResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraSchedulerManagerStartCronJobResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerStartCronJobResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraSchedulerManagerStartCronJobResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("startCronJob_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerStartCronJobResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraSchedulerManagerStartCronJobResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerStartCronJobResult(%+v)", *p) +} + +// Attributes: +// - Job +// - ShardIds +type AuroraSchedulerManagerRestartShardsArgs struct { + // unused fields # 1 to 2 + ShardIds []int32 `thrift:"shardIds,3" db:"shardIds" json:"shardIds"` + // unused field # 4 + Job *JobKey `thrift:"job,5" db:"job" json:"job"` +} + +func NewAuroraSchedulerManagerRestartShardsArgs() *AuroraSchedulerManagerRestartShardsArgs { + return &AuroraSchedulerManagerRestartShardsArgs{} +} + +var AuroraSchedulerManagerRestartShardsArgs_Job_DEFAULT *JobKey + +func (p *AuroraSchedulerManagerRestartShardsArgs) GetJob() *JobKey { + if !p.IsSetJob() { + return AuroraSchedulerManagerRestartShardsArgs_Job_DEFAULT + } + return p.Job +} + +func (p *AuroraSchedulerManagerRestartShardsArgs) GetShardIds() []int32 { + return p.ShardIds +} +func (p *AuroraSchedulerManagerRestartShardsArgs) IsSetJob() bool { + return p.Job != nil +} + +func (p *AuroraSchedulerManagerRestartShardsArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 5: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField5(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.SET { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerRestartShardsArgs) ReadField5(iprot thrift.TProtocol) error { + p.Job = &JobKey{} + if err := p.Job.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Job), err) + } + return nil +} + +func (p *AuroraSchedulerManagerRestartShardsArgs) ReadField3(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]int32, 0, size) + p.ShardIds = tSet + for i := 0; i < size; i++ { + var _elem160 int32 + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 0: ", err) + } else { + _elem160 = v + } + p.ShardIds = append(p.ShardIds, _elem160) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerRestartShardsArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("restartShards_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField3(oprot); err != nil { + return err + } + if err := p.writeField5(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerRestartShardsArgs) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("shardIds", thrift.SET, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:shardIds: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.I32, len(p.ShardIds)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.ShardIds); i++ { + for j := i + 1; j < len(p.ShardIds); j++ { + if reflect.DeepEqual(p.ShardIds[i], p.ShardIds[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.ShardIds[i])) + } + } + } + for _, v := range p.ShardIds { + if err := oprot.WriteI32(int32(v)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:shardIds: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerRestartShardsArgs) writeField5(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("job", thrift.STRUCT, 5); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:job: ", p), err) + } + if err := p.Job.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Job), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 5:job: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerRestartShardsArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerRestartShardsArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraSchedulerManagerRestartShardsResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraSchedulerManagerRestartShardsResult() *AuroraSchedulerManagerRestartShardsResult { + return &AuroraSchedulerManagerRestartShardsResult{} +} + +var AuroraSchedulerManagerRestartShardsResult_Success_DEFAULT *Response + +func (p *AuroraSchedulerManagerRestartShardsResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraSchedulerManagerRestartShardsResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraSchedulerManagerRestartShardsResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraSchedulerManagerRestartShardsResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerRestartShardsResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraSchedulerManagerRestartShardsResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("restartShards_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerRestartShardsResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraSchedulerManagerRestartShardsResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerRestartShardsResult(%+v)", *p) +} + +// Attributes: +// - Job +// - Instances +// - Message +type AuroraSchedulerManagerKillTasksArgs struct { + // unused fields # 1 to 3 + Job *JobKey `thrift:"job,4" db:"job" json:"job"` + Instances []int32 `thrift:"instances,5" db:"instances" json:"instances"` + Message string `thrift:"message,6" db:"message" json:"message"` +} + +func NewAuroraSchedulerManagerKillTasksArgs() *AuroraSchedulerManagerKillTasksArgs { + return &AuroraSchedulerManagerKillTasksArgs{} +} + +var AuroraSchedulerManagerKillTasksArgs_Job_DEFAULT *JobKey + +func (p *AuroraSchedulerManagerKillTasksArgs) GetJob() *JobKey { + if !p.IsSetJob() { + return AuroraSchedulerManagerKillTasksArgs_Job_DEFAULT + } + return p.Job +} + +func (p *AuroraSchedulerManagerKillTasksArgs) GetInstances() []int32 { + return p.Instances +} + +func (p *AuroraSchedulerManagerKillTasksArgs) GetMessage() string { + return p.Message +} +func (p *AuroraSchedulerManagerKillTasksArgs) IsSetJob() bool { + return p.Job != nil +} + +func (p *AuroraSchedulerManagerKillTasksArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 4: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 5: + if fieldTypeId == thrift.SET { + if err := p.ReadField5(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 6: + if fieldTypeId == thrift.STRING { + if err := p.ReadField6(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerKillTasksArgs) ReadField4(iprot thrift.TProtocol) error { + p.Job = &JobKey{} + if err := p.Job.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Job), err) + } + return nil +} + +func (p *AuroraSchedulerManagerKillTasksArgs) ReadField5(iprot thrift.TProtocol) error { + _, size, err := iprot.ReadSetBegin() + if err != nil { + return thrift.PrependError("error reading set begin: ", err) + } + tSet := make([]int32, 0, size) + p.Instances = tSet + for i := 0; i < size; i++ { + var _elem161 int32 + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 0: ", err) + } else { + _elem161 = v + } + p.Instances = append(p.Instances, _elem161) + } + if err := iprot.ReadSetEnd(); err != nil { + return thrift.PrependError("error reading set end: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerKillTasksArgs) ReadField6(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 6: ", err) + } else { + p.Message = v + } + return nil +} + +func (p *AuroraSchedulerManagerKillTasksArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("killTasks_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField4(oprot); err != nil { + return err + } + if err := p.writeField5(oprot); err != nil { + return err + } + if err := p.writeField6(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerKillTasksArgs) writeField4(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("job", thrift.STRUCT, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:job: ", p), err) + } + if err := p.Job.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Job), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:job: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerKillTasksArgs) writeField5(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("instances", thrift.SET, 5); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:instances: ", p), err) + } + if err := oprot.WriteSetBegin(thrift.I32, len(p.Instances)); err != nil { + return thrift.PrependError("error writing set begin: ", err) + } + for i := 0; i < len(p.Instances); i++ { + for j := i + 1; j < len(p.Instances); j++ { + if reflect.DeepEqual(p.Instances[i], p.Instances[j]) { + return thrift.PrependError("", fmt.Errorf("%T error writing set field: slice is not unique", p.Instances[i])) + } + } + } + for _, v := range p.Instances { + if err := oprot.WriteI32(int32(v)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) + } + } + if err := oprot.WriteSetEnd(); err != nil { + return thrift.PrependError("error writing set end: ", err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 5:instances: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerKillTasksArgs) writeField6(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("message", thrift.STRING, 6); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 6:message: ", p), err) + } + if err := oprot.WriteString(string(p.Message)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.message (6) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 6:message: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerKillTasksArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerKillTasksArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraSchedulerManagerKillTasksResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraSchedulerManagerKillTasksResult() *AuroraSchedulerManagerKillTasksResult { + return &AuroraSchedulerManagerKillTasksResult{} +} + +var AuroraSchedulerManagerKillTasksResult_Success_DEFAULT *Response + +func (p *AuroraSchedulerManagerKillTasksResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraSchedulerManagerKillTasksResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraSchedulerManagerKillTasksResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraSchedulerManagerKillTasksResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerKillTasksResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraSchedulerManagerKillTasksResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("killTasks_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerKillTasksResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraSchedulerManagerKillTasksResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerKillTasksResult(%+v)", *p) +} + +// Attributes: +// - Key +// - Count +type AuroraSchedulerManagerAddInstancesArgs struct { + // unused fields # 1 to 2 + Key *InstanceKey `thrift:"key,3" db:"key" json:"key"` + Count int32 `thrift:"count,4" db:"count" json:"count"` +} + +func NewAuroraSchedulerManagerAddInstancesArgs() *AuroraSchedulerManagerAddInstancesArgs { + return &AuroraSchedulerManagerAddInstancesArgs{} +} + +var AuroraSchedulerManagerAddInstancesArgs_Key_DEFAULT *InstanceKey + +func (p *AuroraSchedulerManagerAddInstancesArgs) GetKey() *InstanceKey { + if !p.IsSetKey() { + return AuroraSchedulerManagerAddInstancesArgs_Key_DEFAULT + } + return p.Key +} + +func (p *AuroraSchedulerManagerAddInstancesArgs) GetCount() int32 { + return p.Count +} +func (p *AuroraSchedulerManagerAddInstancesArgs) IsSetKey() bool { + return p.Key != nil +} + +func (p *AuroraSchedulerManagerAddInstancesArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 3: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 4: + if fieldTypeId == thrift.I32 { + if err := p.ReadField4(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerAddInstancesArgs) ReadField3(iprot thrift.TProtocol) error { + p.Key = &InstanceKey{} + if err := p.Key.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) + } + return nil +} + +func (p *AuroraSchedulerManagerAddInstancesArgs) ReadField4(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 4: ", err) + } else { + p.Count = v + } + return nil +} + +func (p *AuroraSchedulerManagerAddInstancesArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("addInstances_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField3(oprot); err != nil { + return err + } + if err := p.writeField4(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerAddInstancesArgs) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:key: ", p), err) + } + if err := p.Key.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:key: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerAddInstancesArgs) writeField4(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("count", thrift.I32, 4); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:count: ", p), err) + } + if err := oprot.WriteI32(int32(p.Count)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.count (4) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 4:count: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerAddInstancesArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerAddInstancesArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraSchedulerManagerAddInstancesResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraSchedulerManagerAddInstancesResult() *AuroraSchedulerManagerAddInstancesResult { + return &AuroraSchedulerManagerAddInstancesResult{} +} + +var AuroraSchedulerManagerAddInstancesResult_Success_DEFAULT *Response + +func (p *AuroraSchedulerManagerAddInstancesResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraSchedulerManagerAddInstancesResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraSchedulerManagerAddInstancesResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraSchedulerManagerAddInstancesResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerAddInstancesResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraSchedulerManagerAddInstancesResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("addInstances_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerAddInstancesResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraSchedulerManagerAddInstancesResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerAddInstancesResult(%+v)", *p) +} + +// Attributes: +// - Config +type AuroraSchedulerManagerReplaceCronTemplateArgs struct { + Config *JobConfiguration `thrift:"config,1" db:"config" json:"config"` +} + +func NewAuroraSchedulerManagerReplaceCronTemplateArgs() *AuroraSchedulerManagerReplaceCronTemplateArgs { + return &AuroraSchedulerManagerReplaceCronTemplateArgs{} +} + +var AuroraSchedulerManagerReplaceCronTemplateArgs_Config_DEFAULT *JobConfiguration + +func (p *AuroraSchedulerManagerReplaceCronTemplateArgs) GetConfig() *JobConfiguration { + if !p.IsSetConfig() { + return AuroraSchedulerManagerReplaceCronTemplateArgs_Config_DEFAULT + } + return p.Config +} +func (p *AuroraSchedulerManagerReplaceCronTemplateArgs) IsSetConfig() bool { + return p.Config != nil +} + +func (p *AuroraSchedulerManagerReplaceCronTemplateArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerReplaceCronTemplateArgs) ReadField1(iprot thrift.TProtocol) error { + p.Config = &JobConfiguration{} + if err := p.Config.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Config), err) + } + return nil +} + +func (p *AuroraSchedulerManagerReplaceCronTemplateArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("replaceCronTemplate_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerReplaceCronTemplateArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("config", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:config: ", p), err) + } + if err := p.Config.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Config), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:config: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerReplaceCronTemplateArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerReplaceCronTemplateArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraSchedulerManagerReplaceCronTemplateResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraSchedulerManagerReplaceCronTemplateResult() *AuroraSchedulerManagerReplaceCronTemplateResult { + return &AuroraSchedulerManagerReplaceCronTemplateResult{} +} + +var AuroraSchedulerManagerReplaceCronTemplateResult_Success_DEFAULT *Response + +func (p *AuroraSchedulerManagerReplaceCronTemplateResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraSchedulerManagerReplaceCronTemplateResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraSchedulerManagerReplaceCronTemplateResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraSchedulerManagerReplaceCronTemplateResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerReplaceCronTemplateResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraSchedulerManagerReplaceCronTemplateResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("replaceCronTemplate_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerReplaceCronTemplateResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraSchedulerManagerReplaceCronTemplateResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerReplaceCronTemplateResult(%+v)", *p) +} + +// Attributes: +// - Request: A description of how to change the job. +// - Message: A user-specified message to include with the induced job update state change. +type AuroraSchedulerManagerStartJobUpdateArgs struct { + Request *JobUpdateRequest `thrift:"request,1" db:"request" json:"request"` + // unused field # 2 + Message string `thrift:"message,3" db:"message" json:"message"` +} + +func NewAuroraSchedulerManagerStartJobUpdateArgs() *AuroraSchedulerManagerStartJobUpdateArgs { + return &AuroraSchedulerManagerStartJobUpdateArgs{} +} + +var AuroraSchedulerManagerStartJobUpdateArgs_Request_DEFAULT *JobUpdateRequest + +func (p *AuroraSchedulerManagerStartJobUpdateArgs) GetRequest() *JobUpdateRequest { + if !p.IsSetRequest() { + return AuroraSchedulerManagerStartJobUpdateArgs_Request_DEFAULT + } + return p.Request +} + +func (p *AuroraSchedulerManagerStartJobUpdateArgs) GetMessage() string { + return p.Message +} +func (p *AuroraSchedulerManagerStartJobUpdateArgs) IsSetRequest() bool { + return p.Request != nil +} + +func (p *AuroraSchedulerManagerStartJobUpdateArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.STRING { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerStartJobUpdateArgs) ReadField1(iprot thrift.TProtocol) error { + p.Request = &JobUpdateRequest{} + if err := p.Request.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Request), err) + } + return nil +} + +func (p *AuroraSchedulerManagerStartJobUpdateArgs) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.Message = v + } + return nil +} + +func (p *AuroraSchedulerManagerStartJobUpdateArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("startJobUpdate_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerStartJobUpdateArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("request", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:request: ", p), err) + } + if err := p.Request.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Request), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:request: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerStartJobUpdateArgs) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("message", thrift.STRING, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:message: ", p), err) + } + if err := oprot.WriteString(string(p.Message)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.message (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:message: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerStartJobUpdateArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerStartJobUpdateArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraSchedulerManagerStartJobUpdateResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraSchedulerManagerStartJobUpdateResult() *AuroraSchedulerManagerStartJobUpdateResult { + return &AuroraSchedulerManagerStartJobUpdateResult{} +} + +var AuroraSchedulerManagerStartJobUpdateResult_Success_DEFAULT *Response + +func (p *AuroraSchedulerManagerStartJobUpdateResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraSchedulerManagerStartJobUpdateResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraSchedulerManagerStartJobUpdateResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraSchedulerManagerStartJobUpdateResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerStartJobUpdateResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraSchedulerManagerStartJobUpdateResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("startJobUpdate_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerStartJobUpdateResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraSchedulerManagerStartJobUpdateResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerStartJobUpdateResult(%+v)", *p) +} + +// Attributes: +// - Key: The update to pause. +// - Message: A user-specified message to include with the induced job update state change. +type AuroraSchedulerManagerPauseJobUpdateArgs struct { + Key *JobUpdateKey `thrift:"key,1" db:"key" json:"key"` + // unused field # 2 + Message string `thrift:"message,3" db:"message" json:"message"` +} + +func NewAuroraSchedulerManagerPauseJobUpdateArgs() *AuroraSchedulerManagerPauseJobUpdateArgs { + return &AuroraSchedulerManagerPauseJobUpdateArgs{} +} + +var AuroraSchedulerManagerPauseJobUpdateArgs_Key_DEFAULT *JobUpdateKey + +func (p *AuroraSchedulerManagerPauseJobUpdateArgs) GetKey() *JobUpdateKey { + if !p.IsSetKey() { + return AuroraSchedulerManagerPauseJobUpdateArgs_Key_DEFAULT + } + return p.Key +} + +func (p *AuroraSchedulerManagerPauseJobUpdateArgs) GetMessage() string { + return p.Message +} +func (p *AuroraSchedulerManagerPauseJobUpdateArgs) IsSetKey() bool { + return p.Key != nil +} + +func (p *AuroraSchedulerManagerPauseJobUpdateArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.STRING { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerPauseJobUpdateArgs) ReadField1(iprot thrift.TProtocol) error { + p.Key = &JobUpdateKey{} + if err := p.Key.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) + } + return nil +} + +func (p *AuroraSchedulerManagerPauseJobUpdateArgs) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.Message = v + } + return nil +} + +func (p *AuroraSchedulerManagerPauseJobUpdateArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("pauseJobUpdate_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerPauseJobUpdateArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:key: ", p), err) + } + if err := p.Key.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:key: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerPauseJobUpdateArgs) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("message", thrift.STRING, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:message: ", p), err) + } + if err := oprot.WriteString(string(p.Message)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.message (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:message: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerPauseJobUpdateArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerPauseJobUpdateArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraSchedulerManagerPauseJobUpdateResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraSchedulerManagerPauseJobUpdateResult() *AuroraSchedulerManagerPauseJobUpdateResult { + return &AuroraSchedulerManagerPauseJobUpdateResult{} +} + +var AuroraSchedulerManagerPauseJobUpdateResult_Success_DEFAULT *Response + +func (p *AuroraSchedulerManagerPauseJobUpdateResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraSchedulerManagerPauseJobUpdateResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraSchedulerManagerPauseJobUpdateResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraSchedulerManagerPauseJobUpdateResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerPauseJobUpdateResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraSchedulerManagerPauseJobUpdateResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("pauseJobUpdate_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerPauseJobUpdateResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraSchedulerManagerPauseJobUpdateResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerPauseJobUpdateResult(%+v)", *p) +} + +// Attributes: +// - Key: The update to resume. +// - Message: A user-specified message to include with the induced job update state change. +type AuroraSchedulerManagerResumeJobUpdateArgs struct { + Key *JobUpdateKey `thrift:"key,1" db:"key" json:"key"` + // unused field # 2 + Message string `thrift:"message,3" db:"message" json:"message"` +} + +func NewAuroraSchedulerManagerResumeJobUpdateArgs() *AuroraSchedulerManagerResumeJobUpdateArgs { + return &AuroraSchedulerManagerResumeJobUpdateArgs{} +} + +var AuroraSchedulerManagerResumeJobUpdateArgs_Key_DEFAULT *JobUpdateKey + +func (p *AuroraSchedulerManagerResumeJobUpdateArgs) GetKey() *JobUpdateKey { + if !p.IsSetKey() { + return AuroraSchedulerManagerResumeJobUpdateArgs_Key_DEFAULT + } + return p.Key +} + +func (p *AuroraSchedulerManagerResumeJobUpdateArgs) GetMessage() string { + return p.Message +} +func (p *AuroraSchedulerManagerResumeJobUpdateArgs) IsSetKey() bool { + return p.Key != nil +} + +func (p *AuroraSchedulerManagerResumeJobUpdateArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.STRING { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerResumeJobUpdateArgs) ReadField1(iprot thrift.TProtocol) error { + p.Key = &JobUpdateKey{} + if err := p.Key.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) + } + return nil +} + +func (p *AuroraSchedulerManagerResumeJobUpdateArgs) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.Message = v + } + return nil +} + +func (p *AuroraSchedulerManagerResumeJobUpdateArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("resumeJobUpdate_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerResumeJobUpdateArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:key: ", p), err) + } + if err := p.Key.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:key: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerResumeJobUpdateArgs) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("message", thrift.STRING, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:message: ", p), err) + } + if err := oprot.WriteString(string(p.Message)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.message (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:message: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerResumeJobUpdateArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerResumeJobUpdateArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraSchedulerManagerResumeJobUpdateResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraSchedulerManagerResumeJobUpdateResult() *AuroraSchedulerManagerResumeJobUpdateResult { + return &AuroraSchedulerManagerResumeJobUpdateResult{} +} + +var AuroraSchedulerManagerResumeJobUpdateResult_Success_DEFAULT *Response + +func (p *AuroraSchedulerManagerResumeJobUpdateResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraSchedulerManagerResumeJobUpdateResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraSchedulerManagerResumeJobUpdateResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraSchedulerManagerResumeJobUpdateResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerResumeJobUpdateResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraSchedulerManagerResumeJobUpdateResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("resumeJobUpdate_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerResumeJobUpdateResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraSchedulerManagerResumeJobUpdateResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerResumeJobUpdateResult(%+v)", *p) +} + +// Attributes: +// - Key: The update to abort. +// - Message: A user-specified message to include with the induced job update state change. +type AuroraSchedulerManagerAbortJobUpdateArgs struct { + Key *JobUpdateKey `thrift:"key,1" db:"key" json:"key"` + // unused field # 2 + Message string `thrift:"message,3" db:"message" json:"message"` +} + +func NewAuroraSchedulerManagerAbortJobUpdateArgs() *AuroraSchedulerManagerAbortJobUpdateArgs { + return &AuroraSchedulerManagerAbortJobUpdateArgs{} +} + +var AuroraSchedulerManagerAbortJobUpdateArgs_Key_DEFAULT *JobUpdateKey + +func (p *AuroraSchedulerManagerAbortJobUpdateArgs) GetKey() *JobUpdateKey { + if !p.IsSetKey() { + return AuroraSchedulerManagerAbortJobUpdateArgs_Key_DEFAULT + } + return p.Key +} + +func (p *AuroraSchedulerManagerAbortJobUpdateArgs) GetMessage() string { + return p.Message +} +func (p *AuroraSchedulerManagerAbortJobUpdateArgs) IsSetKey() bool { + return p.Key != nil +} + +func (p *AuroraSchedulerManagerAbortJobUpdateArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.STRING { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerAbortJobUpdateArgs) ReadField1(iprot thrift.TProtocol) error { + p.Key = &JobUpdateKey{} + if err := p.Key.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) + } + return nil +} + +func (p *AuroraSchedulerManagerAbortJobUpdateArgs) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.Message = v + } + return nil +} + +func (p *AuroraSchedulerManagerAbortJobUpdateArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("abortJobUpdate_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerAbortJobUpdateArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:key: ", p), err) + } + if err := p.Key.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:key: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerAbortJobUpdateArgs) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("message", thrift.STRING, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:message: ", p), err) + } + if err := oprot.WriteString(string(p.Message)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.message (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:message: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerAbortJobUpdateArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerAbortJobUpdateArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraSchedulerManagerAbortJobUpdateResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraSchedulerManagerAbortJobUpdateResult() *AuroraSchedulerManagerAbortJobUpdateResult { + return &AuroraSchedulerManagerAbortJobUpdateResult{} +} + +var AuroraSchedulerManagerAbortJobUpdateResult_Success_DEFAULT *Response + +func (p *AuroraSchedulerManagerAbortJobUpdateResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraSchedulerManagerAbortJobUpdateResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraSchedulerManagerAbortJobUpdateResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraSchedulerManagerAbortJobUpdateResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerAbortJobUpdateResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraSchedulerManagerAbortJobUpdateResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("abortJobUpdate_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerAbortJobUpdateResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraSchedulerManagerAbortJobUpdateResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerAbortJobUpdateResult(%+v)", *p) +} + +// Attributes: +// - Key: The update to rollback. +// - Message: A user-specified message to include with the induced job update state change. +type AuroraSchedulerManagerRollbackJobUpdateArgs struct { + Key *JobUpdateKey `thrift:"key,1" db:"key" json:"key"` + Message string `thrift:"message,2" db:"message" json:"message"` +} + +func NewAuroraSchedulerManagerRollbackJobUpdateArgs() *AuroraSchedulerManagerRollbackJobUpdateArgs { + return &AuroraSchedulerManagerRollbackJobUpdateArgs{} +} + +var AuroraSchedulerManagerRollbackJobUpdateArgs_Key_DEFAULT *JobUpdateKey + +func (p *AuroraSchedulerManagerRollbackJobUpdateArgs) GetKey() *JobUpdateKey { + if !p.IsSetKey() { + return AuroraSchedulerManagerRollbackJobUpdateArgs_Key_DEFAULT + } + return p.Key +} + +func (p *AuroraSchedulerManagerRollbackJobUpdateArgs) GetMessage() string { + return p.Message +} +func (p *AuroraSchedulerManagerRollbackJobUpdateArgs) IsSetKey() bool { + return p.Key != nil +} + +func (p *AuroraSchedulerManagerRollbackJobUpdateArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRING { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerRollbackJobUpdateArgs) ReadField1(iprot thrift.TProtocol) error { + p.Key = &JobUpdateKey{} + if err := p.Key.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) + } + return nil +} + +func (p *AuroraSchedulerManagerRollbackJobUpdateArgs) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + p.Message = v + } + return nil +} + +func (p *AuroraSchedulerManagerRollbackJobUpdateArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("rollbackJobUpdate_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerRollbackJobUpdateArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:key: ", p), err) + } + if err := p.Key.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:key: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerRollbackJobUpdateArgs) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("message", thrift.STRING, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:message: ", p), err) + } + if err := oprot.WriteString(string(p.Message)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.message (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:message: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerRollbackJobUpdateArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerRollbackJobUpdateArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraSchedulerManagerRollbackJobUpdateResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraSchedulerManagerRollbackJobUpdateResult() *AuroraSchedulerManagerRollbackJobUpdateResult { + return &AuroraSchedulerManagerRollbackJobUpdateResult{} +} + +var AuroraSchedulerManagerRollbackJobUpdateResult_Success_DEFAULT *Response + +func (p *AuroraSchedulerManagerRollbackJobUpdateResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraSchedulerManagerRollbackJobUpdateResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraSchedulerManagerRollbackJobUpdateResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraSchedulerManagerRollbackJobUpdateResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerRollbackJobUpdateResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraSchedulerManagerRollbackJobUpdateResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("rollbackJobUpdate_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerRollbackJobUpdateResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraSchedulerManagerRollbackJobUpdateResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerRollbackJobUpdateResult(%+v)", *p) +} + +// Attributes: +// - Key +type AuroraSchedulerManagerPulseJobUpdateArgs struct { + Key *JobUpdateKey `thrift:"key,1" db:"key" json:"key"` +} + +func NewAuroraSchedulerManagerPulseJobUpdateArgs() *AuroraSchedulerManagerPulseJobUpdateArgs { + return &AuroraSchedulerManagerPulseJobUpdateArgs{} +} + +var AuroraSchedulerManagerPulseJobUpdateArgs_Key_DEFAULT *JobUpdateKey + +func (p *AuroraSchedulerManagerPulseJobUpdateArgs) GetKey() *JobUpdateKey { + if !p.IsSetKey() { + return AuroraSchedulerManagerPulseJobUpdateArgs_Key_DEFAULT + } + return p.Key +} +func (p *AuroraSchedulerManagerPulseJobUpdateArgs) IsSetKey() bool { + return p.Key != nil +} + +func (p *AuroraSchedulerManagerPulseJobUpdateArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerPulseJobUpdateArgs) ReadField1(iprot thrift.TProtocol) error { + p.Key = &JobUpdateKey{} + if err := p.Key.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) + } + return nil +} + +func (p *AuroraSchedulerManagerPulseJobUpdateArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("pulseJobUpdate_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerPulseJobUpdateArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:key: ", p), err) + } + if err := p.Key.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:key: ", p), err) + } + return err +} + +func (p *AuroraSchedulerManagerPulseJobUpdateArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerPulseJobUpdateArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraSchedulerManagerPulseJobUpdateResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraSchedulerManagerPulseJobUpdateResult() *AuroraSchedulerManagerPulseJobUpdateResult { + return &AuroraSchedulerManagerPulseJobUpdateResult{} +} + +var AuroraSchedulerManagerPulseJobUpdateResult_Success_DEFAULT *Response + +func (p *AuroraSchedulerManagerPulseJobUpdateResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraSchedulerManagerPulseJobUpdateResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraSchedulerManagerPulseJobUpdateResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraSchedulerManagerPulseJobUpdateResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraSchedulerManagerPulseJobUpdateResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraSchedulerManagerPulseJobUpdateResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("pulseJobUpdate_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraSchedulerManagerPulseJobUpdateResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraSchedulerManagerPulseJobUpdateResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraSchedulerManagerPulseJobUpdateResult(%+v)", *p) +} + +type AuroraAdmin interface { + AuroraSchedulerManager + + // Assign quota to a user. This will overwrite any pre-existing quota for the user. + // + // Parameters: + // - OwnerRole + // - Quota + SetQuota(ctx context.Context, ownerRole string, quota *ResourceAggregate) (r *Response, err error) + // Forces a task into a specific state. This does not guarantee the task will enter the given + // state, as the task must still transition within the bounds of the state machine. However, + // it attempts to enter that state via the state machine. + // + // Parameters: + // - TaskId + // - Status + ForceTaskState(ctx context.Context, taskId string, status ScheduleStatus) (r *Response, err error) + // Immediately writes a storage snapshot to disk. + PerformBackup(ctx context.Context) (r *Response, err error) + // Lists backups that are available for recovery. + ListBackups(ctx context.Context) (r *Response, err error) + // Loads a backup to an in-memory storage. This must precede all other recovery operations. + // + // Parameters: + // - BackupId + StageRecovery(ctx context.Context, backupId string) (r *Response, err error) + // Queries for tasks in a staged recovery. + // + // Parameters: + // - Query + QueryRecovery(ctx context.Context, query *TaskQuery) (r *Response, err error) + // Deletes tasks from a staged recovery. + // + // Parameters: + // - Query + DeleteRecoveryTasks(ctx context.Context, query *TaskQuery) (r *Response, err error) + // Commits a staged recovery, completely replacing the previous storage state. + CommitRecovery(ctx context.Context) (r *Response, err error) + // Unloads (aborts) a staged recovery. + UnloadRecovery(ctx context.Context) (r *Response, err error) + // Put the given hosts into maintenance mode. + // + // Parameters: + // - Hosts + StartMaintenance(ctx context.Context, hosts *Hosts) (r *Response, err error) + // Ask scheduler to begin moving tasks scheduled on given hosts. + // + // Parameters: + // - Hosts + DrainHosts(ctx context.Context, hosts *Hosts) (r *Response, err error) + // Retrieve the current maintenance states for a group of hosts. + // + // Parameters: + // - Hosts + MaintenanceStatus(ctx context.Context, hosts *Hosts) (r *Response, err error) + // Set the given hosts back into serving mode. + // + // Parameters: + // - Hosts + EndMaintenance(ctx context.Context, hosts *Hosts) (r *Response, err error) + // Ask scheduler to put hosts into DRAINING mode and move scheduled tasks off of the hosts + // such that its SLA requirements are satisfied. Use defaultSlaPolicy if it is not set for a task. + // + // + // Parameters: + // - Hosts + // - DefaultSlaPolicy + // - TimeoutSecs + SlaDrainHosts(ctx context.Context, hosts *Hosts, defaultSlaPolicy *SlaPolicy, timeoutSecs int64) (r *Response, err error) + // Start a storage snapshot and block until it completes. + Snapshot(ctx context.Context) (r *Response, err error) + // Tell scheduler to trigger an explicit task reconciliation with the given settings. + // + // Parameters: + // - Settings + TriggerExplicitTaskReconciliation(ctx context.Context, settings *ExplicitReconciliationSettings) (r *Response, err error) + // Tell scheduler to trigger an implicit task reconciliation. + TriggerImplicitTaskReconciliation(ctx context.Context) (r *Response, err error) + // Force prune any (terminal) tasks that match the query. If no statuses are supplied with the + // query, it will default to all terminal task states. If statuses are supplied, they must be + // terminal states. + // + // Parameters: + // - Query + PruneTasks(ctx context.Context, query *TaskQuery) (r *Response, err error) +} + +type AuroraAdminClient struct { + *AuroraSchedulerManagerClient +} + +func NewAuroraAdminClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *AuroraAdminClient { + return &AuroraAdminClient{AuroraSchedulerManagerClient: NewAuroraSchedulerManagerClientFactory(t, f)} +} + +func NewAuroraAdminClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *AuroraAdminClient { + return &AuroraAdminClient{AuroraSchedulerManagerClient: NewAuroraSchedulerManagerClientProtocol(t, iprot, oprot)} +} + +func NewAuroraAdminClient(c thrift.TClient) *AuroraAdminClient { + return &AuroraAdminClient{ + AuroraSchedulerManagerClient: NewAuroraSchedulerManagerClient(c), + } +} + +// Assign quota to a user. This will overwrite any pre-existing quota for the user. +// +// Parameters: +// - OwnerRole +// - Quota +func (p *AuroraAdminClient) SetQuota(ctx context.Context, ownerRole string, quota *ResourceAggregate) (r *Response, err error) { + var _args316 AuroraAdminSetQuotaArgs + _args316.OwnerRole = ownerRole + _args316.Quota = quota + var _result317 AuroraAdminSetQuotaResult + if err = p.Client_().Call(ctx, "setQuota", &_args316, &_result317); err != nil { + return + } + return _result317.GetSuccess(), nil +} + +// Forces a task into a specific state. This does not guarantee the task will enter the given +// state, as the task must still transition within the bounds of the state machine. However, +// it attempts to enter that state via the state machine. +// +// Parameters: +// - TaskId +// - Status +func (p *AuroraAdminClient) ForceTaskState(ctx context.Context, taskId string, status ScheduleStatus) (r *Response, err error) { + var _args318 AuroraAdminForceTaskStateArgs + _args318.TaskId = taskId + _args318.Status = status + var _result319 AuroraAdminForceTaskStateResult + if err = p.Client_().Call(ctx, "forceTaskState", &_args318, &_result319); err != nil { + return + } + return _result319.GetSuccess(), nil +} + +// Immediately writes a storage snapshot to disk. +func (p *AuroraAdminClient) PerformBackup(ctx context.Context) (r *Response, err error) { + var _args320 AuroraAdminPerformBackupArgs + var _result321 AuroraAdminPerformBackupResult + if err = p.Client_().Call(ctx, "performBackup", &_args320, &_result321); err != nil { + return + } + return _result321.GetSuccess(), nil +} + +// Lists backups that are available for recovery. +func (p *AuroraAdminClient) ListBackups(ctx context.Context) (r *Response, err error) { + var _args322 AuroraAdminListBackupsArgs + var _result323 AuroraAdminListBackupsResult + if err = p.Client_().Call(ctx, "listBackups", &_args322, &_result323); err != nil { + return + } + return _result323.GetSuccess(), nil +} + +// Loads a backup to an in-memory storage. This must precede all other recovery operations. +// +// Parameters: +// - BackupId +func (p *AuroraAdminClient) StageRecovery(ctx context.Context, backupId string) (r *Response, err error) { + var _args324 AuroraAdminStageRecoveryArgs + _args324.BackupId = backupId + var _result325 AuroraAdminStageRecoveryResult + if err = p.Client_().Call(ctx, "stageRecovery", &_args324, &_result325); err != nil { + return + } + return _result325.GetSuccess(), nil +} + +// Queries for tasks in a staged recovery. +// +// Parameters: +// - Query +func (p *AuroraAdminClient) QueryRecovery(ctx context.Context, query *TaskQuery) (r *Response, err error) { + var _args326 AuroraAdminQueryRecoveryArgs + _args326.Query = query + var _result327 AuroraAdminQueryRecoveryResult + if err = p.Client_().Call(ctx, "queryRecovery", &_args326, &_result327); err != nil { + return + } + return _result327.GetSuccess(), nil +} + +// Deletes tasks from a staged recovery. +// +// Parameters: +// - Query +func (p *AuroraAdminClient) DeleteRecoveryTasks(ctx context.Context, query *TaskQuery) (r *Response, err error) { + var _args328 AuroraAdminDeleteRecoveryTasksArgs + _args328.Query = query + var _result329 AuroraAdminDeleteRecoveryTasksResult + if err = p.Client_().Call(ctx, "deleteRecoveryTasks", &_args328, &_result329); err != nil { + return + } + return _result329.GetSuccess(), nil +} + +// Commits a staged recovery, completely replacing the previous storage state. +func (p *AuroraAdminClient) CommitRecovery(ctx context.Context) (r *Response, err error) { + var _args330 AuroraAdminCommitRecoveryArgs + var _result331 AuroraAdminCommitRecoveryResult + if err = p.Client_().Call(ctx, "commitRecovery", &_args330, &_result331); err != nil { + return + } + return _result331.GetSuccess(), nil +} + +// Unloads (aborts) a staged recovery. +func (p *AuroraAdminClient) UnloadRecovery(ctx context.Context) (r *Response, err error) { + var _args332 AuroraAdminUnloadRecoveryArgs + var _result333 AuroraAdminUnloadRecoveryResult + if err = p.Client_().Call(ctx, "unloadRecovery", &_args332, &_result333); err != nil { + return + } + return _result333.GetSuccess(), nil +} + +// Put the given hosts into maintenance mode. +// +// Parameters: +// - Hosts +func (p *AuroraAdminClient) StartMaintenance(ctx context.Context, hosts *Hosts) (r *Response, err error) { + var _args334 AuroraAdminStartMaintenanceArgs + _args334.Hosts = hosts + var _result335 AuroraAdminStartMaintenanceResult + if err = p.Client_().Call(ctx, "startMaintenance", &_args334, &_result335); err != nil { + return + } + return _result335.GetSuccess(), nil +} + +// Ask scheduler to begin moving tasks scheduled on given hosts. +// +// Parameters: +// - Hosts +func (p *AuroraAdminClient) DrainHosts(ctx context.Context, hosts *Hosts) (r *Response, err error) { + var _args336 AuroraAdminDrainHostsArgs + _args336.Hosts = hosts + var _result337 AuroraAdminDrainHostsResult + if err = p.Client_().Call(ctx, "drainHosts", &_args336, &_result337); err != nil { + return + } + return _result337.GetSuccess(), nil +} + +// Retrieve the current maintenance states for a group of hosts. +// +// Parameters: +// - Hosts +func (p *AuroraAdminClient) MaintenanceStatus(ctx context.Context, hosts *Hosts) (r *Response, err error) { + var _args338 AuroraAdminMaintenanceStatusArgs + _args338.Hosts = hosts + var _result339 AuroraAdminMaintenanceStatusResult + if err = p.Client_().Call(ctx, "maintenanceStatus", &_args338, &_result339); err != nil { + return + } + return _result339.GetSuccess(), nil +} + +// Set the given hosts back into serving mode. +// +// Parameters: +// - Hosts +func (p *AuroraAdminClient) EndMaintenance(ctx context.Context, hosts *Hosts) (r *Response, err error) { + var _args340 AuroraAdminEndMaintenanceArgs + _args340.Hosts = hosts + var _result341 AuroraAdminEndMaintenanceResult + if err = p.Client_().Call(ctx, "endMaintenance", &_args340, &_result341); err != nil { + return + } + return _result341.GetSuccess(), nil +} + +// Ask scheduler to put hosts into DRAINING mode and move scheduled tasks off of the hosts +// such that its SLA requirements are satisfied. Use defaultSlaPolicy if it is not set for a task. +// +// +// Parameters: +// - Hosts +// - DefaultSlaPolicy +// - TimeoutSecs +func (p *AuroraAdminClient) SlaDrainHosts(ctx context.Context, hosts *Hosts, defaultSlaPolicy *SlaPolicy, timeoutSecs int64) (r *Response, err error) { + var _args342 AuroraAdminSlaDrainHostsArgs + _args342.Hosts = hosts + _args342.DefaultSlaPolicy = defaultSlaPolicy + _args342.TimeoutSecs = timeoutSecs + var _result343 AuroraAdminSlaDrainHostsResult + if err = p.Client_().Call(ctx, "slaDrainHosts", &_args342, &_result343); err != nil { + return + } + return _result343.GetSuccess(), nil +} + +// Start a storage snapshot and block until it completes. +func (p *AuroraAdminClient) Snapshot(ctx context.Context) (r *Response, err error) { + var _args344 AuroraAdminSnapshotArgs + var _result345 AuroraAdminSnapshotResult + if err = p.Client_().Call(ctx, "snapshot", &_args344, &_result345); err != nil { + return + } + return _result345.GetSuccess(), nil +} + +// Tell scheduler to trigger an explicit task reconciliation with the given settings. +// +// Parameters: +// - Settings +func (p *AuroraAdminClient) TriggerExplicitTaskReconciliation(ctx context.Context, settings *ExplicitReconciliationSettings) (r *Response, err error) { + var _args346 AuroraAdminTriggerExplicitTaskReconciliationArgs + _args346.Settings = settings + var _result347 AuroraAdminTriggerExplicitTaskReconciliationResult + if err = p.Client_().Call(ctx, "triggerExplicitTaskReconciliation", &_args346, &_result347); err != nil { + return + } + return _result347.GetSuccess(), nil +} + +// Tell scheduler to trigger an implicit task reconciliation. +func (p *AuroraAdminClient) TriggerImplicitTaskReconciliation(ctx context.Context) (r *Response, err error) { + var _args348 AuroraAdminTriggerImplicitTaskReconciliationArgs + var _result349 AuroraAdminTriggerImplicitTaskReconciliationResult + if err = p.Client_().Call(ctx, "triggerImplicitTaskReconciliation", &_args348, &_result349); err != nil { + return + } + return _result349.GetSuccess(), nil +} + +// Force prune any (terminal) tasks that match the query. If no statuses are supplied with the +// query, it will default to all terminal task states. If statuses are supplied, they must be +// terminal states. +// +// Parameters: +// - Query +func (p *AuroraAdminClient) PruneTasks(ctx context.Context, query *TaskQuery) (r *Response, err error) { + var _args350 AuroraAdminPruneTasksArgs + _args350.Query = query + var _result351 AuroraAdminPruneTasksResult + if err = p.Client_().Call(ctx, "pruneTasks", &_args350, &_result351); err != nil { + return + } + return _result351.GetSuccess(), nil +} + +type AuroraAdminProcessor struct { + *AuroraSchedulerManagerProcessor +} + +func NewAuroraAdminProcessor(handler AuroraAdmin) *AuroraAdminProcessor { + self352 := &AuroraAdminProcessor{NewAuroraSchedulerManagerProcessor(handler)} + self352.AddToProcessorMap("setQuota", &auroraAdminProcessorSetQuota{handler: handler}) + self352.AddToProcessorMap("forceTaskState", &auroraAdminProcessorForceTaskState{handler: handler}) + self352.AddToProcessorMap("performBackup", &auroraAdminProcessorPerformBackup{handler: handler}) + self352.AddToProcessorMap("listBackups", &auroraAdminProcessorListBackups{handler: handler}) + self352.AddToProcessorMap("stageRecovery", &auroraAdminProcessorStageRecovery{handler: handler}) + self352.AddToProcessorMap("queryRecovery", &auroraAdminProcessorQueryRecovery{handler: handler}) + self352.AddToProcessorMap("deleteRecoveryTasks", &auroraAdminProcessorDeleteRecoveryTasks{handler: handler}) + self352.AddToProcessorMap("commitRecovery", &auroraAdminProcessorCommitRecovery{handler: handler}) + self352.AddToProcessorMap("unloadRecovery", &auroraAdminProcessorUnloadRecovery{handler: handler}) + self352.AddToProcessorMap("startMaintenance", &auroraAdminProcessorStartMaintenance{handler: handler}) + self352.AddToProcessorMap("drainHosts", &auroraAdminProcessorDrainHosts{handler: handler}) + self352.AddToProcessorMap("maintenanceStatus", &auroraAdminProcessorMaintenanceStatus{handler: handler}) + self352.AddToProcessorMap("endMaintenance", &auroraAdminProcessorEndMaintenance{handler: handler}) + self352.AddToProcessorMap("slaDrainHosts", &auroraAdminProcessorSlaDrainHosts{handler: handler}) + self352.AddToProcessorMap("snapshot", &auroraAdminProcessorSnapshot{handler: handler}) + self352.AddToProcessorMap("triggerExplicitTaskReconciliation", &auroraAdminProcessorTriggerExplicitTaskReconciliation{handler: handler}) + self352.AddToProcessorMap("triggerImplicitTaskReconciliation", &auroraAdminProcessorTriggerImplicitTaskReconciliation{handler: handler}) + self352.AddToProcessorMap("pruneTasks", &auroraAdminProcessorPruneTasks{handler: handler}) + return self352 +} + +type auroraAdminProcessorSetQuota struct { + handler AuroraAdmin +} + +func (p *auroraAdminProcessorSetQuota) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraAdminSetQuotaArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("setQuota", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraAdminSetQuotaResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.SetQuota(ctx, args.OwnerRole, args.Quota); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing setQuota: "+err2.Error()) + oprot.WriteMessageBegin("setQuota", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("setQuota", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraAdminProcessorForceTaskState struct { + handler AuroraAdmin +} + +func (p *auroraAdminProcessorForceTaskState) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraAdminForceTaskStateArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("forceTaskState", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraAdminForceTaskStateResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.ForceTaskState(ctx, args.TaskId, args.Status); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing forceTaskState: "+err2.Error()) + oprot.WriteMessageBegin("forceTaskState", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("forceTaskState", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraAdminProcessorPerformBackup struct { + handler AuroraAdmin +} + +func (p *auroraAdminProcessorPerformBackup) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraAdminPerformBackupArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("performBackup", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraAdminPerformBackupResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.PerformBackup(ctx); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing performBackup: "+err2.Error()) + oprot.WriteMessageBegin("performBackup", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("performBackup", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraAdminProcessorListBackups struct { + handler AuroraAdmin +} + +func (p *auroraAdminProcessorListBackups) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraAdminListBackupsArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("listBackups", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraAdminListBackupsResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.ListBackups(ctx); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing listBackups: "+err2.Error()) + oprot.WriteMessageBegin("listBackups", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("listBackups", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraAdminProcessorStageRecovery struct { + handler AuroraAdmin +} + +func (p *auroraAdminProcessorStageRecovery) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraAdminStageRecoveryArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("stageRecovery", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraAdminStageRecoveryResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.StageRecovery(ctx, args.BackupId); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing stageRecovery: "+err2.Error()) + oprot.WriteMessageBegin("stageRecovery", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("stageRecovery", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraAdminProcessorQueryRecovery struct { + handler AuroraAdmin +} + +func (p *auroraAdminProcessorQueryRecovery) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraAdminQueryRecoveryArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("queryRecovery", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraAdminQueryRecoveryResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.QueryRecovery(ctx, args.Query); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing queryRecovery: "+err2.Error()) + oprot.WriteMessageBegin("queryRecovery", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("queryRecovery", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraAdminProcessorDeleteRecoveryTasks struct { + handler AuroraAdmin +} + +func (p *auroraAdminProcessorDeleteRecoveryTasks) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraAdminDeleteRecoveryTasksArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("deleteRecoveryTasks", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraAdminDeleteRecoveryTasksResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.DeleteRecoveryTasks(ctx, args.Query); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing deleteRecoveryTasks: "+err2.Error()) + oprot.WriteMessageBegin("deleteRecoveryTasks", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("deleteRecoveryTasks", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraAdminProcessorCommitRecovery struct { + handler AuroraAdmin +} + +func (p *auroraAdminProcessorCommitRecovery) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraAdminCommitRecoveryArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("commitRecovery", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraAdminCommitRecoveryResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.CommitRecovery(ctx); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing commitRecovery: "+err2.Error()) + oprot.WriteMessageBegin("commitRecovery", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("commitRecovery", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraAdminProcessorUnloadRecovery struct { + handler AuroraAdmin +} + +func (p *auroraAdminProcessorUnloadRecovery) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraAdminUnloadRecoveryArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("unloadRecovery", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraAdminUnloadRecoveryResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.UnloadRecovery(ctx); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing unloadRecovery: "+err2.Error()) + oprot.WriteMessageBegin("unloadRecovery", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("unloadRecovery", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraAdminProcessorStartMaintenance struct { + handler AuroraAdmin +} + +func (p *auroraAdminProcessorStartMaintenance) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraAdminStartMaintenanceArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("startMaintenance", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraAdminStartMaintenanceResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.StartMaintenance(ctx, args.Hosts); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing startMaintenance: "+err2.Error()) + oprot.WriteMessageBegin("startMaintenance", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("startMaintenance", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraAdminProcessorDrainHosts struct { + handler AuroraAdmin +} + +func (p *auroraAdminProcessorDrainHosts) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraAdminDrainHostsArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("drainHosts", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraAdminDrainHostsResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.DrainHosts(ctx, args.Hosts); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing drainHosts: "+err2.Error()) + oprot.WriteMessageBegin("drainHosts", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("drainHosts", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraAdminProcessorMaintenanceStatus struct { + handler AuroraAdmin +} + +func (p *auroraAdminProcessorMaintenanceStatus) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraAdminMaintenanceStatusArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("maintenanceStatus", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraAdminMaintenanceStatusResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.MaintenanceStatus(ctx, args.Hosts); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing maintenanceStatus: "+err2.Error()) + oprot.WriteMessageBegin("maintenanceStatus", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("maintenanceStatus", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraAdminProcessorEndMaintenance struct { + handler AuroraAdmin +} + +func (p *auroraAdminProcessorEndMaintenance) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraAdminEndMaintenanceArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("endMaintenance", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraAdminEndMaintenanceResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.EndMaintenance(ctx, args.Hosts); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing endMaintenance: "+err2.Error()) + oprot.WriteMessageBegin("endMaintenance", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("endMaintenance", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraAdminProcessorSlaDrainHosts struct { + handler AuroraAdmin +} + +func (p *auroraAdminProcessorSlaDrainHosts) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraAdminSlaDrainHostsArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("slaDrainHosts", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraAdminSlaDrainHostsResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.SlaDrainHosts(ctx, args.Hosts, args.DefaultSlaPolicy, args.TimeoutSecs); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing slaDrainHosts: "+err2.Error()) + oprot.WriteMessageBegin("slaDrainHosts", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("slaDrainHosts", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraAdminProcessorSnapshot struct { + handler AuroraAdmin +} + +func (p *auroraAdminProcessorSnapshot) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraAdminSnapshotArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("snapshot", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraAdminSnapshotResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.Snapshot(ctx); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing snapshot: "+err2.Error()) + oprot.WriteMessageBegin("snapshot", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("snapshot", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraAdminProcessorTriggerExplicitTaskReconciliation struct { + handler AuroraAdmin +} + +func (p *auroraAdminProcessorTriggerExplicitTaskReconciliation) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraAdminTriggerExplicitTaskReconciliationArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("triggerExplicitTaskReconciliation", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraAdminTriggerExplicitTaskReconciliationResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.TriggerExplicitTaskReconciliation(ctx, args.Settings); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing triggerExplicitTaskReconciliation: "+err2.Error()) + oprot.WriteMessageBegin("triggerExplicitTaskReconciliation", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("triggerExplicitTaskReconciliation", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraAdminProcessorTriggerImplicitTaskReconciliation struct { + handler AuroraAdmin +} + +func (p *auroraAdminProcessorTriggerImplicitTaskReconciliation) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraAdminTriggerImplicitTaskReconciliationArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("triggerImplicitTaskReconciliation", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraAdminTriggerImplicitTaskReconciliationResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.TriggerImplicitTaskReconciliation(ctx); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing triggerImplicitTaskReconciliation: "+err2.Error()) + oprot.WriteMessageBegin("triggerImplicitTaskReconciliation", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("triggerImplicitTaskReconciliation", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +type auroraAdminProcessorPruneTasks struct { + handler AuroraAdmin +} + +func (p *auroraAdminProcessorPruneTasks) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { + args := AuroraAdminPruneTasksArgs{} + if err = args.Read(iprot); err != nil { + iprot.ReadMessageEnd() + x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) + oprot.WriteMessageBegin("pruneTasks", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return false, err + } + + iprot.ReadMessageEnd() + result := AuroraAdminPruneTasksResult{} + var retval *Response + var err2 error + if retval, err2 = p.handler.PruneTasks(ctx, args.Query); err2 != nil { + x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing pruneTasks: "+err2.Error()) + oprot.WriteMessageBegin("pruneTasks", thrift.EXCEPTION, seqId) + x.Write(oprot) + oprot.WriteMessageEnd() + oprot.Flush(ctx) + return true, err2 + } else { + result.Success = retval + } + if err2 = oprot.WriteMessageBegin("pruneTasks", thrift.REPLY, seqId); err2 != nil { + err = err2 + } + if err2 = result.Write(oprot); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { + err = err2 + } + if err2 = oprot.Flush(ctx); err == nil && err2 != nil { + err = err2 + } + if err != nil { + return + } + return true, err +} + +// HELPER FUNCTIONS AND STRUCTURES + +// Attributes: +// - OwnerRole +// - Quota +type AuroraAdminSetQuotaArgs struct { + OwnerRole string `thrift:"ownerRole,1" db:"ownerRole" json:"ownerRole"` + Quota *ResourceAggregate `thrift:"quota,2" db:"quota" json:"quota"` +} + +func NewAuroraAdminSetQuotaArgs() *AuroraAdminSetQuotaArgs { + return &AuroraAdminSetQuotaArgs{} +} + +func (p *AuroraAdminSetQuotaArgs) GetOwnerRole() string { + return p.OwnerRole +} + +var AuroraAdminSetQuotaArgs_Quota_DEFAULT *ResourceAggregate + +func (p *AuroraAdminSetQuotaArgs) GetQuota() *ResourceAggregate { + if !p.IsSetQuota() { + return AuroraAdminSetQuotaArgs_Quota_DEFAULT + } + return p.Quota +} +func (p *AuroraAdminSetQuotaArgs) IsSetQuota() bool { + return p.Quota != nil +} + +func (p *AuroraAdminSetQuotaArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminSetQuotaArgs) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.OwnerRole = v + } + return nil +} + +func (p *AuroraAdminSetQuotaArgs) ReadField2(iprot thrift.TProtocol) error { + p.Quota = &ResourceAggregate{} + if err := p.Quota.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Quota), err) + } + return nil +} + +func (p *AuroraAdminSetQuotaArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("setQuota_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminSetQuotaArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("ownerRole", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:ownerRole: ", p), err) + } + if err := oprot.WriteString(string(p.OwnerRole)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.ownerRole (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:ownerRole: ", p), err) + } + return err +} + +func (p *AuroraAdminSetQuotaArgs) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("quota", thrift.STRUCT, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:quota: ", p), err) + } + if err := p.Quota.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Quota), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:quota: ", p), err) + } + return err +} + +func (p *AuroraAdminSetQuotaArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminSetQuotaArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraAdminSetQuotaResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraAdminSetQuotaResult() *AuroraAdminSetQuotaResult { + return &AuroraAdminSetQuotaResult{} +} + +var AuroraAdminSetQuotaResult_Success_DEFAULT *Response + +func (p *AuroraAdminSetQuotaResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraAdminSetQuotaResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraAdminSetQuotaResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraAdminSetQuotaResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminSetQuotaResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraAdminSetQuotaResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("setQuota_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminSetQuotaResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraAdminSetQuotaResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminSetQuotaResult(%+v)", *p) +} + +// Attributes: +// - TaskId +// - Status +type AuroraAdminForceTaskStateArgs struct { + TaskId string `thrift:"taskId,1" db:"taskId" json:"taskId"` + Status ScheduleStatus `thrift:"status,2" db:"status" json:"status"` +} + +func NewAuroraAdminForceTaskStateArgs() *AuroraAdminForceTaskStateArgs { + return &AuroraAdminForceTaskStateArgs{} +} + +func (p *AuroraAdminForceTaskStateArgs) GetTaskId() string { + return p.TaskId +} + +func (p *AuroraAdminForceTaskStateArgs) GetStatus() ScheduleStatus { + return p.Status +} +func (p *AuroraAdminForceTaskStateArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.I32 { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminForceTaskStateArgs) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.TaskId = v + } + return nil +} + +func (p *AuroraAdminForceTaskStateArgs) ReadField2(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI32(); err != nil { + return thrift.PrependError("error reading field 2: ", err) + } else { + temp := ScheduleStatus(v) + p.Status = temp + } + return nil +} + +func (p *AuroraAdminForceTaskStateArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("forceTaskState_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminForceTaskStateArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("taskId", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:taskId: ", p), err) + } + if err := oprot.WriteString(string(p.TaskId)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.taskId (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:taskId: ", p), err) + } + return err +} + +func (p *AuroraAdminForceTaskStateArgs) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("status", thrift.I32, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:status: ", p), err) + } + if err := oprot.WriteI32(int32(p.Status)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.status (2) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:status: ", p), err) + } + return err +} + +func (p *AuroraAdminForceTaskStateArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminForceTaskStateArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraAdminForceTaskStateResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraAdminForceTaskStateResult() *AuroraAdminForceTaskStateResult { + return &AuroraAdminForceTaskStateResult{} +} + +var AuroraAdminForceTaskStateResult_Success_DEFAULT *Response + +func (p *AuroraAdminForceTaskStateResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraAdminForceTaskStateResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraAdminForceTaskStateResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraAdminForceTaskStateResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminForceTaskStateResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraAdminForceTaskStateResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("forceTaskState_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminForceTaskStateResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraAdminForceTaskStateResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminForceTaskStateResult(%+v)", *p) +} + +type AuroraAdminPerformBackupArgs struct { +} + +func NewAuroraAdminPerformBackupArgs() *AuroraAdminPerformBackupArgs { + return &AuroraAdminPerformBackupArgs{} +} + +func (p *AuroraAdminPerformBackupArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminPerformBackupArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("performBackup_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminPerformBackupArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminPerformBackupArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraAdminPerformBackupResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraAdminPerformBackupResult() *AuroraAdminPerformBackupResult { + return &AuroraAdminPerformBackupResult{} +} + +var AuroraAdminPerformBackupResult_Success_DEFAULT *Response + +func (p *AuroraAdminPerformBackupResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraAdminPerformBackupResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraAdminPerformBackupResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraAdminPerformBackupResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminPerformBackupResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraAdminPerformBackupResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("performBackup_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminPerformBackupResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraAdminPerformBackupResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminPerformBackupResult(%+v)", *p) +} + +type AuroraAdminListBackupsArgs struct { +} + +func NewAuroraAdminListBackupsArgs() *AuroraAdminListBackupsArgs { + return &AuroraAdminListBackupsArgs{} +} + +func (p *AuroraAdminListBackupsArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminListBackupsArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("listBackups_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminListBackupsArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminListBackupsArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraAdminListBackupsResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraAdminListBackupsResult() *AuroraAdminListBackupsResult { + return &AuroraAdminListBackupsResult{} +} + +var AuroraAdminListBackupsResult_Success_DEFAULT *Response + +func (p *AuroraAdminListBackupsResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraAdminListBackupsResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraAdminListBackupsResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraAdminListBackupsResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminListBackupsResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraAdminListBackupsResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("listBackups_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminListBackupsResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraAdminListBackupsResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminListBackupsResult(%+v)", *p) +} + +// Attributes: +// - BackupId +type AuroraAdminStageRecoveryArgs struct { + BackupId string `thrift:"backupId,1" db:"backupId" json:"backupId"` +} + +func NewAuroraAdminStageRecoveryArgs() *AuroraAdminStageRecoveryArgs { + return &AuroraAdminStageRecoveryArgs{} +} + +func (p *AuroraAdminStageRecoveryArgs) GetBackupId() string { + return p.BackupId +} +func (p *AuroraAdminStageRecoveryArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRING { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminStageRecoveryArgs) ReadField1(iprot thrift.TProtocol) error { + if v, err := iprot.ReadString(); err != nil { + return thrift.PrependError("error reading field 1: ", err) + } else { + p.BackupId = v + } + return nil +} + +func (p *AuroraAdminStageRecoveryArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("stageRecovery_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminStageRecoveryArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("backupId", thrift.STRING, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:backupId: ", p), err) + } + if err := oprot.WriteString(string(p.BackupId)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.backupId (1) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:backupId: ", p), err) + } + return err +} + +func (p *AuroraAdminStageRecoveryArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminStageRecoveryArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraAdminStageRecoveryResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraAdminStageRecoveryResult() *AuroraAdminStageRecoveryResult { + return &AuroraAdminStageRecoveryResult{} +} + +var AuroraAdminStageRecoveryResult_Success_DEFAULT *Response + +func (p *AuroraAdminStageRecoveryResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraAdminStageRecoveryResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraAdminStageRecoveryResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraAdminStageRecoveryResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminStageRecoveryResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraAdminStageRecoveryResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("stageRecovery_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminStageRecoveryResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraAdminStageRecoveryResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminStageRecoveryResult(%+v)", *p) +} + +// Attributes: +// - Query +type AuroraAdminQueryRecoveryArgs struct { + Query *TaskQuery `thrift:"query,1" db:"query" json:"query"` +} + +func NewAuroraAdminQueryRecoveryArgs() *AuroraAdminQueryRecoveryArgs { + return &AuroraAdminQueryRecoveryArgs{} +} + +var AuroraAdminQueryRecoveryArgs_Query_DEFAULT *TaskQuery + +func (p *AuroraAdminQueryRecoveryArgs) GetQuery() *TaskQuery { + if !p.IsSetQuery() { + return AuroraAdminQueryRecoveryArgs_Query_DEFAULT + } + return p.Query +} +func (p *AuroraAdminQueryRecoveryArgs) IsSetQuery() bool { + return p.Query != nil +} + +func (p *AuroraAdminQueryRecoveryArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminQueryRecoveryArgs) ReadField1(iprot thrift.TProtocol) error { + p.Query = &TaskQuery{} + if err := p.Query.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Query), err) + } + return nil +} + +func (p *AuroraAdminQueryRecoveryArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("queryRecovery_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminQueryRecoveryArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("query", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:query: ", p), err) + } + if err := p.Query.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Query), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:query: ", p), err) + } + return err +} + +func (p *AuroraAdminQueryRecoveryArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminQueryRecoveryArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraAdminQueryRecoveryResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraAdminQueryRecoveryResult() *AuroraAdminQueryRecoveryResult { + return &AuroraAdminQueryRecoveryResult{} +} + +var AuroraAdminQueryRecoveryResult_Success_DEFAULT *Response + +func (p *AuroraAdminQueryRecoveryResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraAdminQueryRecoveryResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraAdminQueryRecoveryResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraAdminQueryRecoveryResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminQueryRecoveryResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraAdminQueryRecoveryResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("queryRecovery_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminQueryRecoveryResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraAdminQueryRecoveryResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminQueryRecoveryResult(%+v)", *p) +} + +// Attributes: +// - Query +type AuroraAdminDeleteRecoveryTasksArgs struct { + Query *TaskQuery `thrift:"query,1" db:"query" json:"query"` +} + +func NewAuroraAdminDeleteRecoveryTasksArgs() *AuroraAdminDeleteRecoveryTasksArgs { + return &AuroraAdminDeleteRecoveryTasksArgs{} +} + +var AuroraAdminDeleteRecoveryTasksArgs_Query_DEFAULT *TaskQuery + +func (p *AuroraAdminDeleteRecoveryTasksArgs) GetQuery() *TaskQuery { + if !p.IsSetQuery() { + return AuroraAdminDeleteRecoveryTasksArgs_Query_DEFAULT + } + return p.Query +} +func (p *AuroraAdminDeleteRecoveryTasksArgs) IsSetQuery() bool { + return p.Query != nil +} + +func (p *AuroraAdminDeleteRecoveryTasksArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminDeleteRecoveryTasksArgs) ReadField1(iprot thrift.TProtocol) error { + p.Query = &TaskQuery{} + if err := p.Query.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Query), err) + } + return nil +} + +func (p *AuroraAdminDeleteRecoveryTasksArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("deleteRecoveryTasks_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminDeleteRecoveryTasksArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("query", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:query: ", p), err) + } + if err := p.Query.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Query), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:query: ", p), err) + } + return err +} + +func (p *AuroraAdminDeleteRecoveryTasksArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminDeleteRecoveryTasksArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraAdminDeleteRecoveryTasksResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraAdminDeleteRecoveryTasksResult() *AuroraAdminDeleteRecoveryTasksResult { + return &AuroraAdminDeleteRecoveryTasksResult{} +} + +var AuroraAdminDeleteRecoveryTasksResult_Success_DEFAULT *Response + +func (p *AuroraAdminDeleteRecoveryTasksResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraAdminDeleteRecoveryTasksResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraAdminDeleteRecoveryTasksResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraAdminDeleteRecoveryTasksResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminDeleteRecoveryTasksResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraAdminDeleteRecoveryTasksResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("deleteRecoveryTasks_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminDeleteRecoveryTasksResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraAdminDeleteRecoveryTasksResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminDeleteRecoveryTasksResult(%+v)", *p) +} + +type AuroraAdminCommitRecoveryArgs struct { +} + +func NewAuroraAdminCommitRecoveryArgs() *AuroraAdminCommitRecoveryArgs { + return &AuroraAdminCommitRecoveryArgs{} +} + +func (p *AuroraAdminCommitRecoveryArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminCommitRecoveryArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("commitRecovery_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminCommitRecoveryArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminCommitRecoveryArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraAdminCommitRecoveryResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraAdminCommitRecoveryResult() *AuroraAdminCommitRecoveryResult { + return &AuroraAdminCommitRecoveryResult{} +} + +var AuroraAdminCommitRecoveryResult_Success_DEFAULT *Response + +func (p *AuroraAdminCommitRecoveryResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraAdminCommitRecoveryResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraAdminCommitRecoveryResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraAdminCommitRecoveryResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminCommitRecoveryResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraAdminCommitRecoveryResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("commitRecovery_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminCommitRecoveryResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraAdminCommitRecoveryResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminCommitRecoveryResult(%+v)", *p) +} + +type AuroraAdminUnloadRecoveryArgs struct { +} + +func NewAuroraAdminUnloadRecoveryArgs() *AuroraAdminUnloadRecoveryArgs { + return &AuroraAdminUnloadRecoveryArgs{} +} + +func (p *AuroraAdminUnloadRecoveryArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminUnloadRecoveryArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("unloadRecovery_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminUnloadRecoveryArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminUnloadRecoveryArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraAdminUnloadRecoveryResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraAdminUnloadRecoveryResult() *AuroraAdminUnloadRecoveryResult { + return &AuroraAdminUnloadRecoveryResult{} +} + +var AuroraAdminUnloadRecoveryResult_Success_DEFAULT *Response + +func (p *AuroraAdminUnloadRecoveryResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraAdminUnloadRecoveryResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraAdminUnloadRecoveryResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraAdminUnloadRecoveryResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminUnloadRecoveryResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraAdminUnloadRecoveryResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("unloadRecovery_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminUnloadRecoveryResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraAdminUnloadRecoveryResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminUnloadRecoveryResult(%+v)", *p) +} + +// Attributes: +// - Hosts +type AuroraAdminStartMaintenanceArgs struct { + Hosts *Hosts `thrift:"hosts,1" db:"hosts" json:"hosts"` +} + +func NewAuroraAdminStartMaintenanceArgs() *AuroraAdminStartMaintenanceArgs { + return &AuroraAdminStartMaintenanceArgs{} +} + +var AuroraAdminStartMaintenanceArgs_Hosts_DEFAULT *Hosts + +func (p *AuroraAdminStartMaintenanceArgs) GetHosts() *Hosts { + if !p.IsSetHosts() { + return AuroraAdminStartMaintenanceArgs_Hosts_DEFAULT + } + return p.Hosts +} +func (p *AuroraAdminStartMaintenanceArgs) IsSetHosts() bool { + return p.Hosts != nil +} + +func (p *AuroraAdminStartMaintenanceArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminStartMaintenanceArgs) ReadField1(iprot thrift.TProtocol) error { + p.Hosts = &Hosts{} + if err := p.Hosts.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Hosts), err) + } + return nil +} + +func (p *AuroraAdminStartMaintenanceArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("startMaintenance_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminStartMaintenanceArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("hosts", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:hosts: ", p), err) + } + if err := p.Hosts.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Hosts), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:hosts: ", p), err) + } + return err +} + +func (p *AuroraAdminStartMaintenanceArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminStartMaintenanceArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraAdminStartMaintenanceResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraAdminStartMaintenanceResult() *AuroraAdminStartMaintenanceResult { + return &AuroraAdminStartMaintenanceResult{} +} + +var AuroraAdminStartMaintenanceResult_Success_DEFAULT *Response + +func (p *AuroraAdminStartMaintenanceResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraAdminStartMaintenanceResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraAdminStartMaintenanceResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraAdminStartMaintenanceResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminStartMaintenanceResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraAdminStartMaintenanceResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("startMaintenance_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminStartMaintenanceResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraAdminStartMaintenanceResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminStartMaintenanceResult(%+v)", *p) +} + +// Attributes: +// - Hosts +type AuroraAdminDrainHostsArgs struct { + Hosts *Hosts `thrift:"hosts,1" db:"hosts" json:"hosts"` +} + +func NewAuroraAdminDrainHostsArgs() *AuroraAdminDrainHostsArgs { + return &AuroraAdminDrainHostsArgs{} +} + +var AuroraAdminDrainHostsArgs_Hosts_DEFAULT *Hosts + +func (p *AuroraAdminDrainHostsArgs) GetHosts() *Hosts { + if !p.IsSetHosts() { + return AuroraAdminDrainHostsArgs_Hosts_DEFAULT + } + return p.Hosts +} +func (p *AuroraAdminDrainHostsArgs) IsSetHosts() bool { + return p.Hosts != nil +} + +func (p *AuroraAdminDrainHostsArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminDrainHostsArgs) ReadField1(iprot thrift.TProtocol) error { + p.Hosts = &Hosts{} + if err := p.Hosts.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Hosts), err) + } + return nil +} + +func (p *AuroraAdminDrainHostsArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("drainHosts_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminDrainHostsArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("hosts", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:hosts: ", p), err) + } + if err := p.Hosts.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Hosts), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:hosts: ", p), err) + } + return err +} + +func (p *AuroraAdminDrainHostsArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminDrainHostsArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraAdminDrainHostsResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraAdminDrainHostsResult() *AuroraAdminDrainHostsResult { + return &AuroraAdminDrainHostsResult{} +} + +var AuroraAdminDrainHostsResult_Success_DEFAULT *Response + +func (p *AuroraAdminDrainHostsResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraAdminDrainHostsResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraAdminDrainHostsResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraAdminDrainHostsResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminDrainHostsResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraAdminDrainHostsResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("drainHosts_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminDrainHostsResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraAdminDrainHostsResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminDrainHostsResult(%+v)", *p) +} + +// Attributes: +// - Hosts +type AuroraAdminMaintenanceStatusArgs struct { + Hosts *Hosts `thrift:"hosts,1" db:"hosts" json:"hosts"` +} + +func NewAuroraAdminMaintenanceStatusArgs() *AuroraAdminMaintenanceStatusArgs { + return &AuroraAdminMaintenanceStatusArgs{} +} + +var AuroraAdminMaintenanceStatusArgs_Hosts_DEFAULT *Hosts + +func (p *AuroraAdminMaintenanceStatusArgs) GetHosts() *Hosts { + if !p.IsSetHosts() { + return AuroraAdminMaintenanceStatusArgs_Hosts_DEFAULT + } + return p.Hosts +} +func (p *AuroraAdminMaintenanceStatusArgs) IsSetHosts() bool { + return p.Hosts != nil +} + +func (p *AuroraAdminMaintenanceStatusArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminMaintenanceStatusArgs) ReadField1(iprot thrift.TProtocol) error { + p.Hosts = &Hosts{} + if err := p.Hosts.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Hosts), err) + } + return nil +} + +func (p *AuroraAdminMaintenanceStatusArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("maintenanceStatus_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminMaintenanceStatusArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("hosts", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:hosts: ", p), err) + } + if err := p.Hosts.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Hosts), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:hosts: ", p), err) + } + return err +} + +func (p *AuroraAdminMaintenanceStatusArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminMaintenanceStatusArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraAdminMaintenanceStatusResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraAdminMaintenanceStatusResult() *AuroraAdminMaintenanceStatusResult { + return &AuroraAdminMaintenanceStatusResult{} +} + +var AuroraAdminMaintenanceStatusResult_Success_DEFAULT *Response + +func (p *AuroraAdminMaintenanceStatusResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraAdminMaintenanceStatusResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraAdminMaintenanceStatusResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraAdminMaintenanceStatusResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminMaintenanceStatusResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraAdminMaintenanceStatusResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("maintenanceStatus_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminMaintenanceStatusResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraAdminMaintenanceStatusResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminMaintenanceStatusResult(%+v)", *p) +} + +// Attributes: +// - Hosts +type AuroraAdminEndMaintenanceArgs struct { + Hosts *Hosts `thrift:"hosts,1" db:"hosts" json:"hosts"` +} + +func NewAuroraAdminEndMaintenanceArgs() *AuroraAdminEndMaintenanceArgs { + return &AuroraAdminEndMaintenanceArgs{} +} + +var AuroraAdminEndMaintenanceArgs_Hosts_DEFAULT *Hosts + +func (p *AuroraAdminEndMaintenanceArgs) GetHosts() *Hosts { + if !p.IsSetHosts() { + return AuroraAdminEndMaintenanceArgs_Hosts_DEFAULT + } + return p.Hosts +} +func (p *AuroraAdminEndMaintenanceArgs) IsSetHosts() bool { + return p.Hosts != nil +} + +func (p *AuroraAdminEndMaintenanceArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminEndMaintenanceArgs) ReadField1(iprot thrift.TProtocol) error { + p.Hosts = &Hosts{} + if err := p.Hosts.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Hosts), err) + } + return nil +} + +func (p *AuroraAdminEndMaintenanceArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("endMaintenance_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminEndMaintenanceArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("hosts", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:hosts: ", p), err) + } + if err := p.Hosts.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Hosts), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:hosts: ", p), err) + } + return err +} + +func (p *AuroraAdminEndMaintenanceArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminEndMaintenanceArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraAdminEndMaintenanceResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraAdminEndMaintenanceResult() *AuroraAdminEndMaintenanceResult { + return &AuroraAdminEndMaintenanceResult{} +} + +var AuroraAdminEndMaintenanceResult_Success_DEFAULT *Response + +func (p *AuroraAdminEndMaintenanceResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraAdminEndMaintenanceResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraAdminEndMaintenanceResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraAdminEndMaintenanceResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminEndMaintenanceResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraAdminEndMaintenanceResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("endMaintenance_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminEndMaintenanceResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraAdminEndMaintenanceResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminEndMaintenanceResult(%+v)", *p) +} + +// Attributes: +// - Hosts +// - DefaultSlaPolicy +// - TimeoutSecs +type AuroraAdminSlaDrainHostsArgs struct { + Hosts *Hosts `thrift:"hosts,1" db:"hosts" json:"hosts"` + DefaultSlaPolicy *SlaPolicy `thrift:"defaultSlaPolicy,2" db:"defaultSlaPolicy" json:"defaultSlaPolicy"` + TimeoutSecs int64 `thrift:"timeoutSecs,3" db:"timeoutSecs" json:"timeoutSecs"` +} + +func NewAuroraAdminSlaDrainHostsArgs() *AuroraAdminSlaDrainHostsArgs { + return &AuroraAdminSlaDrainHostsArgs{} +} + +var AuroraAdminSlaDrainHostsArgs_Hosts_DEFAULT *Hosts + +func (p *AuroraAdminSlaDrainHostsArgs) GetHosts() *Hosts { + if !p.IsSetHosts() { + return AuroraAdminSlaDrainHostsArgs_Hosts_DEFAULT + } + return p.Hosts +} + +var AuroraAdminSlaDrainHostsArgs_DefaultSlaPolicy_DEFAULT *SlaPolicy + +func (p *AuroraAdminSlaDrainHostsArgs) GetDefaultSlaPolicy() *SlaPolicy { + if !p.IsSetDefaultSlaPolicy() { + return AuroraAdminSlaDrainHostsArgs_DefaultSlaPolicy_DEFAULT + } + return p.DefaultSlaPolicy +} + +func (p *AuroraAdminSlaDrainHostsArgs) GetTimeoutSecs() int64 { + return p.TimeoutSecs +} +func (p *AuroraAdminSlaDrainHostsArgs) IsSetHosts() bool { + return p.Hosts != nil +} + +func (p *AuroraAdminSlaDrainHostsArgs) IsSetDefaultSlaPolicy() bool { + return p.DefaultSlaPolicy != nil +} + +func (p *AuroraAdminSlaDrainHostsArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 2: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField2(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + case 3: + if fieldTypeId == thrift.I64 { + if err := p.ReadField3(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminSlaDrainHostsArgs) ReadField1(iprot thrift.TProtocol) error { + p.Hosts = &Hosts{} + if err := p.Hosts.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Hosts), err) + } + return nil +} + +func (p *AuroraAdminSlaDrainHostsArgs) ReadField2(iprot thrift.TProtocol) error { + p.DefaultSlaPolicy = &SlaPolicy{} + if err := p.DefaultSlaPolicy.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.DefaultSlaPolicy), err) + } + return nil +} + +func (p *AuroraAdminSlaDrainHostsArgs) ReadField3(iprot thrift.TProtocol) error { + if v, err := iprot.ReadI64(); err != nil { + return thrift.PrependError("error reading field 3: ", err) + } else { + p.TimeoutSecs = v + } + return nil +} + +func (p *AuroraAdminSlaDrainHostsArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("slaDrainHosts_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + if err := p.writeField2(oprot); err != nil { + return err + } + if err := p.writeField3(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminSlaDrainHostsArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("hosts", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:hosts: ", p), err) + } + if err := p.Hosts.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Hosts), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:hosts: ", p), err) + } + return err +} + +func (p *AuroraAdminSlaDrainHostsArgs) writeField2(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("defaultSlaPolicy", thrift.STRUCT, 2); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:defaultSlaPolicy: ", p), err) + } + if err := p.DefaultSlaPolicy.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.DefaultSlaPolicy), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 2:defaultSlaPolicy: ", p), err) + } + return err +} + +func (p *AuroraAdminSlaDrainHostsArgs) writeField3(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("timeoutSecs", thrift.I64, 3); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:timeoutSecs: ", p), err) + } + if err := oprot.WriteI64(int64(p.TimeoutSecs)); err != nil { + return thrift.PrependError(fmt.Sprintf("%T.timeoutSecs (3) field write error: ", p), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 3:timeoutSecs: ", p), err) + } + return err +} + +func (p *AuroraAdminSlaDrainHostsArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminSlaDrainHostsArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraAdminSlaDrainHostsResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraAdminSlaDrainHostsResult() *AuroraAdminSlaDrainHostsResult { + return &AuroraAdminSlaDrainHostsResult{} +} + +var AuroraAdminSlaDrainHostsResult_Success_DEFAULT *Response + +func (p *AuroraAdminSlaDrainHostsResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraAdminSlaDrainHostsResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraAdminSlaDrainHostsResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraAdminSlaDrainHostsResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminSlaDrainHostsResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraAdminSlaDrainHostsResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("slaDrainHosts_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminSlaDrainHostsResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraAdminSlaDrainHostsResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminSlaDrainHostsResult(%+v)", *p) +} + +type AuroraAdminSnapshotArgs struct { +} + +func NewAuroraAdminSnapshotArgs() *AuroraAdminSnapshotArgs { + return &AuroraAdminSnapshotArgs{} +} + +func (p *AuroraAdminSnapshotArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminSnapshotArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("snapshot_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminSnapshotArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminSnapshotArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraAdminSnapshotResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraAdminSnapshotResult() *AuroraAdminSnapshotResult { + return &AuroraAdminSnapshotResult{} +} + +var AuroraAdminSnapshotResult_Success_DEFAULT *Response + +func (p *AuroraAdminSnapshotResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraAdminSnapshotResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraAdminSnapshotResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraAdminSnapshotResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminSnapshotResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraAdminSnapshotResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("snapshot_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminSnapshotResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraAdminSnapshotResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminSnapshotResult(%+v)", *p) +} + +// Attributes: +// - Settings +type AuroraAdminTriggerExplicitTaskReconciliationArgs struct { + Settings *ExplicitReconciliationSettings `thrift:"settings,1" db:"settings" json:"settings"` +} + +func NewAuroraAdminTriggerExplicitTaskReconciliationArgs() *AuroraAdminTriggerExplicitTaskReconciliationArgs { + return &AuroraAdminTriggerExplicitTaskReconciliationArgs{} +} + +var AuroraAdminTriggerExplicitTaskReconciliationArgs_Settings_DEFAULT *ExplicitReconciliationSettings + +func (p *AuroraAdminTriggerExplicitTaskReconciliationArgs) GetSettings() *ExplicitReconciliationSettings { + if !p.IsSetSettings() { + return AuroraAdminTriggerExplicitTaskReconciliationArgs_Settings_DEFAULT + } + return p.Settings +} +func (p *AuroraAdminTriggerExplicitTaskReconciliationArgs) IsSetSettings() bool { + return p.Settings != nil +} + +func (p *AuroraAdminTriggerExplicitTaskReconciliationArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminTriggerExplicitTaskReconciliationArgs) ReadField1(iprot thrift.TProtocol) error { + p.Settings = &ExplicitReconciliationSettings{} + if err := p.Settings.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Settings), err) + } + return nil +} + +func (p *AuroraAdminTriggerExplicitTaskReconciliationArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("triggerExplicitTaskReconciliation_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminTriggerExplicitTaskReconciliationArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("settings", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:settings: ", p), err) + } + if err := p.Settings.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Settings), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:settings: ", p), err) + } + return err +} + +func (p *AuroraAdminTriggerExplicitTaskReconciliationArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminTriggerExplicitTaskReconciliationArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraAdminTriggerExplicitTaskReconciliationResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraAdminTriggerExplicitTaskReconciliationResult() *AuroraAdminTriggerExplicitTaskReconciliationResult { + return &AuroraAdminTriggerExplicitTaskReconciliationResult{} +} + +var AuroraAdminTriggerExplicitTaskReconciliationResult_Success_DEFAULT *Response + +func (p *AuroraAdminTriggerExplicitTaskReconciliationResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraAdminTriggerExplicitTaskReconciliationResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraAdminTriggerExplicitTaskReconciliationResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraAdminTriggerExplicitTaskReconciliationResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminTriggerExplicitTaskReconciliationResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraAdminTriggerExplicitTaskReconciliationResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("triggerExplicitTaskReconciliation_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminTriggerExplicitTaskReconciliationResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraAdminTriggerExplicitTaskReconciliationResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminTriggerExplicitTaskReconciliationResult(%+v)", *p) +} + +type AuroraAdminTriggerImplicitTaskReconciliationArgs struct { +} + +func NewAuroraAdminTriggerImplicitTaskReconciliationArgs() *AuroraAdminTriggerImplicitTaskReconciliationArgs { + return &AuroraAdminTriggerImplicitTaskReconciliationArgs{} +} + +func (p *AuroraAdminTriggerImplicitTaskReconciliationArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminTriggerImplicitTaskReconciliationArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("triggerImplicitTaskReconciliation_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminTriggerImplicitTaskReconciliationArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminTriggerImplicitTaskReconciliationArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraAdminTriggerImplicitTaskReconciliationResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraAdminTriggerImplicitTaskReconciliationResult() *AuroraAdminTriggerImplicitTaskReconciliationResult { + return &AuroraAdminTriggerImplicitTaskReconciliationResult{} +} + +var AuroraAdminTriggerImplicitTaskReconciliationResult_Success_DEFAULT *Response + +func (p *AuroraAdminTriggerImplicitTaskReconciliationResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraAdminTriggerImplicitTaskReconciliationResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraAdminTriggerImplicitTaskReconciliationResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraAdminTriggerImplicitTaskReconciliationResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminTriggerImplicitTaskReconciliationResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraAdminTriggerImplicitTaskReconciliationResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("triggerImplicitTaskReconciliation_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminTriggerImplicitTaskReconciliationResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraAdminTriggerImplicitTaskReconciliationResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminTriggerImplicitTaskReconciliationResult(%+v)", *p) +} + +// Attributes: +// - Query +type AuroraAdminPruneTasksArgs struct { + Query *TaskQuery `thrift:"query,1" db:"query" json:"query"` +} + +func NewAuroraAdminPruneTasksArgs() *AuroraAdminPruneTasksArgs { + return &AuroraAdminPruneTasksArgs{} +} + +var AuroraAdminPruneTasksArgs_Query_DEFAULT *TaskQuery + +func (p *AuroraAdminPruneTasksArgs) GetQuery() *TaskQuery { + if !p.IsSetQuery() { + return AuroraAdminPruneTasksArgs_Query_DEFAULT + } + return p.Query +} +func (p *AuroraAdminPruneTasksArgs) IsSetQuery() bool { + return p.Query != nil +} + +func (p *AuroraAdminPruneTasksArgs) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 1: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField1(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminPruneTasksArgs) ReadField1(iprot thrift.TProtocol) error { + p.Query = &TaskQuery{} + if err := p.Query.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Query), err) + } + return nil +} + +func (p *AuroraAdminPruneTasksArgs) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("pruneTasks_args"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField1(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminPruneTasksArgs) writeField1(oprot thrift.TProtocol) (err error) { + if err := oprot.WriteFieldBegin("query", thrift.STRUCT, 1); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:query: ", p), err) + } + if err := p.Query.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Query), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 1:query: ", p), err) + } + return err +} + +func (p *AuroraAdminPruneTasksArgs) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminPruneTasksArgs(%+v)", *p) +} + +// Attributes: +// - Success +type AuroraAdminPruneTasksResult struct { + Success *Response `thrift:"success,0" db:"success" json:"success,omitempty"` +} + +func NewAuroraAdminPruneTasksResult() *AuroraAdminPruneTasksResult { + return &AuroraAdminPruneTasksResult{} +} + +var AuroraAdminPruneTasksResult_Success_DEFAULT *Response + +func (p *AuroraAdminPruneTasksResult) GetSuccess() *Response { + if !p.IsSetSuccess() { + return AuroraAdminPruneTasksResult_Success_DEFAULT + } + return p.Success +} +func (p *AuroraAdminPruneTasksResult) IsSetSuccess() bool { + return p.Success != nil +} + +func (p *AuroraAdminPruneTasksResult) Read(iprot thrift.TProtocol) error { + if _, err := iprot.ReadStructBegin(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) + } + + for { + _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() + if err != nil { + return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) + } + if fieldTypeId == thrift.STOP { + break + } + switch fieldId { + case 0: + if fieldTypeId == thrift.STRUCT { + if err := p.ReadField0(iprot); err != nil { + return err + } + } else { + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + default: + if err := iprot.Skip(fieldTypeId); err != nil { + return err + } + } + if err := iprot.ReadFieldEnd(); err != nil { + return err + } + } + if err := iprot.ReadStructEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) + } + return nil +} + +func (p *AuroraAdminPruneTasksResult) ReadField0(iprot thrift.TProtocol) error { + p.Success = &Response{} + if err := p.Success.Read(iprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) + } + return nil +} + +func (p *AuroraAdminPruneTasksResult) Write(oprot thrift.TProtocol) error { + if err := oprot.WriteStructBegin("pruneTasks_result"); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) + } + if p != nil { + if err := p.writeField0(oprot); err != nil { + return err + } + } + if err := oprot.WriteFieldStop(); err != nil { + return thrift.PrependError("write field stop error: ", err) + } + if err := oprot.WriteStructEnd(); err != nil { + return thrift.PrependError("write struct stop error: ", err) + } + return nil +} + +func (p *AuroraAdminPruneTasksResult) writeField0(oprot thrift.TProtocol) (err error) { + if p.IsSetSuccess() { + if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) + } + if err := p.Success.Write(oprot); err != nil { + return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) + } + if err := oprot.WriteFieldEnd(); err != nil { + return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) + } + } + return err +} + +func (p *AuroraAdminPruneTasksResult) String() string { + if p == nil { + return "" + } + return fmt.Sprintf("AuroraAdminPruneTasksResult(%+v)", *p) +} diff --git a/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/aurora_admin-remote/aurora_admin-remote.go b/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/aurora_admin-remote/aurora_admin-remote.go index d6f7bfd..63d54ed 100755 --- a/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/aurora_admin-remote/aurora_admin-remote.go +++ b/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/aurora_admin-remote/aurora_admin-remote.go @@ -1,19 +1,21 @@ -// Autogenerated by Thrift Compiler (0.9.3) +// Autogenerated by Thrift Compiler (0.12.0) // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING package main import ( "apache/aurora" + "context" "flag" "fmt" - "git.apache.org/thrift.git/lib/go/thrift" "math" "net" "net/url" "os" "strconv" "strings" + + "git.apache.org/thrift.git/lib/go/thrift" ) func Usage() { @@ -69,6 +71,22 @@ func Usage() { os.Exit(0) } +type httpHeaders map[string]string + +func (h httpHeaders) String() string { + var m map[string]string = h + return fmt.Sprintf("%s", m) +} + +func (h httpHeaders) Set(value string) error { + parts := strings.Split(value, ": ") + if len(parts) != 2 { + return fmt.Errorf("header should be of format 'Key: Value'") + } + h[parts[0]] = parts[1] + return nil +} + func main() { flag.Usage = Usage var host string @@ -77,7 +95,8 @@ func main() { var urlString string var framed bool var useHttp bool - var parsedUrl url.URL + headers := make(httpHeaders) + var parsedUrl *url.URL var trans thrift.TTransport _ = strconv.Atoi _ = math.Abs @@ -88,16 +107,18 @@ func main() { flag.StringVar(&urlString, "u", "", "Specify the url") flag.BoolVar(&framed, "framed", false, "Use framed transport") flag.BoolVar(&useHttp, "http", false, "Use http") + flag.Var(headers, "H", "Headers to set on the http(s) request (e.g. -H \"Key: Value\")") flag.Parse() if len(urlString) > 0 { - parsedUrl, err := url.Parse(urlString) + var err error + parsedUrl, err = url.Parse(urlString) if err != nil { fmt.Fprintln(os.Stderr, "Error parsing URL: ", err) flag.Usage() } host = parsedUrl.Host - useHttp = len(parsedUrl.Scheme) <= 0 || parsedUrl.Scheme == "http" + useHttp = len(parsedUrl.Scheme) <= 0 || parsedUrl.Scheme == "http" || parsedUrl.Scheme == "https" } else if useHttp { _, err := url.Parse(fmt.Sprint("http://", host, ":", port)) if err != nil { @@ -110,6 +131,12 @@ func main() { var err error if useHttp { trans, err = thrift.NewTHttpClient(parsedUrl.String()) + if len(headers) > 0 { + httptrans := trans.(*thrift.THttpClient) + for key, value := range headers { + httptrans.SetHeader(key, value) + } + } } else { portStr := fmt.Sprint(port) if strings.Contains(host, ":") { @@ -152,7 +179,9 @@ func main() { Usage() os.Exit(1) } - client := aurora.NewAuroraAdminClientFactory(trans, protocolFactory) + iprot := protocolFactory.GetProtocol(trans) + oprot := protocolFactory.GetProtocol(trans) + client := aurora.NewAuroraAdminClient(thrift.NewTStandardClient(iprot, oprot)) if err := trans.Open(); err != nil { fmt.Fprintln(os.Stderr, "Error opening socket to ", host, ":", port, " ", err) os.Exit(1) @@ -174,7 +203,7 @@ func main() { Usage() return } - factory357 := thrift.NewTSimpleJSONProtocolFactory() + factory357 := thrift.NewTJSONProtocolFactory() jsProt358 := factory357.GetProtocol(mbTrans355) argvalue1 := aurora.NewResourceAggregate() err359 := argvalue1.Read(jsProt358) @@ -183,7 +212,7 @@ func main() { return } value1 := argvalue1 - fmt.Print(client.SetQuota(value0, value1)) + fmt.Print(client.SetQuota(context.Background(), value0, value1)) fmt.Print("\n") break case "forceTaskState": @@ -200,7 +229,7 @@ func main() { } argvalue1 := aurora.ScheduleStatus(tmp1) value1 := argvalue1 - fmt.Print(client.ForceTaskState(value0, value1)) + fmt.Print(client.ForceTaskState(context.Background(), value0, value1)) fmt.Print("\n") break case "performBackup": @@ -208,7 +237,7 @@ func main() { fmt.Fprintln(os.Stderr, "PerformBackup requires 0 args") flag.Usage() } - fmt.Print(client.PerformBackup()) + fmt.Print(client.PerformBackup(context.Background())) fmt.Print("\n") break case "listBackups": @@ -216,7 +245,7 @@ func main() { fmt.Fprintln(os.Stderr, "ListBackups requires 0 args") flag.Usage() } - fmt.Print(client.ListBackups()) + fmt.Print(client.ListBackups(context.Background())) fmt.Print("\n") break case "stageRecovery": @@ -226,7 +255,7 @@ func main() { } argvalue0 := flag.Arg(1) value0 := argvalue0 - fmt.Print(client.StageRecovery(value0)) + fmt.Print(client.StageRecovery(context.Background(), value0)) fmt.Print("\n") break case "queryRecovery": @@ -242,7 +271,7 @@ func main() { Usage() return } - factory365 := thrift.NewTSimpleJSONProtocolFactory() + factory365 := thrift.NewTJSONProtocolFactory() jsProt366 := factory365.GetProtocol(mbTrans363) argvalue0 := aurora.NewTaskQuery() err367 := argvalue0.Read(jsProt366) @@ -251,7 +280,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.QueryRecovery(value0)) + fmt.Print(client.QueryRecovery(context.Background(), value0)) fmt.Print("\n") break case "deleteRecoveryTasks": @@ -267,7 +296,7 @@ func main() { Usage() return } - factory371 := thrift.NewTSimpleJSONProtocolFactory() + factory371 := thrift.NewTJSONProtocolFactory() jsProt372 := factory371.GetProtocol(mbTrans369) argvalue0 := aurora.NewTaskQuery() err373 := argvalue0.Read(jsProt372) @@ -276,7 +305,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.DeleteRecoveryTasks(value0)) + fmt.Print(client.DeleteRecoveryTasks(context.Background(), value0)) fmt.Print("\n") break case "commitRecovery": @@ -284,7 +313,7 @@ func main() { fmt.Fprintln(os.Stderr, "CommitRecovery requires 0 args") flag.Usage() } - fmt.Print(client.CommitRecovery()) + fmt.Print(client.CommitRecovery(context.Background())) fmt.Print("\n") break case "unloadRecovery": @@ -292,7 +321,7 @@ func main() { fmt.Fprintln(os.Stderr, "UnloadRecovery requires 0 args") flag.Usage() } - fmt.Print(client.UnloadRecovery()) + fmt.Print(client.UnloadRecovery(context.Background())) fmt.Print("\n") break case "startMaintenance": @@ -308,7 +337,7 @@ func main() { Usage() return } - factory377 := thrift.NewTSimpleJSONProtocolFactory() + factory377 := thrift.NewTJSONProtocolFactory() jsProt378 := factory377.GetProtocol(mbTrans375) argvalue0 := aurora.NewHosts() err379 := argvalue0.Read(jsProt378) @@ -317,7 +346,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.StartMaintenance(value0)) + fmt.Print(client.StartMaintenance(context.Background(), value0)) fmt.Print("\n") break case "drainHosts": @@ -333,7 +362,7 @@ func main() { Usage() return } - factory383 := thrift.NewTSimpleJSONProtocolFactory() + factory383 := thrift.NewTJSONProtocolFactory() jsProt384 := factory383.GetProtocol(mbTrans381) argvalue0 := aurora.NewHosts() err385 := argvalue0.Read(jsProt384) @@ -342,7 +371,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.DrainHosts(value0)) + fmt.Print(client.DrainHosts(context.Background(), value0)) fmt.Print("\n") break case "maintenanceStatus": @@ -358,7 +387,7 @@ func main() { Usage() return } - factory389 := thrift.NewTSimpleJSONProtocolFactory() + factory389 := thrift.NewTJSONProtocolFactory() jsProt390 := factory389.GetProtocol(mbTrans387) argvalue0 := aurora.NewHosts() err391 := argvalue0.Read(jsProt390) @@ -367,7 +396,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.MaintenanceStatus(value0)) + fmt.Print(client.MaintenanceStatus(context.Background(), value0)) fmt.Print("\n") break case "endMaintenance": @@ -383,7 +412,7 @@ func main() { Usage() return } - factory395 := thrift.NewTSimpleJSONProtocolFactory() + factory395 := thrift.NewTJSONProtocolFactory() jsProt396 := factory395.GetProtocol(mbTrans393) argvalue0 := aurora.NewHosts() err397 := argvalue0.Read(jsProt396) @@ -392,7 +421,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.EndMaintenance(value0)) + fmt.Print(client.EndMaintenance(context.Background(), value0)) fmt.Print("\n") break case "slaDrainHosts": @@ -408,7 +437,7 @@ func main() { Usage() return } - factory401 := thrift.NewTSimpleJSONProtocolFactory() + factory401 := thrift.NewTJSONProtocolFactory() jsProt402 := factory401.GetProtocol(mbTrans399) argvalue0 := aurora.NewHosts() err403 := argvalue0.Read(jsProt402) @@ -425,7 +454,7 @@ func main() { Usage() return } - factory407 := thrift.NewTSimpleJSONProtocolFactory() + factory407 := thrift.NewTJSONProtocolFactory() jsProt408 := factory407.GetProtocol(mbTrans405) argvalue1 := aurora.NewSlaPolicy() err409 := argvalue1.Read(jsProt408) @@ -440,7 +469,7 @@ func main() { return } value2 := argvalue2 - fmt.Print(client.SlaDrainHosts(value0, value1, value2)) + fmt.Print(client.SlaDrainHosts(context.Background(), value0, value1, value2)) fmt.Print("\n") break case "snapshot": @@ -448,7 +477,7 @@ func main() { fmt.Fprintln(os.Stderr, "Snapshot requires 0 args") flag.Usage() } - fmt.Print(client.Snapshot()) + fmt.Print(client.Snapshot(context.Background())) fmt.Print("\n") break case "triggerExplicitTaskReconciliation": @@ -464,7 +493,7 @@ func main() { Usage() return } - factory414 := thrift.NewTSimpleJSONProtocolFactory() + factory414 := thrift.NewTJSONProtocolFactory() jsProt415 := factory414.GetProtocol(mbTrans412) argvalue0 := aurora.NewExplicitReconciliationSettings() err416 := argvalue0.Read(jsProt415) @@ -473,7 +502,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.TriggerExplicitTaskReconciliation(value0)) + fmt.Print(client.TriggerExplicitTaskReconciliation(context.Background(), value0)) fmt.Print("\n") break case "triggerImplicitTaskReconciliation": @@ -481,7 +510,7 @@ func main() { fmt.Fprintln(os.Stderr, "TriggerImplicitTaskReconciliation requires 0 args") flag.Usage() } - fmt.Print(client.TriggerImplicitTaskReconciliation()) + fmt.Print(client.TriggerImplicitTaskReconciliation(context.Background())) fmt.Print("\n") break case "pruneTasks": @@ -497,7 +526,7 @@ func main() { Usage() return } - factory420 := thrift.NewTSimpleJSONProtocolFactory() + factory420 := thrift.NewTJSONProtocolFactory() jsProt421 := factory420.GetProtocol(mbTrans418) argvalue0 := aurora.NewTaskQuery() err422 := argvalue0.Read(jsProt421) @@ -506,7 +535,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.PruneTasks(value0)) + fmt.Print(client.PruneTasks(context.Background(), value0)) fmt.Print("\n") break case "createJob": @@ -522,7 +551,7 @@ func main() { Usage() return } - factory426 := thrift.NewTSimpleJSONProtocolFactory() + factory426 := thrift.NewTJSONProtocolFactory() jsProt427 := factory426.GetProtocol(mbTrans424) argvalue0 := aurora.NewJobConfiguration() err428 := argvalue0.Read(jsProt427) @@ -531,7 +560,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.CreateJob(value0)) + fmt.Print(client.CreateJob(context.Background(), value0)) fmt.Print("\n") break case "scheduleCronJob": @@ -547,7 +576,7 @@ func main() { Usage() return } - factory432 := thrift.NewTSimpleJSONProtocolFactory() + factory432 := thrift.NewTJSONProtocolFactory() jsProt433 := factory432.GetProtocol(mbTrans430) argvalue0 := aurora.NewJobConfiguration() err434 := argvalue0.Read(jsProt433) @@ -556,7 +585,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.ScheduleCronJob(value0)) + fmt.Print(client.ScheduleCronJob(context.Background(), value0)) fmt.Print("\n") break case "descheduleCronJob": @@ -572,7 +601,7 @@ func main() { Usage() return } - factory438 := thrift.NewTSimpleJSONProtocolFactory() + factory438 := thrift.NewTJSONProtocolFactory() jsProt439 := factory438.GetProtocol(mbTrans436) argvalue0 := aurora.NewJobKey() err440 := argvalue0.Read(jsProt439) @@ -581,7 +610,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.DescheduleCronJob(value0)) + fmt.Print(client.DescheduleCronJob(context.Background(), value0)) fmt.Print("\n") break case "startCronJob": @@ -597,7 +626,7 @@ func main() { Usage() return } - factory444 := thrift.NewTSimpleJSONProtocolFactory() + factory444 := thrift.NewTJSONProtocolFactory() jsProt445 := factory444.GetProtocol(mbTrans442) argvalue0 := aurora.NewJobKey() err446 := argvalue0.Read(jsProt445) @@ -606,7 +635,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.StartCronJob(value0)) + fmt.Print(client.StartCronJob(context.Background(), value0)) fmt.Print("\n") break case "restartShards": @@ -622,7 +651,7 @@ func main() { Usage() return } - factory450 := thrift.NewTSimpleJSONProtocolFactory() + factory450 := thrift.NewTJSONProtocolFactory() jsProt451 := factory450.GetProtocol(mbTrans448) argvalue0 := aurora.NewJobKey() err452 := argvalue0.Read(jsProt451) @@ -639,7 +668,7 @@ func main() { Usage() return } - factory456 := thrift.NewTSimpleJSONProtocolFactory() + factory456 := thrift.NewTJSONProtocolFactory() jsProt457 := factory456.GetProtocol(mbTrans454) containerStruct1 := aurora.NewAuroraAdminRestartShardsArgs() err458 := containerStruct1.ReadField2(jsProt457) @@ -649,7 +678,7 @@ func main() { } argvalue1 := containerStruct1.ShardIds value1 := argvalue1 - fmt.Print(client.RestartShards(value0, value1)) + fmt.Print(client.RestartShards(context.Background(), value0, value1)) fmt.Print("\n") break case "killTasks": @@ -665,7 +694,7 @@ func main() { Usage() return } - factory462 := thrift.NewTSimpleJSONProtocolFactory() + factory462 := thrift.NewTJSONProtocolFactory() jsProt463 := factory462.GetProtocol(mbTrans460) argvalue0 := aurora.NewJobKey() err464 := argvalue0.Read(jsProt463) @@ -682,7 +711,7 @@ func main() { Usage() return } - factory468 := thrift.NewTSimpleJSONProtocolFactory() + factory468 := thrift.NewTJSONProtocolFactory() jsProt469 := factory468.GetProtocol(mbTrans466) containerStruct1 := aurora.NewAuroraAdminKillTasksArgs() err470 := containerStruct1.ReadField2(jsProt469) @@ -694,7 +723,7 @@ func main() { value1 := argvalue1 argvalue2 := flag.Arg(3) value2 := argvalue2 - fmt.Print(client.KillTasks(value0, value1, value2)) + fmt.Print(client.KillTasks(context.Background(), value0, value1, value2)) fmt.Print("\n") break case "addInstances": @@ -710,7 +739,7 @@ func main() { Usage() return } - factory475 := thrift.NewTSimpleJSONProtocolFactory() + factory475 := thrift.NewTJSONProtocolFactory() jsProt476 := factory475.GetProtocol(mbTrans473) argvalue0 := aurora.NewInstanceKey() err477 := argvalue0.Read(jsProt476) @@ -726,7 +755,7 @@ func main() { } argvalue1 := int32(tmp1) value1 := argvalue1 - fmt.Print(client.AddInstances(value0, value1)) + fmt.Print(client.AddInstances(context.Background(), value0, value1)) fmt.Print("\n") break case "replaceCronTemplate": @@ -742,7 +771,7 @@ func main() { Usage() return } - factory482 := thrift.NewTSimpleJSONProtocolFactory() + factory482 := thrift.NewTJSONProtocolFactory() jsProt483 := factory482.GetProtocol(mbTrans480) argvalue0 := aurora.NewJobConfiguration() err484 := argvalue0.Read(jsProt483) @@ -751,7 +780,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.ReplaceCronTemplate(value0)) + fmt.Print(client.ReplaceCronTemplate(context.Background(), value0)) fmt.Print("\n") break case "startJobUpdate": @@ -767,7 +796,7 @@ func main() { Usage() return } - factory488 := thrift.NewTSimpleJSONProtocolFactory() + factory488 := thrift.NewTJSONProtocolFactory() jsProt489 := factory488.GetProtocol(mbTrans486) argvalue0 := aurora.NewJobUpdateRequest() err490 := argvalue0.Read(jsProt489) @@ -778,7 +807,7 @@ func main() { value0 := argvalue0 argvalue1 := flag.Arg(2) value1 := argvalue1 - fmt.Print(client.StartJobUpdate(value0, value1)) + fmt.Print(client.StartJobUpdate(context.Background(), value0, value1)) fmt.Print("\n") break case "pauseJobUpdate": @@ -794,7 +823,7 @@ func main() { Usage() return } - factory495 := thrift.NewTSimpleJSONProtocolFactory() + factory495 := thrift.NewTJSONProtocolFactory() jsProt496 := factory495.GetProtocol(mbTrans493) argvalue0 := aurora.NewJobUpdateKey() err497 := argvalue0.Read(jsProt496) @@ -805,7 +834,7 @@ func main() { value0 := argvalue0 argvalue1 := flag.Arg(2) value1 := argvalue1 - fmt.Print(client.PauseJobUpdate(value0, value1)) + fmt.Print(client.PauseJobUpdate(context.Background(), value0, value1)) fmt.Print("\n") break case "resumeJobUpdate": @@ -821,7 +850,7 @@ func main() { Usage() return } - factory502 := thrift.NewTSimpleJSONProtocolFactory() + factory502 := thrift.NewTJSONProtocolFactory() jsProt503 := factory502.GetProtocol(mbTrans500) argvalue0 := aurora.NewJobUpdateKey() err504 := argvalue0.Read(jsProt503) @@ -832,7 +861,7 @@ func main() { value0 := argvalue0 argvalue1 := flag.Arg(2) value1 := argvalue1 - fmt.Print(client.ResumeJobUpdate(value0, value1)) + fmt.Print(client.ResumeJobUpdate(context.Background(), value0, value1)) fmt.Print("\n") break case "abortJobUpdate": @@ -848,7 +877,7 @@ func main() { Usage() return } - factory509 := thrift.NewTSimpleJSONProtocolFactory() + factory509 := thrift.NewTJSONProtocolFactory() jsProt510 := factory509.GetProtocol(mbTrans507) argvalue0 := aurora.NewJobUpdateKey() err511 := argvalue0.Read(jsProt510) @@ -859,7 +888,7 @@ func main() { value0 := argvalue0 argvalue1 := flag.Arg(2) value1 := argvalue1 - fmt.Print(client.AbortJobUpdate(value0, value1)) + fmt.Print(client.AbortJobUpdate(context.Background(), value0, value1)) fmt.Print("\n") break case "rollbackJobUpdate": @@ -875,7 +904,7 @@ func main() { Usage() return } - factory516 := thrift.NewTSimpleJSONProtocolFactory() + factory516 := thrift.NewTJSONProtocolFactory() jsProt517 := factory516.GetProtocol(mbTrans514) argvalue0 := aurora.NewJobUpdateKey() err518 := argvalue0.Read(jsProt517) @@ -886,7 +915,7 @@ func main() { value0 := argvalue0 argvalue1 := flag.Arg(2) value1 := argvalue1 - fmt.Print(client.RollbackJobUpdate(value0, value1)) + fmt.Print(client.RollbackJobUpdate(context.Background(), value0, value1)) fmt.Print("\n") break case "pulseJobUpdate": @@ -902,7 +931,7 @@ func main() { Usage() return } - factory523 := thrift.NewTSimpleJSONProtocolFactory() + factory523 := thrift.NewTJSONProtocolFactory() jsProt524 := factory523.GetProtocol(mbTrans521) argvalue0 := aurora.NewJobUpdateKey() err525 := argvalue0.Read(jsProt524) @@ -911,7 +940,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.PulseJobUpdate(value0)) + fmt.Print(client.PulseJobUpdate(context.Background(), value0)) fmt.Print("\n") break case "getRoleSummary": @@ -919,7 +948,7 @@ func main() { fmt.Fprintln(os.Stderr, "GetRoleSummary requires 0 args") flag.Usage() } - fmt.Print(client.GetRoleSummary()) + fmt.Print(client.GetRoleSummary(context.Background())) fmt.Print("\n") break case "getJobSummary": @@ -929,7 +958,7 @@ func main() { } argvalue0 := flag.Arg(1) value0 := argvalue0 - fmt.Print(client.GetJobSummary(value0)) + fmt.Print(client.GetJobSummary(context.Background(), value0)) fmt.Print("\n") break case "getTasksStatus": @@ -945,7 +974,7 @@ func main() { Usage() return } - factory530 := thrift.NewTSimpleJSONProtocolFactory() + factory530 := thrift.NewTJSONProtocolFactory() jsProt531 := factory530.GetProtocol(mbTrans528) argvalue0 := aurora.NewTaskQuery() err532 := argvalue0.Read(jsProt531) @@ -954,7 +983,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.GetTasksStatus(value0)) + fmt.Print(client.GetTasksStatus(context.Background(), value0)) fmt.Print("\n") break case "getTasksWithoutConfigs": @@ -970,7 +999,7 @@ func main() { Usage() return } - factory536 := thrift.NewTSimpleJSONProtocolFactory() + factory536 := thrift.NewTJSONProtocolFactory() jsProt537 := factory536.GetProtocol(mbTrans534) argvalue0 := aurora.NewTaskQuery() err538 := argvalue0.Read(jsProt537) @@ -979,7 +1008,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.GetTasksWithoutConfigs(value0)) + fmt.Print(client.GetTasksWithoutConfigs(context.Background(), value0)) fmt.Print("\n") break case "getPendingReason": @@ -995,7 +1024,7 @@ func main() { Usage() return } - factory542 := thrift.NewTSimpleJSONProtocolFactory() + factory542 := thrift.NewTJSONProtocolFactory() jsProt543 := factory542.GetProtocol(mbTrans540) argvalue0 := aurora.NewTaskQuery() err544 := argvalue0.Read(jsProt543) @@ -1004,7 +1033,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.GetPendingReason(value0)) + fmt.Print(client.GetPendingReason(context.Background(), value0)) fmt.Print("\n") break case "getConfigSummary": @@ -1020,7 +1049,7 @@ func main() { Usage() return } - factory548 := thrift.NewTSimpleJSONProtocolFactory() + factory548 := thrift.NewTJSONProtocolFactory() jsProt549 := factory548.GetProtocol(mbTrans546) argvalue0 := aurora.NewJobKey() err550 := argvalue0.Read(jsProt549) @@ -1029,7 +1058,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.GetConfigSummary(value0)) + fmt.Print(client.GetConfigSummary(context.Background(), value0)) fmt.Print("\n") break case "getJobs": @@ -1039,7 +1068,7 @@ func main() { } argvalue0 := flag.Arg(1) value0 := argvalue0 - fmt.Print(client.GetJobs(value0)) + fmt.Print(client.GetJobs(context.Background(), value0)) fmt.Print("\n") break case "getQuota": @@ -1049,7 +1078,7 @@ func main() { } argvalue0 := flag.Arg(1) value0 := argvalue0 - fmt.Print(client.GetQuota(value0)) + fmt.Print(client.GetQuota(context.Background(), value0)) fmt.Print("\n") break case "populateJobConfig": @@ -1065,7 +1094,7 @@ func main() { Usage() return } - factory556 := thrift.NewTSimpleJSONProtocolFactory() + factory556 := thrift.NewTJSONProtocolFactory() jsProt557 := factory556.GetProtocol(mbTrans554) argvalue0 := aurora.NewJobConfiguration() err558 := argvalue0.Read(jsProt557) @@ -1074,7 +1103,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.PopulateJobConfig(value0)) + fmt.Print(client.PopulateJobConfig(context.Background(), value0)) fmt.Print("\n") break case "getJobUpdateSummaries": @@ -1090,7 +1119,7 @@ func main() { Usage() return } - factory562 := thrift.NewTSimpleJSONProtocolFactory() + factory562 := thrift.NewTJSONProtocolFactory() jsProt563 := factory562.GetProtocol(mbTrans560) argvalue0 := aurora.NewJobUpdateQuery() err564 := argvalue0.Read(jsProt563) @@ -1099,7 +1128,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.GetJobUpdateSummaries(value0)) + fmt.Print(client.GetJobUpdateSummaries(context.Background(), value0)) fmt.Print("\n") break case "getJobUpdateDetails": @@ -1115,7 +1144,7 @@ func main() { Usage() return } - factory568 := thrift.NewTSimpleJSONProtocolFactory() + factory568 := thrift.NewTJSONProtocolFactory() jsProt569 := factory568.GetProtocol(mbTrans566) argvalue0 := aurora.NewJobUpdateQuery() err570 := argvalue0.Read(jsProt569) @@ -1124,7 +1153,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.GetJobUpdateDetails(value0)) + fmt.Print(client.GetJobUpdateDetails(context.Background(), value0)) fmt.Print("\n") break case "getJobUpdateDiff": @@ -1140,7 +1169,7 @@ func main() { Usage() return } - factory574 := thrift.NewTSimpleJSONProtocolFactory() + factory574 := thrift.NewTJSONProtocolFactory() jsProt575 := factory574.GetProtocol(mbTrans572) argvalue0 := aurora.NewJobUpdateRequest() err576 := argvalue0.Read(jsProt575) @@ -1149,7 +1178,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.GetJobUpdateDiff(value0)) + fmt.Print(client.GetJobUpdateDiff(context.Background(), value0)) fmt.Print("\n") break case "getTierConfigs": @@ -1157,7 +1186,7 @@ func main() { fmt.Fprintln(os.Stderr, "GetTierConfigs requires 0 args") flag.Usage() } - fmt.Print(client.GetTierConfigs()) + fmt.Print(client.GetTierConfigs(context.Background())) fmt.Print("\n") break case "": diff --git a/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/aurora_scheduler_manager-remote/aurora_scheduler_manager-remote.go b/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/aurora_scheduler_manager-remote/aurora_scheduler_manager-remote.go index 3ca67ea..20cdd79 100755 --- a/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/aurora_scheduler_manager-remote/aurora_scheduler_manager-remote.go +++ b/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/aurora_scheduler_manager-remote/aurora_scheduler_manager-remote.go @@ -1,19 +1,21 @@ -// Autogenerated by Thrift Compiler (0.9.3) +// Autogenerated by Thrift Compiler (0.12.0) // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING package main import ( "apache/aurora" + "context" "flag" "fmt" - "git.apache.org/thrift.git/lib/go/thrift" "math" "net" "net/url" "os" "strconv" "strings" + + "git.apache.org/thrift.git/lib/go/thrift" ) func Usage() { @@ -51,6 +53,22 @@ func Usage() { os.Exit(0) } +type httpHeaders map[string]string + +func (h httpHeaders) String() string { + var m map[string]string = h + return fmt.Sprintf("%s", m) +} + +func (h httpHeaders) Set(value string) error { + parts := strings.Split(value, ": ") + if len(parts) != 2 { + return fmt.Errorf("header should be of format 'Key: Value'") + } + h[parts[0]] = parts[1] + return nil +} + func main() { flag.Usage = Usage var host string @@ -59,7 +77,8 @@ func main() { var urlString string var framed bool var useHttp bool - var parsedUrl url.URL + headers := make(httpHeaders) + var parsedUrl *url.URL var trans thrift.TTransport _ = strconv.Atoi _ = math.Abs @@ -70,16 +89,18 @@ func main() { flag.StringVar(&urlString, "u", "", "Specify the url") flag.BoolVar(&framed, "framed", false, "Use framed transport") flag.BoolVar(&useHttp, "http", false, "Use http") + flag.Var(headers, "H", "Headers to set on the http(s) request (e.g. -H \"Key: Value\")") flag.Parse() if len(urlString) > 0 { - parsedUrl, err := url.Parse(urlString) + var err error + parsedUrl, err = url.Parse(urlString) if err != nil { fmt.Fprintln(os.Stderr, "Error parsing URL: ", err) flag.Usage() } host = parsedUrl.Host - useHttp = len(parsedUrl.Scheme) <= 0 || parsedUrl.Scheme == "http" + useHttp = len(parsedUrl.Scheme) <= 0 || parsedUrl.Scheme == "http" || parsedUrl.Scheme == "https" } else if useHttp { _, err := url.Parse(fmt.Sprint("http://", host, ":", port)) if err != nil { @@ -92,6 +113,12 @@ func main() { var err error if useHttp { trans, err = thrift.NewTHttpClient(parsedUrl.String()) + if len(headers) > 0 { + httptrans := trans.(*thrift.THttpClient) + for key, value := range headers { + httptrans.SetHeader(key, value) + } + } } else { portStr := fmt.Sprint(port) if strings.Contains(host, ":") { @@ -134,7 +161,9 @@ func main() { Usage() os.Exit(1) } - client := aurora.NewAuroraSchedulerManagerClientFactory(trans, protocolFactory) + iprot := protocolFactory.GetProtocol(trans) + oprot := protocolFactory.GetProtocol(trans) + client := aurora.NewAuroraSchedulerManagerClient(thrift.NewTStandardClient(iprot, oprot)) if err := trans.Open(); err != nil { fmt.Fprintln(os.Stderr, "Error opening socket to ", host, ":", port, " ", err) os.Exit(1) @@ -154,7 +183,7 @@ func main() { Usage() return } - factory165 := thrift.NewTSimpleJSONProtocolFactory() + factory165 := thrift.NewTJSONProtocolFactory() jsProt166 := factory165.GetProtocol(mbTrans163) argvalue0 := aurora.NewJobConfiguration() err167 := argvalue0.Read(jsProt166) @@ -163,7 +192,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.CreateJob(value0)) + fmt.Print(client.CreateJob(context.Background(), value0)) fmt.Print("\n") break case "scheduleCronJob": @@ -179,7 +208,7 @@ func main() { Usage() return } - factory171 := thrift.NewTSimpleJSONProtocolFactory() + factory171 := thrift.NewTJSONProtocolFactory() jsProt172 := factory171.GetProtocol(mbTrans169) argvalue0 := aurora.NewJobConfiguration() err173 := argvalue0.Read(jsProt172) @@ -188,7 +217,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.ScheduleCronJob(value0)) + fmt.Print(client.ScheduleCronJob(context.Background(), value0)) fmt.Print("\n") break case "descheduleCronJob": @@ -204,7 +233,7 @@ func main() { Usage() return } - factory177 := thrift.NewTSimpleJSONProtocolFactory() + factory177 := thrift.NewTJSONProtocolFactory() jsProt178 := factory177.GetProtocol(mbTrans175) argvalue0 := aurora.NewJobKey() err179 := argvalue0.Read(jsProt178) @@ -213,7 +242,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.DescheduleCronJob(value0)) + fmt.Print(client.DescheduleCronJob(context.Background(), value0)) fmt.Print("\n") break case "startCronJob": @@ -229,7 +258,7 @@ func main() { Usage() return } - factory183 := thrift.NewTSimpleJSONProtocolFactory() + factory183 := thrift.NewTJSONProtocolFactory() jsProt184 := factory183.GetProtocol(mbTrans181) argvalue0 := aurora.NewJobKey() err185 := argvalue0.Read(jsProt184) @@ -238,7 +267,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.StartCronJob(value0)) + fmt.Print(client.StartCronJob(context.Background(), value0)) fmt.Print("\n") break case "restartShards": @@ -254,7 +283,7 @@ func main() { Usage() return } - factory189 := thrift.NewTSimpleJSONProtocolFactory() + factory189 := thrift.NewTJSONProtocolFactory() jsProt190 := factory189.GetProtocol(mbTrans187) argvalue0 := aurora.NewJobKey() err191 := argvalue0.Read(jsProt190) @@ -271,7 +300,7 @@ func main() { Usage() return } - factory195 := thrift.NewTSimpleJSONProtocolFactory() + factory195 := thrift.NewTJSONProtocolFactory() jsProt196 := factory195.GetProtocol(mbTrans193) containerStruct1 := aurora.NewAuroraSchedulerManagerRestartShardsArgs() err197 := containerStruct1.ReadField2(jsProt196) @@ -281,7 +310,7 @@ func main() { } argvalue1 := containerStruct1.ShardIds value1 := argvalue1 - fmt.Print(client.RestartShards(value0, value1)) + fmt.Print(client.RestartShards(context.Background(), value0, value1)) fmt.Print("\n") break case "killTasks": @@ -297,7 +326,7 @@ func main() { Usage() return } - factory201 := thrift.NewTSimpleJSONProtocolFactory() + factory201 := thrift.NewTJSONProtocolFactory() jsProt202 := factory201.GetProtocol(mbTrans199) argvalue0 := aurora.NewJobKey() err203 := argvalue0.Read(jsProt202) @@ -314,7 +343,7 @@ func main() { Usage() return } - factory207 := thrift.NewTSimpleJSONProtocolFactory() + factory207 := thrift.NewTJSONProtocolFactory() jsProt208 := factory207.GetProtocol(mbTrans205) containerStruct1 := aurora.NewAuroraSchedulerManagerKillTasksArgs() err209 := containerStruct1.ReadField2(jsProt208) @@ -326,7 +355,7 @@ func main() { value1 := argvalue1 argvalue2 := flag.Arg(3) value2 := argvalue2 - fmt.Print(client.KillTasks(value0, value1, value2)) + fmt.Print(client.KillTasks(context.Background(), value0, value1, value2)) fmt.Print("\n") break case "addInstances": @@ -342,7 +371,7 @@ func main() { Usage() return } - factory214 := thrift.NewTSimpleJSONProtocolFactory() + factory214 := thrift.NewTJSONProtocolFactory() jsProt215 := factory214.GetProtocol(mbTrans212) argvalue0 := aurora.NewInstanceKey() err216 := argvalue0.Read(jsProt215) @@ -358,7 +387,7 @@ func main() { } argvalue1 := int32(tmp1) value1 := argvalue1 - fmt.Print(client.AddInstances(value0, value1)) + fmt.Print(client.AddInstances(context.Background(), value0, value1)) fmt.Print("\n") break case "replaceCronTemplate": @@ -374,7 +403,7 @@ func main() { Usage() return } - factory221 := thrift.NewTSimpleJSONProtocolFactory() + factory221 := thrift.NewTJSONProtocolFactory() jsProt222 := factory221.GetProtocol(mbTrans219) argvalue0 := aurora.NewJobConfiguration() err223 := argvalue0.Read(jsProt222) @@ -383,7 +412,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.ReplaceCronTemplate(value0)) + fmt.Print(client.ReplaceCronTemplate(context.Background(), value0)) fmt.Print("\n") break case "startJobUpdate": @@ -399,7 +428,7 @@ func main() { Usage() return } - factory227 := thrift.NewTSimpleJSONProtocolFactory() + factory227 := thrift.NewTJSONProtocolFactory() jsProt228 := factory227.GetProtocol(mbTrans225) argvalue0 := aurora.NewJobUpdateRequest() err229 := argvalue0.Read(jsProt228) @@ -410,7 +439,7 @@ func main() { value0 := argvalue0 argvalue1 := flag.Arg(2) value1 := argvalue1 - fmt.Print(client.StartJobUpdate(value0, value1)) + fmt.Print(client.StartJobUpdate(context.Background(), value0, value1)) fmt.Print("\n") break case "pauseJobUpdate": @@ -426,7 +455,7 @@ func main() { Usage() return } - factory234 := thrift.NewTSimpleJSONProtocolFactory() + factory234 := thrift.NewTJSONProtocolFactory() jsProt235 := factory234.GetProtocol(mbTrans232) argvalue0 := aurora.NewJobUpdateKey() err236 := argvalue0.Read(jsProt235) @@ -437,7 +466,7 @@ func main() { value0 := argvalue0 argvalue1 := flag.Arg(2) value1 := argvalue1 - fmt.Print(client.PauseJobUpdate(value0, value1)) + fmt.Print(client.PauseJobUpdate(context.Background(), value0, value1)) fmt.Print("\n") break case "resumeJobUpdate": @@ -453,7 +482,7 @@ func main() { Usage() return } - factory241 := thrift.NewTSimpleJSONProtocolFactory() + factory241 := thrift.NewTJSONProtocolFactory() jsProt242 := factory241.GetProtocol(mbTrans239) argvalue0 := aurora.NewJobUpdateKey() err243 := argvalue0.Read(jsProt242) @@ -464,7 +493,7 @@ func main() { value0 := argvalue0 argvalue1 := flag.Arg(2) value1 := argvalue1 - fmt.Print(client.ResumeJobUpdate(value0, value1)) + fmt.Print(client.ResumeJobUpdate(context.Background(), value0, value1)) fmt.Print("\n") break case "abortJobUpdate": @@ -480,7 +509,7 @@ func main() { Usage() return } - factory248 := thrift.NewTSimpleJSONProtocolFactory() + factory248 := thrift.NewTJSONProtocolFactory() jsProt249 := factory248.GetProtocol(mbTrans246) argvalue0 := aurora.NewJobUpdateKey() err250 := argvalue0.Read(jsProt249) @@ -491,7 +520,7 @@ func main() { value0 := argvalue0 argvalue1 := flag.Arg(2) value1 := argvalue1 - fmt.Print(client.AbortJobUpdate(value0, value1)) + fmt.Print(client.AbortJobUpdate(context.Background(), value0, value1)) fmt.Print("\n") break case "rollbackJobUpdate": @@ -507,7 +536,7 @@ func main() { Usage() return } - factory255 := thrift.NewTSimpleJSONProtocolFactory() + factory255 := thrift.NewTJSONProtocolFactory() jsProt256 := factory255.GetProtocol(mbTrans253) argvalue0 := aurora.NewJobUpdateKey() err257 := argvalue0.Read(jsProt256) @@ -518,7 +547,7 @@ func main() { value0 := argvalue0 argvalue1 := flag.Arg(2) value1 := argvalue1 - fmt.Print(client.RollbackJobUpdate(value0, value1)) + fmt.Print(client.RollbackJobUpdate(context.Background(), value0, value1)) fmt.Print("\n") break case "pulseJobUpdate": @@ -534,7 +563,7 @@ func main() { Usage() return } - factory262 := thrift.NewTSimpleJSONProtocolFactory() + factory262 := thrift.NewTJSONProtocolFactory() jsProt263 := factory262.GetProtocol(mbTrans260) argvalue0 := aurora.NewJobUpdateKey() err264 := argvalue0.Read(jsProt263) @@ -543,7 +572,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.PulseJobUpdate(value0)) + fmt.Print(client.PulseJobUpdate(context.Background(), value0)) fmt.Print("\n") break case "getRoleSummary": @@ -551,7 +580,7 @@ func main() { fmt.Fprintln(os.Stderr, "GetRoleSummary requires 0 args") flag.Usage() } - fmt.Print(client.GetRoleSummary()) + fmt.Print(client.GetRoleSummary(context.Background())) fmt.Print("\n") break case "getJobSummary": @@ -561,7 +590,7 @@ func main() { } argvalue0 := flag.Arg(1) value0 := argvalue0 - fmt.Print(client.GetJobSummary(value0)) + fmt.Print(client.GetJobSummary(context.Background(), value0)) fmt.Print("\n") break case "getTasksStatus": @@ -577,7 +606,7 @@ func main() { Usage() return } - factory269 := thrift.NewTSimpleJSONProtocolFactory() + factory269 := thrift.NewTJSONProtocolFactory() jsProt270 := factory269.GetProtocol(mbTrans267) argvalue0 := aurora.NewTaskQuery() err271 := argvalue0.Read(jsProt270) @@ -586,7 +615,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.GetTasksStatus(value0)) + fmt.Print(client.GetTasksStatus(context.Background(), value0)) fmt.Print("\n") break case "getTasksWithoutConfigs": @@ -602,7 +631,7 @@ func main() { Usage() return } - factory275 := thrift.NewTSimpleJSONProtocolFactory() + factory275 := thrift.NewTJSONProtocolFactory() jsProt276 := factory275.GetProtocol(mbTrans273) argvalue0 := aurora.NewTaskQuery() err277 := argvalue0.Read(jsProt276) @@ -611,7 +640,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.GetTasksWithoutConfigs(value0)) + fmt.Print(client.GetTasksWithoutConfigs(context.Background(), value0)) fmt.Print("\n") break case "getPendingReason": @@ -627,7 +656,7 @@ func main() { Usage() return } - factory281 := thrift.NewTSimpleJSONProtocolFactory() + factory281 := thrift.NewTJSONProtocolFactory() jsProt282 := factory281.GetProtocol(mbTrans279) argvalue0 := aurora.NewTaskQuery() err283 := argvalue0.Read(jsProt282) @@ -636,7 +665,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.GetPendingReason(value0)) + fmt.Print(client.GetPendingReason(context.Background(), value0)) fmt.Print("\n") break case "getConfigSummary": @@ -652,7 +681,7 @@ func main() { Usage() return } - factory287 := thrift.NewTSimpleJSONProtocolFactory() + factory287 := thrift.NewTJSONProtocolFactory() jsProt288 := factory287.GetProtocol(mbTrans285) argvalue0 := aurora.NewJobKey() err289 := argvalue0.Read(jsProt288) @@ -661,7 +690,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.GetConfigSummary(value0)) + fmt.Print(client.GetConfigSummary(context.Background(), value0)) fmt.Print("\n") break case "getJobs": @@ -671,7 +700,7 @@ func main() { } argvalue0 := flag.Arg(1) value0 := argvalue0 - fmt.Print(client.GetJobs(value0)) + fmt.Print(client.GetJobs(context.Background(), value0)) fmt.Print("\n") break case "getQuota": @@ -681,7 +710,7 @@ func main() { } argvalue0 := flag.Arg(1) value0 := argvalue0 - fmt.Print(client.GetQuota(value0)) + fmt.Print(client.GetQuota(context.Background(), value0)) fmt.Print("\n") break case "populateJobConfig": @@ -697,7 +726,7 @@ func main() { Usage() return } - factory295 := thrift.NewTSimpleJSONProtocolFactory() + factory295 := thrift.NewTJSONProtocolFactory() jsProt296 := factory295.GetProtocol(mbTrans293) argvalue0 := aurora.NewJobConfiguration() err297 := argvalue0.Read(jsProt296) @@ -706,7 +735,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.PopulateJobConfig(value0)) + fmt.Print(client.PopulateJobConfig(context.Background(), value0)) fmt.Print("\n") break case "getJobUpdateSummaries": @@ -722,7 +751,7 @@ func main() { Usage() return } - factory301 := thrift.NewTSimpleJSONProtocolFactory() + factory301 := thrift.NewTJSONProtocolFactory() jsProt302 := factory301.GetProtocol(mbTrans299) argvalue0 := aurora.NewJobUpdateQuery() err303 := argvalue0.Read(jsProt302) @@ -731,7 +760,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.GetJobUpdateSummaries(value0)) + fmt.Print(client.GetJobUpdateSummaries(context.Background(), value0)) fmt.Print("\n") break case "getJobUpdateDetails": @@ -747,7 +776,7 @@ func main() { Usage() return } - factory307 := thrift.NewTSimpleJSONProtocolFactory() + factory307 := thrift.NewTJSONProtocolFactory() jsProt308 := factory307.GetProtocol(mbTrans305) argvalue0 := aurora.NewJobUpdateQuery() err309 := argvalue0.Read(jsProt308) @@ -756,7 +785,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.GetJobUpdateDetails(value0)) + fmt.Print(client.GetJobUpdateDetails(context.Background(), value0)) fmt.Print("\n") break case "getJobUpdateDiff": @@ -772,7 +801,7 @@ func main() { Usage() return } - factory313 := thrift.NewTSimpleJSONProtocolFactory() + factory313 := thrift.NewTJSONProtocolFactory() jsProt314 := factory313.GetProtocol(mbTrans311) argvalue0 := aurora.NewJobUpdateRequest() err315 := argvalue0.Read(jsProt314) @@ -781,7 +810,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.GetJobUpdateDiff(value0)) + fmt.Print(client.GetJobUpdateDiff(context.Background(), value0)) fmt.Print("\n") break case "getTierConfigs": @@ -789,7 +818,7 @@ func main() { fmt.Fprintln(os.Stderr, "GetTierConfigs requires 0 args") flag.Usage() } - fmt.Print(client.GetTierConfigs()) + fmt.Print(client.GetTierConfigs(context.Background())) fmt.Print("\n") break case "": diff --git a/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/auroraadmin.go b/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/auroraadmin.go deleted file mode 100644 index b00e9cf..0000000 --- a/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/auroraadmin.go +++ /dev/null @@ -1,5870 +0,0 @@ -// Autogenerated by Thrift Compiler (0.9.3) -// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - -package aurora - -import ( - "bytes" - "fmt" - "git.apache.org/thrift.git/lib/go/thrift" -) - -// (needed to ensure safety because of naive import list construction.) -var _ = thrift.ZERO -var _ = fmt.Printf -var _ = bytes.Equal - -type AuroraAdmin interface { - AuroraSchedulerManager - - // Assign quota to a user. This will overwrite any pre-existing quota for the user. - // - // Parameters: - // - OwnerRole - // - Quota - SetQuota(ownerRole string, quota *ResourceAggregate) (r *Response, err error) - // Forces a task into a specific state. This does not guarantee the task will enter the given - // state, as the task must still transition within the bounds of the state machine. However, - // it attempts to enter that state via the state machine. - // - // Parameters: - // - TaskId - // - Status - ForceTaskState(taskId string, status ScheduleStatus) (r *Response, err error) - // Immediately writes a storage snapshot to disk. - PerformBackup() (r *Response, err error) - // Lists backups that are available for recovery. - ListBackups() (r *Response, err error) - // Loads a backup to an in-memory storage. This must precede all other recovery operations. - // - // Parameters: - // - BackupId - StageRecovery(backupId string) (r *Response, err error) - // Queries for tasks in a staged recovery. - // - // Parameters: - // - Query - QueryRecovery(query *TaskQuery) (r *Response, err error) - // Deletes tasks from a staged recovery. - // - // Parameters: - // - Query - DeleteRecoveryTasks(query *TaskQuery) (r *Response, err error) - // Commits a staged recovery, completely replacing the previous storage state. - CommitRecovery() (r *Response, err error) - // Unloads (aborts) a staged recovery. - UnloadRecovery() (r *Response, err error) - // Put the given hosts into maintenance mode. - // - // Parameters: - // - Hosts - StartMaintenance(hosts *Hosts) (r *Response, err error) - // Ask scheduler to begin moving tasks scheduled on given hosts. - // - // Parameters: - // - Hosts - DrainHosts(hosts *Hosts) (r *Response, err error) - // Retrieve the current maintenance states for a group of hosts. - // - // Parameters: - // - Hosts - MaintenanceStatus(hosts *Hosts) (r *Response, err error) - // Set the given hosts back into serving mode. - // - // Parameters: - // - Hosts - EndMaintenance(hosts *Hosts) (r *Response, err error) - // Ask scheduler to put hosts into DRAINING mode and move scheduled tasks off of the hosts - // such that its SLA requirements are satisfied. Use defaultSlaPolicy if it is not set for a task. - // - // - // Parameters: - // - Hosts - // - DefaultSlaPolicy - // - TimeoutSecs - SlaDrainHosts(hosts *Hosts, defaultSlaPolicy *SlaPolicy, timeoutSecs int64) (r *Response, err error) - // Start a storage snapshot and block until it completes. - Snapshot() (r *Response, err error) - // Tell scheduler to trigger an explicit task reconciliation with the given settings. - // - // Parameters: - // - Settings - TriggerExplicitTaskReconciliation(settings *ExplicitReconciliationSettings) (r *Response, err error) - // Tell scheduler to trigger an implicit task reconciliation. - TriggerImplicitTaskReconciliation() (r *Response, err error) - // Force prune any (terminal) tasks that match the query. If no statuses are supplied with the - // query, it will default to all terminal task states. If statuses are supplied, they must be - // terminal states. - // - // Parameters: - // - Query - PruneTasks(query *TaskQuery) (r *Response, err error) -} - -type AuroraAdminClient struct { - *AuroraSchedulerManagerClient -} - -func NewAuroraAdminClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *AuroraAdminClient { - return &AuroraAdminClient{AuroraSchedulerManagerClient: NewAuroraSchedulerManagerClientFactory(t, f)} -} - -func NewAuroraAdminClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *AuroraAdminClient { - return &AuroraAdminClient{AuroraSchedulerManagerClient: NewAuroraSchedulerManagerClientProtocol(t, iprot, oprot)} -} - -// Assign quota to a user. This will overwrite any pre-existing quota for the user. -// -// Parameters: -// - OwnerRole -// - Quota -func (p *AuroraAdminClient) SetQuota(ownerRole string, quota *ResourceAggregate) (r *Response, err error) { - if err = p.sendSetQuota(ownerRole, quota); err != nil { - return - } - return p.recvSetQuota() -} - -func (p *AuroraAdminClient) sendSetQuota(ownerRole string, quota *ResourceAggregate) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("setQuota", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraAdminSetQuotaArgs{ - OwnerRole: ownerRole, - Quota: quota, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraAdminClient) recvSetQuota() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "setQuota" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "setQuota failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "setQuota failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error316 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error317 error - error317, err = error316.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error317 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "setQuota failed: invalid message type") - return - } - result := AuroraAdminSetQuotaResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Forces a task into a specific state. This does not guarantee the task will enter the given -// state, as the task must still transition within the bounds of the state machine. However, -// it attempts to enter that state via the state machine. -// -// Parameters: -// - TaskId -// - Status -func (p *AuroraAdminClient) ForceTaskState(taskId string, status ScheduleStatus) (r *Response, err error) { - if err = p.sendForceTaskState(taskId, status); err != nil { - return - } - return p.recvForceTaskState() -} - -func (p *AuroraAdminClient) sendForceTaskState(taskId string, status ScheduleStatus) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("forceTaskState", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraAdminForceTaskStateArgs{ - TaskId: taskId, - Status: status, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraAdminClient) recvForceTaskState() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "forceTaskState" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "forceTaskState failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "forceTaskState failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error318 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error319 error - error319, err = error318.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error319 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "forceTaskState failed: invalid message type") - return - } - result := AuroraAdminForceTaskStateResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Immediately writes a storage snapshot to disk. -func (p *AuroraAdminClient) PerformBackup() (r *Response, err error) { - if err = p.sendPerformBackup(); err != nil { - return - } - return p.recvPerformBackup() -} - -func (p *AuroraAdminClient) sendPerformBackup() (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("performBackup", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraAdminPerformBackupArgs{} - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraAdminClient) recvPerformBackup() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "performBackup" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "performBackup failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "performBackup failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error320 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error321 error - error321, err = error320.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error321 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "performBackup failed: invalid message type") - return - } - result := AuroraAdminPerformBackupResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Lists backups that are available for recovery. -func (p *AuroraAdminClient) ListBackups() (r *Response, err error) { - if err = p.sendListBackups(); err != nil { - return - } - return p.recvListBackups() -} - -func (p *AuroraAdminClient) sendListBackups() (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("listBackups", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraAdminListBackupsArgs{} - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraAdminClient) recvListBackups() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "listBackups" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "listBackups failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "listBackups failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error322 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error323 error - error323, err = error322.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error323 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "listBackups failed: invalid message type") - return - } - result := AuroraAdminListBackupsResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Loads a backup to an in-memory storage. This must precede all other recovery operations. -// -// Parameters: -// - BackupId -func (p *AuroraAdminClient) StageRecovery(backupId string) (r *Response, err error) { - if err = p.sendStageRecovery(backupId); err != nil { - return - } - return p.recvStageRecovery() -} - -func (p *AuroraAdminClient) sendStageRecovery(backupId string) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("stageRecovery", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraAdminStageRecoveryArgs{ - BackupId: backupId, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraAdminClient) recvStageRecovery() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "stageRecovery" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "stageRecovery failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "stageRecovery failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error324 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error325 error - error325, err = error324.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error325 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "stageRecovery failed: invalid message type") - return - } - result := AuroraAdminStageRecoveryResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Queries for tasks in a staged recovery. -// -// Parameters: -// - Query -func (p *AuroraAdminClient) QueryRecovery(query *TaskQuery) (r *Response, err error) { - if err = p.sendQueryRecovery(query); err != nil { - return - } - return p.recvQueryRecovery() -} - -func (p *AuroraAdminClient) sendQueryRecovery(query *TaskQuery) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("queryRecovery", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraAdminQueryRecoveryArgs{ - Query: query, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraAdminClient) recvQueryRecovery() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "queryRecovery" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "queryRecovery failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "queryRecovery failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error326 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error327 error - error327, err = error326.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error327 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "queryRecovery failed: invalid message type") - return - } - result := AuroraAdminQueryRecoveryResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Deletes tasks from a staged recovery. -// -// Parameters: -// - Query -func (p *AuroraAdminClient) DeleteRecoveryTasks(query *TaskQuery) (r *Response, err error) { - if err = p.sendDeleteRecoveryTasks(query); err != nil { - return - } - return p.recvDeleteRecoveryTasks() -} - -func (p *AuroraAdminClient) sendDeleteRecoveryTasks(query *TaskQuery) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("deleteRecoveryTasks", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraAdminDeleteRecoveryTasksArgs{ - Query: query, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraAdminClient) recvDeleteRecoveryTasks() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "deleteRecoveryTasks" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "deleteRecoveryTasks failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "deleteRecoveryTasks failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error328 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error329 error - error329, err = error328.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error329 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "deleteRecoveryTasks failed: invalid message type") - return - } - result := AuroraAdminDeleteRecoveryTasksResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Commits a staged recovery, completely replacing the previous storage state. -func (p *AuroraAdminClient) CommitRecovery() (r *Response, err error) { - if err = p.sendCommitRecovery(); err != nil { - return - } - return p.recvCommitRecovery() -} - -func (p *AuroraAdminClient) sendCommitRecovery() (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("commitRecovery", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraAdminCommitRecoveryArgs{} - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraAdminClient) recvCommitRecovery() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "commitRecovery" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "commitRecovery failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "commitRecovery failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error330 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error331 error - error331, err = error330.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error331 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "commitRecovery failed: invalid message type") - return - } - result := AuroraAdminCommitRecoveryResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Unloads (aborts) a staged recovery. -func (p *AuroraAdminClient) UnloadRecovery() (r *Response, err error) { - if err = p.sendUnloadRecovery(); err != nil { - return - } - return p.recvUnloadRecovery() -} - -func (p *AuroraAdminClient) sendUnloadRecovery() (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("unloadRecovery", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraAdminUnloadRecoveryArgs{} - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraAdminClient) recvUnloadRecovery() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "unloadRecovery" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "unloadRecovery failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "unloadRecovery failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error332 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error333 error - error333, err = error332.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error333 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "unloadRecovery failed: invalid message type") - return - } - result := AuroraAdminUnloadRecoveryResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Put the given hosts into maintenance mode. -// -// Parameters: -// - Hosts -func (p *AuroraAdminClient) StartMaintenance(hosts *Hosts) (r *Response, err error) { - if err = p.sendStartMaintenance(hosts); err != nil { - return - } - return p.recvStartMaintenance() -} - -func (p *AuroraAdminClient) sendStartMaintenance(hosts *Hosts) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("startMaintenance", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraAdminStartMaintenanceArgs{ - Hosts: hosts, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraAdminClient) recvStartMaintenance() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "startMaintenance" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "startMaintenance failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "startMaintenance failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error334 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error335 error - error335, err = error334.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error335 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "startMaintenance failed: invalid message type") - return - } - result := AuroraAdminStartMaintenanceResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Ask scheduler to begin moving tasks scheduled on given hosts. -// -// Parameters: -// - Hosts -func (p *AuroraAdminClient) DrainHosts(hosts *Hosts) (r *Response, err error) { - if err = p.sendDrainHosts(hosts); err != nil { - return - } - return p.recvDrainHosts() -} - -func (p *AuroraAdminClient) sendDrainHosts(hosts *Hosts) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("drainHosts", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraAdminDrainHostsArgs{ - Hosts: hosts, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraAdminClient) recvDrainHosts() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "drainHosts" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "drainHosts failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "drainHosts failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error336 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error337 error - error337, err = error336.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error337 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "drainHosts failed: invalid message type") - return - } - result := AuroraAdminDrainHostsResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Retrieve the current maintenance states for a group of hosts. -// -// Parameters: -// - Hosts -func (p *AuroraAdminClient) MaintenanceStatus(hosts *Hosts) (r *Response, err error) { - if err = p.sendMaintenanceStatus(hosts); err != nil { - return - } - return p.recvMaintenanceStatus() -} - -func (p *AuroraAdminClient) sendMaintenanceStatus(hosts *Hosts) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("maintenanceStatus", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraAdminMaintenanceStatusArgs{ - Hosts: hosts, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraAdminClient) recvMaintenanceStatus() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "maintenanceStatus" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "maintenanceStatus failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "maintenanceStatus failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error338 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error339 error - error339, err = error338.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error339 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "maintenanceStatus failed: invalid message type") - return - } - result := AuroraAdminMaintenanceStatusResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Set the given hosts back into serving mode. -// -// Parameters: -// - Hosts -func (p *AuroraAdminClient) EndMaintenance(hosts *Hosts) (r *Response, err error) { - if err = p.sendEndMaintenance(hosts); err != nil { - return - } - return p.recvEndMaintenance() -} - -func (p *AuroraAdminClient) sendEndMaintenance(hosts *Hosts) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("endMaintenance", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraAdminEndMaintenanceArgs{ - Hosts: hosts, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraAdminClient) recvEndMaintenance() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "endMaintenance" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "endMaintenance failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "endMaintenance failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error340 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error341 error - error341, err = error340.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error341 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "endMaintenance failed: invalid message type") - return - } - result := AuroraAdminEndMaintenanceResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Ask scheduler to put hosts into DRAINING mode and move scheduled tasks off of the hosts -// such that its SLA requirements are satisfied. Use defaultSlaPolicy if it is not set for a task. -// -// -// Parameters: -// - Hosts -// - DefaultSlaPolicy -// - TimeoutSecs -func (p *AuroraAdminClient) SlaDrainHosts(hosts *Hosts, defaultSlaPolicy *SlaPolicy, timeoutSecs int64) (r *Response, err error) { - if err = p.sendSlaDrainHosts(hosts, defaultSlaPolicy, timeoutSecs); err != nil { - return - } - return p.recvSlaDrainHosts() -} - -func (p *AuroraAdminClient) sendSlaDrainHosts(hosts *Hosts, defaultSlaPolicy *SlaPolicy, timeoutSecs int64) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("slaDrainHosts", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraAdminSlaDrainHostsArgs{ - Hosts: hosts, - DefaultSlaPolicy: defaultSlaPolicy, - TimeoutSecs: timeoutSecs, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraAdminClient) recvSlaDrainHosts() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "slaDrainHosts" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "slaDrainHosts failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "slaDrainHosts failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error342 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error343 error - error343, err = error342.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error343 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "slaDrainHosts failed: invalid message type") - return - } - result := AuroraAdminSlaDrainHostsResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Start a storage snapshot and block until it completes. -func (p *AuroraAdminClient) Snapshot() (r *Response, err error) { - if err = p.sendSnapshot(); err != nil { - return - } - return p.recvSnapshot() -} - -func (p *AuroraAdminClient) sendSnapshot() (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("snapshot", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraAdminSnapshotArgs{} - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraAdminClient) recvSnapshot() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "snapshot" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "snapshot failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "snapshot failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error344 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error345 error - error345, err = error344.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error345 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "snapshot failed: invalid message type") - return - } - result := AuroraAdminSnapshotResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Tell scheduler to trigger an explicit task reconciliation with the given settings. -// -// Parameters: -// - Settings -func (p *AuroraAdminClient) TriggerExplicitTaskReconciliation(settings *ExplicitReconciliationSettings) (r *Response, err error) { - if err = p.sendTriggerExplicitTaskReconciliation(settings); err != nil { - return - } - return p.recvTriggerExplicitTaskReconciliation() -} - -func (p *AuroraAdminClient) sendTriggerExplicitTaskReconciliation(settings *ExplicitReconciliationSettings) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("triggerExplicitTaskReconciliation", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraAdminTriggerExplicitTaskReconciliationArgs{ - Settings: settings, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraAdminClient) recvTriggerExplicitTaskReconciliation() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "triggerExplicitTaskReconciliation" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "triggerExplicitTaskReconciliation failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "triggerExplicitTaskReconciliation failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error346 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error347 error - error347, err = error346.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error347 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "triggerExplicitTaskReconciliation failed: invalid message type") - return - } - result := AuroraAdminTriggerExplicitTaskReconciliationResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Tell scheduler to trigger an implicit task reconciliation. -func (p *AuroraAdminClient) TriggerImplicitTaskReconciliation() (r *Response, err error) { - if err = p.sendTriggerImplicitTaskReconciliation(); err != nil { - return - } - return p.recvTriggerImplicitTaskReconciliation() -} - -func (p *AuroraAdminClient) sendTriggerImplicitTaskReconciliation() (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("triggerImplicitTaskReconciliation", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraAdminTriggerImplicitTaskReconciliationArgs{} - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraAdminClient) recvTriggerImplicitTaskReconciliation() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "triggerImplicitTaskReconciliation" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "triggerImplicitTaskReconciliation failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "triggerImplicitTaskReconciliation failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error348 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error349 error - error349, err = error348.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error349 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "triggerImplicitTaskReconciliation failed: invalid message type") - return - } - result := AuroraAdminTriggerImplicitTaskReconciliationResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Force prune any (terminal) tasks that match the query. If no statuses are supplied with the -// query, it will default to all terminal task states. If statuses are supplied, they must be -// terminal states. -// -// Parameters: -// - Query -func (p *AuroraAdminClient) PruneTasks(query *TaskQuery) (r *Response, err error) { - if err = p.sendPruneTasks(query); err != nil { - return - } - return p.recvPruneTasks() -} - -func (p *AuroraAdminClient) sendPruneTasks(query *TaskQuery) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("pruneTasks", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraAdminPruneTasksArgs{ - Query: query, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraAdminClient) recvPruneTasks() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "pruneTasks" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "pruneTasks failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "pruneTasks failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error350 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error351 error - error351, err = error350.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error351 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "pruneTasks failed: invalid message type") - return - } - result := AuroraAdminPruneTasksResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -type AuroraAdminProcessor struct { - *AuroraSchedulerManagerProcessor -} - -func NewAuroraAdminProcessor(handler AuroraAdmin) *AuroraAdminProcessor { - self352 := &AuroraAdminProcessor{NewAuroraSchedulerManagerProcessor(handler)} - self352.AddToProcessorMap("setQuota", &auroraAdminProcessorSetQuota{handler: handler}) - self352.AddToProcessorMap("forceTaskState", &auroraAdminProcessorForceTaskState{handler: handler}) - self352.AddToProcessorMap("performBackup", &auroraAdminProcessorPerformBackup{handler: handler}) - self352.AddToProcessorMap("listBackups", &auroraAdminProcessorListBackups{handler: handler}) - self352.AddToProcessorMap("stageRecovery", &auroraAdminProcessorStageRecovery{handler: handler}) - self352.AddToProcessorMap("queryRecovery", &auroraAdminProcessorQueryRecovery{handler: handler}) - self352.AddToProcessorMap("deleteRecoveryTasks", &auroraAdminProcessorDeleteRecoveryTasks{handler: handler}) - self352.AddToProcessorMap("commitRecovery", &auroraAdminProcessorCommitRecovery{handler: handler}) - self352.AddToProcessorMap("unloadRecovery", &auroraAdminProcessorUnloadRecovery{handler: handler}) - self352.AddToProcessorMap("startMaintenance", &auroraAdminProcessorStartMaintenance{handler: handler}) - self352.AddToProcessorMap("drainHosts", &auroraAdminProcessorDrainHosts{handler: handler}) - self352.AddToProcessorMap("maintenanceStatus", &auroraAdminProcessorMaintenanceStatus{handler: handler}) - self352.AddToProcessorMap("endMaintenance", &auroraAdminProcessorEndMaintenance{handler: handler}) - self352.AddToProcessorMap("slaDrainHosts", &auroraAdminProcessorSlaDrainHosts{handler: handler}) - self352.AddToProcessorMap("snapshot", &auroraAdminProcessorSnapshot{handler: handler}) - self352.AddToProcessorMap("triggerExplicitTaskReconciliation", &auroraAdminProcessorTriggerExplicitTaskReconciliation{handler: handler}) - self352.AddToProcessorMap("triggerImplicitTaskReconciliation", &auroraAdminProcessorTriggerImplicitTaskReconciliation{handler: handler}) - self352.AddToProcessorMap("pruneTasks", &auroraAdminProcessorPruneTasks{handler: handler}) - return self352 -} - -type auroraAdminProcessorSetQuota struct { - handler AuroraAdmin -} - -func (p *auroraAdminProcessorSetQuota) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraAdminSetQuotaArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("setQuota", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraAdminSetQuotaResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.SetQuota(args.OwnerRole, args.Quota); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing setQuota: "+err2.Error()) - oprot.WriteMessageBegin("setQuota", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("setQuota", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraAdminProcessorForceTaskState struct { - handler AuroraAdmin -} - -func (p *auroraAdminProcessorForceTaskState) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraAdminForceTaskStateArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("forceTaskState", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraAdminForceTaskStateResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.ForceTaskState(args.TaskId, args.Status); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing forceTaskState: "+err2.Error()) - oprot.WriteMessageBegin("forceTaskState", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("forceTaskState", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraAdminProcessorPerformBackup struct { - handler AuroraAdmin -} - -func (p *auroraAdminProcessorPerformBackup) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraAdminPerformBackupArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("performBackup", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraAdminPerformBackupResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.PerformBackup(); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing performBackup: "+err2.Error()) - oprot.WriteMessageBegin("performBackup", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("performBackup", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraAdminProcessorListBackups struct { - handler AuroraAdmin -} - -func (p *auroraAdminProcessorListBackups) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraAdminListBackupsArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("listBackups", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraAdminListBackupsResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.ListBackups(); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing listBackups: "+err2.Error()) - oprot.WriteMessageBegin("listBackups", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("listBackups", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraAdminProcessorStageRecovery struct { - handler AuroraAdmin -} - -func (p *auroraAdminProcessorStageRecovery) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraAdminStageRecoveryArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("stageRecovery", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraAdminStageRecoveryResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.StageRecovery(args.BackupId); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing stageRecovery: "+err2.Error()) - oprot.WriteMessageBegin("stageRecovery", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("stageRecovery", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraAdminProcessorQueryRecovery struct { - handler AuroraAdmin -} - -func (p *auroraAdminProcessorQueryRecovery) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraAdminQueryRecoveryArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("queryRecovery", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraAdminQueryRecoveryResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.QueryRecovery(args.Query); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing queryRecovery: "+err2.Error()) - oprot.WriteMessageBegin("queryRecovery", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("queryRecovery", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraAdminProcessorDeleteRecoveryTasks struct { - handler AuroraAdmin -} - -func (p *auroraAdminProcessorDeleteRecoveryTasks) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraAdminDeleteRecoveryTasksArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("deleteRecoveryTasks", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraAdminDeleteRecoveryTasksResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.DeleteRecoveryTasks(args.Query); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing deleteRecoveryTasks: "+err2.Error()) - oprot.WriteMessageBegin("deleteRecoveryTasks", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("deleteRecoveryTasks", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraAdminProcessorCommitRecovery struct { - handler AuroraAdmin -} - -func (p *auroraAdminProcessorCommitRecovery) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraAdminCommitRecoveryArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("commitRecovery", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraAdminCommitRecoveryResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.CommitRecovery(); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing commitRecovery: "+err2.Error()) - oprot.WriteMessageBegin("commitRecovery", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("commitRecovery", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraAdminProcessorUnloadRecovery struct { - handler AuroraAdmin -} - -func (p *auroraAdminProcessorUnloadRecovery) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraAdminUnloadRecoveryArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("unloadRecovery", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraAdminUnloadRecoveryResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.UnloadRecovery(); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing unloadRecovery: "+err2.Error()) - oprot.WriteMessageBegin("unloadRecovery", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("unloadRecovery", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraAdminProcessorStartMaintenance struct { - handler AuroraAdmin -} - -func (p *auroraAdminProcessorStartMaintenance) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraAdminStartMaintenanceArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("startMaintenance", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraAdminStartMaintenanceResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.StartMaintenance(args.Hosts); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing startMaintenance: "+err2.Error()) - oprot.WriteMessageBegin("startMaintenance", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("startMaintenance", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraAdminProcessorDrainHosts struct { - handler AuroraAdmin -} - -func (p *auroraAdminProcessorDrainHosts) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraAdminDrainHostsArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("drainHosts", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraAdminDrainHostsResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.DrainHosts(args.Hosts); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing drainHosts: "+err2.Error()) - oprot.WriteMessageBegin("drainHosts", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("drainHosts", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraAdminProcessorMaintenanceStatus struct { - handler AuroraAdmin -} - -func (p *auroraAdminProcessorMaintenanceStatus) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraAdminMaintenanceStatusArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("maintenanceStatus", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraAdminMaintenanceStatusResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.MaintenanceStatus(args.Hosts); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing maintenanceStatus: "+err2.Error()) - oprot.WriteMessageBegin("maintenanceStatus", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("maintenanceStatus", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraAdminProcessorEndMaintenance struct { - handler AuroraAdmin -} - -func (p *auroraAdminProcessorEndMaintenance) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraAdminEndMaintenanceArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("endMaintenance", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraAdminEndMaintenanceResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.EndMaintenance(args.Hosts); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing endMaintenance: "+err2.Error()) - oprot.WriteMessageBegin("endMaintenance", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("endMaintenance", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraAdminProcessorSlaDrainHosts struct { - handler AuroraAdmin -} - -func (p *auroraAdminProcessorSlaDrainHosts) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraAdminSlaDrainHostsArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("slaDrainHosts", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraAdminSlaDrainHostsResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.SlaDrainHosts(args.Hosts, args.DefaultSlaPolicy, args.TimeoutSecs); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing slaDrainHosts: "+err2.Error()) - oprot.WriteMessageBegin("slaDrainHosts", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("slaDrainHosts", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraAdminProcessorSnapshot struct { - handler AuroraAdmin -} - -func (p *auroraAdminProcessorSnapshot) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraAdminSnapshotArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("snapshot", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraAdminSnapshotResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.Snapshot(); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing snapshot: "+err2.Error()) - oprot.WriteMessageBegin("snapshot", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("snapshot", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraAdminProcessorTriggerExplicitTaskReconciliation struct { - handler AuroraAdmin -} - -func (p *auroraAdminProcessorTriggerExplicitTaskReconciliation) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraAdminTriggerExplicitTaskReconciliationArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("triggerExplicitTaskReconciliation", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraAdminTriggerExplicitTaskReconciliationResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.TriggerExplicitTaskReconciliation(args.Settings); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing triggerExplicitTaskReconciliation: "+err2.Error()) - oprot.WriteMessageBegin("triggerExplicitTaskReconciliation", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("triggerExplicitTaskReconciliation", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraAdminProcessorTriggerImplicitTaskReconciliation struct { - handler AuroraAdmin -} - -func (p *auroraAdminProcessorTriggerImplicitTaskReconciliation) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraAdminTriggerImplicitTaskReconciliationArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("triggerImplicitTaskReconciliation", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraAdminTriggerImplicitTaskReconciliationResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.TriggerImplicitTaskReconciliation(); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing triggerImplicitTaskReconciliation: "+err2.Error()) - oprot.WriteMessageBegin("triggerImplicitTaskReconciliation", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("triggerImplicitTaskReconciliation", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraAdminProcessorPruneTasks struct { - handler AuroraAdmin -} - -func (p *auroraAdminProcessorPruneTasks) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraAdminPruneTasksArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("pruneTasks", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraAdminPruneTasksResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.PruneTasks(args.Query); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing pruneTasks: "+err2.Error()) - oprot.WriteMessageBegin("pruneTasks", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("pruneTasks", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -// HELPER FUNCTIONS AND STRUCTURES - -// Attributes: -// - OwnerRole -// - Quota -type AuroraAdminSetQuotaArgs struct { - OwnerRole string `thrift:"ownerRole,1" json:"ownerRole"` - Quota *ResourceAggregate `thrift:"quota,2" json:"quota"` -} - -func NewAuroraAdminSetQuotaArgs() *AuroraAdminSetQuotaArgs { - return &AuroraAdminSetQuotaArgs{} -} - -func (p *AuroraAdminSetQuotaArgs) GetOwnerRole() string { - return p.OwnerRole -} - -var AuroraAdminSetQuotaArgs_Quota_DEFAULT *ResourceAggregate - -func (p *AuroraAdminSetQuotaArgs) GetQuota() *ResourceAggregate { - if !p.IsSetQuota() { - return AuroraAdminSetQuotaArgs_Quota_DEFAULT - } - return p.Quota -} -func (p *AuroraAdminSetQuotaArgs) IsSetQuota() bool { - return p.Quota != nil -} - -func (p *AuroraAdminSetQuotaArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminSetQuotaArgs) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.OwnerRole = v - } - return nil -} - -func (p *AuroraAdminSetQuotaArgs) readField2(iprot thrift.TProtocol) error { - p.Quota = &ResourceAggregate{} - if err := p.Quota.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Quota), err) - } - return nil -} - -func (p *AuroraAdminSetQuotaArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("setQuota_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminSetQuotaArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("ownerRole", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:ownerRole: ", p), err) - } - if err := oprot.WriteString(string(p.OwnerRole)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.ownerRole (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:ownerRole: ", p), err) - } - return err -} - -func (p *AuroraAdminSetQuotaArgs) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("quota", thrift.STRUCT, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:quota: ", p), err) - } - if err := p.Quota.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Quota), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:quota: ", p), err) - } - return err -} - -func (p *AuroraAdminSetQuotaArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminSetQuotaArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraAdminSetQuotaResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraAdminSetQuotaResult() *AuroraAdminSetQuotaResult { - return &AuroraAdminSetQuotaResult{} -} - -var AuroraAdminSetQuotaResult_Success_DEFAULT *Response - -func (p *AuroraAdminSetQuotaResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraAdminSetQuotaResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraAdminSetQuotaResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraAdminSetQuotaResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminSetQuotaResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraAdminSetQuotaResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("setQuota_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminSetQuotaResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraAdminSetQuotaResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminSetQuotaResult(%+v)", *p) -} - -// Attributes: -// - TaskId -// - Status -type AuroraAdminForceTaskStateArgs struct { - TaskId string `thrift:"taskId,1" json:"taskId"` - Status ScheduleStatus `thrift:"status,2" json:"status"` -} - -func NewAuroraAdminForceTaskStateArgs() *AuroraAdminForceTaskStateArgs { - return &AuroraAdminForceTaskStateArgs{} -} - -func (p *AuroraAdminForceTaskStateArgs) GetTaskId() string { - return p.TaskId -} - -func (p *AuroraAdminForceTaskStateArgs) GetStatus() ScheduleStatus { - return p.Status -} -func (p *AuroraAdminForceTaskStateArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminForceTaskStateArgs) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.TaskId = v - } - return nil -} - -func (p *AuroraAdminForceTaskStateArgs) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - temp := ScheduleStatus(v) - p.Status = temp - } - return nil -} - -func (p *AuroraAdminForceTaskStateArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("forceTaskState_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminForceTaskStateArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("taskId", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:taskId: ", p), err) - } - if err := oprot.WriteString(string(p.TaskId)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.taskId (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:taskId: ", p), err) - } - return err -} - -func (p *AuroraAdminForceTaskStateArgs) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("status", thrift.I32, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:status: ", p), err) - } - if err := oprot.WriteI32(int32(p.Status)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.status (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:status: ", p), err) - } - return err -} - -func (p *AuroraAdminForceTaskStateArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminForceTaskStateArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraAdminForceTaskStateResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraAdminForceTaskStateResult() *AuroraAdminForceTaskStateResult { - return &AuroraAdminForceTaskStateResult{} -} - -var AuroraAdminForceTaskStateResult_Success_DEFAULT *Response - -func (p *AuroraAdminForceTaskStateResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraAdminForceTaskStateResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraAdminForceTaskStateResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraAdminForceTaskStateResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminForceTaskStateResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraAdminForceTaskStateResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("forceTaskState_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminForceTaskStateResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraAdminForceTaskStateResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminForceTaskStateResult(%+v)", *p) -} - -type AuroraAdminPerformBackupArgs struct { -} - -func NewAuroraAdminPerformBackupArgs() *AuroraAdminPerformBackupArgs { - return &AuroraAdminPerformBackupArgs{} -} - -func (p *AuroraAdminPerformBackupArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminPerformBackupArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("performBackup_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminPerformBackupArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminPerformBackupArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraAdminPerformBackupResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraAdminPerformBackupResult() *AuroraAdminPerformBackupResult { - return &AuroraAdminPerformBackupResult{} -} - -var AuroraAdminPerformBackupResult_Success_DEFAULT *Response - -func (p *AuroraAdminPerformBackupResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraAdminPerformBackupResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraAdminPerformBackupResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraAdminPerformBackupResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminPerformBackupResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraAdminPerformBackupResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("performBackup_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminPerformBackupResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraAdminPerformBackupResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminPerformBackupResult(%+v)", *p) -} - -type AuroraAdminListBackupsArgs struct { -} - -func NewAuroraAdminListBackupsArgs() *AuroraAdminListBackupsArgs { - return &AuroraAdminListBackupsArgs{} -} - -func (p *AuroraAdminListBackupsArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminListBackupsArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("listBackups_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminListBackupsArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminListBackupsArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraAdminListBackupsResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraAdminListBackupsResult() *AuroraAdminListBackupsResult { - return &AuroraAdminListBackupsResult{} -} - -var AuroraAdminListBackupsResult_Success_DEFAULT *Response - -func (p *AuroraAdminListBackupsResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraAdminListBackupsResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraAdminListBackupsResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraAdminListBackupsResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminListBackupsResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraAdminListBackupsResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("listBackups_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminListBackupsResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraAdminListBackupsResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminListBackupsResult(%+v)", *p) -} - -// Attributes: -// - BackupId -type AuroraAdminStageRecoveryArgs struct { - BackupId string `thrift:"backupId,1" json:"backupId"` -} - -func NewAuroraAdminStageRecoveryArgs() *AuroraAdminStageRecoveryArgs { - return &AuroraAdminStageRecoveryArgs{} -} - -func (p *AuroraAdminStageRecoveryArgs) GetBackupId() string { - return p.BackupId -} -func (p *AuroraAdminStageRecoveryArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminStageRecoveryArgs) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.BackupId = v - } - return nil -} - -func (p *AuroraAdminStageRecoveryArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("stageRecovery_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminStageRecoveryArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("backupId", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:backupId: ", p), err) - } - if err := oprot.WriteString(string(p.BackupId)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.backupId (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:backupId: ", p), err) - } - return err -} - -func (p *AuroraAdminStageRecoveryArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminStageRecoveryArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraAdminStageRecoveryResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraAdminStageRecoveryResult() *AuroraAdminStageRecoveryResult { - return &AuroraAdminStageRecoveryResult{} -} - -var AuroraAdminStageRecoveryResult_Success_DEFAULT *Response - -func (p *AuroraAdminStageRecoveryResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraAdminStageRecoveryResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraAdminStageRecoveryResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraAdminStageRecoveryResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminStageRecoveryResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraAdminStageRecoveryResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("stageRecovery_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminStageRecoveryResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraAdminStageRecoveryResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminStageRecoveryResult(%+v)", *p) -} - -// Attributes: -// - Query -type AuroraAdminQueryRecoveryArgs struct { - Query *TaskQuery `thrift:"query,1" json:"query"` -} - -func NewAuroraAdminQueryRecoveryArgs() *AuroraAdminQueryRecoveryArgs { - return &AuroraAdminQueryRecoveryArgs{} -} - -var AuroraAdminQueryRecoveryArgs_Query_DEFAULT *TaskQuery - -func (p *AuroraAdminQueryRecoveryArgs) GetQuery() *TaskQuery { - if !p.IsSetQuery() { - return AuroraAdminQueryRecoveryArgs_Query_DEFAULT - } - return p.Query -} -func (p *AuroraAdminQueryRecoveryArgs) IsSetQuery() bool { - return p.Query != nil -} - -func (p *AuroraAdminQueryRecoveryArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminQueryRecoveryArgs) readField1(iprot thrift.TProtocol) error { - p.Query = &TaskQuery{} - if err := p.Query.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Query), err) - } - return nil -} - -func (p *AuroraAdminQueryRecoveryArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("queryRecovery_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminQueryRecoveryArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("query", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:query: ", p), err) - } - if err := p.Query.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Query), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:query: ", p), err) - } - return err -} - -func (p *AuroraAdminQueryRecoveryArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminQueryRecoveryArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraAdminQueryRecoveryResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraAdminQueryRecoveryResult() *AuroraAdminQueryRecoveryResult { - return &AuroraAdminQueryRecoveryResult{} -} - -var AuroraAdminQueryRecoveryResult_Success_DEFAULT *Response - -func (p *AuroraAdminQueryRecoveryResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraAdminQueryRecoveryResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraAdminQueryRecoveryResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraAdminQueryRecoveryResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminQueryRecoveryResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraAdminQueryRecoveryResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("queryRecovery_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminQueryRecoveryResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraAdminQueryRecoveryResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminQueryRecoveryResult(%+v)", *p) -} - -// Attributes: -// - Query -type AuroraAdminDeleteRecoveryTasksArgs struct { - Query *TaskQuery `thrift:"query,1" json:"query"` -} - -func NewAuroraAdminDeleteRecoveryTasksArgs() *AuroraAdminDeleteRecoveryTasksArgs { - return &AuroraAdminDeleteRecoveryTasksArgs{} -} - -var AuroraAdminDeleteRecoveryTasksArgs_Query_DEFAULT *TaskQuery - -func (p *AuroraAdminDeleteRecoveryTasksArgs) GetQuery() *TaskQuery { - if !p.IsSetQuery() { - return AuroraAdminDeleteRecoveryTasksArgs_Query_DEFAULT - } - return p.Query -} -func (p *AuroraAdminDeleteRecoveryTasksArgs) IsSetQuery() bool { - return p.Query != nil -} - -func (p *AuroraAdminDeleteRecoveryTasksArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminDeleteRecoveryTasksArgs) readField1(iprot thrift.TProtocol) error { - p.Query = &TaskQuery{} - if err := p.Query.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Query), err) - } - return nil -} - -func (p *AuroraAdminDeleteRecoveryTasksArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("deleteRecoveryTasks_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminDeleteRecoveryTasksArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("query", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:query: ", p), err) - } - if err := p.Query.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Query), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:query: ", p), err) - } - return err -} - -func (p *AuroraAdminDeleteRecoveryTasksArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminDeleteRecoveryTasksArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraAdminDeleteRecoveryTasksResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraAdminDeleteRecoveryTasksResult() *AuroraAdminDeleteRecoveryTasksResult { - return &AuroraAdminDeleteRecoveryTasksResult{} -} - -var AuroraAdminDeleteRecoveryTasksResult_Success_DEFAULT *Response - -func (p *AuroraAdminDeleteRecoveryTasksResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraAdminDeleteRecoveryTasksResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraAdminDeleteRecoveryTasksResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraAdminDeleteRecoveryTasksResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminDeleteRecoveryTasksResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraAdminDeleteRecoveryTasksResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("deleteRecoveryTasks_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminDeleteRecoveryTasksResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraAdminDeleteRecoveryTasksResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminDeleteRecoveryTasksResult(%+v)", *p) -} - -type AuroraAdminCommitRecoveryArgs struct { -} - -func NewAuroraAdminCommitRecoveryArgs() *AuroraAdminCommitRecoveryArgs { - return &AuroraAdminCommitRecoveryArgs{} -} - -func (p *AuroraAdminCommitRecoveryArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminCommitRecoveryArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("commitRecovery_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminCommitRecoveryArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminCommitRecoveryArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraAdminCommitRecoveryResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraAdminCommitRecoveryResult() *AuroraAdminCommitRecoveryResult { - return &AuroraAdminCommitRecoveryResult{} -} - -var AuroraAdminCommitRecoveryResult_Success_DEFAULT *Response - -func (p *AuroraAdminCommitRecoveryResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraAdminCommitRecoveryResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraAdminCommitRecoveryResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraAdminCommitRecoveryResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminCommitRecoveryResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraAdminCommitRecoveryResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("commitRecovery_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminCommitRecoveryResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraAdminCommitRecoveryResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminCommitRecoveryResult(%+v)", *p) -} - -type AuroraAdminUnloadRecoveryArgs struct { -} - -func NewAuroraAdminUnloadRecoveryArgs() *AuroraAdminUnloadRecoveryArgs { - return &AuroraAdminUnloadRecoveryArgs{} -} - -func (p *AuroraAdminUnloadRecoveryArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminUnloadRecoveryArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("unloadRecovery_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminUnloadRecoveryArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminUnloadRecoveryArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraAdminUnloadRecoveryResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraAdminUnloadRecoveryResult() *AuroraAdminUnloadRecoveryResult { - return &AuroraAdminUnloadRecoveryResult{} -} - -var AuroraAdminUnloadRecoveryResult_Success_DEFAULT *Response - -func (p *AuroraAdminUnloadRecoveryResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraAdminUnloadRecoveryResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraAdminUnloadRecoveryResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraAdminUnloadRecoveryResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminUnloadRecoveryResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraAdminUnloadRecoveryResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("unloadRecovery_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminUnloadRecoveryResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraAdminUnloadRecoveryResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminUnloadRecoveryResult(%+v)", *p) -} - -// Attributes: -// - Hosts -type AuroraAdminStartMaintenanceArgs struct { - Hosts *Hosts `thrift:"hosts,1" json:"hosts"` -} - -func NewAuroraAdminStartMaintenanceArgs() *AuroraAdminStartMaintenanceArgs { - return &AuroraAdminStartMaintenanceArgs{} -} - -var AuroraAdminStartMaintenanceArgs_Hosts_DEFAULT *Hosts - -func (p *AuroraAdminStartMaintenanceArgs) GetHosts() *Hosts { - if !p.IsSetHosts() { - return AuroraAdminStartMaintenanceArgs_Hosts_DEFAULT - } - return p.Hosts -} -func (p *AuroraAdminStartMaintenanceArgs) IsSetHosts() bool { - return p.Hosts != nil -} - -func (p *AuroraAdminStartMaintenanceArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminStartMaintenanceArgs) readField1(iprot thrift.TProtocol) error { - p.Hosts = &Hosts{} - if err := p.Hosts.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Hosts), err) - } - return nil -} - -func (p *AuroraAdminStartMaintenanceArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("startMaintenance_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminStartMaintenanceArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("hosts", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:hosts: ", p), err) - } - if err := p.Hosts.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Hosts), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:hosts: ", p), err) - } - return err -} - -func (p *AuroraAdminStartMaintenanceArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminStartMaintenanceArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraAdminStartMaintenanceResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraAdminStartMaintenanceResult() *AuroraAdminStartMaintenanceResult { - return &AuroraAdminStartMaintenanceResult{} -} - -var AuroraAdminStartMaintenanceResult_Success_DEFAULT *Response - -func (p *AuroraAdminStartMaintenanceResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraAdminStartMaintenanceResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraAdminStartMaintenanceResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraAdminStartMaintenanceResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminStartMaintenanceResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraAdminStartMaintenanceResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("startMaintenance_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminStartMaintenanceResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraAdminStartMaintenanceResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminStartMaintenanceResult(%+v)", *p) -} - -// Attributes: -// - Hosts -type AuroraAdminDrainHostsArgs struct { - Hosts *Hosts `thrift:"hosts,1" json:"hosts"` -} - -func NewAuroraAdminDrainHostsArgs() *AuroraAdminDrainHostsArgs { - return &AuroraAdminDrainHostsArgs{} -} - -var AuroraAdminDrainHostsArgs_Hosts_DEFAULT *Hosts - -func (p *AuroraAdminDrainHostsArgs) GetHosts() *Hosts { - if !p.IsSetHosts() { - return AuroraAdminDrainHostsArgs_Hosts_DEFAULT - } - return p.Hosts -} -func (p *AuroraAdminDrainHostsArgs) IsSetHosts() bool { - return p.Hosts != nil -} - -func (p *AuroraAdminDrainHostsArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminDrainHostsArgs) readField1(iprot thrift.TProtocol) error { - p.Hosts = &Hosts{} - if err := p.Hosts.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Hosts), err) - } - return nil -} - -func (p *AuroraAdminDrainHostsArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("drainHosts_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminDrainHostsArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("hosts", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:hosts: ", p), err) - } - if err := p.Hosts.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Hosts), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:hosts: ", p), err) - } - return err -} - -func (p *AuroraAdminDrainHostsArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminDrainHostsArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraAdminDrainHostsResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraAdminDrainHostsResult() *AuroraAdminDrainHostsResult { - return &AuroraAdminDrainHostsResult{} -} - -var AuroraAdminDrainHostsResult_Success_DEFAULT *Response - -func (p *AuroraAdminDrainHostsResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraAdminDrainHostsResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraAdminDrainHostsResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraAdminDrainHostsResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminDrainHostsResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraAdminDrainHostsResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("drainHosts_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminDrainHostsResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraAdminDrainHostsResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminDrainHostsResult(%+v)", *p) -} - -// Attributes: -// - Hosts -type AuroraAdminMaintenanceStatusArgs struct { - Hosts *Hosts `thrift:"hosts,1" json:"hosts"` -} - -func NewAuroraAdminMaintenanceStatusArgs() *AuroraAdminMaintenanceStatusArgs { - return &AuroraAdminMaintenanceStatusArgs{} -} - -var AuroraAdminMaintenanceStatusArgs_Hosts_DEFAULT *Hosts - -func (p *AuroraAdminMaintenanceStatusArgs) GetHosts() *Hosts { - if !p.IsSetHosts() { - return AuroraAdminMaintenanceStatusArgs_Hosts_DEFAULT - } - return p.Hosts -} -func (p *AuroraAdminMaintenanceStatusArgs) IsSetHosts() bool { - return p.Hosts != nil -} - -func (p *AuroraAdminMaintenanceStatusArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminMaintenanceStatusArgs) readField1(iprot thrift.TProtocol) error { - p.Hosts = &Hosts{} - if err := p.Hosts.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Hosts), err) - } - return nil -} - -func (p *AuroraAdminMaintenanceStatusArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("maintenanceStatus_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminMaintenanceStatusArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("hosts", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:hosts: ", p), err) - } - if err := p.Hosts.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Hosts), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:hosts: ", p), err) - } - return err -} - -func (p *AuroraAdminMaintenanceStatusArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminMaintenanceStatusArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraAdminMaintenanceStatusResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraAdminMaintenanceStatusResult() *AuroraAdminMaintenanceStatusResult { - return &AuroraAdminMaintenanceStatusResult{} -} - -var AuroraAdminMaintenanceStatusResult_Success_DEFAULT *Response - -func (p *AuroraAdminMaintenanceStatusResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraAdminMaintenanceStatusResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraAdminMaintenanceStatusResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraAdminMaintenanceStatusResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminMaintenanceStatusResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraAdminMaintenanceStatusResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("maintenanceStatus_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminMaintenanceStatusResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraAdminMaintenanceStatusResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminMaintenanceStatusResult(%+v)", *p) -} - -// Attributes: -// - Hosts -type AuroraAdminEndMaintenanceArgs struct { - Hosts *Hosts `thrift:"hosts,1" json:"hosts"` -} - -func NewAuroraAdminEndMaintenanceArgs() *AuroraAdminEndMaintenanceArgs { - return &AuroraAdminEndMaintenanceArgs{} -} - -var AuroraAdminEndMaintenanceArgs_Hosts_DEFAULT *Hosts - -func (p *AuroraAdminEndMaintenanceArgs) GetHosts() *Hosts { - if !p.IsSetHosts() { - return AuroraAdminEndMaintenanceArgs_Hosts_DEFAULT - } - return p.Hosts -} -func (p *AuroraAdminEndMaintenanceArgs) IsSetHosts() bool { - return p.Hosts != nil -} - -func (p *AuroraAdminEndMaintenanceArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminEndMaintenanceArgs) readField1(iprot thrift.TProtocol) error { - p.Hosts = &Hosts{} - if err := p.Hosts.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Hosts), err) - } - return nil -} - -func (p *AuroraAdminEndMaintenanceArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("endMaintenance_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminEndMaintenanceArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("hosts", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:hosts: ", p), err) - } - if err := p.Hosts.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Hosts), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:hosts: ", p), err) - } - return err -} - -func (p *AuroraAdminEndMaintenanceArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminEndMaintenanceArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraAdminEndMaintenanceResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraAdminEndMaintenanceResult() *AuroraAdminEndMaintenanceResult { - return &AuroraAdminEndMaintenanceResult{} -} - -var AuroraAdminEndMaintenanceResult_Success_DEFAULT *Response - -func (p *AuroraAdminEndMaintenanceResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraAdminEndMaintenanceResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraAdminEndMaintenanceResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraAdminEndMaintenanceResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminEndMaintenanceResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraAdminEndMaintenanceResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("endMaintenance_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminEndMaintenanceResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraAdminEndMaintenanceResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminEndMaintenanceResult(%+v)", *p) -} - -// Attributes: -// - Hosts -// - DefaultSlaPolicy -// - TimeoutSecs -type AuroraAdminSlaDrainHostsArgs struct { - Hosts *Hosts `thrift:"hosts,1" json:"hosts"` - DefaultSlaPolicy *SlaPolicy `thrift:"defaultSlaPolicy,2" json:"defaultSlaPolicy"` - TimeoutSecs int64 `thrift:"timeoutSecs,3" json:"timeoutSecs"` -} - -func NewAuroraAdminSlaDrainHostsArgs() *AuroraAdminSlaDrainHostsArgs { - return &AuroraAdminSlaDrainHostsArgs{} -} - -var AuroraAdminSlaDrainHostsArgs_Hosts_DEFAULT *Hosts - -func (p *AuroraAdminSlaDrainHostsArgs) GetHosts() *Hosts { - if !p.IsSetHosts() { - return AuroraAdminSlaDrainHostsArgs_Hosts_DEFAULT - } - return p.Hosts -} - -var AuroraAdminSlaDrainHostsArgs_DefaultSlaPolicy_DEFAULT *SlaPolicy - -func (p *AuroraAdminSlaDrainHostsArgs) GetDefaultSlaPolicy() *SlaPolicy { - if !p.IsSetDefaultSlaPolicy() { - return AuroraAdminSlaDrainHostsArgs_DefaultSlaPolicy_DEFAULT - } - return p.DefaultSlaPolicy -} - -func (p *AuroraAdminSlaDrainHostsArgs) GetTimeoutSecs() int64 { - return p.TimeoutSecs -} -func (p *AuroraAdminSlaDrainHostsArgs) IsSetHosts() bool { - return p.Hosts != nil -} - -func (p *AuroraAdminSlaDrainHostsArgs) IsSetDefaultSlaPolicy() bool { - return p.DefaultSlaPolicy != nil -} - -func (p *AuroraAdminSlaDrainHostsArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminSlaDrainHostsArgs) readField1(iprot thrift.TProtocol) error { - p.Hosts = &Hosts{} - if err := p.Hosts.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Hosts), err) - } - return nil -} - -func (p *AuroraAdminSlaDrainHostsArgs) readField2(iprot thrift.TProtocol) error { - p.DefaultSlaPolicy = &SlaPolicy{} - if err := p.DefaultSlaPolicy.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.DefaultSlaPolicy), err) - } - return nil -} - -func (p *AuroraAdminSlaDrainHostsArgs) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI64(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.TimeoutSecs = v - } - return nil -} - -func (p *AuroraAdminSlaDrainHostsArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("slaDrainHosts_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminSlaDrainHostsArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("hosts", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:hosts: ", p), err) - } - if err := p.Hosts.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Hosts), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:hosts: ", p), err) - } - return err -} - -func (p *AuroraAdminSlaDrainHostsArgs) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("defaultSlaPolicy", thrift.STRUCT, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:defaultSlaPolicy: ", p), err) - } - if err := p.DefaultSlaPolicy.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.DefaultSlaPolicy), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:defaultSlaPolicy: ", p), err) - } - return err -} - -func (p *AuroraAdminSlaDrainHostsArgs) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("timeoutSecs", thrift.I64, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:timeoutSecs: ", p), err) - } - if err := oprot.WriteI64(int64(p.TimeoutSecs)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.timeoutSecs (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:timeoutSecs: ", p), err) - } - return err -} - -func (p *AuroraAdminSlaDrainHostsArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminSlaDrainHostsArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraAdminSlaDrainHostsResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraAdminSlaDrainHostsResult() *AuroraAdminSlaDrainHostsResult { - return &AuroraAdminSlaDrainHostsResult{} -} - -var AuroraAdminSlaDrainHostsResult_Success_DEFAULT *Response - -func (p *AuroraAdminSlaDrainHostsResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraAdminSlaDrainHostsResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraAdminSlaDrainHostsResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraAdminSlaDrainHostsResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminSlaDrainHostsResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraAdminSlaDrainHostsResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("slaDrainHosts_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminSlaDrainHostsResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraAdminSlaDrainHostsResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminSlaDrainHostsResult(%+v)", *p) -} - -type AuroraAdminSnapshotArgs struct { -} - -func NewAuroraAdminSnapshotArgs() *AuroraAdminSnapshotArgs { - return &AuroraAdminSnapshotArgs{} -} - -func (p *AuroraAdminSnapshotArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminSnapshotArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("snapshot_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminSnapshotArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminSnapshotArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraAdminSnapshotResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraAdminSnapshotResult() *AuroraAdminSnapshotResult { - return &AuroraAdminSnapshotResult{} -} - -var AuroraAdminSnapshotResult_Success_DEFAULT *Response - -func (p *AuroraAdminSnapshotResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraAdminSnapshotResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraAdminSnapshotResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraAdminSnapshotResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminSnapshotResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraAdminSnapshotResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("snapshot_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminSnapshotResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraAdminSnapshotResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminSnapshotResult(%+v)", *p) -} - -// Attributes: -// - Settings -type AuroraAdminTriggerExplicitTaskReconciliationArgs struct { - Settings *ExplicitReconciliationSettings `thrift:"settings,1" json:"settings"` -} - -func NewAuroraAdminTriggerExplicitTaskReconciliationArgs() *AuroraAdminTriggerExplicitTaskReconciliationArgs { - return &AuroraAdminTriggerExplicitTaskReconciliationArgs{} -} - -var AuroraAdminTriggerExplicitTaskReconciliationArgs_Settings_DEFAULT *ExplicitReconciliationSettings - -func (p *AuroraAdminTriggerExplicitTaskReconciliationArgs) GetSettings() *ExplicitReconciliationSettings { - if !p.IsSetSettings() { - return AuroraAdminTriggerExplicitTaskReconciliationArgs_Settings_DEFAULT - } - return p.Settings -} -func (p *AuroraAdminTriggerExplicitTaskReconciliationArgs) IsSetSettings() bool { - return p.Settings != nil -} - -func (p *AuroraAdminTriggerExplicitTaskReconciliationArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminTriggerExplicitTaskReconciliationArgs) readField1(iprot thrift.TProtocol) error { - p.Settings = &ExplicitReconciliationSettings{} - if err := p.Settings.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Settings), err) - } - return nil -} - -func (p *AuroraAdminTriggerExplicitTaskReconciliationArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("triggerExplicitTaskReconciliation_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminTriggerExplicitTaskReconciliationArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("settings", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:settings: ", p), err) - } - if err := p.Settings.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Settings), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:settings: ", p), err) - } - return err -} - -func (p *AuroraAdminTriggerExplicitTaskReconciliationArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminTriggerExplicitTaskReconciliationArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraAdminTriggerExplicitTaskReconciliationResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraAdminTriggerExplicitTaskReconciliationResult() *AuroraAdminTriggerExplicitTaskReconciliationResult { - return &AuroraAdminTriggerExplicitTaskReconciliationResult{} -} - -var AuroraAdminTriggerExplicitTaskReconciliationResult_Success_DEFAULT *Response - -func (p *AuroraAdminTriggerExplicitTaskReconciliationResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraAdminTriggerExplicitTaskReconciliationResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraAdminTriggerExplicitTaskReconciliationResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraAdminTriggerExplicitTaskReconciliationResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminTriggerExplicitTaskReconciliationResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraAdminTriggerExplicitTaskReconciliationResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("triggerExplicitTaskReconciliation_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminTriggerExplicitTaskReconciliationResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraAdminTriggerExplicitTaskReconciliationResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminTriggerExplicitTaskReconciliationResult(%+v)", *p) -} - -type AuroraAdminTriggerImplicitTaskReconciliationArgs struct { -} - -func NewAuroraAdminTriggerImplicitTaskReconciliationArgs() *AuroraAdminTriggerImplicitTaskReconciliationArgs { - return &AuroraAdminTriggerImplicitTaskReconciliationArgs{} -} - -func (p *AuroraAdminTriggerImplicitTaskReconciliationArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminTriggerImplicitTaskReconciliationArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("triggerImplicitTaskReconciliation_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminTriggerImplicitTaskReconciliationArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminTriggerImplicitTaskReconciliationArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraAdminTriggerImplicitTaskReconciliationResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraAdminTriggerImplicitTaskReconciliationResult() *AuroraAdminTriggerImplicitTaskReconciliationResult { - return &AuroraAdminTriggerImplicitTaskReconciliationResult{} -} - -var AuroraAdminTriggerImplicitTaskReconciliationResult_Success_DEFAULT *Response - -func (p *AuroraAdminTriggerImplicitTaskReconciliationResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraAdminTriggerImplicitTaskReconciliationResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraAdminTriggerImplicitTaskReconciliationResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraAdminTriggerImplicitTaskReconciliationResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminTriggerImplicitTaskReconciliationResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraAdminTriggerImplicitTaskReconciliationResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("triggerImplicitTaskReconciliation_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminTriggerImplicitTaskReconciliationResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraAdminTriggerImplicitTaskReconciliationResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminTriggerImplicitTaskReconciliationResult(%+v)", *p) -} - -// Attributes: -// - Query -type AuroraAdminPruneTasksArgs struct { - Query *TaskQuery `thrift:"query,1" json:"query"` -} - -func NewAuroraAdminPruneTasksArgs() *AuroraAdminPruneTasksArgs { - return &AuroraAdminPruneTasksArgs{} -} - -var AuroraAdminPruneTasksArgs_Query_DEFAULT *TaskQuery - -func (p *AuroraAdminPruneTasksArgs) GetQuery() *TaskQuery { - if !p.IsSetQuery() { - return AuroraAdminPruneTasksArgs_Query_DEFAULT - } - return p.Query -} -func (p *AuroraAdminPruneTasksArgs) IsSetQuery() bool { - return p.Query != nil -} - -func (p *AuroraAdminPruneTasksArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminPruneTasksArgs) readField1(iprot thrift.TProtocol) error { - p.Query = &TaskQuery{} - if err := p.Query.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Query), err) - } - return nil -} - -func (p *AuroraAdminPruneTasksArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("pruneTasks_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminPruneTasksArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("query", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:query: ", p), err) - } - if err := p.Query.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Query), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:query: ", p), err) - } - return err -} - -func (p *AuroraAdminPruneTasksArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminPruneTasksArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraAdminPruneTasksResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraAdminPruneTasksResult() *AuroraAdminPruneTasksResult { - return &AuroraAdminPruneTasksResult{} -} - -var AuroraAdminPruneTasksResult_Success_DEFAULT *Response - -func (p *AuroraAdminPruneTasksResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraAdminPruneTasksResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraAdminPruneTasksResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraAdminPruneTasksResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraAdminPruneTasksResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraAdminPruneTasksResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("pruneTasks_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraAdminPruneTasksResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraAdminPruneTasksResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraAdminPruneTasksResult(%+v)", *p) -} diff --git a/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/auroraschedulermanager.go b/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/auroraschedulermanager.go deleted file mode 100644 index a448b72..0000000 --- a/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/auroraschedulermanager.go +++ /dev/null @@ -1,5115 +0,0 @@ -// Autogenerated by Thrift Compiler (0.9.3) -// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - -package aurora - -import ( - "bytes" - "fmt" - "git.apache.org/thrift.git/lib/go/thrift" -) - -// (needed to ensure safety because of naive import list construction.) -var _ = thrift.ZERO -var _ = fmt.Printf -var _ = bytes.Equal - -type AuroraSchedulerManager interface { - ReadOnlyScheduler - - // Creates a new job. The request will be denied if a job with the provided name already exists - // in the cluster. - // - // Parameters: - // - Description - CreateJob(description *JobConfiguration) (r *Response, err error) - // Enters a job into the cron schedule, without actually starting the job. - // If the job is already present in the schedule, this will update the schedule entry with the new - // configuration. - // - // Parameters: - // - Description - ScheduleCronJob(description *JobConfiguration) (r *Response, err error) - // Removes a job from the cron schedule. The request will be denied if the job was not previously - // scheduled with scheduleCronJob. - // - // Parameters: - // - Job - DescheduleCronJob(job *JobKey) (r *Response, err error) - // Starts a cron job immediately. The request will be denied if the specified job does not - // exist for the role account, or the job is not a cron job. - // - // Parameters: - // - Job - StartCronJob(job *JobKey) (r *Response, err error) - // Restarts a batch of shards. - // - // Parameters: - // - Job - // - ShardIds - RestartShards(job *JobKey, shardIds map[int32]bool) (r *Response, err error) - // Initiates a kill on tasks. - // - // Parameters: - // - Job - // - Instances - // - Message - KillTasks(job *JobKey, instances map[int32]bool, message string) (r *Response, err error) - // Adds new instances with the TaskConfig of the existing instance pointed by the key. - // - // Parameters: - // - Key - // - Count - AddInstances(key *InstanceKey, count int32) (r *Response, err error) - // Replaces the template (configuration) for the existing cron job. - // The cron job template (configuration) must exist for the call to succeed. - // - // Parameters: - // - Config - ReplaceCronTemplate(config *JobConfiguration) (r *Response, err error) - // Starts update of the existing service job. - // - // Parameters: - // - Request: A description of how to change the job. - // - Message: A user-specified message to include with the induced job update state change. - StartJobUpdate(request *JobUpdateRequest, message string) (r *Response, err error) - // Pauses the specified job update. Can be resumed by resumeUpdate call. - // - // Parameters: - // - Key: The update to pause. - // - Message: A user-specified message to include with the induced job update state change. - PauseJobUpdate(key *JobUpdateKey, message string) (r *Response, err error) - // Resumes progress of a previously paused job update. - // - // Parameters: - // - Key: The update to resume. - // - Message: A user-specified message to include with the induced job update state change. - ResumeJobUpdate(key *JobUpdateKey, message string) (r *Response, err error) - // Permanently aborts the job update. Does not remove the update history. - // - // Parameters: - // - Key: The update to abort. - // - Message: A user-specified message to include with the induced job update state change. - AbortJobUpdate(key *JobUpdateKey, message string) (r *Response, err error) - // Rollbacks the specified active job update to the initial state. - // - // Parameters: - // - Key: The update to rollback. - // - Message: A user-specified message to include with the induced job update state change. - RollbackJobUpdate(key *JobUpdateKey, message string) (r *Response, err error) - // Allows progress of the job update in case blockIfNoPulsesAfterMs is specified in - // JobUpdateSettings. Unblocks progress if the update was previously blocked. - // Responds with ResponseCode.INVALID_REQUEST in case an unknown update key is specified. - // - // Parameters: - // - Key - PulseJobUpdate(key *JobUpdateKey) (r *Response, err error) -} - -type AuroraSchedulerManagerClient struct { - *ReadOnlySchedulerClient -} - -func NewAuroraSchedulerManagerClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *AuroraSchedulerManagerClient { - return &AuroraSchedulerManagerClient{ReadOnlySchedulerClient: NewReadOnlySchedulerClientFactory(t, f)} -} - -func NewAuroraSchedulerManagerClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *AuroraSchedulerManagerClient { - return &AuroraSchedulerManagerClient{ReadOnlySchedulerClient: NewReadOnlySchedulerClientProtocol(t, iprot, oprot)} -} - -// Creates a new job. The request will be denied if a job with the provided name already exists -// in the cluster. -// -// Parameters: -// - Description -func (p *AuroraSchedulerManagerClient) CreateJob(description *JobConfiguration) (r *Response, err error) { - if err = p.sendCreateJob(description); err != nil { - return - } - return p.recvCreateJob() -} - -func (p *AuroraSchedulerManagerClient) sendCreateJob(description *JobConfiguration) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("createJob", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraSchedulerManagerCreateJobArgs{ - Description: description, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraSchedulerManagerClient) recvCreateJob() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "createJob" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "createJob failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "createJob failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error131 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error132 error - error132, err = error131.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error132 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "createJob failed: invalid message type") - return - } - result := AuroraSchedulerManagerCreateJobResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Enters a job into the cron schedule, without actually starting the job. -// If the job is already present in the schedule, this will update the schedule entry with the new -// configuration. -// -// Parameters: -// - Description -func (p *AuroraSchedulerManagerClient) ScheduleCronJob(description *JobConfiguration) (r *Response, err error) { - if err = p.sendScheduleCronJob(description); err != nil { - return - } - return p.recvScheduleCronJob() -} - -func (p *AuroraSchedulerManagerClient) sendScheduleCronJob(description *JobConfiguration) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("scheduleCronJob", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraSchedulerManagerScheduleCronJobArgs{ - Description: description, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraSchedulerManagerClient) recvScheduleCronJob() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "scheduleCronJob" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "scheduleCronJob failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "scheduleCronJob failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error133 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error134 error - error134, err = error133.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error134 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "scheduleCronJob failed: invalid message type") - return - } - result := AuroraSchedulerManagerScheduleCronJobResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Removes a job from the cron schedule. The request will be denied if the job was not previously -// scheduled with scheduleCronJob. -// -// Parameters: -// - Job -func (p *AuroraSchedulerManagerClient) DescheduleCronJob(job *JobKey) (r *Response, err error) { - if err = p.sendDescheduleCronJob(job); err != nil { - return - } - return p.recvDescheduleCronJob() -} - -func (p *AuroraSchedulerManagerClient) sendDescheduleCronJob(job *JobKey) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("descheduleCronJob", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraSchedulerManagerDescheduleCronJobArgs{ - Job: job, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraSchedulerManagerClient) recvDescheduleCronJob() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "descheduleCronJob" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "descheduleCronJob failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "descheduleCronJob failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error135 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error136 error - error136, err = error135.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error136 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "descheduleCronJob failed: invalid message type") - return - } - result := AuroraSchedulerManagerDescheduleCronJobResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Starts a cron job immediately. The request will be denied if the specified job does not -// exist for the role account, or the job is not a cron job. -// -// Parameters: -// - Job -func (p *AuroraSchedulerManagerClient) StartCronJob(job *JobKey) (r *Response, err error) { - if err = p.sendStartCronJob(job); err != nil { - return - } - return p.recvStartCronJob() -} - -func (p *AuroraSchedulerManagerClient) sendStartCronJob(job *JobKey) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("startCronJob", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraSchedulerManagerStartCronJobArgs{ - Job: job, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraSchedulerManagerClient) recvStartCronJob() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "startCronJob" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "startCronJob failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "startCronJob failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error137 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error138 error - error138, err = error137.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error138 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "startCronJob failed: invalid message type") - return - } - result := AuroraSchedulerManagerStartCronJobResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Restarts a batch of shards. -// -// Parameters: -// - Job -// - ShardIds -func (p *AuroraSchedulerManagerClient) RestartShards(job *JobKey, shardIds map[int32]bool) (r *Response, err error) { - if err = p.sendRestartShards(job, shardIds); err != nil { - return - } - return p.recvRestartShards() -} - -func (p *AuroraSchedulerManagerClient) sendRestartShards(job *JobKey, shardIds map[int32]bool) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("restartShards", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraSchedulerManagerRestartShardsArgs{ - Job: job, - ShardIds: shardIds, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraSchedulerManagerClient) recvRestartShards() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "restartShards" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "restartShards failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "restartShards failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error139 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error140 error - error140, err = error139.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error140 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "restartShards failed: invalid message type") - return - } - result := AuroraSchedulerManagerRestartShardsResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Initiates a kill on tasks. -// -// Parameters: -// - Job -// - Instances -// - Message -func (p *AuroraSchedulerManagerClient) KillTasks(job *JobKey, instances map[int32]bool, message string) (r *Response, err error) { - if err = p.sendKillTasks(job, instances, message); err != nil { - return - } - return p.recvKillTasks() -} - -func (p *AuroraSchedulerManagerClient) sendKillTasks(job *JobKey, instances map[int32]bool, message string) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("killTasks", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraSchedulerManagerKillTasksArgs{ - Job: job, - Instances: instances, - Message: message, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraSchedulerManagerClient) recvKillTasks() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "killTasks" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "killTasks failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "killTasks failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error141 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error142 error - error142, err = error141.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error142 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "killTasks failed: invalid message type") - return - } - result := AuroraSchedulerManagerKillTasksResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Adds new instances with the TaskConfig of the existing instance pointed by the key. -// -// Parameters: -// - Key -// - Count -func (p *AuroraSchedulerManagerClient) AddInstances(key *InstanceKey, count int32) (r *Response, err error) { - if err = p.sendAddInstances(key, count); err != nil { - return - } - return p.recvAddInstances() -} - -func (p *AuroraSchedulerManagerClient) sendAddInstances(key *InstanceKey, count int32) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("addInstances", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraSchedulerManagerAddInstancesArgs{ - Key: key, - Count: count, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraSchedulerManagerClient) recvAddInstances() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "addInstances" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "addInstances failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "addInstances failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error143 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error144 error - error144, err = error143.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error144 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "addInstances failed: invalid message type") - return - } - result := AuroraSchedulerManagerAddInstancesResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Replaces the template (configuration) for the existing cron job. -// The cron job template (configuration) must exist for the call to succeed. -// -// Parameters: -// - Config -func (p *AuroraSchedulerManagerClient) ReplaceCronTemplate(config *JobConfiguration) (r *Response, err error) { - if err = p.sendReplaceCronTemplate(config); err != nil { - return - } - return p.recvReplaceCronTemplate() -} - -func (p *AuroraSchedulerManagerClient) sendReplaceCronTemplate(config *JobConfiguration) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("replaceCronTemplate", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraSchedulerManagerReplaceCronTemplateArgs{ - Config: config, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraSchedulerManagerClient) recvReplaceCronTemplate() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "replaceCronTemplate" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "replaceCronTemplate failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "replaceCronTemplate failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error145 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error146 error - error146, err = error145.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error146 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "replaceCronTemplate failed: invalid message type") - return - } - result := AuroraSchedulerManagerReplaceCronTemplateResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Starts update of the existing service job. -// -// Parameters: -// - Request: A description of how to change the job. -// - Message: A user-specified message to include with the induced job update state change. -func (p *AuroraSchedulerManagerClient) StartJobUpdate(request *JobUpdateRequest, message string) (r *Response, err error) { - if err = p.sendStartJobUpdate(request, message); err != nil { - return - } - return p.recvStartJobUpdate() -} - -func (p *AuroraSchedulerManagerClient) sendStartJobUpdate(request *JobUpdateRequest, message string) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("startJobUpdate", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraSchedulerManagerStartJobUpdateArgs{ - Request: request, - Message: message, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraSchedulerManagerClient) recvStartJobUpdate() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "startJobUpdate" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "startJobUpdate failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "startJobUpdate failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error147 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error148 error - error148, err = error147.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error148 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "startJobUpdate failed: invalid message type") - return - } - result := AuroraSchedulerManagerStartJobUpdateResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Pauses the specified job update. Can be resumed by resumeUpdate call. -// -// Parameters: -// - Key: The update to pause. -// - Message: A user-specified message to include with the induced job update state change. -func (p *AuroraSchedulerManagerClient) PauseJobUpdate(key *JobUpdateKey, message string) (r *Response, err error) { - if err = p.sendPauseJobUpdate(key, message); err != nil { - return - } - return p.recvPauseJobUpdate() -} - -func (p *AuroraSchedulerManagerClient) sendPauseJobUpdate(key *JobUpdateKey, message string) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("pauseJobUpdate", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraSchedulerManagerPauseJobUpdateArgs{ - Key: key, - Message: message, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraSchedulerManagerClient) recvPauseJobUpdate() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "pauseJobUpdate" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "pauseJobUpdate failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "pauseJobUpdate failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error149 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error150 error - error150, err = error149.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error150 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "pauseJobUpdate failed: invalid message type") - return - } - result := AuroraSchedulerManagerPauseJobUpdateResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Resumes progress of a previously paused job update. -// -// Parameters: -// - Key: The update to resume. -// - Message: A user-specified message to include with the induced job update state change. -func (p *AuroraSchedulerManagerClient) ResumeJobUpdate(key *JobUpdateKey, message string) (r *Response, err error) { - if err = p.sendResumeJobUpdate(key, message); err != nil { - return - } - return p.recvResumeJobUpdate() -} - -func (p *AuroraSchedulerManagerClient) sendResumeJobUpdate(key *JobUpdateKey, message string) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("resumeJobUpdate", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraSchedulerManagerResumeJobUpdateArgs{ - Key: key, - Message: message, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraSchedulerManagerClient) recvResumeJobUpdate() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "resumeJobUpdate" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "resumeJobUpdate failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "resumeJobUpdate failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error151 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error152 error - error152, err = error151.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error152 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "resumeJobUpdate failed: invalid message type") - return - } - result := AuroraSchedulerManagerResumeJobUpdateResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Permanently aborts the job update. Does not remove the update history. -// -// Parameters: -// - Key: The update to abort. -// - Message: A user-specified message to include with the induced job update state change. -func (p *AuroraSchedulerManagerClient) AbortJobUpdate(key *JobUpdateKey, message string) (r *Response, err error) { - if err = p.sendAbortJobUpdate(key, message); err != nil { - return - } - return p.recvAbortJobUpdate() -} - -func (p *AuroraSchedulerManagerClient) sendAbortJobUpdate(key *JobUpdateKey, message string) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("abortJobUpdate", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraSchedulerManagerAbortJobUpdateArgs{ - Key: key, - Message: message, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraSchedulerManagerClient) recvAbortJobUpdate() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "abortJobUpdate" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "abortJobUpdate failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "abortJobUpdate failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error153 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error154 error - error154, err = error153.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error154 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "abortJobUpdate failed: invalid message type") - return - } - result := AuroraSchedulerManagerAbortJobUpdateResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Rollbacks the specified active job update to the initial state. -// -// Parameters: -// - Key: The update to rollback. -// - Message: A user-specified message to include with the induced job update state change. -func (p *AuroraSchedulerManagerClient) RollbackJobUpdate(key *JobUpdateKey, message string) (r *Response, err error) { - if err = p.sendRollbackJobUpdate(key, message); err != nil { - return - } - return p.recvRollbackJobUpdate() -} - -func (p *AuroraSchedulerManagerClient) sendRollbackJobUpdate(key *JobUpdateKey, message string) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("rollbackJobUpdate", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraSchedulerManagerRollbackJobUpdateArgs{ - Key: key, - Message: message, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraSchedulerManagerClient) recvRollbackJobUpdate() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "rollbackJobUpdate" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "rollbackJobUpdate failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "rollbackJobUpdate failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error155 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error156 error - error156, err = error155.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error156 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "rollbackJobUpdate failed: invalid message type") - return - } - result := AuroraSchedulerManagerRollbackJobUpdateResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Allows progress of the job update in case blockIfNoPulsesAfterMs is specified in -// JobUpdateSettings. Unblocks progress if the update was previously blocked. -// Responds with ResponseCode.INVALID_REQUEST in case an unknown update key is specified. -// -// Parameters: -// - Key -func (p *AuroraSchedulerManagerClient) PulseJobUpdate(key *JobUpdateKey) (r *Response, err error) { - if err = p.sendPulseJobUpdate(key); err != nil { - return - } - return p.recvPulseJobUpdate() -} - -func (p *AuroraSchedulerManagerClient) sendPulseJobUpdate(key *JobUpdateKey) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("pulseJobUpdate", thrift.CALL, p.SeqId); err != nil { - return - } - args := AuroraSchedulerManagerPulseJobUpdateArgs{ - Key: key, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *AuroraSchedulerManagerClient) recvPulseJobUpdate() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "pulseJobUpdate" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "pulseJobUpdate failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "pulseJobUpdate failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error157 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error158 error - error158, err = error157.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error158 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "pulseJobUpdate failed: invalid message type") - return - } - result := AuroraSchedulerManagerPulseJobUpdateResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -type AuroraSchedulerManagerProcessor struct { - *ReadOnlySchedulerProcessor -} - -func NewAuroraSchedulerManagerProcessor(handler AuroraSchedulerManager) *AuroraSchedulerManagerProcessor { - self159 := &AuroraSchedulerManagerProcessor{NewReadOnlySchedulerProcessor(handler)} - self159.AddToProcessorMap("createJob", &auroraSchedulerManagerProcessorCreateJob{handler: handler}) - self159.AddToProcessorMap("scheduleCronJob", &auroraSchedulerManagerProcessorScheduleCronJob{handler: handler}) - self159.AddToProcessorMap("descheduleCronJob", &auroraSchedulerManagerProcessorDescheduleCronJob{handler: handler}) - self159.AddToProcessorMap("startCronJob", &auroraSchedulerManagerProcessorStartCronJob{handler: handler}) - self159.AddToProcessorMap("restartShards", &auroraSchedulerManagerProcessorRestartShards{handler: handler}) - self159.AddToProcessorMap("killTasks", &auroraSchedulerManagerProcessorKillTasks{handler: handler}) - self159.AddToProcessorMap("addInstances", &auroraSchedulerManagerProcessorAddInstances{handler: handler}) - self159.AddToProcessorMap("replaceCronTemplate", &auroraSchedulerManagerProcessorReplaceCronTemplate{handler: handler}) - self159.AddToProcessorMap("startJobUpdate", &auroraSchedulerManagerProcessorStartJobUpdate{handler: handler}) - self159.AddToProcessorMap("pauseJobUpdate", &auroraSchedulerManagerProcessorPauseJobUpdate{handler: handler}) - self159.AddToProcessorMap("resumeJobUpdate", &auroraSchedulerManagerProcessorResumeJobUpdate{handler: handler}) - self159.AddToProcessorMap("abortJobUpdate", &auroraSchedulerManagerProcessorAbortJobUpdate{handler: handler}) - self159.AddToProcessorMap("rollbackJobUpdate", &auroraSchedulerManagerProcessorRollbackJobUpdate{handler: handler}) - self159.AddToProcessorMap("pulseJobUpdate", &auroraSchedulerManagerProcessorPulseJobUpdate{handler: handler}) - return self159 -} - -type auroraSchedulerManagerProcessorCreateJob struct { - handler AuroraSchedulerManager -} - -func (p *auroraSchedulerManagerProcessorCreateJob) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraSchedulerManagerCreateJobArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("createJob", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraSchedulerManagerCreateJobResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.CreateJob(args.Description); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing createJob: "+err2.Error()) - oprot.WriteMessageBegin("createJob", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("createJob", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraSchedulerManagerProcessorScheduleCronJob struct { - handler AuroraSchedulerManager -} - -func (p *auroraSchedulerManagerProcessorScheduleCronJob) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraSchedulerManagerScheduleCronJobArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("scheduleCronJob", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraSchedulerManagerScheduleCronJobResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.ScheduleCronJob(args.Description); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing scheduleCronJob: "+err2.Error()) - oprot.WriteMessageBegin("scheduleCronJob", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("scheduleCronJob", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraSchedulerManagerProcessorDescheduleCronJob struct { - handler AuroraSchedulerManager -} - -func (p *auroraSchedulerManagerProcessorDescheduleCronJob) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraSchedulerManagerDescheduleCronJobArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("descheduleCronJob", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraSchedulerManagerDescheduleCronJobResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.DescheduleCronJob(args.Job); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing descheduleCronJob: "+err2.Error()) - oprot.WriteMessageBegin("descheduleCronJob", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("descheduleCronJob", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraSchedulerManagerProcessorStartCronJob struct { - handler AuroraSchedulerManager -} - -func (p *auroraSchedulerManagerProcessorStartCronJob) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraSchedulerManagerStartCronJobArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("startCronJob", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraSchedulerManagerStartCronJobResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.StartCronJob(args.Job); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing startCronJob: "+err2.Error()) - oprot.WriteMessageBegin("startCronJob", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("startCronJob", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraSchedulerManagerProcessorRestartShards struct { - handler AuroraSchedulerManager -} - -func (p *auroraSchedulerManagerProcessorRestartShards) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraSchedulerManagerRestartShardsArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("restartShards", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraSchedulerManagerRestartShardsResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.RestartShards(args.Job, args.ShardIds); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing restartShards: "+err2.Error()) - oprot.WriteMessageBegin("restartShards", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("restartShards", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraSchedulerManagerProcessorKillTasks struct { - handler AuroraSchedulerManager -} - -func (p *auroraSchedulerManagerProcessorKillTasks) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraSchedulerManagerKillTasksArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("killTasks", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraSchedulerManagerKillTasksResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.KillTasks(args.Job, args.Instances, args.Message); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing killTasks: "+err2.Error()) - oprot.WriteMessageBegin("killTasks", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("killTasks", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraSchedulerManagerProcessorAddInstances struct { - handler AuroraSchedulerManager -} - -func (p *auroraSchedulerManagerProcessorAddInstances) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraSchedulerManagerAddInstancesArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("addInstances", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraSchedulerManagerAddInstancesResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.AddInstances(args.Key, args.Count); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing addInstances: "+err2.Error()) - oprot.WriteMessageBegin("addInstances", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("addInstances", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraSchedulerManagerProcessorReplaceCronTemplate struct { - handler AuroraSchedulerManager -} - -func (p *auroraSchedulerManagerProcessorReplaceCronTemplate) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraSchedulerManagerReplaceCronTemplateArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("replaceCronTemplate", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraSchedulerManagerReplaceCronTemplateResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.ReplaceCronTemplate(args.Config); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing replaceCronTemplate: "+err2.Error()) - oprot.WriteMessageBegin("replaceCronTemplate", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("replaceCronTemplate", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraSchedulerManagerProcessorStartJobUpdate struct { - handler AuroraSchedulerManager -} - -func (p *auroraSchedulerManagerProcessorStartJobUpdate) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraSchedulerManagerStartJobUpdateArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("startJobUpdate", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraSchedulerManagerStartJobUpdateResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.StartJobUpdate(args.Request, args.Message); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing startJobUpdate: "+err2.Error()) - oprot.WriteMessageBegin("startJobUpdate", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("startJobUpdate", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraSchedulerManagerProcessorPauseJobUpdate struct { - handler AuroraSchedulerManager -} - -func (p *auroraSchedulerManagerProcessorPauseJobUpdate) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraSchedulerManagerPauseJobUpdateArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("pauseJobUpdate", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraSchedulerManagerPauseJobUpdateResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.PauseJobUpdate(args.Key, args.Message); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing pauseJobUpdate: "+err2.Error()) - oprot.WriteMessageBegin("pauseJobUpdate", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("pauseJobUpdate", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraSchedulerManagerProcessorResumeJobUpdate struct { - handler AuroraSchedulerManager -} - -func (p *auroraSchedulerManagerProcessorResumeJobUpdate) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraSchedulerManagerResumeJobUpdateArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("resumeJobUpdate", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraSchedulerManagerResumeJobUpdateResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.ResumeJobUpdate(args.Key, args.Message); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing resumeJobUpdate: "+err2.Error()) - oprot.WriteMessageBegin("resumeJobUpdate", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("resumeJobUpdate", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraSchedulerManagerProcessorAbortJobUpdate struct { - handler AuroraSchedulerManager -} - -func (p *auroraSchedulerManagerProcessorAbortJobUpdate) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraSchedulerManagerAbortJobUpdateArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("abortJobUpdate", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraSchedulerManagerAbortJobUpdateResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.AbortJobUpdate(args.Key, args.Message); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing abortJobUpdate: "+err2.Error()) - oprot.WriteMessageBegin("abortJobUpdate", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("abortJobUpdate", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraSchedulerManagerProcessorRollbackJobUpdate struct { - handler AuroraSchedulerManager -} - -func (p *auroraSchedulerManagerProcessorRollbackJobUpdate) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraSchedulerManagerRollbackJobUpdateArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("rollbackJobUpdate", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraSchedulerManagerRollbackJobUpdateResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.RollbackJobUpdate(args.Key, args.Message); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing rollbackJobUpdate: "+err2.Error()) - oprot.WriteMessageBegin("rollbackJobUpdate", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("rollbackJobUpdate", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type auroraSchedulerManagerProcessorPulseJobUpdate struct { - handler AuroraSchedulerManager -} - -func (p *auroraSchedulerManagerProcessorPulseJobUpdate) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AuroraSchedulerManagerPulseJobUpdateArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("pulseJobUpdate", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AuroraSchedulerManagerPulseJobUpdateResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.PulseJobUpdate(args.Key); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing pulseJobUpdate: "+err2.Error()) - oprot.WriteMessageBegin("pulseJobUpdate", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("pulseJobUpdate", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -// HELPER FUNCTIONS AND STRUCTURES - -// Attributes: -// - Description -type AuroraSchedulerManagerCreateJobArgs struct { - Description *JobConfiguration `thrift:"description,1" json:"description"` -} - -func NewAuroraSchedulerManagerCreateJobArgs() *AuroraSchedulerManagerCreateJobArgs { - return &AuroraSchedulerManagerCreateJobArgs{} -} - -var AuroraSchedulerManagerCreateJobArgs_Description_DEFAULT *JobConfiguration - -func (p *AuroraSchedulerManagerCreateJobArgs) GetDescription() *JobConfiguration { - if !p.IsSetDescription() { - return AuroraSchedulerManagerCreateJobArgs_Description_DEFAULT - } - return p.Description -} -func (p *AuroraSchedulerManagerCreateJobArgs) IsSetDescription() bool { - return p.Description != nil -} - -func (p *AuroraSchedulerManagerCreateJobArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerCreateJobArgs) readField1(iprot thrift.TProtocol) error { - p.Description = &JobConfiguration{} - if err := p.Description.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Description), err) - } - return nil -} - -func (p *AuroraSchedulerManagerCreateJobArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("createJob_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerCreateJobArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("description", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:description: ", p), err) - } - if err := p.Description.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Description), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:description: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerCreateJobArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerCreateJobArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraSchedulerManagerCreateJobResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraSchedulerManagerCreateJobResult() *AuroraSchedulerManagerCreateJobResult { - return &AuroraSchedulerManagerCreateJobResult{} -} - -var AuroraSchedulerManagerCreateJobResult_Success_DEFAULT *Response - -func (p *AuroraSchedulerManagerCreateJobResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraSchedulerManagerCreateJobResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraSchedulerManagerCreateJobResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraSchedulerManagerCreateJobResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerCreateJobResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraSchedulerManagerCreateJobResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("createJob_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerCreateJobResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraSchedulerManagerCreateJobResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerCreateJobResult(%+v)", *p) -} - -// Attributes: -// - Description -type AuroraSchedulerManagerScheduleCronJobArgs struct { - Description *JobConfiguration `thrift:"description,1" json:"description"` -} - -func NewAuroraSchedulerManagerScheduleCronJobArgs() *AuroraSchedulerManagerScheduleCronJobArgs { - return &AuroraSchedulerManagerScheduleCronJobArgs{} -} - -var AuroraSchedulerManagerScheduleCronJobArgs_Description_DEFAULT *JobConfiguration - -func (p *AuroraSchedulerManagerScheduleCronJobArgs) GetDescription() *JobConfiguration { - if !p.IsSetDescription() { - return AuroraSchedulerManagerScheduleCronJobArgs_Description_DEFAULT - } - return p.Description -} -func (p *AuroraSchedulerManagerScheduleCronJobArgs) IsSetDescription() bool { - return p.Description != nil -} - -func (p *AuroraSchedulerManagerScheduleCronJobArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerScheduleCronJobArgs) readField1(iprot thrift.TProtocol) error { - p.Description = &JobConfiguration{} - if err := p.Description.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Description), err) - } - return nil -} - -func (p *AuroraSchedulerManagerScheduleCronJobArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("scheduleCronJob_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerScheduleCronJobArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("description", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:description: ", p), err) - } - if err := p.Description.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Description), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:description: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerScheduleCronJobArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerScheduleCronJobArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraSchedulerManagerScheduleCronJobResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraSchedulerManagerScheduleCronJobResult() *AuroraSchedulerManagerScheduleCronJobResult { - return &AuroraSchedulerManagerScheduleCronJobResult{} -} - -var AuroraSchedulerManagerScheduleCronJobResult_Success_DEFAULT *Response - -func (p *AuroraSchedulerManagerScheduleCronJobResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraSchedulerManagerScheduleCronJobResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraSchedulerManagerScheduleCronJobResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraSchedulerManagerScheduleCronJobResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerScheduleCronJobResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraSchedulerManagerScheduleCronJobResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("scheduleCronJob_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerScheduleCronJobResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraSchedulerManagerScheduleCronJobResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerScheduleCronJobResult(%+v)", *p) -} - -// Attributes: -// - Job -type AuroraSchedulerManagerDescheduleCronJobArgs struct { - // unused fields # 1 to 3 - Job *JobKey `thrift:"job,4" json:"job"` -} - -func NewAuroraSchedulerManagerDescheduleCronJobArgs() *AuroraSchedulerManagerDescheduleCronJobArgs { - return &AuroraSchedulerManagerDescheduleCronJobArgs{} -} - -var AuroraSchedulerManagerDescheduleCronJobArgs_Job_DEFAULT *JobKey - -func (p *AuroraSchedulerManagerDescheduleCronJobArgs) GetJob() *JobKey { - if !p.IsSetJob() { - return AuroraSchedulerManagerDescheduleCronJobArgs_Job_DEFAULT - } - return p.Job -} -func (p *AuroraSchedulerManagerDescheduleCronJobArgs) IsSetJob() bool { - return p.Job != nil -} - -func (p *AuroraSchedulerManagerDescheduleCronJobArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerDescheduleCronJobArgs) readField4(iprot thrift.TProtocol) error { - p.Job = &JobKey{} - if err := p.Job.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Job), err) - } - return nil -} - -func (p *AuroraSchedulerManagerDescheduleCronJobArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("descheduleCronJob_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerDescheduleCronJobArgs) writeField4(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("job", thrift.STRUCT, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:job: ", p), err) - } - if err := p.Job.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Job), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:job: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerDescheduleCronJobArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerDescheduleCronJobArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraSchedulerManagerDescheduleCronJobResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraSchedulerManagerDescheduleCronJobResult() *AuroraSchedulerManagerDescheduleCronJobResult { - return &AuroraSchedulerManagerDescheduleCronJobResult{} -} - -var AuroraSchedulerManagerDescheduleCronJobResult_Success_DEFAULT *Response - -func (p *AuroraSchedulerManagerDescheduleCronJobResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraSchedulerManagerDescheduleCronJobResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraSchedulerManagerDescheduleCronJobResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraSchedulerManagerDescheduleCronJobResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerDescheduleCronJobResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraSchedulerManagerDescheduleCronJobResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("descheduleCronJob_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerDescheduleCronJobResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraSchedulerManagerDescheduleCronJobResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerDescheduleCronJobResult(%+v)", *p) -} - -// Attributes: -// - Job -type AuroraSchedulerManagerStartCronJobArgs struct { - // unused fields # 1 to 3 - Job *JobKey `thrift:"job,4" json:"job"` -} - -func NewAuroraSchedulerManagerStartCronJobArgs() *AuroraSchedulerManagerStartCronJobArgs { - return &AuroraSchedulerManagerStartCronJobArgs{} -} - -var AuroraSchedulerManagerStartCronJobArgs_Job_DEFAULT *JobKey - -func (p *AuroraSchedulerManagerStartCronJobArgs) GetJob() *JobKey { - if !p.IsSetJob() { - return AuroraSchedulerManagerStartCronJobArgs_Job_DEFAULT - } - return p.Job -} -func (p *AuroraSchedulerManagerStartCronJobArgs) IsSetJob() bool { - return p.Job != nil -} - -func (p *AuroraSchedulerManagerStartCronJobArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerStartCronJobArgs) readField4(iprot thrift.TProtocol) error { - p.Job = &JobKey{} - if err := p.Job.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Job), err) - } - return nil -} - -func (p *AuroraSchedulerManagerStartCronJobArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("startCronJob_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerStartCronJobArgs) writeField4(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("job", thrift.STRUCT, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:job: ", p), err) - } - if err := p.Job.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Job), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:job: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerStartCronJobArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerStartCronJobArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraSchedulerManagerStartCronJobResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraSchedulerManagerStartCronJobResult() *AuroraSchedulerManagerStartCronJobResult { - return &AuroraSchedulerManagerStartCronJobResult{} -} - -var AuroraSchedulerManagerStartCronJobResult_Success_DEFAULT *Response - -func (p *AuroraSchedulerManagerStartCronJobResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraSchedulerManagerStartCronJobResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraSchedulerManagerStartCronJobResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraSchedulerManagerStartCronJobResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerStartCronJobResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraSchedulerManagerStartCronJobResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("startCronJob_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerStartCronJobResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraSchedulerManagerStartCronJobResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerStartCronJobResult(%+v)", *p) -} - -// Attributes: -// - Job -// - ShardIds -type AuroraSchedulerManagerRestartShardsArgs struct { - // unused fields # 1 to 2 - ShardIds map[int32]bool `thrift:"shardIds,3" json:"shardIds"` - // unused field # 4 - Job *JobKey `thrift:"job,5" json:"job"` -} - -func NewAuroraSchedulerManagerRestartShardsArgs() *AuroraSchedulerManagerRestartShardsArgs { - return &AuroraSchedulerManagerRestartShardsArgs{} -} - -var AuroraSchedulerManagerRestartShardsArgs_Job_DEFAULT *JobKey - -func (p *AuroraSchedulerManagerRestartShardsArgs) GetJob() *JobKey { - if !p.IsSetJob() { - return AuroraSchedulerManagerRestartShardsArgs_Job_DEFAULT - } - return p.Job -} - -func (p *AuroraSchedulerManagerRestartShardsArgs) GetShardIds() map[int32]bool { - return p.ShardIds -} -func (p *AuroraSchedulerManagerRestartShardsArgs) IsSetJob() bool { - return p.Job != nil -} - -func (p *AuroraSchedulerManagerRestartShardsArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 5: - if err := p.readField5(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerRestartShardsArgs) readField5(iprot thrift.TProtocol) error { - p.Job = &JobKey{} - if err := p.Job.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Job), err) - } - return nil -} - -func (p *AuroraSchedulerManagerRestartShardsArgs) readField3(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[int32]bool, size) - p.ShardIds = tSet - for i := 0; i < size; i++ { - var _elem160 int32 - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 0: ", err) - } else { - _elem160 = v - } - p.ShardIds[_elem160] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerRestartShardsArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("restartShards_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := p.writeField5(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerRestartShardsArgs) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("shardIds", thrift.SET, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:shardIds: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.I32, len(p.ShardIds)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.ShardIds { - if err := oprot.WriteI32(int32(v)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:shardIds: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerRestartShardsArgs) writeField5(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("job", thrift.STRUCT, 5); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:job: ", p), err) - } - if err := p.Job.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Job), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 5:job: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerRestartShardsArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerRestartShardsArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraSchedulerManagerRestartShardsResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraSchedulerManagerRestartShardsResult() *AuroraSchedulerManagerRestartShardsResult { - return &AuroraSchedulerManagerRestartShardsResult{} -} - -var AuroraSchedulerManagerRestartShardsResult_Success_DEFAULT *Response - -func (p *AuroraSchedulerManagerRestartShardsResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraSchedulerManagerRestartShardsResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraSchedulerManagerRestartShardsResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraSchedulerManagerRestartShardsResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerRestartShardsResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraSchedulerManagerRestartShardsResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("restartShards_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerRestartShardsResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraSchedulerManagerRestartShardsResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerRestartShardsResult(%+v)", *p) -} - -// Attributes: -// - Job -// - Instances -// - Message -type AuroraSchedulerManagerKillTasksArgs struct { - // unused fields # 1 to 3 - Job *JobKey `thrift:"job,4" json:"job"` - Instances map[int32]bool `thrift:"instances,5" json:"instances"` - Message string `thrift:"message,6" json:"message"` -} - -func NewAuroraSchedulerManagerKillTasksArgs() *AuroraSchedulerManagerKillTasksArgs { - return &AuroraSchedulerManagerKillTasksArgs{} -} - -var AuroraSchedulerManagerKillTasksArgs_Job_DEFAULT *JobKey - -func (p *AuroraSchedulerManagerKillTasksArgs) GetJob() *JobKey { - if !p.IsSetJob() { - return AuroraSchedulerManagerKillTasksArgs_Job_DEFAULT - } - return p.Job -} - -func (p *AuroraSchedulerManagerKillTasksArgs) GetInstances() map[int32]bool { - return p.Instances -} - -func (p *AuroraSchedulerManagerKillTasksArgs) GetMessage() string { - return p.Message -} -func (p *AuroraSchedulerManagerKillTasksArgs) IsSetJob() bool { - return p.Job != nil -} - -func (p *AuroraSchedulerManagerKillTasksArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - case 5: - if err := p.readField5(iprot); err != nil { - return err - } - case 6: - if err := p.readField6(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerKillTasksArgs) readField4(iprot thrift.TProtocol) error { - p.Job = &JobKey{} - if err := p.Job.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Job), err) - } - return nil -} - -func (p *AuroraSchedulerManagerKillTasksArgs) readField5(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[int32]bool, size) - p.Instances = tSet - for i := 0; i < size; i++ { - var _elem161 int32 - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 0: ", err) - } else { - _elem161 = v - } - p.Instances[_elem161] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerKillTasksArgs) readField6(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 6: ", err) - } else { - p.Message = v - } - return nil -} - -func (p *AuroraSchedulerManagerKillTasksArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("killTasks_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := p.writeField5(oprot); err != nil { - return err - } - if err := p.writeField6(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerKillTasksArgs) writeField4(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("job", thrift.STRUCT, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:job: ", p), err) - } - if err := p.Job.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Job), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:job: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerKillTasksArgs) writeField5(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("instances", thrift.SET, 5); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:instances: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.I32, len(p.Instances)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Instances { - if err := oprot.WriteI32(int32(v)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 5:instances: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerKillTasksArgs) writeField6(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("message", thrift.STRING, 6); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 6:message: ", p), err) - } - if err := oprot.WriteString(string(p.Message)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.message (6) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 6:message: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerKillTasksArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerKillTasksArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraSchedulerManagerKillTasksResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraSchedulerManagerKillTasksResult() *AuroraSchedulerManagerKillTasksResult { - return &AuroraSchedulerManagerKillTasksResult{} -} - -var AuroraSchedulerManagerKillTasksResult_Success_DEFAULT *Response - -func (p *AuroraSchedulerManagerKillTasksResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraSchedulerManagerKillTasksResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraSchedulerManagerKillTasksResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraSchedulerManagerKillTasksResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerKillTasksResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraSchedulerManagerKillTasksResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("killTasks_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerKillTasksResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraSchedulerManagerKillTasksResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerKillTasksResult(%+v)", *p) -} - -// Attributes: -// - Key -// - Count -type AuroraSchedulerManagerAddInstancesArgs struct { - // unused fields # 1 to 2 - Key *InstanceKey `thrift:"key,3" json:"key"` - Count int32 `thrift:"count,4" json:"count"` -} - -func NewAuroraSchedulerManagerAddInstancesArgs() *AuroraSchedulerManagerAddInstancesArgs { - return &AuroraSchedulerManagerAddInstancesArgs{} -} - -var AuroraSchedulerManagerAddInstancesArgs_Key_DEFAULT *InstanceKey - -func (p *AuroraSchedulerManagerAddInstancesArgs) GetKey() *InstanceKey { - if !p.IsSetKey() { - return AuroraSchedulerManagerAddInstancesArgs_Key_DEFAULT - } - return p.Key -} - -func (p *AuroraSchedulerManagerAddInstancesArgs) GetCount() int32 { - return p.Count -} -func (p *AuroraSchedulerManagerAddInstancesArgs) IsSetKey() bool { - return p.Key != nil -} - -func (p *AuroraSchedulerManagerAddInstancesArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerAddInstancesArgs) readField3(iprot thrift.TProtocol) error { - p.Key = &InstanceKey{} - if err := p.Key.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) - } - return nil -} - -func (p *AuroraSchedulerManagerAddInstancesArgs) readField4(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 4: ", err) - } else { - p.Count = v - } - return nil -} - -func (p *AuroraSchedulerManagerAddInstancesArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("addInstances_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerAddInstancesArgs) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:key: ", p), err) - } - if err := p.Key.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:key: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerAddInstancesArgs) writeField4(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("count", thrift.I32, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:count: ", p), err) - } - if err := oprot.WriteI32(int32(p.Count)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.count (4) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:count: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerAddInstancesArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerAddInstancesArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraSchedulerManagerAddInstancesResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraSchedulerManagerAddInstancesResult() *AuroraSchedulerManagerAddInstancesResult { - return &AuroraSchedulerManagerAddInstancesResult{} -} - -var AuroraSchedulerManagerAddInstancesResult_Success_DEFAULT *Response - -func (p *AuroraSchedulerManagerAddInstancesResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraSchedulerManagerAddInstancesResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraSchedulerManagerAddInstancesResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraSchedulerManagerAddInstancesResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerAddInstancesResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraSchedulerManagerAddInstancesResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("addInstances_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerAddInstancesResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraSchedulerManagerAddInstancesResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerAddInstancesResult(%+v)", *p) -} - -// Attributes: -// - Config -type AuroraSchedulerManagerReplaceCronTemplateArgs struct { - Config *JobConfiguration `thrift:"config,1" json:"config"` -} - -func NewAuroraSchedulerManagerReplaceCronTemplateArgs() *AuroraSchedulerManagerReplaceCronTemplateArgs { - return &AuroraSchedulerManagerReplaceCronTemplateArgs{} -} - -var AuroraSchedulerManagerReplaceCronTemplateArgs_Config_DEFAULT *JobConfiguration - -func (p *AuroraSchedulerManagerReplaceCronTemplateArgs) GetConfig() *JobConfiguration { - if !p.IsSetConfig() { - return AuroraSchedulerManagerReplaceCronTemplateArgs_Config_DEFAULT - } - return p.Config -} -func (p *AuroraSchedulerManagerReplaceCronTemplateArgs) IsSetConfig() bool { - return p.Config != nil -} - -func (p *AuroraSchedulerManagerReplaceCronTemplateArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerReplaceCronTemplateArgs) readField1(iprot thrift.TProtocol) error { - p.Config = &JobConfiguration{} - if err := p.Config.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Config), err) - } - return nil -} - -func (p *AuroraSchedulerManagerReplaceCronTemplateArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("replaceCronTemplate_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerReplaceCronTemplateArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("config", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:config: ", p), err) - } - if err := p.Config.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Config), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:config: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerReplaceCronTemplateArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerReplaceCronTemplateArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraSchedulerManagerReplaceCronTemplateResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraSchedulerManagerReplaceCronTemplateResult() *AuroraSchedulerManagerReplaceCronTemplateResult { - return &AuroraSchedulerManagerReplaceCronTemplateResult{} -} - -var AuroraSchedulerManagerReplaceCronTemplateResult_Success_DEFAULT *Response - -func (p *AuroraSchedulerManagerReplaceCronTemplateResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraSchedulerManagerReplaceCronTemplateResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraSchedulerManagerReplaceCronTemplateResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraSchedulerManagerReplaceCronTemplateResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerReplaceCronTemplateResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraSchedulerManagerReplaceCronTemplateResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("replaceCronTemplate_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerReplaceCronTemplateResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraSchedulerManagerReplaceCronTemplateResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerReplaceCronTemplateResult(%+v)", *p) -} - -// Attributes: -// - Request: A description of how to change the job. -// - Message: A user-specified message to include with the induced job update state change. -type AuroraSchedulerManagerStartJobUpdateArgs struct { - Request *JobUpdateRequest `thrift:"request,1" json:"request"` - // unused field # 2 - Message string `thrift:"message,3" json:"message"` -} - -func NewAuroraSchedulerManagerStartJobUpdateArgs() *AuroraSchedulerManagerStartJobUpdateArgs { - return &AuroraSchedulerManagerStartJobUpdateArgs{} -} - -var AuroraSchedulerManagerStartJobUpdateArgs_Request_DEFAULT *JobUpdateRequest - -func (p *AuroraSchedulerManagerStartJobUpdateArgs) GetRequest() *JobUpdateRequest { - if !p.IsSetRequest() { - return AuroraSchedulerManagerStartJobUpdateArgs_Request_DEFAULT - } - return p.Request -} - -func (p *AuroraSchedulerManagerStartJobUpdateArgs) GetMessage() string { - return p.Message -} -func (p *AuroraSchedulerManagerStartJobUpdateArgs) IsSetRequest() bool { - return p.Request != nil -} - -func (p *AuroraSchedulerManagerStartJobUpdateArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerStartJobUpdateArgs) readField1(iprot thrift.TProtocol) error { - p.Request = &JobUpdateRequest{} - if err := p.Request.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Request), err) - } - return nil -} - -func (p *AuroraSchedulerManagerStartJobUpdateArgs) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.Message = v - } - return nil -} - -func (p *AuroraSchedulerManagerStartJobUpdateArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("startJobUpdate_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerStartJobUpdateArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("request", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:request: ", p), err) - } - if err := p.Request.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Request), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:request: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerStartJobUpdateArgs) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("message", thrift.STRING, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:message: ", p), err) - } - if err := oprot.WriteString(string(p.Message)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.message (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:message: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerStartJobUpdateArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerStartJobUpdateArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraSchedulerManagerStartJobUpdateResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraSchedulerManagerStartJobUpdateResult() *AuroraSchedulerManagerStartJobUpdateResult { - return &AuroraSchedulerManagerStartJobUpdateResult{} -} - -var AuroraSchedulerManagerStartJobUpdateResult_Success_DEFAULT *Response - -func (p *AuroraSchedulerManagerStartJobUpdateResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraSchedulerManagerStartJobUpdateResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraSchedulerManagerStartJobUpdateResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraSchedulerManagerStartJobUpdateResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerStartJobUpdateResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraSchedulerManagerStartJobUpdateResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("startJobUpdate_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerStartJobUpdateResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraSchedulerManagerStartJobUpdateResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerStartJobUpdateResult(%+v)", *p) -} - -// Attributes: -// - Key: The update to pause. -// - Message: A user-specified message to include with the induced job update state change. -type AuroraSchedulerManagerPauseJobUpdateArgs struct { - Key *JobUpdateKey `thrift:"key,1" json:"key"` - // unused field # 2 - Message string `thrift:"message,3" json:"message"` -} - -func NewAuroraSchedulerManagerPauseJobUpdateArgs() *AuroraSchedulerManagerPauseJobUpdateArgs { - return &AuroraSchedulerManagerPauseJobUpdateArgs{} -} - -var AuroraSchedulerManagerPauseJobUpdateArgs_Key_DEFAULT *JobUpdateKey - -func (p *AuroraSchedulerManagerPauseJobUpdateArgs) GetKey() *JobUpdateKey { - if !p.IsSetKey() { - return AuroraSchedulerManagerPauseJobUpdateArgs_Key_DEFAULT - } - return p.Key -} - -func (p *AuroraSchedulerManagerPauseJobUpdateArgs) GetMessage() string { - return p.Message -} -func (p *AuroraSchedulerManagerPauseJobUpdateArgs) IsSetKey() bool { - return p.Key != nil -} - -func (p *AuroraSchedulerManagerPauseJobUpdateArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerPauseJobUpdateArgs) readField1(iprot thrift.TProtocol) error { - p.Key = &JobUpdateKey{} - if err := p.Key.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) - } - return nil -} - -func (p *AuroraSchedulerManagerPauseJobUpdateArgs) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.Message = v - } - return nil -} - -func (p *AuroraSchedulerManagerPauseJobUpdateArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("pauseJobUpdate_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerPauseJobUpdateArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:key: ", p), err) - } - if err := p.Key.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:key: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerPauseJobUpdateArgs) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("message", thrift.STRING, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:message: ", p), err) - } - if err := oprot.WriteString(string(p.Message)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.message (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:message: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerPauseJobUpdateArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerPauseJobUpdateArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraSchedulerManagerPauseJobUpdateResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraSchedulerManagerPauseJobUpdateResult() *AuroraSchedulerManagerPauseJobUpdateResult { - return &AuroraSchedulerManagerPauseJobUpdateResult{} -} - -var AuroraSchedulerManagerPauseJobUpdateResult_Success_DEFAULT *Response - -func (p *AuroraSchedulerManagerPauseJobUpdateResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraSchedulerManagerPauseJobUpdateResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraSchedulerManagerPauseJobUpdateResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraSchedulerManagerPauseJobUpdateResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerPauseJobUpdateResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraSchedulerManagerPauseJobUpdateResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("pauseJobUpdate_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerPauseJobUpdateResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraSchedulerManagerPauseJobUpdateResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerPauseJobUpdateResult(%+v)", *p) -} - -// Attributes: -// - Key: The update to resume. -// - Message: A user-specified message to include with the induced job update state change. -type AuroraSchedulerManagerResumeJobUpdateArgs struct { - Key *JobUpdateKey `thrift:"key,1" json:"key"` - // unused field # 2 - Message string `thrift:"message,3" json:"message"` -} - -func NewAuroraSchedulerManagerResumeJobUpdateArgs() *AuroraSchedulerManagerResumeJobUpdateArgs { - return &AuroraSchedulerManagerResumeJobUpdateArgs{} -} - -var AuroraSchedulerManagerResumeJobUpdateArgs_Key_DEFAULT *JobUpdateKey - -func (p *AuroraSchedulerManagerResumeJobUpdateArgs) GetKey() *JobUpdateKey { - if !p.IsSetKey() { - return AuroraSchedulerManagerResumeJobUpdateArgs_Key_DEFAULT - } - return p.Key -} - -func (p *AuroraSchedulerManagerResumeJobUpdateArgs) GetMessage() string { - return p.Message -} -func (p *AuroraSchedulerManagerResumeJobUpdateArgs) IsSetKey() bool { - return p.Key != nil -} - -func (p *AuroraSchedulerManagerResumeJobUpdateArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerResumeJobUpdateArgs) readField1(iprot thrift.TProtocol) error { - p.Key = &JobUpdateKey{} - if err := p.Key.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) - } - return nil -} - -func (p *AuroraSchedulerManagerResumeJobUpdateArgs) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.Message = v - } - return nil -} - -func (p *AuroraSchedulerManagerResumeJobUpdateArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("resumeJobUpdate_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerResumeJobUpdateArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:key: ", p), err) - } - if err := p.Key.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:key: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerResumeJobUpdateArgs) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("message", thrift.STRING, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:message: ", p), err) - } - if err := oprot.WriteString(string(p.Message)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.message (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:message: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerResumeJobUpdateArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerResumeJobUpdateArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraSchedulerManagerResumeJobUpdateResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraSchedulerManagerResumeJobUpdateResult() *AuroraSchedulerManagerResumeJobUpdateResult { - return &AuroraSchedulerManagerResumeJobUpdateResult{} -} - -var AuroraSchedulerManagerResumeJobUpdateResult_Success_DEFAULT *Response - -func (p *AuroraSchedulerManagerResumeJobUpdateResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraSchedulerManagerResumeJobUpdateResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraSchedulerManagerResumeJobUpdateResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraSchedulerManagerResumeJobUpdateResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerResumeJobUpdateResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraSchedulerManagerResumeJobUpdateResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("resumeJobUpdate_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerResumeJobUpdateResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraSchedulerManagerResumeJobUpdateResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerResumeJobUpdateResult(%+v)", *p) -} - -// Attributes: -// - Key: The update to abort. -// - Message: A user-specified message to include with the induced job update state change. -type AuroraSchedulerManagerAbortJobUpdateArgs struct { - Key *JobUpdateKey `thrift:"key,1" json:"key"` - // unused field # 2 - Message string `thrift:"message,3" json:"message"` -} - -func NewAuroraSchedulerManagerAbortJobUpdateArgs() *AuroraSchedulerManagerAbortJobUpdateArgs { - return &AuroraSchedulerManagerAbortJobUpdateArgs{} -} - -var AuroraSchedulerManagerAbortJobUpdateArgs_Key_DEFAULT *JobUpdateKey - -func (p *AuroraSchedulerManagerAbortJobUpdateArgs) GetKey() *JobUpdateKey { - if !p.IsSetKey() { - return AuroraSchedulerManagerAbortJobUpdateArgs_Key_DEFAULT - } - return p.Key -} - -func (p *AuroraSchedulerManagerAbortJobUpdateArgs) GetMessage() string { - return p.Message -} -func (p *AuroraSchedulerManagerAbortJobUpdateArgs) IsSetKey() bool { - return p.Key != nil -} - -func (p *AuroraSchedulerManagerAbortJobUpdateArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerAbortJobUpdateArgs) readField1(iprot thrift.TProtocol) error { - p.Key = &JobUpdateKey{} - if err := p.Key.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) - } - return nil -} - -func (p *AuroraSchedulerManagerAbortJobUpdateArgs) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.Message = v - } - return nil -} - -func (p *AuroraSchedulerManagerAbortJobUpdateArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("abortJobUpdate_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerAbortJobUpdateArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:key: ", p), err) - } - if err := p.Key.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:key: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerAbortJobUpdateArgs) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("message", thrift.STRING, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:message: ", p), err) - } - if err := oprot.WriteString(string(p.Message)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.message (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:message: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerAbortJobUpdateArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerAbortJobUpdateArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraSchedulerManagerAbortJobUpdateResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraSchedulerManagerAbortJobUpdateResult() *AuroraSchedulerManagerAbortJobUpdateResult { - return &AuroraSchedulerManagerAbortJobUpdateResult{} -} - -var AuroraSchedulerManagerAbortJobUpdateResult_Success_DEFAULT *Response - -func (p *AuroraSchedulerManagerAbortJobUpdateResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraSchedulerManagerAbortJobUpdateResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraSchedulerManagerAbortJobUpdateResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraSchedulerManagerAbortJobUpdateResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerAbortJobUpdateResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraSchedulerManagerAbortJobUpdateResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("abortJobUpdate_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerAbortJobUpdateResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraSchedulerManagerAbortJobUpdateResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerAbortJobUpdateResult(%+v)", *p) -} - -// Attributes: -// - Key: The update to rollback. -// - Message: A user-specified message to include with the induced job update state change. -type AuroraSchedulerManagerRollbackJobUpdateArgs struct { - Key *JobUpdateKey `thrift:"key,1" json:"key"` - Message string `thrift:"message,2" json:"message"` -} - -func NewAuroraSchedulerManagerRollbackJobUpdateArgs() *AuroraSchedulerManagerRollbackJobUpdateArgs { - return &AuroraSchedulerManagerRollbackJobUpdateArgs{} -} - -var AuroraSchedulerManagerRollbackJobUpdateArgs_Key_DEFAULT *JobUpdateKey - -func (p *AuroraSchedulerManagerRollbackJobUpdateArgs) GetKey() *JobUpdateKey { - if !p.IsSetKey() { - return AuroraSchedulerManagerRollbackJobUpdateArgs_Key_DEFAULT - } - return p.Key -} - -func (p *AuroraSchedulerManagerRollbackJobUpdateArgs) GetMessage() string { - return p.Message -} -func (p *AuroraSchedulerManagerRollbackJobUpdateArgs) IsSetKey() bool { - return p.Key != nil -} - -func (p *AuroraSchedulerManagerRollbackJobUpdateArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerRollbackJobUpdateArgs) readField1(iprot thrift.TProtocol) error { - p.Key = &JobUpdateKey{} - if err := p.Key.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) - } - return nil -} - -func (p *AuroraSchedulerManagerRollbackJobUpdateArgs) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.Message = v - } - return nil -} - -func (p *AuroraSchedulerManagerRollbackJobUpdateArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("rollbackJobUpdate_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerRollbackJobUpdateArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:key: ", p), err) - } - if err := p.Key.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:key: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerRollbackJobUpdateArgs) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("message", thrift.STRING, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:message: ", p), err) - } - if err := oprot.WriteString(string(p.Message)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.message (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:message: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerRollbackJobUpdateArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerRollbackJobUpdateArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraSchedulerManagerRollbackJobUpdateResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraSchedulerManagerRollbackJobUpdateResult() *AuroraSchedulerManagerRollbackJobUpdateResult { - return &AuroraSchedulerManagerRollbackJobUpdateResult{} -} - -var AuroraSchedulerManagerRollbackJobUpdateResult_Success_DEFAULT *Response - -func (p *AuroraSchedulerManagerRollbackJobUpdateResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraSchedulerManagerRollbackJobUpdateResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraSchedulerManagerRollbackJobUpdateResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraSchedulerManagerRollbackJobUpdateResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerRollbackJobUpdateResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraSchedulerManagerRollbackJobUpdateResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("rollbackJobUpdate_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerRollbackJobUpdateResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraSchedulerManagerRollbackJobUpdateResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerRollbackJobUpdateResult(%+v)", *p) -} - -// Attributes: -// - Key -type AuroraSchedulerManagerPulseJobUpdateArgs struct { - Key *JobUpdateKey `thrift:"key,1" json:"key"` -} - -func NewAuroraSchedulerManagerPulseJobUpdateArgs() *AuroraSchedulerManagerPulseJobUpdateArgs { - return &AuroraSchedulerManagerPulseJobUpdateArgs{} -} - -var AuroraSchedulerManagerPulseJobUpdateArgs_Key_DEFAULT *JobUpdateKey - -func (p *AuroraSchedulerManagerPulseJobUpdateArgs) GetKey() *JobUpdateKey { - if !p.IsSetKey() { - return AuroraSchedulerManagerPulseJobUpdateArgs_Key_DEFAULT - } - return p.Key -} -func (p *AuroraSchedulerManagerPulseJobUpdateArgs) IsSetKey() bool { - return p.Key != nil -} - -func (p *AuroraSchedulerManagerPulseJobUpdateArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerPulseJobUpdateArgs) readField1(iprot thrift.TProtocol) error { - p.Key = &JobUpdateKey{} - if err := p.Key.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) - } - return nil -} - -func (p *AuroraSchedulerManagerPulseJobUpdateArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("pulseJobUpdate_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerPulseJobUpdateArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:key: ", p), err) - } - if err := p.Key.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:key: ", p), err) - } - return err -} - -func (p *AuroraSchedulerManagerPulseJobUpdateArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerPulseJobUpdateArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AuroraSchedulerManagerPulseJobUpdateResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewAuroraSchedulerManagerPulseJobUpdateResult() *AuroraSchedulerManagerPulseJobUpdateResult { - return &AuroraSchedulerManagerPulseJobUpdateResult{} -} - -var AuroraSchedulerManagerPulseJobUpdateResult_Success_DEFAULT *Response - -func (p *AuroraSchedulerManagerPulseJobUpdateResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return AuroraSchedulerManagerPulseJobUpdateResult_Success_DEFAULT - } - return p.Success -} -func (p *AuroraSchedulerManagerPulseJobUpdateResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AuroraSchedulerManagerPulseJobUpdateResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AuroraSchedulerManagerPulseJobUpdateResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AuroraSchedulerManagerPulseJobUpdateResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("pulseJobUpdate_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AuroraSchedulerManagerPulseJobUpdateResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *AuroraSchedulerManagerPulseJobUpdateResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AuroraSchedulerManagerPulseJobUpdateResult(%+v)", *p) -} diff --git a/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/constants.go b/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/constants.go deleted file mode 100644 index 9284ff5..0000000 --- a/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/constants.go +++ /dev/null @@ -1,89 +0,0 @@ -// Autogenerated by Thrift Compiler (0.9.3) -// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - -package aurora - -import ( - "bytes" - "fmt" - "git.apache.org/thrift.git/lib/go/thrift" -) - -// (needed to ensure safety because of naive import list construction.) -var _ = thrift.ZERO -var _ = fmt.Printf -var _ = bytes.Equal - -const AURORA_EXECUTOR_NAME = "AuroraExecutor" - -var ACTIVE_STATES map[ScheduleStatus]bool -var SLAVE_ASSIGNED_STATES map[ScheduleStatus]bool -var LIVE_STATES map[ScheduleStatus]bool -var TERMINAL_STATES map[ScheduleStatus]bool - -const GOOD_IDENTIFIER_PATTERN = "^[\\w\\-\\.]+$" -const GOOD_IDENTIFIER_PATTERN_JVM = "^[\\w\\-\\.]+$" -const GOOD_IDENTIFIER_PATTERN_PYTHON = "^[\\w\\-\\.]+$" - -var ACTIVE_JOB_UPDATE_STATES map[JobUpdateStatus]bool -var AWAITNG_PULSE_JOB_UPDATE_STATES map[JobUpdateStatus]bool - -const BYPASS_LEADER_REDIRECT_HEADER_NAME = "Bypass-Leader-Redirect" -const TASK_FILESYSTEM_MOUNT_POINT = "taskfs" - -func init() { - ACTIVE_STATES = map[ScheduleStatus]bool{ - 9: true, - 17: true, - 6: true, - 0: true, - 13: true, - 12: true, - 2: true, - 1: true, - 18: true, - 16: true, - } - - SLAVE_ASSIGNED_STATES = map[ScheduleStatus]bool{ - 9: true, - 17: true, - 6: true, - 13: true, - 12: true, - 2: true, - 18: true, - 1: true, - } - - LIVE_STATES = map[ScheduleStatus]bool{ - 6: true, - 13: true, - 12: true, - 17: true, - 18: true, - 2: true, - } - - TERMINAL_STATES = map[ScheduleStatus]bool{ - 4: true, - 3: true, - 5: true, - 7: true, - } - - ACTIVE_JOB_UPDATE_STATES = map[JobUpdateStatus]bool{ - 0: true, - 1: true, - 2: true, - 3: true, - 9: true, - 10: true, - } - - AWAITNG_PULSE_JOB_UPDATE_STATES = map[JobUpdateStatus]bool{ - 9: true, - 10: true, - } - -} diff --git a/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/read_only_scheduler-remote/read_only_scheduler-remote.go b/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/read_only_scheduler-remote/read_only_scheduler-remote.go index 2c2687f..01a1f77 100755 --- a/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/read_only_scheduler-remote/read_only_scheduler-remote.go +++ b/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/read_only_scheduler-remote/read_only_scheduler-remote.go @@ -1,19 +1,21 @@ -// Autogenerated by Thrift Compiler (0.9.3) +// Autogenerated by Thrift Compiler (0.12.0) // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING package main import ( "apache/aurora" + "context" "flag" "fmt" - "git.apache.org/thrift.git/lib/go/thrift" "math" "net" "net/url" "os" "strconv" "strings" + + "git.apache.org/thrift.git/lib/go/thrift" ) func Usage() { @@ -37,6 +39,22 @@ func Usage() { os.Exit(0) } +type httpHeaders map[string]string + +func (h httpHeaders) String() string { + var m map[string]string = h + return fmt.Sprintf("%s", m) +} + +func (h httpHeaders) Set(value string) error { + parts := strings.Split(value, ": ") + if len(parts) != 2 { + return fmt.Errorf("header should be of format 'Key: Value'") + } + h[parts[0]] = parts[1] + return nil +} + func main() { flag.Usage = Usage var host string @@ -45,7 +63,8 @@ func main() { var urlString string var framed bool var useHttp bool - var parsedUrl url.URL + headers := make(httpHeaders) + var parsedUrl *url.URL var trans thrift.TTransport _ = strconv.Atoi _ = math.Abs @@ -56,16 +75,18 @@ func main() { flag.StringVar(&urlString, "u", "", "Specify the url") flag.BoolVar(&framed, "framed", false, "Use framed transport") flag.BoolVar(&useHttp, "http", false, "Use http") + flag.Var(headers, "H", "Headers to set on the http(s) request (e.g. -H \"Key: Value\")") flag.Parse() if len(urlString) > 0 { - parsedUrl, err := url.Parse(urlString) + var err error + parsedUrl, err = url.Parse(urlString) if err != nil { fmt.Fprintln(os.Stderr, "Error parsing URL: ", err) flag.Usage() } host = parsedUrl.Host - useHttp = len(parsedUrl.Scheme) <= 0 || parsedUrl.Scheme == "http" + useHttp = len(parsedUrl.Scheme) <= 0 || parsedUrl.Scheme == "http" || parsedUrl.Scheme == "https" } else if useHttp { _, err := url.Parse(fmt.Sprint("http://", host, ":", port)) if err != nil { @@ -78,6 +99,12 @@ func main() { var err error if useHttp { trans, err = thrift.NewTHttpClient(parsedUrl.String()) + if len(headers) > 0 { + httptrans := trans.(*thrift.THttpClient) + for key, value := range headers { + httptrans.SetHeader(key, value) + } + } } else { portStr := fmt.Sprint(port) if strings.Contains(host, ":") { @@ -120,7 +147,9 @@ func main() { Usage() os.Exit(1) } - client := aurora.NewReadOnlySchedulerClientFactory(trans, protocolFactory) + iprot := protocolFactory.GetProtocol(trans) + oprot := protocolFactory.GetProtocol(trans) + client := aurora.NewReadOnlySchedulerClient(thrift.NewTStandardClient(iprot, oprot)) if err := trans.Open(); err != nil { fmt.Fprintln(os.Stderr, "Error opening socket to ", host, ":", port, " ", err) os.Exit(1) @@ -132,7 +161,7 @@ func main() { fmt.Fprintln(os.Stderr, "GetRoleSummary requires 0 args") flag.Usage() } - fmt.Print(client.GetRoleSummary()) + fmt.Print(client.GetRoleSummary(context.Background())) fmt.Print("\n") break case "getJobSummary": @@ -142,7 +171,7 @@ func main() { } argvalue0 := flag.Arg(1) value0 := argvalue0 - fmt.Print(client.GetJobSummary(value0)) + fmt.Print(client.GetJobSummary(context.Background(), value0)) fmt.Print("\n") break case "getTasksStatus": @@ -158,7 +187,7 @@ func main() { Usage() return } - factory84 := thrift.NewTSimpleJSONProtocolFactory() + factory84 := thrift.NewTJSONProtocolFactory() jsProt85 := factory84.GetProtocol(mbTrans82) argvalue0 := aurora.NewTaskQuery() err86 := argvalue0.Read(jsProt85) @@ -167,7 +196,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.GetTasksStatus(value0)) + fmt.Print(client.GetTasksStatus(context.Background(), value0)) fmt.Print("\n") break case "getTasksWithoutConfigs": @@ -183,7 +212,7 @@ func main() { Usage() return } - factory90 := thrift.NewTSimpleJSONProtocolFactory() + factory90 := thrift.NewTJSONProtocolFactory() jsProt91 := factory90.GetProtocol(mbTrans88) argvalue0 := aurora.NewTaskQuery() err92 := argvalue0.Read(jsProt91) @@ -192,7 +221,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.GetTasksWithoutConfigs(value0)) + fmt.Print(client.GetTasksWithoutConfigs(context.Background(), value0)) fmt.Print("\n") break case "getPendingReason": @@ -208,7 +237,7 @@ func main() { Usage() return } - factory96 := thrift.NewTSimpleJSONProtocolFactory() + factory96 := thrift.NewTJSONProtocolFactory() jsProt97 := factory96.GetProtocol(mbTrans94) argvalue0 := aurora.NewTaskQuery() err98 := argvalue0.Read(jsProt97) @@ -217,7 +246,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.GetPendingReason(value0)) + fmt.Print(client.GetPendingReason(context.Background(), value0)) fmt.Print("\n") break case "getConfigSummary": @@ -233,7 +262,7 @@ func main() { Usage() return } - factory102 := thrift.NewTSimpleJSONProtocolFactory() + factory102 := thrift.NewTJSONProtocolFactory() jsProt103 := factory102.GetProtocol(mbTrans100) argvalue0 := aurora.NewJobKey() err104 := argvalue0.Read(jsProt103) @@ -242,7 +271,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.GetConfigSummary(value0)) + fmt.Print(client.GetConfigSummary(context.Background(), value0)) fmt.Print("\n") break case "getJobs": @@ -252,7 +281,7 @@ func main() { } argvalue0 := flag.Arg(1) value0 := argvalue0 - fmt.Print(client.GetJobs(value0)) + fmt.Print(client.GetJobs(context.Background(), value0)) fmt.Print("\n") break case "getQuota": @@ -262,7 +291,7 @@ func main() { } argvalue0 := flag.Arg(1) value0 := argvalue0 - fmt.Print(client.GetQuota(value0)) + fmt.Print(client.GetQuota(context.Background(), value0)) fmt.Print("\n") break case "populateJobConfig": @@ -278,7 +307,7 @@ func main() { Usage() return } - factory110 := thrift.NewTSimpleJSONProtocolFactory() + factory110 := thrift.NewTJSONProtocolFactory() jsProt111 := factory110.GetProtocol(mbTrans108) argvalue0 := aurora.NewJobConfiguration() err112 := argvalue0.Read(jsProt111) @@ -287,7 +316,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.PopulateJobConfig(value0)) + fmt.Print(client.PopulateJobConfig(context.Background(), value0)) fmt.Print("\n") break case "getJobUpdateSummaries": @@ -303,7 +332,7 @@ func main() { Usage() return } - factory116 := thrift.NewTSimpleJSONProtocolFactory() + factory116 := thrift.NewTJSONProtocolFactory() jsProt117 := factory116.GetProtocol(mbTrans114) argvalue0 := aurora.NewJobUpdateQuery() err118 := argvalue0.Read(jsProt117) @@ -312,7 +341,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.GetJobUpdateSummaries(value0)) + fmt.Print(client.GetJobUpdateSummaries(context.Background(), value0)) fmt.Print("\n") break case "getJobUpdateDetails": @@ -328,7 +357,7 @@ func main() { Usage() return } - factory122 := thrift.NewTSimpleJSONProtocolFactory() + factory122 := thrift.NewTJSONProtocolFactory() jsProt123 := factory122.GetProtocol(mbTrans120) argvalue0 := aurora.NewJobUpdateQuery() err124 := argvalue0.Read(jsProt123) @@ -337,7 +366,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.GetJobUpdateDetails(value0)) + fmt.Print(client.GetJobUpdateDetails(context.Background(), value0)) fmt.Print("\n") break case "getJobUpdateDiff": @@ -353,7 +382,7 @@ func main() { Usage() return } - factory128 := thrift.NewTSimpleJSONProtocolFactory() + factory128 := thrift.NewTJSONProtocolFactory() jsProt129 := factory128.GetProtocol(mbTrans126) argvalue0 := aurora.NewJobUpdateRequest() err130 := argvalue0.Read(jsProt129) @@ -362,7 +391,7 @@ func main() { return } value0 := argvalue0 - fmt.Print(client.GetJobUpdateDiff(value0)) + fmt.Print(client.GetJobUpdateDiff(context.Background(), value0)) fmt.Print("\n") break case "getTierConfigs": @@ -370,7 +399,7 @@ func main() { fmt.Fprintln(os.Stderr, "GetTierConfigs requires 0 args") flag.Usage() } - fmt.Print(client.GetTierConfigs()) + fmt.Print(client.GetTierConfigs(context.Background())) fmt.Print("\n") break case "": diff --git a/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/readonlyscheduler.go b/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/readonlyscheduler.go deleted file mode 100644 index dba7255..0000000 --- a/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/readonlyscheduler.go +++ /dev/null @@ -1,4293 +0,0 @@ -// Autogenerated by Thrift Compiler (0.9.3) -// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - -package aurora - -import ( - "bytes" - "fmt" - "git.apache.org/thrift.git/lib/go/thrift" -) - -// (needed to ensure safety because of naive import list construction.) -var _ = thrift.ZERO -var _ = fmt.Printf -var _ = bytes.Equal - -type ReadOnlyScheduler interface { - // Returns a summary of the jobs grouped by role. - GetRoleSummary() (r *Response, err error) - // Returns a summary of jobs, optionally only those owned by a specific role. - // - // Parameters: - // - Role - GetJobSummary(role string) (r *Response, err error) - // Fetches the status of tasks. - // - // Parameters: - // - Query - GetTasksStatus(query *TaskQuery) (r *Response, err error) - // Same as getTaskStatus but without the TaskConfig.ExecutorConfig data set. - // This is an interim solution until we have a better way to query TaskConfigs (AURORA-541). - // - // Parameters: - // - Query - GetTasksWithoutConfigs(query *TaskQuery) (r *Response, err error) - // Returns user-friendly reasons (if available) for tasks retained in PENDING state. - // - // Parameters: - // - Query - GetPendingReason(query *TaskQuery) (r *Response, err error) - // Fetches the configuration summary of active tasks for the specified job. - // - // Parameters: - // - Job - GetConfigSummary(job *JobKey) (r *Response, err error) - // Fetches the status of jobs. - // ownerRole is optional, in which case all jobs are returned. - // - // Parameters: - // - OwnerRole - GetJobs(ownerRole string) (r *Response, err error) - // Fetches the quota allocated for a user. - // - // Parameters: - // - OwnerRole - GetQuota(ownerRole string) (r *Response, err error) - // Populates fields in a job configuration as though it were about to be run. - // This can be used to diff a configuration running tasks. - // - // Parameters: - // - Description - PopulateJobConfig(description *JobConfiguration) (r *Response, err error) - // Gets job update summaries. - // - // Parameters: - // - JobUpdateQuery - GetJobUpdateSummaries(jobUpdateQuery *JobUpdateQuery) (r *Response, err error) - // Gets job update details. - // - // Parameters: - // - Query - GetJobUpdateDetails(query *JobUpdateQuery) (r *Response, err error) - // Gets the diff between client (desired) and server (current) job states. - // - // Parameters: - // - Request - GetJobUpdateDiff(request *JobUpdateRequest) (r *Response, err error) - // Gets tier configurations. - GetTierConfigs() (r *Response, err error) -} - -type ReadOnlySchedulerClient struct { - Transport thrift.TTransport - ProtocolFactory thrift.TProtocolFactory - InputProtocol thrift.TProtocol - OutputProtocol thrift.TProtocol - SeqId int32 -} - -func NewReadOnlySchedulerClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *ReadOnlySchedulerClient { - return &ReadOnlySchedulerClient{Transport: t, - ProtocolFactory: f, - InputProtocol: f.GetProtocol(t), - OutputProtocol: f.GetProtocol(t), - SeqId: 0, - } -} - -func NewReadOnlySchedulerClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *ReadOnlySchedulerClient { - return &ReadOnlySchedulerClient{Transport: t, - ProtocolFactory: nil, - InputProtocol: iprot, - OutputProtocol: oprot, - SeqId: 0, - } -} - -// Returns a summary of the jobs grouped by role. -func (p *ReadOnlySchedulerClient) GetRoleSummary() (r *Response, err error) { - if err = p.sendGetRoleSummary(); err != nil { - return - } - return p.recvGetRoleSummary() -} - -func (p *ReadOnlySchedulerClient) sendGetRoleSummary() (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("getRoleSummary", thrift.CALL, p.SeqId); err != nil { - return - } - args := ReadOnlySchedulerGetRoleSummaryArgs{} - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *ReadOnlySchedulerClient) recvGetRoleSummary() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "getRoleSummary" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "getRoleSummary failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "getRoleSummary failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error52 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error53 error - error53, err = error52.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error53 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "getRoleSummary failed: invalid message type") - return - } - result := ReadOnlySchedulerGetRoleSummaryResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Returns a summary of jobs, optionally only those owned by a specific role. -// -// Parameters: -// - Role -func (p *ReadOnlySchedulerClient) GetJobSummary(role string) (r *Response, err error) { - if err = p.sendGetJobSummary(role); err != nil { - return - } - return p.recvGetJobSummary() -} - -func (p *ReadOnlySchedulerClient) sendGetJobSummary(role string) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("getJobSummary", thrift.CALL, p.SeqId); err != nil { - return - } - args := ReadOnlySchedulerGetJobSummaryArgs{ - Role: role, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *ReadOnlySchedulerClient) recvGetJobSummary() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "getJobSummary" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "getJobSummary failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "getJobSummary failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error54 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error55 error - error55, err = error54.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error55 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "getJobSummary failed: invalid message type") - return - } - result := ReadOnlySchedulerGetJobSummaryResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Fetches the status of tasks. -// -// Parameters: -// - Query -func (p *ReadOnlySchedulerClient) GetTasksStatus(query *TaskQuery) (r *Response, err error) { - if err = p.sendGetTasksStatus(query); err != nil { - return - } - return p.recvGetTasksStatus() -} - -func (p *ReadOnlySchedulerClient) sendGetTasksStatus(query *TaskQuery) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("getTasksStatus", thrift.CALL, p.SeqId); err != nil { - return - } - args := ReadOnlySchedulerGetTasksStatusArgs{ - Query: query, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *ReadOnlySchedulerClient) recvGetTasksStatus() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "getTasksStatus" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "getTasksStatus failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "getTasksStatus failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error56 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error57 error - error57, err = error56.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error57 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "getTasksStatus failed: invalid message type") - return - } - result := ReadOnlySchedulerGetTasksStatusResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Same as getTaskStatus but without the TaskConfig.ExecutorConfig data set. -// This is an interim solution until we have a better way to query TaskConfigs (AURORA-541). -// -// Parameters: -// - Query -func (p *ReadOnlySchedulerClient) GetTasksWithoutConfigs(query *TaskQuery) (r *Response, err error) { - if err = p.sendGetTasksWithoutConfigs(query); err != nil { - return - } - return p.recvGetTasksWithoutConfigs() -} - -func (p *ReadOnlySchedulerClient) sendGetTasksWithoutConfigs(query *TaskQuery) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("getTasksWithoutConfigs", thrift.CALL, p.SeqId); err != nil { - return - } - args := ReadOnlySchedulerGetTasksWithoutConfigsArgs{ - Query: query, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *ReadOnlySchedulerClient) recvGetTasksWithoutConfigs() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "getTasksWithoutConfigs" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "getTasksWithoutConfigs failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "getTasksWithoutConfigs failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error58 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error59 error - error59, err = error58.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error59 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "getTasksWithoutConfigs failed: invalid message type") - return - } - result := ReadOnlySchedulerGetTasksWithoutConfigsResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Returns user-friendly reasons (if available) for tasks retained in PENDING state. -// -// Parameters: -// - Query -func (p *ReadOnlySchedulerClient) GetPendingReason(query *TaskQuery) (r *Response, err error) { - if err = p.sendGetPendingReason(query); err != nil { - return - } - return p.recvGetPendingReason() -} - -func (p *ReadOnlySchedulerClient) sendGetPendingReason(query *TaskQuery) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("getPendingReason", thrift.CALL, p.SeqId); err != nil { - return - } - args := ReadOnlySchedulerGetPendingReasonArgs{ - Query: query, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *ReadOnlySchedulerClient) recvGetPendingReason() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "getPendingReason" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "getPendingReason failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "getPendingReason failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error60 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error61 error - error61, err = error60.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error61 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "getPendingReason failed: invalid message type") - return - } - result := ReadOnlySchedulerGetPendingReasonResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Fetches the configuration summary of active tasks for the specified job. -// -// Parameters: -// - Job -func (p *ReadOnlySchedulerClient) GetConfigSummary(job *JobKey) (r *Response, err error) { - if err = p.sendGetConfigSummary(job); err != nil { - return - } - return p.recvGetConfigSummary() -} - -func (p *ReadOnlySchedulerClient) sendGetConfigSummary(job *JobKey) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("getConfigSummary", thrift.CALL, p.SeqId); err != nil { - return - } - args := ReadOnlySchedulerGetConfigSummaryArgs{ - Job: job, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *ReadOnlySchedulerClient) recvGetConfigSummary() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "getConfigSummary" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "getConfigSummary failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "getConfigSummary failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error62 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error63 error - error63, err = error62.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error63 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "getConfigSummary failed: invalid message type") - return - } - result := ReadOnlySchedulerGetConfigSummaryResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Fetches the status of jobs. -// ownerRole is optional, in which case all jobs are returned. -// -// Parameters: -// - OwnerRole -func (p *ReadOnlySchedulerClient) GetJobs(ownerRole string) (r *Response, err error) { - if err = p.sendGetJobs(ownerRole); err != nil { - return - } - return p.recvGetJobs() -} - -func (p *ReadOnlySchedulerClient) sendGetJobs(ownerRole string) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("getJobs", thrift.CALL, p.SeqId); err != nil { - return - } - args := ReadOnlySchedulerGetJobsArgs{ - OwnerRole: ownerRole, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *ReadOnlySchedulerClient) recvGetJobs() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "getJobs" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "getJobs failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "getJobs failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error64 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error65 error - error65, err = error64.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error65 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "getJobs failed: invalid message type") - return - } - result := ReadOnlySchedulerGetJobsResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Fetches the quota allocated for a user. -// -// Parameters: -// - OwnerRole -func (p *ReadOnlySchedulerClient) GetQuota(ownerRole string) (r *Response, err error) { - if err = p.sendGetQuota(ownerRole); err != nil { - return - } - return p.recvGetQuota() -} - -func (p *ReadOnlySchedulerClient) sendGetQuota(ownerRole string) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("getQuota", thrift.CALL, p.SeqId); err != nil { - return - } - args := ReadOnlySchedulerGetQuotaArgs{ - OwnerRole: ownerRole, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *ReadOnlySchedulerClient) recvGetQuota() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "getQuota" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "getQuota failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "getQuota failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error66 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error67 error - error67, err = error66.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error67 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "getQuota failed: invalid message type") - return - } - result := ReadOnlySchedulerGetQuotaResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Populates fields in a job configuration as though it were about to be run. -// This can be used to diff a configuration running tasks. -// -// Parameters: -// - Description -func (p *ReadOnlySchedulerClient) PopulateJobConfig(description *JobConfiguration) (r *Response, err error) { - if err = p.sendPopulateJobConfig(description); err != nil { - return - } - return p.recvPopulateJobConfig() -} - -func (p *ReadOnlySchedulerClient) sendPopulateJobConfig(description *JobConfiguration) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("populateJobConfig", thrift.CALL, p.SeqId); err != nil { - return - } - args := ReadOnlySchedulerPopulateJobConfigArgs{ - Description: description, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *ReadOnlySchedulerClient) recvPopulateJobConfig() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "populateJobConfig" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "populateJobConfig failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "populateJobConfig failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error68 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error69 error - error69, err = error68.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error69 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "populateJobConfig failed: invalid message type") - return - } - result := ReadOnlySchedulerPopulateJobConfigResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Gets job update summaries. -// -// Parameters: -// - JobUpdateQuery -func (p *ReadOnlySchedulerClient) GetJobUpdateSummaries(jobUpdateQuery *JobUpdateQuery) (r *Response, err error) { - if err = p.sendGetJobUpdateSummaries(jobUpdateQuery); err != nil { - return - } - return p.recvGetJobUpdateSummaries() -} - -func (p *ReadOnlySchedulerClient) sendGetJobUpdateSummaries(jobUpdateQuery *JobUpdateQuery) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("getJobUpdateSummaries", thrift.CALL, p.SeqId); err != nil { - return - } - args := ReadOnlySchedulerGetJobUpdateSummariesArgs{ - JobUpdateQuery: jobUpdateQuery, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *ReadOnlySchedulerClient) recvGetJobUpdateSummaries() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "getJobUpdateSummaries" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "getJobUpdateSummaries failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "getJobUpdateSummaries failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error70 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error71 error - error71, err = error70.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error71 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "getJobUpdateSummaries failed: invalid message type") - return - } - result := ReadOnlySchedulerGetJobUpdateSummariesResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Gets job update details. -// -// Parameters: -// - Query -func (p *ReadOnlySchedulerClient) GetJobUpdateDetails(query *JobUpdateQuery) (r *Response, err error) { - if err = p.sendGetJobUpdateDetails(query); err != nil { - return - } - return p.recvGetJobUpdateDetails() -} - -func (p *ReadOnlySchedulerClient) sendGetJobUpdateDetails(query *JobUpdateQuery) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("getJobUpdateDetails", thrift.CALL, p.SeqId); err != nil { - return - } - args := ReadOnlySchedulerGetJobUpdateDetailsArgs{ - Query: query, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *ReadOnlySchedulerClient) recvGetJobUpdateDetails() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "getJobUpdateDetails" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "getJobUpdateDetails failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "getJobUpdateDetails failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error72 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error73 error - error73, err = error72.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error73 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "getJobUpdateDetails failed: invalid message type") - return - } - result := ReadOnlySchedulerGetJobUpdateDetailsResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Gets the diff between client (desired) and server (current) job states. -// -// Parameters: -// - Request -func (p *ReadOnlySchedulerClient) GetJobUpdateDiff(request *JobUpdateRequest) (r *Response, err error) { - if err = p.sendGetJobUpdateDiff(request); err != nil { - return - } - return p.recvGetJobUpdateDiff() -} - -func (p *ReadOnlySchedulerClient) sendGetJobUpdateDiff(request *JobUpdateRequest) (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("getJobUpdateDiff", thrift.CALL, p.SeqId); err != nil { - return - } - args := ReadOnlySchedulerGetJobUpdateDiffArgs{ - Request: request, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *ReadOnlySchedulerClient) recvGetJobUpdateDiff() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "getJobUpdateDiff" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "getJobUpdateDiff failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "getJobUpdateDiff failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error74 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error75 error - error75, err = error74.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error75 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "getJobUpdateDiff failed: invalid message type") - return - } - result := ReadOnlySchedulerGetJobUpdateDiffResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Gets tier configurations. -func (p *ReadOnlySchedulerClient) GetTierConfigs() (r *Response, err error) { - if err = p.sendGetTierConfigs(); err != nil { - return - } - return p.recvGetTierConfigs() -} - -func (p *ReadOnlySchedulerClient) sendGetTierConfigs() (err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("getTierConfigs", thrift.CALL, p.SeqId); err != nil { - return - } - args := ReadOnlySchedulerGetTierConfigsArgs{} - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - -func (p *ReadOnlySchedulerClient) recvGetTierConfigs() (value *Response, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "getTierConfigs" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "getTierConfigs failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "getTierConfigs failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error76 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error77 error - error77, err = error76.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error77 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "getTierConfigs failed: invalid message type") - return - } - result := ReadOnlySchedulerGetTierConfigsResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -type ReadOnlySchedulerProcessor struct { - processorMap map[string]thrift.TProcessorFunction - handler ReadOnlyScheduler -} - -func (p *ReadOnlySchedulerProcessor) AddToProcessorMap(key string, processor thrift.TProcessorFunction) { - p.processorMap[key] = processor -} - -func (p *ReadOnlySchedulerProcessor) GetProcessorFunction(key string) (processor thrift.TProcessorFunction, ok bool) { - processor, ok = p.processorMap[key] - return processor, ok -} - -func (p *ReadOnlySchedulerProcessor) ProcessorMap() map[string]thrift.TProcessorFunction { - return p.processorMap -} - -func NewReadOnlySchedulerProcessor(handler ReadOnlyScheduler) *ReadOnlySchedulerProcessor { - - self78 := &ReadOnlySchedulerProcessor{handler: handler, processorMap: make(map[string]thrift.TProcessorFunction)} - self78.processorMap["getRoleSummary"] = &readOnlySchedulerProcessorGetRoleSummary{handler: handler} - self78.processorMap["getJobSummary"] = &readOnlySchedulerProcessorGetJobSummary{handler: handler} - self78.processorMap["getTasksStatus"] = &readOnlySchedulerProcessorGetTasksStatus{handler: handler} - self78.processorMap["getTasksWithoutConfigs"] = &readOnlySchedulerProcessorGetTasksWithoutConfigs{handler: handler} - self78.processorMap["getPendingReason"] = &readOnlySchedulerProcessorGetPendingReason{handler: handler} - self78.processorMap["getConfigSummary"] = &readOnlySchedulerProcessorGetConfigSummary{handler: handler} - self78.processorMap["getJobs"] = &readOnlySchedulerProcessorGetJobs{handler: handler} - self78.processorMap["getQuota"] = &readOnlySchedulerProcessorGetQuota{handler: handler} - self78.processorMap["populateJobConfig"] = &readOnlySchedulerProcessorPopulateJobConfig{handler: handler} - self78.processorMap["getJobUpdateSummaries"] = &readOnlySchedulerProcessorGetJobUpdateSummaries{handler: handler} - self78.processorMap["getJobUpdateDetails"] = &readOnlySchedulerProcessorGetJobUpdateDetails{handler: handler} - self78.processorMap["getJobUpdateDiff"] = &readOnlySchedulerProcessorGetJobUpdateDiff{handler: handler} - self78.processorMap["getTierConfigs"] = &readOnlySchedulerProcessorGetTierConfigs{handler: handler} - return self78 -} - -func (p *ReadOnlySchedulerProcessor) Process(iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - name, _, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return false, err - } - if processor, ok := p.GetProcessorFunction(name); ok { - return processor.Process(seqId, iprot, oprot) - } - iprot.Skip(thrift.STRUCT) - iprot.ReadMessageEnd() - x79 := thrift.NewTApplicationException(thrift.UNKNOWN_METHOD, "Unknown function "+name) - oprot.WriteMessageBegin(name, thrift.EXCEPTION, seqId) - x79.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, x79 - -} - -type readOnlySchedulerProcessorGetRoleSummary struct { - handler ReadOnlyScheduler -} - -func (p *readOnlySchedulerProcessorGetRoleSummary) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := ReadOnlySchedulerGetRoleSummaryArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("getRoleSummary", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := ReadOnlySchedulerGetRoleSummaryResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.GetRoleSummary(); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getRoleSummary: "+err2.Error()) - oprot.WriteMessageBegin("getRoleSummary", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("getRoleSummary", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type readOnlySchedulerProcessorGetJobSummary struct { - handler ReadOnlyScheduler -} - -func (p *readOnlySchedulerProcessorGetJobSummary) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := ReadOnlySchedulerGetJobSummaryArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("getJobSummary", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := ReadOnlySchedulerGetJobSummaryResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.GetJobSummary(args.Role); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getJobSummary: "+err2.Error()) - oprot.WriteMessageBegin("getJobSummary", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("getJobSummary", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type readOnlySchedulerProcessorGetTasksStatus struct { - handler ReadOnlyScheduler -} - -func (p *readOnlySchedulerProcessorGetTasksStatus) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := ReadOnlySchedulerGetTasksStatusArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("getTasksStatus", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := ReadOnlySchedulerGetTasksStatusResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.GetTasksStatus(args.Query); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getTasksStatus: "+err2.Error()) - oprot.WriteMessageBegin("getTasksStatus", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("getTasksStatus", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type readOnlySchedulerProcessorGetTasksWithoutConfigs struct { - handler ReadOnlyScheduler -} - -func (p *readOnlySchedulerProcessorGetTasksWithoutConfigs) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := ReadOnlySchedulerGetTasksWithoutConfigsArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("getTasksWithoutConfigs", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := ReadOnlySchedulerGetTasksWithoutConfigsResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.GetTasksWithoutConfigs(args.Query); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getTasksWithoutConfigs: "+err2.Error()) - oprot.WriteMessageBegin("getTasksWithoutConfigs", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("getTasksWithoutConfigs", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type readOnlySchedulerProcessorGetPendingReason struct { - handler ReadOnlyScheduler -} - -func (p *readOnlySchedulerProcessorGetPendingReason) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := ReadOnlySchedulerGetPendingReasonArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("getPendingReason", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := ReadOnlySchedulerGetPendingReasonResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.GetPendingReason(args.Query); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getPendingReason: "+err2.Error()) - oprot.WriteMessageBegin("getPendingReason", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("getPendingReason", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type readOnlySchedulerProcessorGetConfigSummary struct { - handler ReadOnlyScheduler -} - -func (p *readOnlySchedulerProcessorGetConfigSummary) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := ReadOnlySchedulerGetConfigSummaryArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("getConfigSummary", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := ReadOnlySchedulerGetConfigSummaryResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.GetConfigSummary(args.Job); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getConfigSummary: "+err2.Error()) - oprot.WriteMessageBegin("getConfigSummary", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("getConfigSummary", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type readOnlySchedulerProcessorGetJobs struct { - handler ReadOnlyScheduler -} - -func (p *readOnlySchedulerProcessorGetJobs) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := ReadOnlySchedulerGetJobsArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("getJobs", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := ReadOnlySchedulerGetJobsResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.GetJobs(args.OwnerRole); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getJobs: "+err2.Error()) - oprot.WriteMessageBegin("getJobs", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("getJobs", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type readOnlySchedulerProcessorGetQuota struct { - handler ReadOnlyScheduler -} - -func (p *readOnlySchedulerProcessorGetQuota) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := ReadOnlySchedulerGetQuotaArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("getQuota", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := ReadOnlySchedulerGetQuotaResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.GetQuota(args.OwnerRole); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getQuota: "+err2.Error()) - oprot.WriteMessageBegin("getQuota", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("getQuota", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type readOnlySchedulerProcessorPopulateJobConfig struct { - handler ReadOnlyScheduler -} - -func (p *readOnlySchedulerProcessorPopulateJobConfig) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := ReadOnlySchedulerPopulateJobConfigArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("populateJobConfig", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := ReadOnlySchedulerPopulateJobConfigResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.PopulateJobConfig(args.Description); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing populateJobConfig: "+err2.Error()) - oprot.WriteMessageBegin("populateJobConfig", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("populateJobConfig", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type readOnlySchedulerProcessorGetJobUpdateSummaries struct { - handler ReadOnlyScheduler -} - -func (p *readOnlySchedulerProcessorGetJobUpdateSummaries) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := ReadOnlySchedulerGetJobUpdateSummariesArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("getJobUpdateSummaries", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := ReadOnlySchedulerGetJobUpdateSummariesResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.GetJobUpdateSummaries(args.JobUpdateQuery); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getJobUpdateSummaries: "+err2.Error()) - oprot.WriteMessageBegin("getJobUpdateSummaries", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("getJobUpdateSummaries", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type readOnlySchedulerProcessorGetJobUpdateDetails struct { - handler ReadOnlyScheduler -} - -func (p *readOnlySchedulerProcessorGetJobUpdateDetails) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := ReadOnlySchedulerGetJobUpdateDetailsArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("getJobUpdateDetails", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := ReadOnlySchedulerGetJobUpdateDetailsResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.GetJobUpdateDetails(args.Query); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getJobUpdateDetails: "+err2.Error()) - oprot.WriteMessageBegin("getJobUpdateDetails", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("getJobUpdateDetails", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type readOnlySchedulerProcessorGetJobUpdateDiff struct { - handler ReadOnlyScheduler -} - -func (p *readOnlySchedulerProcessorGetJobUpdateDiff) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := ReadOnlySchedulerGetJobUpdateDiffArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("getJobUpdateDiff", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := ReadOnlySchedulerGetJobUpdateDiffResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.GetJobUpdateDiff(args.Request); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getJobUpdateDiff: "+err2.Error()) - oprot.WriteMessageBegin("getJobUpdateDiff", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("getJobUpdateDiff", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type readOnlySchedulerProcessorGetTierConfigs struct { - handler ReadOnlyScheduler -} - -func (p *readOnlySchedulerProcessorGetTierConfigs) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := ReadOnlySchedulerGetTierConfigsArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("getTierConfigs", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := ReadOnlySchedulerGetTierConfigsResult{} - var retval *Response - var err2 error - if retval, err2 = p.handler.GetTierConfigs(); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getTierConfigs: "+err2.Error()) - oprot.WriteMessageBegin("getTierConfigs", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval - } - if err2 = oprot.WriteMessageBegin("getTierConfigs", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -// HELPER FUNCTIONS AND STRUCTURES - -type ReadOnlySchedulerGetRoleSummaryArgs struct { -} - -func NewReadOnlySchedulerGetRoleSummaryArgs() *ReadOnlySchedulerGetRoleSummaryArgs { - return &ReadOnlySchedulerGetRoleSummaryArgs{} -} - -func (p *ReadOnlySchedulerGetRoleSummaryArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetRoleSummaryArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getRoleSummary_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetRoleSummaryArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetRoleSummaryArgs(%+v)", *p) -} - -// Attributes: -// - Success -type ReadOnlySchedulerGetRoleSummaryResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewReadOnlySchedulerGetRoleSummaryResult() *ReadOnlySchedulerGetRoleSummaryResult { - return &ReadOnlySchedulerGetRoleSummaryResult{} -} - -var ReadOnlySchedulerGetRoleSummaryResult_Success_DEFAULT *Response - -func (p *ReadOnlySchedulerGetRoleSummaryResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return ReadOnlySchedulerGetRoleSummaryResult_Success_DEFAULT - } - return p.Success -} -func (p *ReadOnlySchedulerGetRoleSummaryResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *ReadOnlySchedulerGetRoleSummaryResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetRoleSummaryResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetRoleSummaryResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getRoleSummary_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetRoleSummaryResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *ReadOnlySchedulerGetRoleSummaryResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetRoleSummaryResult(%+v)", *p) -} - -// Attributes: -// - Role -type ReadOnlySchedulerGetJobSummaryArgs struct { - Role string `thrift:"role,1" json:"role"` -} - -func NewReadOnlySchedulerGetJobSummaryArgs() *ReadOnlySchedulerGetJobSummaryArgs { - return &ReadOnlySchedulerGetJobSummaryArgs{} -} - -func (p *ReadOnlySchedulerGetJobSummaryArgs) GetRole() string { - return p.Role -} -func (p *ReadOnlySchedulerGetJobSummaryArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobSummaryArgs) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Role = v - } - return nil -} - -func (p *ReadOnlySchedulerGetJobSummaryArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getJobSummary_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobSummaryArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("role", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:role: ", p), err) - } - if err := oprot.WriteString(string(p.Role)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.role (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:role: ", p), err) - } - return err -} - -func (p *ReadOnlySchedulerGetJobSummaryArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetJobSummaryArgs(%+v)", *p) -} - -// Attributes: -// - Success -type ReadOnlySchedulerGetJobSummaryResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewReadOnlySchedulerGetJobSummaryResult() *ReadOnlySchedulerGetJobSummaryResult { - return &ReadOnlySchedulerGetJobSummaryResult{} -} - -var ReadOnlySchedulerGetJobSummaryResult_Success_DEFAULT *Response - -func (p *ReadOnlySchedulerGetJobSummaryResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return ReadOnlySchedulerGetJobSummaryResult_Success_DEFAULT - } - return p.Success -} -func (p *ReadOnlySchedulerGetJobSummaryResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *ReadOnlySchedulerGetJobSummaryResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobSummaryResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobSummaryResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getJobSummary_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobSummaryResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *ReadOnlySchedulerGetJobSummaryResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetJobSummaryResult(%+v)", *p) -} - -// Attributes: -// - Query -type ReadOnlySchedulerGetTasksStatusArgs struct { - Query *TaskQuery `thrift:"query,1" json:"query"` -} - -func NewReadOnlySchedulerGetTasksStatusArgs() *ReadOnlySchedulerGetTasksStatusArgs { - return &ReadOnlySchedulerGetTasksStatusArgs{} -} - -var ReadOnlySchedulerGetTasksStatusArgs_Query_DEFAULT *TaskQuery - -func (p *ReadOnlySchedulerGetTasksStatusArgs) GetQuery() *TaskQuery { - if !p.IsSetQuery() { - return ReadOnlySchedulerGetTasksStatusArgs_Query_DEFAULT - } - return p.Query -} -func (p *ReadOnlySchedulerGetTasksStatusArgs) IsSetQuery() bool { - return p.Query != nil -} - -func (p *ReadOnlySchedulerGetTasksStatusArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetTasksStatusArgs) readField1(iprot thrift.TProtocol) error { - p.Query = &TaskQuery{} - if err := p.Query.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Query), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetTasksStatusArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getTasksStatus_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetTasksStatusArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("query", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:query: ", p), err) - } - if err := p.Query.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Query), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:query: ", p), err) - } - return err -} - -func (p *ReadOnlySchedulerGetTasksStatusArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetTasksStatusArgs(%+v)", *p) -} - -// Attributes: -// - Success -type ReadOnlySchedulerGetTasksStatusResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewReadOnlySchedulerGetTasksStatusResult() *ReadOnlySchedulerGetTasksStatusResult { - return &ReadOnlySchedulerGetTasksStatusResult{} -} - -var ReadOnlySchedulerGetTasksStatusResult_Success_DEFAULT *Response - -func (p *ReadOnlySchedulerGetTasksStatusResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return ReadOnlySchedulerGetTasksStatusResult_Success_DEFAULT - } - return p.Success -} -func (p *ReadOnlySchedulerGetTasksStatusResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *ReadOnlySchedulerGetTasksStatusResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetTasksStatusResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetTasksStatusResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getTasksStatus_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetTasksStatusResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *ReadOnlySchedulerGetTasksStatusResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetTasksStatusResult(%+v)", *p) -} - -// Attributes: -// - Query -type ReadOnlySchedulerGetTasksWithoutConfigsArgs struct { - Query *TaskQuery `thrift:"query,1" json:"query"` -} - -func NewReadOnlySchedulerGetTasksWithoutConfigsArgs() *ReadOnlySchedulerGetTasksWithoutConfigsArgs { - return &ReadOnlySchedulerGetTasksWithoutConfigsArgs{} -} - -var ReadOnlySchedulerGetTasksWithoutConfigsArgs_Query_DEFAULT *TaskQuery - -func (p *ReadOnlySchedulerGetTasksWithoutConfigsArgs) GetQuery() *TaskQuery { - if !p.IsSetQuery() { - return ReadOnlySchedulerGetTasksWithoutConfigsArgs_Query_DEFAULT - } - return p.Query -} -func (p *ReadOnlySchedulerGetTasksWithoutConfigsArgs) IsSetQuery() bool { - return p.Query != nil -} - -func (p *ReadOnlySchedulerGetTasksWithoutConfigsArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetTasksWithoutConfigsArgs) readField1(iprot thrift.TProtocol) error { - p.Query = &TaskQuery{} - if err := p.Query.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Query), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetTasksWithoutConfigsArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getTasksWithoutConfigs_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetTasksWithoutConfigsArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("query", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:query: ", p), err) - } - if err := p.Query.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Query), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:query: ", p), err) - } - return err -} - -func (p *ReadOnlySchedulerGetTasksWithoutConfigsArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetTasksWithoutConfigsArgs(%+v)", *p) -} - -// Attributes: -// - Success -type ReadOnlySchedulerGetTasksWithoutConfigsResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewReadOnlySchedulerGetTasksWithoutConfigsResult() *ReadOnlySchedulerGetTasksWithoutConfigsResult { - return &ReadOnlySchedulerGetTasksWithoutConfigsResult{} -} - -var ReadOnlySchedulerGetTasksWithoutConfigsResult_Success_DEFAULT *Response - -func (p *ReadOnlySchedulerGetTasksWithoutConfigsResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return ReadOnlySchedulerGetTasksWithoutConfigsResult_Success_DEFAULT - } - return p.Success -} -func (p *ReadOnlySchedulerGetTasksWithoutConfigsResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *ReadOnlySchedulerGetTasksWithoutConfigsResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetTasksWithoutConfigsResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetTasksWithoutConfigsResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getTasksWithoutConfigs_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetTasksWithoutConfigsResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *ReadOnlySchedulerGetTasksWithoutConfigsResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetTasksWithoutConfigsResult(%+v)", *p) -} - -// Attributes: -// - Query -type ReadOnlySchedulerGetPendingReasonArgs struct { - Query *TaskQuery `thrift:"query,1" json:"query"` -} - -func NewReadOnlySchedulerGetPendingReasonArgs() *ReadOnlySchedulerGetPendingReasonArgs { - return &ReadOnlySchedulerGetPendingReasonArgs{} -} - -var ReadOnlySchedulerGetPendingReasonArgs_Query_DEFAULT *TaskQuery - -func (p *ReadOnlySchedulerGetPendingReasonArgs) GetQuery() *TaskQuery { - if !p.IsSetQuery() { - return ReadOnlySchedulerGetPendingReasonArgs_Query_DEFAULT - } - return p.Query -} -func (p *ReadOnlySchedulerGetPendingReasonArgs) IsSetQuery() bool { - return p.Query != nil -} - -func (p *ReadOnlySchedulerGetPendingReasonArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetPendingReasonArgs) readField1(iprot thrift.TProtocol) error { - p.Query = &TaskQuery{} - if err := p.Query.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Query), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetPendingReasonArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getPendingReason_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetPendingReasonArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("query", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:query: ", p), err) - } - if err := p.Query.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Query), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:query: ", p), err) - } - return err -} - -func (p *ReadOnlySchedulerGetPendingReasonArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetPendingReasonArgs(%+v)", *p) -} - -// Attributes: -// - Success -type ReadOnlySchedulerGetPendingReasonResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewReadOnlySchedulerGetPendingReasonResult() *ReadOnlySchedulerGetPendingReasonResult { - return &ReadOnlySchedulerGetPendingReasonResult{} -} - -var ReadOnlySchedulerGetPendingReasonResult_Success_DEFAULT *Response - -func (p *ReadOnlySchedulerGetPendingReasonResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return ReadOnlySchedulerGetPendingReasonResult_Success_DEFAULT - } - return p.Success -} -func (p *ReadOnlySchedulerGetPendingReasonResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *ReadOnlySchedulerGetPendingReasonResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetPendingReasonResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetPendingReasonResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getPendingReason_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetPendingReasonResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *ReadOnlySchedulerGetPendingReasonResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetPendingReasonResult(%+v)", *p) -} - -// Attributes: -// - Job -type ReadOnlySchedulerGetConfigSummaryArgs struct { - Job *JobKey `thrift:"job,1" json:"job"` -} - -func NewReadOnlySchedulerGetConfigSummaryArgs() *ReadOnlySchedulerGetConfigSummaryArgs { - return &ReadOnlySchedulerGetConfigSummaryArgs{} -} - -var ReadOnlySchedulerGetConfigSummaryArgs_Job_DEFAULT *JobKey - -func (p *ReadOnlySchedulerGetConfigSummaryArgs) GetJob() *JobKey { - if !p.IsSetJob() { - return ReadOnlySchedulerGetConfigSummaryArgs_Job_DEFAULT - } - return p.Job -} -func (p *ReadOnlySchedulerGetConfigSummaryArgs) IsSetJob() bool { - return p.Job != nil -} - -func (p *ReadOnlySchedulerGetConfigSummaryArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetConfigSummaryArgs) readField1(iprot thrift.TProtocol) error { - p.Job = &JobKey{} - if err := p.Job.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Job), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetConfigSummaryArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getConfigSummary_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetConfigSummaryArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("job", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:job: ", p), err) - } - if err := p.Job.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Job), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:job: ", p), err) - } - return err -} - -func (p *ReadOnlySchedulerGetConfigSummaryArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetConfigSummaryArgs(%+v)", *p) -} - -// Attributes: -// - Success -type ReadOnlySchedulerGetConfigSummaryResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewReadOnlySchedulerGetConfigSummaryResult() *ReadOnlySchedulerGetConfigSummaryResult { - return &ReadOnlySchedulerGetConfigSummaryResult{} -} - -var ReadOnlySchedulerGetConfigSummaryResult_Success_DEFAULT *Response - -func (p *ReadOnlySchedulerGetConfigSummaryResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return ReadOnlySchedulerGetConfigSummaryResult_Success_DEFAULT - } - return p.Success -} -func (p *ReadOnlySchedulerGetConfigSummaryResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *ReadOnlySchedulerGetConfigSummaryResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetConfigSummaryResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetConfigSummaryResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getConfigSummary_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetConfigSummaryResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *ReadOnlySchedulerGetConfigSummaryResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetConfigSummaryResult(%+v)", *p) -} - -// Attributes: -// - OwnerRole -type ReadOnlySchedulerGetJobsArgs struct { - OwnerRole string `thrift:"ownerRole,1" json:"ownerRole"` -} - -func NewReadOnlySchedulerGetJobsArgs() *ReadOnlySchedulerGetJobsArgs { - return &ReadOnlySchedulerGetJobsArgs{} -} - -func (p *ReadOnlySchedulerGetJobsArgs) GetOwnerRole() string { - return p.OwnerRole -} -func (p *ReadOnlySchedulerGetJobsArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobsArgs) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.OwnerRole = v - } - return nil -} - -func (p *ReadOnlySchedulerGetJobsArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getJobs_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobsArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("ownerRole", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:ownerRole: ", p), err) - } - if err := oprot.WriteString(string(p.OwnerRole)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.ownerRole (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:ownerRole: ", p), err) - } - return err -} - -func (p *ReadOnlySchedulerGetJobsArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetJobsArgs(%+v)", *p) -} - -// Attributes: -// - Success -type ReadOnlySchedulerGetJobsResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewReadOnlySchedulerGetJobsResult() *ReadOnlySchedulerGetJobsResult { - return &ReadOnlySchedulerGetJobsResult{} -} - -var ReadOnlySchedulerGetJobsResult_Success_DEFAULT *Response - -func (p *ReadOnlySchedulerGetJobsResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return ReadOnlySchedulerGetJobsResult_Success_DEFAULT - } - return p.Success -} -func (p *ReadOnlySchedulerGetJobsResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *ReadOnlySchedulerGetJobsResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobsResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobsResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getJobs_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobsResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *ReadOnlySchedulerGetJobsResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetJobsResult(%+v)", *p) -} - -// Attributes: -// - OwnerRole -type ReadOnlySchedulerGetQuotaArgs struct { - OwnerRole string `thrift:"ownerRole,1" json:"ownerRole"` -} - -func NewReadOnlySchedulerGetQuotaArgs() *ReadOnlySchedulerGetQuotaArgs { - return &ReadOnlySchedulerGetQuotaArgs{} -} - -func (p *ReadOnlySchedulerGetQuotaArgs) GetOwnerRole() string { - return p.OwnerRole -} -func (p *ReadOnlySchedulerGetQuotaArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetQuotaArgs) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.OwnerRole = v - } - return nil -} - -func (p *ReadOnlySchedulerGetQuotaArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getQuota_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetQuotaArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("ownerRole", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:ownerRole: ", p), err) - } - if err := oprot.WriteString(string(p.OwnerRole)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.ownerRole (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:ownerRole: ", p), err) - } - return err -} - -func (p *ReadOnlySchedulerGetQuotaArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetQuotaArgs(%+v)", *p) -} - -// Attributes: -// - Success -type ReadOnlySchedulerGetQuotaResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewReadOnlySchedulerGetQuotaResult() *ReadOnlySchedulerGetQuotaResult { - return &ReadOnlySchedulerGetQuotaResult{} -} - -var ReadOnlySchedulerGetQuotaResult_Success_DEFAULT *Response - -func (p *ReadOnlySchedulerGetQuotaResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return ReadOnlySchedulerGetQuotaResult_Success_DEFAULT - } - return p.Success -} -func (p *ReadOnlySchedulerGetQuotaResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *ReadOnlySchedulerGetQuotaResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetQuotaResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetQuotaResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getQuota_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetQuotaResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *ReadOnlySchedulerGetQuotaResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetQuotaResult(%+v)", *p) -} - -// Attributes: -// - Description -type ReadOnlySchedulerPopulateJobConfigArgs struct { - Description *JobConfiguration `thrift:"description,1" json:"description"` -} - -func NewReadOnlySchedulerPopulateJobConfigArgs() *ReadOnlySchedulerPopulateJobConfigArgs { - return &ReadOnlySchedulerPopulateJobConfigArgs{} -} - -var ReadOnlySchedulerPopulateJobConfigArgs_Description_DEFAULT *JobConfiguration - -func (p *ReadOnlySchedulerPopulateJobConfigArgs) GetDescription() *JobConfiguration { - if !p.IsSetDescription() { - return ReadOnlySchedulerPopulateJobConfigArgs_Description_DEFAULT - } - return p.Description -} -func (p *ReadOnlySchedulerPopulateJobConfigArgs) IsSetDescription() bool { - return p.Description != nil -} - -func (p *ReadOnlySchedulerPopulateJobConfigArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerPopulateJobConfigArgs) readField1(iprot thrift.TProtocol) error { - p.Description = &JobConfiguration{} - if err := p.Description.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Description), err) - } - return nil -} - -func (p *ReadOnlySchedulerPopulateJobConfigArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("populateJobConfig_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerPopulateJobConfigArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("description", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:description: ", p), err) - } - if err := p.Description.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Description), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:description: ", p), err) - } - return err -} - -func (p *ReadOnlySchedulerPopulateJobConfigArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerPopulateJobConfigArgs(%+v)", *p) -} - -// Attributes: -// - Success -type ReadOnlySchedulerPopulateJobConfigResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewReadOnlySchedulerPopulateJobConfigResult() *ReadOnlySchedulerPopulateJobConfigResult { - return &ReadOnlySchedulerPopulateJobConfigResult{} -} - -var ReadOnlySchedulerPopulateJobConfigResult_Success_DEFAULT *Response - -func (p *ReadOnlySchedulerPopulateJobConfigResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return ReadOnlySchedulerPopulateJobConfigResult_Success_DEFAULT - } - return p.Success -} -func (p *ReadOnlySchedulerPopulateJobConfigResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *ReadOnlySchedulerPopulateJobConfigResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerPopulateJobConfigResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *ReadOnlySchedulerPopulateJobConfigResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("populateJobConfig_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerPopulateJobConfigResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *ReadOnlySchedulerPopulateJobConfigResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerPopulateJobConfigResult(%+v)", *p) -} - -// Attributes: -// - JobUpdateQuery -type ReadOnlySchedulerGetJobUpdateSummariesArgs struct { - JobUpdateQuery *JobUpdateQuery `thrift:"jobUpdateQuery,1" json:"jobUpdateQuery"` -} - -func NewReadOnlySchedulerGetJobUpdateSummariesArgs() *ReadOnlySchedulerGetJobUpdateSummariesArgs { - return &ReadOnlySchedulerGetJobUpdateSummariesArgs{} -} - -var ReadOnlySchedulerGetJobUpdateSummariesArgs_JobUpdateQuery_DEFAULT *JobUpdateQuery - -func (p *ReadOnlySchedulerGetJobUpdateSummariesArgs) GetJobUpdateQuery() *JobUpdateQuery { - if !p.IsSetJobUpdateQuery() { - return ReadOnlySchedulerGetJobUpdateSummariesArgs_JobUpdateQuery_DEFAULT - } - return p.JobUpdateQuery -} -func (p *ReadOnlySchedulerGetJobUpdateSummariesArgs) IsSetJobUpdateQuery() bool { - return p.JobUpdateQuery != nil -} - -func (p *ReadOnlySchedulerGetJobUpdateSummariesArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobUpdateSummariesArgs) readField1(iprot thrift.TProtocol) error { - p.JobUpdateQuery = &JobUpdateQuery{} - if err := p.JobUpdateQuery.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.JobUpdateQuery), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobUpdateSummariesArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getJobUpdateSummaries_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobUpdateSummariesArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("jobUpdateQuery", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:jobUpdateQuery: ", p), err) - } - if err := p.JobUpdateQuery.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.JobUpdateQuery), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:jobUpdateQuery: ", p), err) - } - return err -} - -func (p *ReadOnlySchedulerGetJobUpdateSummariesArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetJobUpdateSummariesArgs(%+v)", *p) -} - -// Attributes: -// - Success -type ReadOnlySchedulerGetJobUpdateSummariesResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewReadOnlySchedulerGetJobUpdateSummariesResult() *ReadOnlySchedulerGetJobUpdateSummariesResult { - return &ReadOnlySchedulerGetJobUpdateSummariesResult{} -} - -var ReadOnlySchedulerGetJobUpdateSummariesResult_Success_DEFAULT *Response - -func (p *ReadOnlySchedulerGetJobUpdateSummariesResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return ReadOnlySchedulerGetJobUpdateSummariesResult_Success_DEFAULT - } - return p.Success -} -func (p *ReadOnlySchedulerGetJobUpdateSummariesResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *ReadOnlySchedulerGetJobUpdateSummariesResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobUpdateSummariesResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobUpdateSummariesResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getJobUpdateSummaries_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobUpdateSummariesResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *ReadOnlySchedulerGetJobUpdateSummariesResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetJobUpdateSummariesResult(%+v)", *p) -} - -// Attributes: -// - Query -type ReadOnlySchedulerGetJobUpdateDetailsArgs struct { - // unused field # 1 - Query *JobUpdateQuery `thrift:"query,2" json:"query"` -} - -func NewReadOnlySchedulerGetJobUpdateDetailsArgs() *ReadOnlySchedulerGetJobUpdateDetailsArgs { - return &ReadOnlySchedulerGetJobUpdateDetailsArgs{} -} - -var ReadOnlySchedulerGetJobUpdateDetailsArgs_Query_DEFAULT *JobUpdateQuery - -func (p *ReadOnlySchedulerGetJobUpdateDetailsArgs) GetQuery() *JobUpdateQuery { - if !p.IsSetQuery() { - return ReadOnlySchedulerGetJobUpdateDetailsArgs_Query_DEFAULT - } - return p.Query -} -func (p *ReadOnlySchedulerGetJobUpdateDetailsArgs) IsSetQuery() bool { - return p.Query != nil -} - -func (p *ReadOnlySchedulerGetJobUpdateDetailsArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobUpdateDetailsArgs) readField2(iprot thrift.TProtocol) error { - p.Query = &JobUpdateQuery{} - if err := p.Query.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Query), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobUpdateDetailsArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getJobUpdateDetails_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobUpdateDetailsArgs) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("query", thrift.STRUCT, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:query: ", p), err) - } - if err := p.Query.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Query), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:query: ", p), err) - } - return err -} - -func (p *ReadOnlySchedulerGetJobUpdateDetailsArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetJobUpdateDetailsArgs(%+v)", *p) -} - -// Attributes: -// - Success -type ReadOnlySchedulerGetJobUpdateDetailsResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewReadOnlySchedulerGetJobUpdateDetailsResult() *ReadOnlySchedulerGetJobUpdateDetailsResult { - return &ReadOnlySchedulerGetJobUpdateDetailsResult{} -} - -var ReadOnlySchedulerGetJobUpdateDetailsResult_Success_DEFAULT *Response - -func (p *ReadOnlySchedulerGetJobUpdateDetailsResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return ReadOnlySchedulerGetJobUpdateDetailsResult_Success_DEFAULT - } - return p.Success -} -func (p *ReadOnlySchedulerGetJobUpdateDetailsResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *ReadOnlySchedulerGetJobUpdateDetailsResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobUpdateDetailsResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobUpdateDetailsResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getJobUpdateDetails_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobUpdateDetailsResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *ReadOnlySchedulerGetJobUpdateDetailsResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetJobUpdateDetailsResult(%+v)", *p) -} - -// Attributes: -// - Request -type ReadOnlySchedulerGetJobUpdateDiffArgs struct { - Request *JobUpdateRequest `thrift:"request,1" json:"request"` -} - -func NewReadOnlySchedulerGetJobUpdateDiffArgs() *ReadOnlySchedulerGetJobUpdateDiffArgs { - return &ReadOnlySchedulerGetJobUpdateDiffArgs{} -} - -var ReadOnlySchedulerGetJobUpdateDiffArgs_Request_DEFAULT *JobUpdateRequest - -func (p *ReadOnlySchedulerGetJobUpdateDiffArgs) GetRequest() *JobUpdateRequest { - if !p.IsSetRequest() { - return ReadOnlySchedulerGetJobUpdateDiffArgs_Request_DEFAULT - } - return p.Request -} -func (p *ReadOnlySchedulerGetJobUpdateDiffArgs) IsSetRequest() bool { - return p.Request != nil -} - -func (p *ReadOnlySchedulerGetJobUpdateDiffArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobUpdateDiffArgs) readField1(iprot thrift.TProtocol) error { - p.Request = &JobUpdateRequest{} - if err := p.Request.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Request), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobUpdateDiffArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getJobUpdateDiff_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobUpdateDiffArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("request", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:request: ", p), err) - } - if err := p.Request.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Request), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:request: ", p), err) - } - return err -} - -func (p *ReadOnlySchedulerGetJobUpdateDiffArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetJobUpdateDiffArgs(%+v)", *p) -} - -// Attributes: -// - Success -type ReadOnlySchedulerGetJobUpdateDiffResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewReadOnlySchedulerGetJobUpdateDiffResult() *ReadOnlySchedulerGetJobUpdateDiffResult { - return &ReadOnlySchedulerGetJobUpdateDiffResult{} -} - -var ReadOnlySchedulerGetJobUpdateDiffResult_Success_DEFAULT *Response - -func (p *ReadOnlySchedulerGetJobUpdateDiffResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return ReadOnlySchedulerGetJobUpdateDiffResult_Success_DEFAULT - } - return p.Success -} -func (p *ReadOnlySchedulerGetJobUpdateDiffResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *ReadOnlySchedulerGetJobUpdateDiffResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobUpdateDiffResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobUpdateDiffResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getJobUpdateDiff_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetJobUpdateDiffResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *ReadOnlySchedulerGetJobUpdateDiffResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetJobUpdateDiffResult(%+v)", *p) -} - -type ReadOnlySchedulerGetTierConfigsArgs struct { -} - -func NewReadOnlySchedulerGetTierConfigsArgs() *ReadOnlySchedulerGetTierConfigsArgs { - return &ReadOnlySchedulerGetTierConfigsArgs{} -} - -func (p *ReadOnlySchedulerGetTierConfigsArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetTierConfigsArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getTierConfigs_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetTierConfigsArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetTierConfigsArgs(%+v)", *p) -} - -// Attributes: -// - Success -type ReadOnlySchedulerGetTierConfigsResult struct { - Success *Response `thrift:"success,0" json:"success,omitempty"` -} - -func NewReadOnlySchedulerGetTierConfigsResult() *ReadOnlySchedulerGetTierConfigsResult { - return &ReadOnlySchedulerGetTierConfigsResult{} -} - -var ReadOnlySchedulerGetTierConfigsResult_Success_DEFAULT *Response - -func (p *ReadOnlySchedulerGetTierConfigsResult) GetSuccess() *Response { - if !p.IsSetSuccess() { - return ReadOnlySchedulerGetTierConfigsResult_Success_DEFAULT - } - return p.Success -} -func (p *ReadOnlySchedulerGetTierConfigsResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *ReadOnlySchedulerGetTierConfigsResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 0: - if err := p.readField0(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetTierConfigsResult) readField0(iprot thrift.TProtocol) error { - p.Success = &Response{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *ReadOnlySchedulerGetTierConfigsResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("getTierConfigs_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField0(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ReadOnlySchedulerGetTierConfigsResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) - } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) - } - } - return err -} - -func (p *ReadOnlySchedulerGetTierConfigsResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ReadOnlySchedulerGetTierConfigsResult(%+v)", *p) -} diff --git a/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/ttypes.go b/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/ttypes.go deleted file mode 100644 index 1f1d45c..0000000 --- a/vendor/github.com/paypal/gorealis/gen-go/apache/aurora/ttypes.go +++ /dev/null @@ -1,16424 +0,0 @@ -// Autogenerated by Thrift Compiler (0.9.3) -// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - -package aurora - -import ( - "bytes" - "fmt" - "git.apache.org/thrift.git/lib/go/thrift" -) - -// (needed to ensure safety because of naive import list construction.) -var _ = thrift.ZERO -var _ = fmt.Printf -var _ = bytes.Equal - -var GoUnusedProtection__ int - -type ResponseCode int64 - -const ( - ResponseCode_INVALID_REQUEST ResponseCode = 0 - ResponseCode_OK ResponseCode = 1 - ResponseCode_ERROR ResponseCode = 2 - ResponseCode_WARNING ResponseCode = 3 - ResponseCode_AUTH_FAILED ResponseCode = 4 - ResponseCode_JOB_UPDATING_ERROR ResponseCode = 5 - ResponseCode_ERROR_TRANSIENT ResponseCode = 6 -) - -func (p ResponseCode) String() string { - switch p { - case ResponseCode_INVALID_REQUEST: - return "INVALID_REQUEST" - case ResponseCode_OK: - return "OK" - case ResponseCode_ERROR: - return "ERROR" - case ResponseCode_WARNING: - return "WARNING" - case ResponseCode_AUTH_FAILED: - return "AUTH_FAILED" - case ResponseCode_JOB_UPDATING_ERROR: - return "JOB_UPDATING_ERROR" - case ResponseCode_ERROR_TRANSIENT: - return "ERROR_TRANSIENT" - } - return "" -} - -func ResponseCodeFromString(s string) (ResponseCode, error) { - switch s { - case "INVALID_REQUEST": - return ResponseCode_INVALID_REQUEST, nil - case "OK": - return ResponseCode_OK, nil - case "ERROR": - return ResponseCode_ERROR, nil - case "WARNING": - return ResponseCode_WARNING, nil - case "AUTH_FAILED": - return ResponseCode_AUTH_FAILED, nil - case "JOB_UPDATING_ERROR": - return ResponseCode_JOB_UPDATING_ERROR, nil - case "ERROR_TRANSIENT": - return ResponseCode_ERROR_TRANSIENT, nil - } - return ResponseCode(0), fmt.Errorf("not a valid ResponseCode string") -} - -func ResponseCodePtr(v ResponseCode) *ResponseCode { return &v } - -func (p ResponseCode) MarshalText() ([]byte, error) { - return []byte(p.String()), nil -} - -func (p *ResponseCode) UnmarshalText(text []byte) error { - q, err := ResponseCodeFromString(string(text)) - if err != nil { - return err - } - *p = q - return nil -} - -type MaintenanceMode int64 - -const ( - MaintenanceMode_NONE MaintenanceMode = 1 - MaintenanceMode_SCHEDULED MaintenanceMode = 2 - MaintenanceMode_DRAINING MaintenanceMode = 3 - MaintenanceMode_DRAINED MaintenanceMode = 4 -) - -func (p MaintenanceMode) String() string { - switch p { - case MaintenanceMode_NONE: - return "NONE" - case MaintenanceMode_SCHEDULED: - return "SCHEDULED" - case MaintenanceMode_DRAINING: - return "DRAINING" - case MaintenanceMode_DRAINED: - return "DRAINED" - } - return "" -} - -func MaintenanceModeFromString(s string) (MaintenanceMode, error) { - switch s { - case "NONE": - return MaintenanceMode_NONE, nil - case "SCHEDULED": - return MaintenanceMode_SCHEDULED, nil - case "DRAINING": - return MaintenanceMode_DRAINING, nil - case "DRAINED": - return MaintenanceMode_DRAINED, nil - } - return MaintenanceMode(0), fmt.Errorf("not a valid MaintenanceMode string") -} - -func MaintenanceModePtr(v MaintenanceMode) *MaintenanceMode { return &v } - -func (p MaintenanceMode) MarshalText() ([]byte, error) { - return []byte(p.String()), nil -} - -func (p *MaintenanceMode) UnmarshalText(text []byte) error { - q, err := MaintenanceModeFromString(string(text)) - if err != nil { - return err - } - *p = q - return nil -} - -//The mode for a volume mount -type Mode int64 - -const ( - Mode_RW Mode = 1 - Mode_RO Mode = 2 -) - -func (p Mode) String() string { - switch p { - case Mode_RW: - return "RW" - case Mode_RO: - return "RO" - } - return "" -} - -func ModeFromString(s string) (Mode, error) { - switch s { - case "RW": - return Mode_RW, nil - case "RO": - return Mode_RO, nil - } - return Mode(0), fmt.Errorf("not a valid Mode string") -} - -func ModePtr(v Mode) *Mode { return &v } - -func (p Mode) MarshalText() ([]byte, error) { - return []byte(p.String()), nil -} - -func (p *Mode) UnmarshalText(text []byte) error { - q, err := ModeFromString(string(text)) - if err != nil { - return err - } - *p = q - return nil -} - -//Defines the policy for launching a new cron job when one is already running. -type CronCollisionPolicy int64 - -const ( - CronCollisionPolicy_KILL_EXISTING CronCollisionPolicy = 0 - CronCollisionPolicy_CANCEL_NEW CronCollisionPolicy = 1 - CronCollisionPolicy_RUN_OVERLAP CronCollisionPolicy = 2 -) - -func (p CronCollisionPolicy) String() string { - switch p { - case CronCollisionPolicy_KILL_EXISTING: - return "KILL_EXISTING" - case CronCollisionPolicy_CANCEL_NEW: - return "CANCEL_NEW" - case CronCollisionPolicy_RUN_OVERLAP: - return "RUN_OVERLAP" - } - return "" -} - -func CronCollisionPolicyFromString(s string) (CronCollisionPolicy, error) { - switch s { - case "KILL_EXISTING": - return CronCollisionPolicy_KILL_EXISTING, nil - case "CANCEL_NEW": - return CronCollisionPolicy_CANCEL_NEW, nil - case "RUN_OVERLAP": - return CronCollisionPolicy_RUN_OVERLAP, nil - } - return CronCollisionPolicy(0), fmt.Errorf("not a valid CronCollisionPolicy string") -} - -func CronCollisionPolicyPtr(v CronCollisionPolicy) *CronCollisionPolicy { return &v } - -func (p CronCollisionPolicy) MarshalText() ([]byte, error) { - return []byte(p.String()), nil -} - -func (p *CronCollisionPolicy) UnmarshalText(text []byte) error { - q, err := CronCollisionPolicyFromString(string(text)) - if err != nil { - return err - } - *p = q - return nil -} - -//States that a task may be in. -type ScheduleStatus int64 - -const ( - ScheduleStatus_INIT ScheduleStatus = 11 - ScheduleStatus_THROTTLED ScheduleStatus = 16 - ScheduleStatus_PENDING ScheduleStatus = 0 - ScheduleStatus_ASSIGNED ScheduleStatus = 9 - ScheduleStatus_STARTING ScheduleStatus = 1 - ScheduleStatus_RUNNING ScheduleStatus = 2 - ScheduleStatus_FINISHED ScheduleStatus = 3 - ScheduleStatus_PREEMPTING ScheduleStatus = 13 - ScheduleStatus_RESTARTING ScheduleStatus = 12 - ScheduleStatus_DRAINING ScheduleStatus = 17 - ScheduleStatus_FAILED ScheduleStatus = 4 - ScheduleStatus_KILLED ScheduleStatus = 5 - ScheduleStatus_KILLING ScheduleStatus = 6 - ScheduleStatus_LOST ScheduleStatus = 7 - ScheduleStatus_PARTITIONED ScheduleStatus = 18 -) - -func (p ScheduleStatus) String() string { - switch p { - case ScheduleStatus_INIT: - return "INIT" - case ScheduleStatus_THROTTLED: - return "THROTTLED" - case ScheduleStatus_PENDING: - return "PENDING" - case ScheduleStatus_ASSIGNED: - return "ASSIGNED" - case ScheduleStatus_STARTING: - return "STARTING" - case ScheduleStatus_RUNNING: - return "RUNNING" - case ScheduleStatus_FINISHED: - return "FINISHED" - case ScheduleStatus_PREEMPTING: - return "PREEMPTING" - case ScheduleStatus_RESTARTING: - return "RESTARTING" - case ScheduleStatus_DRAINING: - return "DRAINING" - case ScheduleStatus_FAILED: - return "FAILED" - case ScheduleStatus_KILLED: - return "KILLED" - case ScheduleStatus_KILLING: - return "KILLING" - case ScheduleStatus_LOST: - return "LOST" - case ScheduleStatus_PARTITIONED: - return "PARTITIONED" - } - return "" -} - -func ScheduleStatusFromString(s string) (ScheduleStatus, error) { - switch s { - case "INIT": - return ScheduleStatus_INIT, nil - case "THROTTLED": - return ScheduleStatus_THROTTLED, nil - case "PENDING": - return ScheduleStatus_PENDING, nil - case "ASSIGNED": - return ScheduleStatus_ASSIGNED, nil - case "STARTING": - return ScheduleStatus_STARTING, nil - case "RUNNING": - return ScheduleStatus_RUNNING, nil - case "FINISHED": - return ScheduleStatus_FINISHED, nil - case "PREEMPTING": - return ScheduleStatus_PREEMPTING, nil - case "RESTARTING": - return ScheduleStatus_RESTARTING, nil - case "DRAINING": - return ScheduleStatus_DRAINING, nil - case "FAILED": - return ScheduleStatus_FAILED, nil - case "KILLED": - return ScheduleStatus_KILLED, nil - case "KILLING": - return ScheduleStatus_KILLING, nil - case "LOST": - return ScheduleStatus_LOST, nil - case "PARTITIONED": - return ScheduleStatus_PARTITIONED, nil - } - return ScheduleStatus(0), fmt.Errorf("not a valid ScheduleStatus string") -} - -func ScheduleStatusPtr(v ScheduleStatus) *ScheduleStatus { return &v } - -func (p ScheduleStatus) MarshalText() ([]byte, error) { - return []byte(p.String()), nil -} - -func (p *ScheduleStatus) UnmarshalText(text []byte) error { - q, err := ScheduleStatusFromString(string(text)) - if err != nil { - return err - } - *p = q - return nil -} - -//States that a job update may be in. -type JobUpdateStatus int64 - -const ( - JobUpdateStatus_ROLLING_FORWARD JobUpdateStatus = 0 - JobUpdateStatus_ROLLING_BACK JobUpdateStatus = 1 - JobUpdateStatus_ROLL_FORWARD_PAUSED JobUpdateStatus = 2 - JobUpdateStatus_ROLL_BACK_PAUSED JobUpdateStatus = 3 - JobUpdateStatus_ROLLED_FORWARD JobUpdateStatus = 4 - JobUpdateStatus_ROLLED_BACK JobUpdateStatus = 5 - JobUpdateStatus_ABORTED JobUpdateStatus = 6 - JobUpdateStatus_ERROR JobUpdateStatus = 7 - JobUpdateStatus_FAILED JobUpdateStatus = 8 - JobUpdateStatus_ROLL_FORWARD_AWAITING_PULSE JobUpdateStatus = 9 - JobUpdateStatus_ROLL_BACK_AWAITING_PULSE JobUpdateStatus = 10 -) - -func (p JobUpdateStatus) String() string { - switch p { - case JobUpdateStatus_ROLLING_FORWARD: - return "ROLLING_FORWARD" - case JobUpdateStatus_ROLLING_BACK: - return "ROLLING_BACK" - case JobUpdateStatus_ROLL_FORWARD_PAUSED: - return "ROLL_FORWARD_PAUSED" - case JobUpdateStatus_ROLL_BACK_PAUSED: - return "ROLL_BACK_PAUSED" - case JobUpdateStatus_ROLLED_FORWARD: - return "ROLLED_FORWARD" - case JobUpdateStatus_ROLLED_BACK: - return "ROLLED_BACK" - case JobUpdateStatus_ABORTED: - return "ABORTED" - case JobUpdateStatus_ERROR: - return "ERROR" - case JobUpdateStatus_FAILED: - return "FAILED" - case JobUpdateStatus_ROLL_FORWARD_AWAITING_PULSE: - return "ROLL_FORWARD_AWAITING_PULSE" - case JobUpdateStatus_ROLL_BACK_AWAITING_PULSE: - return "ROLL_BACK_AWAITING_PULSE" - } - return "" -} - -func JobUpdateStatusFromString(s string) (JobUpdateStatus, error) { - switch s { - case "ROLLING_FORWARD": - return JobUpdateStatus_ROLLING_FORWARD, nil - case "ROLLING_BACK": - return JobUpdateStatus_ROLLING_BACK, nil - case "ROLL_FORWARD_PAUSED": - return JobUpdateStatus_ROLL_FORWARD_PAUSED, nil - case "ROLL_BACK_PAUSED": - return JobUpdateStatus_ROLL_BACK_PAUSED, nil - case "ROLLED_FORWARD": - return JobUpdateStatus_ROLLED_FORWARD, nil - case "ROLLED_BACK": - return JobUpdateStatus_ROLLED_BACK, nil - case "ABORTED": - return JobUpdateStatus_ABORTED, nil - case "ERROR": - return JobUpdateStatus_ERROR, nil - case "FAILED": - return JobUpdateStatus_FAILED, nil - case "ROLL_FORWARD_AWAITING_PULSE": - return JobUpdateStatus_ROLL_FORWARD_AWAITING_PULSE, nil - case "ROLL_BACK_AWAITING_PULSE": - return JobUpdateStatus_ROLL_BACK_AWAITING_PULSE, nil - } - return JobUpdateStatus(0), fmt.Errorf("not a valid JobUpdateStatus string") -} - -func JobUpdateStatusPtr(v JobUpdateStatus) *JobUpdateStatus { return &v } - -func (p JobUpdateStatus) MarshalText() ([]byte, error) { - return []byte(p.String()), nil -} - -func (p *JobUpdateStatus) UnmarshalText(text []byte) error { - q, err := JobUpdateStatusFromString(string(text)) - if err != nil { - return err - } - *p = q - return nil -} - -//Job update actions that can be applied to job instances. -type JobUpdateAction int64 - -const ( - JobUpdateAction_INSTANCE_UPDATED JobUpdateAction = 1 - JobUpdateAction_INSTANCE_ROLLED_BACK JobUpdateAction = 2 - JobUpdateAction_INSTANCE_UPDATING JobUpdateAction = 3 - JobUpdateAction_INSTANCE_ROLLING_BACK JobUpdateAction = 4 - JobUpdateAction_INSTANCE_UPDATE_FAILED JobUpdateAction = 5 - JobUpdateAction_INSTANCE_ROLLBACK_FAILED JobUpdateAction = 6 -) - -func (p JobUpdateAction) String() string { - switch p { - case JobUpdateAction_INSTANCE_UPDATED: - return "INSTANCE_UPDATED" - case JobUpdateAction_INSTANCE_ROLLED_BACK: - return "INSTANCE_ROLLED_BACK" - case JobUpdateAction_INSTANCE_UPDATING: - return "INSTANCE_UPDATING" - case JobUpdateAction_INSTANCE_ROLLING_BACK: - return "INSTANCE_ROLLING_BACK" - case JobUpdateAction_INSTANCE_UPDATE_FAILED: - return "INSTANCE_UPDATE_FAILED" - case JobUpdateAction_INSTANCE_ROLLBACK_FAILED: - return "INSTANCE_ROLLBACK_FAILED" - } - return "" -} - -func JobUpdateActionFromString(s string) (JobUpdateAction, error) { - switch s { - case "INSTANCE_UPDATED": - return JobUpdateAction_INSTANCE_UPDATED, nil - case "INSTANCE_ROLLED_BACK": - return JobUpdateAction_INSTANCE_ROLLED_BACK, nil - case "INSTANCE_UPDATING": - return JobUpdateAction_INSTANCE_UPDATING, nil - case "INSTANCE_ROLLING_BACK": - return JobUpdateAction_INSTANCE_ROLLING_BACK, nil - case "INSTANCE_UPDATE_FAILED": - return JobUpdateAction_INSTANCE_UPDATE_FAILED, nil - case "INSTANCE_ROLLBACK_FAILED": - return JobUpdateAction_INSTANCE_ROLLBACK_FAILED, nil - } - return JobUpdateAction(0), fmt.Errorf("not a valid JobUpdateAction string") -} - -func JobUpdateActionPtr(v JobUpdateAction) *JobUpdateAction { return &v } - -func (p JobUpdateAction) MarshalText() ([]byte, error) { - return []byte(p.String()), nil -} - -func (p *JobUpdateAction) UnmarshalText(text []byte) error { - q, err := JobUpdateActionFromString(string(text)) - if err != nil { - return err - } - *p = q - return nil -} - -//Status of the coordinated update. Intended as a response to pulseJobUpdate RPC. -type JobUpdatePulseStatus int64 - -const ( - JobUpdatePulseStatus_OK JobUpdatePulseStatus = 1 - JobUpdatePulseStatus_FINISHED JobUpdatePulseStatus = 2 -) - -func (p JobUpdatePulseStatus) String() string { - switch p { - case JobUpdatePulseStatus_OK: - return "OK" - case JobUpdatePulseStatus_FINISHED: - return "FINISHED" - } - return "" -} - -func JobUpdatePulseStatusFromString(s string) (JobUpdatePulseStatus, error) { - switch s { - case "OK": - return JobUpdatePulseStatus_OK, nil - case "FINISHED": - return JobUpdatePulseStatus_FINISHED, nil - } - return JobUpdatePulseStatus(0), fmt.Errorf("not a valid JobUpdatePulseStatus string") -} - -func JobUpdatePulseStatusPtr(v JobUpdatePulseStatus) *JobUpdatePulseStatus { return &v } - -func (p JobUpdatePulseStatus) MarshalText() ([]byte, error) { - return []byte(p.String()), nil -} - -func (p *JobUpdatePulseStatus) UnmarshalText(text []byte) error { - q, err := JobUpdatePulseStatusFromString(string(text)) - if err != nil { - return err - } - *p = q - return nil -} - -// Attributes: -// - User -type Identity struct { - // unused field # 1 - User string `thrift:"user,2" json:"user"` -} - -func NewIdentity() *Identity { - return &Identity{} -} - -func (p *Identity) GetUser() string { - return p.User -} -func (p *Identity) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *Identity) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.User = v - } - return nil -} - -func (p *Identity) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("Identity"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *Identity) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("user", thrift.STRING, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:user: ", p), err) - } - if err := oprot.WriteString(string(p.User)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.user (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:user: ", p), err) - } - return err -} - -func (p *Identity) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("Identity(%+v)", *p) -} - -// A single host attribute. -// -// Attributes: -// - Name -// - Values -type Attribute struct { - Name string `thrift:"name,1" json:"name"` - Values map[string]bool `thrift:"values,2" json:"values"` -} - -func NewAttribute() *Attribute { - return &Attribute{} -} - -func (p *Attribute) GetName() string { - return p.Name -} - -func (p *Attribute) GetValues() map[string]bool { - return p.Values -} -func (p *Attribute) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *Attribute) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Name = v - } - return nil -} - -func (p *Attribute) readField2(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[string]bool, size) - p.Values = tSet - for i := 0; i < size; i++ { - var _elem0 string - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 0: ", err) - } else { - _elem0 = v - } - p.Values[_elem0] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *Attribute) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("Attribute"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *Attribute) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("name", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:name: ", p), err) - } - if err := oprot.WriteString(string(p.Name)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.name (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:name: ", p), err) - } - return err -} - -func (p *Attribute) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("values", thrift.SET, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:values: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRING, len(p.Values)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Values { - if err := oprot.WriteString(string(v)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:values: ", p), err) - } - return err -} - -func (p *Attribute) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("Attribute(%+v)", *p) -} - -// The attributes assigned to a host. -// -// Attributes: -// - Host -// - Attributes -// - Mode -// - SlaveId -type HostAttributes struct { - Host string `thrift:"host,1" json:"host"` - Attributes map[*Attribute]bool `thrift:"attributes,2" json:"attributes"` - Mode *MaintenanceMode `thrift:"mode,3" json:"mode,omitempty"` - SlaveId *string `thrift:"slaveId,4" json:"slaveId,omitempty"` -} - -func NewHostAttributes() *HostAttributes { - return &HostAttributes{} -} - -func (p *HostAttributes) GetHost() string { - return p.Host -} - -func (p *HostAttributes) GetAttributes() map[*Attribute]bool { - return p.Attributes -} - -var HostAttributes_Mode_DEFAULT MaintenanceMode - -func (p *HostAttributes) GetMode() MaintenanceMode { - if !p.IsSetMode() { - return HostAttributes_Mode_DEFAULT - } - return *p.Mode -} - -var HostAttributes_SlaveId_DEFAULT string - -func (p *HostAttributes) GetSlaveId() string { - if !p.IsSetSlaveId() { - return HostAttributes_SlaveId_DEFAULT - } - return *p.SlaveId -} -func (p *HostAttributes) IsSetMode() bool { - return p.Mode != nil -} - -func (p *HostAttributes) IsSetSlaveId() bool { - return p.SlaveId != nil -} - -func (p *HostAttributes) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *HostAttributes) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Host = v - } - return nil -} - -func (p *HostAttributes) readField2(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*Attribute]bool, size) - p.Attributes = tSet - for i := 0; i < size; i++ { - _elem1 := &Attribute{} - if err := _elem1.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem1), err) - } - p.Attributes[_elem1] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *HostAttributes) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - temp := MaintenanceMode(v) - p.Mode = &temp - } - return nil -} - -func (p *HostAttributes) readField4(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 4: ", err) - } else { - p.SlaveId = &v - } - return nil -} - -func (p *HostAttributes) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("HostAttributes"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *HostAttributes) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("host", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:host: ", p), err) - } - if err := oprot.WriteString(string(p.Host)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.host (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:host: ", p), err) - } - return err -} - -func (p *HostAttributes) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("attributes", thrift.SET, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:attributes: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Attributes)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Attributes { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:attributes: ", p), err) - } - return err -} - -func (p *HostAttributes) writeField3(oprot thrift.TProtocol) (err error) { - if p.IsSetMode() { - if err := oprot.WriteFieldBegin("mode", thrift.I32, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:mode: ", p), err) - } - if err := oprot.WriteI32(int32(*p.Mode)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.mode (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:mode: ", p), err) - } - } - return err -} - -func (p *HostAttributes) writeField4(oprot thrift.TProtocol) (err error) { - if p.IsSetSlaveId() { - if err := oprot.WriteFieldBegin("slaveId", thrift.STRING, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:slaveId: ", p), err) - } - if err := oprot.WriteString(string(*p.SlaveId)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.slaveId (4) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:slaveId: ", p), err) - } - } - return err -} - -func (p *HostAttributes) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("HostAttributes(%+v)", *p) -} - -// A constraint that specifies an explicit set of values, at least one of which must be present -// on a host for a task to be scheduled there. -// -// Attributes: -// - Negated: If true, treat this as a 'not' - to avoid specific values. -// - Values -type ValueConstraint struct { - Negated bool `thrift:"negated,1" json:"negated"` - Values map[string]bool `thrift:"values,2" json:"values"` -} - -func NewValueConstraint() *ValueConstraint { - return &ValueConstraint{} -} - -func (p *ValueConstraint) GetNegated() bool { - return p.Negated -} - -func (p *ValueConstraint) GetValues() map[string]bool { - return p.Values -} -func (p *ValueConstraint) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ValueConstraint) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadBool(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Negated = v - } - return nil -} - -func (p *ValueConstraint) readField2(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[string]bool, size) - p.Values = tSet - for i := 0; i < size; i++ { - var _elem2 string - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 0: ", err) - } else { - _elem2 = v - } - p.Values[_elem2] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *ValueConstraint) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("ValueConstraint"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ValueConstraint) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("negated", thrift.BOOL, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:negated: ", p), err) - } - if err := oprot.WriteBool(bool(p.Negated)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.negated (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:negated: ", p), err) - } - return err -} - -func (p *ValueConstraint) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("values", thrift.SET, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:values: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRING, len(p.Values)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Values { - if err := oprot.WriteString(string(v)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:values: ", p), err) - } - return err -} - -func (p *ValueConstraint) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ValueConstraint(%+v)", *p) -} - -// A constraint the specifies the maximum number of active tasks on a host with a matching -// attribute that may be scheduled simultaneously. -// -// Attributes: -// - Limit -type LimitConstraint struct { - Limit int32 `thrift:"limit,1" json:"limit"` -} - -func NewLimitConstraint() *LimitConstraint { - return &LimitConstraint{} -} - -func (p *LimitConstraint) GetLimit() int32 { - return p.Limit -} -func (p *LimitConstraint) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *LimitConstraint) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Limit = v - } - return nil -} - -func (p *LimitConstraint) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("LimitConstraint"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *LimitConstraint) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("limit", thrift.I32, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:limit: ", p), err) - } - if err := oprot.WriteI32(int32(p.Limit)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.limit (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:limit: ", p), err) - } - return err -} - -func (p *LimitConstraint) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("LimitConstraint(%+v)", *p) -} - -// Types of constraints that may be applied to a task. -// -// Attributes: -// - Value -// - Limit -type TaskConstraint struct { - Value *ValueConstraint `thrift:"value,1" json:"value,omitempty"` - Limit *LimitConstraint `thrift:"limit,2" json:"limit,omitempty"` -} - -func NewTaskConstraint() *TaskConstraint { - return &TaskConstraint{} -} - -var TaskConstraint_Value_DEFAULT *ValueConstraint - -func (p *TaskConstraint) GetValue() *ValueConstraint { - if !p.IsSetValue() { - return TaskConstraint_Value_DEFAULT - } - return p.Value -} - -var TaskConstraint_Limit_DEFAULT *LimitConstraint - -func (p *TaskConstraint) GetLimit() *LimitConstraint { - if !p.IsSetLimit() { - return TaskConstraint_Limit_DEFAULT - } - return p.Limit -} -func (p *TaskConstraint) CountSetFieldsTaskConstraint() int { - count := 0 - if p.IsSetValue() { - count++ - } - if p.IsSetLimit() { - count++ - } - return count - -} - -func (p *TaskConstraint) IsSetValue() bool { - return p.Value != nil -} - -func (p *TaskConstraint) IsSetLimit() bool { - return p.Limit != nil -} - -func (p *TaskConstraint) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *TaskConstraint) readField1(iprot thrift.TProtocol) error { - p.Value = &ValueConstraint{} - if err := p.Value.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Value), err) - } - return nil -} - -func (p *TaskConstraint) readField2(iprot thrift.TProtocol) error { - p.Limit = &LimitConstraint{} - if err := p.Limit.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Limit), err) - } - return nil -} - -func (p *TaskConstraint) Write(oprot thrift.TProtocol) error { - if c := p.CountSetFieldsTaskConstraint(); c != 1 { - return fmt.Errorf("%T write union: exactly one field must be set (%d set).", p, c) - } - if err := oprot.WriteStructBegin("TaskConstraint"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *TaskConstraint) writeField1(oprot thrift.TProtocol) (err error) { - if p.IsSetValue() { - if err := oprot.WriteFieldBegin("value", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:value: ", p), err) - } - if err := p.Value.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Value), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:value: ", p), err) - } - } - return err -} - -func (p *TaskConstraint) writeField2(oprot thrift.TProtocol) (err error) { - if p.IsSetLimit() { - if err := oprot.WriteFieldBegin("limit", thrift.STRUCT, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:limit: ", p), err) - } - if err := p.Limit.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Limit), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:limit: ", p), err) - } - } - return err -} - -func (p *TaskConstraint) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("TaskConstraint(%+v)", *p) -} - -// A constraint that defines whether a task may be scheduled on a host. -// -// Attributes: -// - Name: Mesos slave attribute that the constraint is matched against. -// - Constraint -type Constraint struct { - Name string `thrift:"name,1" json:"name"` - Constraint *TaskConstraint `thrift:"constraint,2" json:"constraint"` -} - -func NewConstraint() *Constraint { - return &Constraint{} -} - -func (p *Constraint) GetName() string { - return p.Name -} - -var Constraint_Constraint_DEFAULT *TaskConstraint - -func (p *Constraint) GetConstraint() *TaskConstraint { - if !p.IsSetConstraint() { - return Constraint_Constraint_DEFAULT - } - return p.Constraint -} -func (p *Constraint) IsSetConstraint() bool { - return p.Constraint != nil -} - -func (p *Constraint) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *Constraint) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Name = v - } - return nil -} - -func (p *Constraint) readField2(iprot thrift.TProtocol) error { - p.Constraint = &TaskConstraint{} - if err := p.Constraint.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Constraint), err) - } - return nil -} - -func (p *Constraint) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("Constraint"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *Constraint) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("name", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:name: ", p), err) - } - if err := oprot.WriteString(string(p.Name)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.name (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:name: ", p), err) - } - return err -} - -func (p *Constraint) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("constraint", thrift.STRUCT, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:constraint: ", p), err) - } - if err := p.Constraint.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Constraint), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:constraint: ", p), err) - } - return err -} - -func (p *Constraint) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("Constraint(%+v)", *p) -} - -// Attributes: -// - Role -// - Name -// - Version -type Package struct { - Role string `thrift:"role,1" json:"role"` - Name string `thrift:"name,2" json:"name"` - Version int32 `thrift:"version,3" json:"version"` -} - -func NewPackage() *Package { - return &Package{} -} - -func (p *Package) GetRole() string { - return p.Role -} - -func (p *Package) GetName() string { - return p.Name -} - -func (p *Package) GetVersion() int32 { - return p.Version -} -func (p *Package) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *Package) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Role = v - } - return nil -} - -func (p *Package) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.Name = v - } - return nil -} - -func (p *Package) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.Version = v - } - return nil -} - -func (p *Package) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("Package"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *Package) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("role", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:role: ", p), err) - } - if err := oprot.WriteString(string(p.Role)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.role (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:role: ", p), err) - } - return err -} - -func (p *Package) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("name", thrift.STRING, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:name: ", p), err) - } - if err := oprot.WriteString(string(p.Name)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.name (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:name: ", p), err) - } - return err -} - -func (p *Package) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("version", thrift.I32, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:version: ", p), err) - } - if err := oprot.WriteI32(int32(p.Version)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.version (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:version: ", p), err) - } - return err -} - -func (p *Package) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("Package(%+v)", *p) -} - -// Arbitrary key-value metadata to be included into TaskConfig. -// -// Attributes: -// - Key -// - Value -type Metadata struct { - Key string `thrift:"key,1" json:"key"` - Value string `thrift:"value,2" json:"value"` -} - -func NewMetadata() *Metadata { - return &Metadata{} -} - -func (p *Metadata) GetKey() string { - return p.Key -} - -func (p *Metadata) GetValue() string { - return p.Value -} -func (p *Metadata) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *Metadata) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Key = v - } - return nil -} - -func (p *Metadata) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.Value = v - } - return nil -} - -func (p *Metadata) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("Metadata"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *Metadata) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("key", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:key: ", p), err) - } - if err := oprot.WriteString(string(p.Key)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.key (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:key: ", p), err) - } - return err -} - -func (p *Metadata) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("value", thrift.STRING, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:value: ", p), err) - } - if err := oprot.WriteString(string(p.Value)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.value (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:value: ", p), err) - } - return err -} - -func (p *Metadata) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("Metadata(%+v)", *p) -} - -// A unique identifier for a Job. -// -// Attributes: -// - Role: User role (Unix service account), for example "mesos" -// - Environment: Environment, for example "devel" -// - Name: Name, for example "labrat" -type JobKey struct { - Role string `thrift:"role,1" json:"role"` - Environment string `thrift:"environment,2" json:"environment"` - Name string `thrift:"name,3" json:"name"` -} - -func NewJobKey() *JobKey { - return &JobKey{} -} - -func (p *JobKey) GetRole() string { - return p.Role -} - -func (p *JobKey) GetEnvironment() string { - return p.Environment -} - -func (p *JobKey) GetName() string { - return p.Name -} -func (p *JobKey) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *JobKey) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Role = v - } - return nil -} - -func (p *JobKey) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.Environment = v - } - return nil -} - -func (p *JobKey) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.Name = v - } - return nil -} - -func (p *JobKey) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("JobKey"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *JobKey) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("role", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:role: ", p), err) - } - if err := oprot.WriteString(string(p.Role)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.role (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:role: ", p), err) - } - return err -} - -func (p *JobKey) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("environment", thrift.STRING, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:environment: ", p), err) - } - if err := oprot.WriteString(string(p.Environment)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.environment (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:environment: ", p), err) - } - return err -} - -func (p *JobKey) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("name", thrift.STRING, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:name: ", p), err) - } - if err := oprot.WriteString(string(p.Name)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.name (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:name: ", p), err) - } - return err -} - -func (p *JobKey) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("JobKey(%+v)", *p) -} - -// A unique lock key. -// -// Attributes: -// - Job -type LockKey struct { - Job *JobKey `thrift:"job,1" json:"job,omitempty"` -} - -func NewLockKey() *LockKey { - return &LockKey{} -} - -var LockKey_Job_DEFAULT *JobKey - -func (p *LockKey) GetJob() *JobKey { - if !p.IsSetJob() { - return LockKey_Job_DEFAULT - } - return p.Job -} -func (p *LockKey) CountSetFieldsLockKey() int { - count := 0 - if p.IsSetJob() { - count++ - } - return count - -} - -func (p *LockKey) IsSetJob() bool { - return p.Job != nil -} - -func (p *LockKey) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *LockKey) readField1(iprot thrift.TProtocol) error { - p.Job = &JobKey{} - if err := p.Job.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Job), err) - } - return nil -} - -func (p *LockKey) Write(oprot thrift.TProtocol) error { - if c := p.CountSetFieldsLockKey(); c != 1 { - return fmt.Errorf("%T write union: exactly one field must be set (%d set).", p, c) - } - if err := oprot.WriteStructBegin("LockKey"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *LockKey) writeField1(oprot thrift.TProtocol) (err error) { - if p.IsSetJob() { - if err := oprot.WriteFieldBegin("job", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:job: ", p), err) - } - if err := p.Job.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Job), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:job: ", p), err) - } - } - return err -} - -func (p *LockKey) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("LockKey(%+v)", *p) -} - -// A generic lock struct to facilitate context specific resource/operation serialization. -// -// Attributes: -// - Key: ID of the lock - unique per storage -// - Token: UUID - facilitating soft lock authorization -// - User: Lock creator -// - TimestampMs: Lock creation timestamp in milliseconds -// - Message: Optional message to record with the lock -type Lock struct { - Key *LockKey `thrift:"key,1" json:"key"` - Token string `thrift:"token,2" json:"token"` - User string `thrift:"user,3" json:"user"` - TimestampMs int64 `thrift:"timestampMs,4" json:"timestampMs"` - Message *string `thrift:"message,5" json:"message,omitempty"` -} - -func NewLock() *Lock { - return &Lock{} -} - -var Lock_Key_DEFAULT *LockKey - -func (p *Lock) GetKey() *LockKey { - if !p.IsSetKey() { - return Lock_Key_DEFAULT - } - return p.Key -} - -func (p *Lock) GetToken() string { - return p.Token -} - -func (p *Lock) GetUser() string { - return p.User -} - -func (p *Lock) GetTimestampMs() int64 { - return p.TimestampMs -} - -var Lock_Message_DEFAULT string - -func (p *Lock) GetMessage() string { - if !p.IsSetMessage() { - return Lock_Message_DEFAULT - } - return *p.Message -} -func (p *Lock) IsSetKey() bool { - return p.Key != nil -} - -func (p *Lock) IsSetMessage() bool { - return p.Message != nil -} - -func (p *Lock) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - case 5: - if err := p.readField5(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *Lock) readField1(iprot thrift.TProtocol) error { - p.Key = &LockKey{} - if err := p.Key.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) - } - return nil -} - -func (p *Lock) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.Token = v - } - return nil -} - -func (p *Lock) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.User = v - } - return nil -} - -func (p *Lock) readField4(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI64(); err != nil { - return thrift.PrependError("error reading field 4: ", err) - } else { - p.TimestampMs = v - } - return nil -} - -func (p *Lock) readField5(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 5: ", err) - } else { - p.Message = &v - } - return nil -} - -func (p *Lock) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("Lock"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := p.writeField5(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *Lock) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:key: ", p), err) - } - if err := p.Key.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:key: ", p), err) - } - return err -} - -func (p *Lock) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("token", thrift.STRING, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:token: ", p), err) - } - if err := oprot.WriteString(string(p.Token)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.token (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:token: ", p), err) - } - return err -} - -func (p *Lock) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("user", thrift.STRING, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:user: ", p), err) - } - if err := oprot.WriteString(string(p.User)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.user (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:user: ", p), err) - } - return err -} - -func (p *Lock) writeField4(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("timestampMs", thrift.I64, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:timestampMs: ", p), err) - } - if err := oprot.WriteI64(int64(p.TimestampMs)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.timestampMs (4) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:timestampMs: ", p), err) - } - return err -} - -func (p *Lock) writeField5(oprot thrift.TProtocol) (err error) { - if p.IsSetMessage() { - if err := oprot.WriteFieldBegin("message", thrift.STRING, 5); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:message: ", p), err) - } - if err := oprot.WriteString(string(*p.Message)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.message (5) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 5:message: ", p), err) - } - } - return err -} - -func (p *Lock) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("Lock(%+v)", *p) -} - -// A unique identifier for the active task within a job. -// -// Attributes: -// - JobKey: Key identifying the job. -// - InstanceId: Unique instance ID for the active task in a job. -type InstanceKey struct { - JobKey *JobKey `thrift:"jobKey,1" json:"jobKey"` - InstanceId int32 `thrift:"instanceId,2" json:"instanceId"` -} - -func NewInstanceKey() *InstanceKey { - return &InstanceKey{} -} - -var InstanceKey_JobKey_DEFAULT *JobKey - -func (p *InstanceKey) GetJobKey() *JobKey { - if !p.IsSetJobKey() { - return InstanceKey_JobKey_DEFAULT - } - return p.JobKey -} - -func (p *InstanceKey) GetInstanceId() int32 { - return p.InstanceId -} -func (p *InstanceKey) IsSetJobKey() bool { - return p.JobKey != nil -} - -func (p *InstanceKey) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *InstanceKey) readField1(iprot thrift.TProtocol) error { - p.JobKey = &JobKey{} - if err := p.JobKey.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.JobKey), err) - } - return nil -} - -func (p *InstanceKey) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.InstanceId = v - } - return nil -} - -func (p *InstanceKey) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("InstanceKey"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *InstanceKey) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("jobKey", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:jobKey: ", p), err) - } - if err := p.JobKey.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.JobKey), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:jobKey: ", p), err) - } - return err -} - -func (p *InstanceKey) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("instanceId", thrift.I32, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:instanceId: ", p), err) - } - if err := oprot.WriteI32(int32(p.InstanceId)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.instanceId (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:instanceId: ", p), err) - } - return err -} - -func (p *InstanceKey) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("InstanceKey(%+v)", *p) -} - -// URI which mirrors CommandInfo.URI in the Mesos Protobuf -// -// Attributes: -// - Value: Where to get the resource from -// - Extract: Extract compressed archive after downloading -// - Cache: Cache value using Mesos Fetcher caching mechanism * -type MesosFetcherURI struct { - Value string `thrift:"value,1" json:"value"` - Extract *bool `thrift:"extract,2" json:"extract,omitempty"` - Cache *bool `thrift:"cache,3" json:"cache,omitempty"` -} - -func NewMesosFetcherURI() *MesosFetcherURI { - return &MesosFetcherURI{} -} - -func (p *MesosFetcherURI) GetValue() string { - return p.Value -} - -var MesosFetcherURI_Extract_DEFAULT bool - -func (p *MesosFetcherURI) GetExtract() bool { - if !p.IsSetExtract() { - return MesosFetcherURI_Extract_DEFAULT - } - return *p.Extract -} - -var MesosFetcherURI_Cache_DEFAULT bool - -func (p *MesosFetcherURI) GetCache() bool { - if !p.IsSetCache() { - return MesosFetcherURI_Cache_DEFAULT - } - return *p.Cache -} -func (p *MesosFetcherURI) IsSetExtract() bool { - return p.Extract != nil -} - -func (p *MesosFetcherURI) IsSetCache() bool { - return p.Cache != nil -} - -func (p *MesosFetcherURI) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *MesosFetcherURI) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Value = v - } - return nil -} - -func (p *MesosFetcherURI) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadBool(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.Extract = &v - } - return nil -} - -func (p *MesosFetcherURI) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadBool(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.Cache = &v - } - return nil -} - -func (p *MesosFetcherURI) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("MesosFetcherURI"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *MesosFetcherURI) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("value", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:value: ", p), err) - } - if err := oprot.WriteString(string(p.Value)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.value (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:value: ", p), err) - } - return err -} - -func (p *MesosFetcherURI) writeField2(oprot thrift.TProtocol) (err error) { - if p.IsSetExtract() { - if err := oprot.WriteFieldBegin("extract", thrift.BOOL, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:extract: ", p), err) - } - if err := oprot.WriteBool(bool(*p.Extract)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.extract (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:extract: ", p), err) - } - } - return err -} - -func (p *MesosFetcherURI) writeField3(oprot thrift.TProtocol) (err error) { - if p.IsSetCache() { - if err := oprot.WriteFieldBegin("cache", thrift.BOOL, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:cache: ", p), err) - } - if err := oprot.WriteBool(bool(*p.Cache)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.cache (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:cache: ", p), err) - } - } - return err -} - -func (p *MesosFetcherURI) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("MesosFetcherURI(%+v)", *p) -} - -// Attributes: -// - Name: Name identifying the Executor. -// - Data: Executor configuration data. -type ExecutorConfig struct { - Name string `thrift:"name,1" json:"name"` - Data string `thrift:"data,2" json:"data"` -} - -func NewExecutorConfig() *ExecutorConfig { - return &ExecutorConfig{} -} - -func (p *ExecutorConfig) GetName() string { - return p.Name -} - -func (p *ExecutorConfig) GetData() string { - return p.Data -} -func (p *ExecutorConfig) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ExecutorConfig) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Name = v - } - return nil -} - -func (p *ExecutorConfig) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.Data = v - } - return nil -} - -func (p *ExecutorConfig) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("ExecutorConfig"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ExecutorConfig) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("name", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:name: ", p), err) - } - if err := oprot.WriteString(string(p.Name)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.name (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:name: ", p), err) - } - return err -} - -func (p *ExecutorConfig) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("data", thrift.STRING, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:data: ", p), err) - } - if err := oprot.WriteString(string(p.Data)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.data (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:data: ", p), err) - } - return err -} - -func (p *ExecutorConfig) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ExecutorConfig(%+v)", *p) -} - -// A volume mount point within a container -// -// Attributes: -// - ContainerPath: The path inside the container where the mount will be created. -// - HostPath: The path on the host that will serve as the source for the mount. -// - Mode: The access mode -type Volume struct { - ContainerPath string `thrift:"containerPath,1" json:"containerPath"` - HostPath string `thrift:"hostPath,2" json:"hostPath"` - Mode Mode `thrift:"mode,3" json:"mode"` -} - -func NewVolume() *Volume { - return &Volume{} -} - -func (p *Volume) GetContainerPath() string { - return p.ContainerPath -} - -func (p *Volume) GetHostPath() string { - return p.HostPath -} - -func (p *Volume) GetMode() Mode { - return p.Mode -} -func (p *Volume) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *Volume) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.ContainerPath = v - } - return nil -} - -func (p *Volume) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.HostPath = v - } - return nil -} - -func (p *Volume) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - temp := Mode(v) - p.Mode = temp - } - return nil -} - -func (p *Volume) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("Volume"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *Volume) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("containerPath", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:containerPath: ", p), err) - } - if err := oprot.WriteString(string(p.ContainerPath)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.containerPath (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:containerPath: ", p), err) - } - return err -} - -func (p *Volume) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("hostPath", thrift.STRING, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:hostPath: ", p), err) - } - if err := oprot.WriteString(string(p.HostPath)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.hostPath (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:hostPath: ", p), err) - } - return err -} - -func (p *Volume) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("mode", thrift.I32, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:mode: ", p), err) - } - if err := oprot.WriteI32(int32(p.Mode)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.mode (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:mode: ", p), err) - } - return err -} - -func (p *Volume) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("Volume(%+v)", *p) -} - -// Describes an image for use with the Mesos unified containerizer in the Docker format -// -// Attributes: -// - Name: The name of the image to run -// - Tag: The Docker tag identifying the image -type DockerImage struct { - Name string `thrift:"name,1" json:"name"` - Tag string `thrift:"tag,2" json:"tag"` -} - -func NewDockerImage() *DockerImage { - return &DockerImage{} -} - -func (p *DockerImage) GetName() string { - return p.Name -} - -func (p *DockerImage) GetTag() string { - return p.Tag -} -func (p *DockerImage) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *DockerImage) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Name = v - } - return nil -} - -func (p *DockerImage) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.Tag = v - } - return nil -} - -func (p *DockerImage) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("DockerImage"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *DockerImage) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("name", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:name: ", p), err) - } - if err := oprot.WriteString(string(p.Name)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.name (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:name: ", p), err) - } - return err -} - -func (p *DockerImage) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("tag", thrift.STRING, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:tag: ", p), err) - } - if err := oprot.WriteString(string(p.Tag)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.tag (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:tag: ", p), err) - } - return err -} - -func (p *DockerImage) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("DockerImage(%+v)", *p) -} - -// Describes an image for use with the Mesos unified containerizer in the AppC format -// -// Attributes: -// - Name: The name of the image to run -// - ImageId: The appc image id identifying the image -type AppcImage struct { - Name string `thrift:"name,1" json:"name"` - ImageId string `thrift:"imageId,2" json:"imageId"` -} - -func NewAppcImage() *AppcImage { - return &AppcImage{} -} - -func (p *AppcImage) GetName() string { - return p.Name -} - -func (p *AppcImage) GetImageId() string { - return p.ImageId -} -func (p *AppcImage) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AppcImage) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Name = v - } - return nil -} - -func (p *AppcImage) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.ImageId = v - } - return nil -} - -func (p *AppcImage) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("AppcImage"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AppcImage) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("name", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:name: ", p), err) - } - if err := oprot.WriteString(string(p.Name)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.name (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:name: ", p), err) - } - return err -} - -func (p *AppcImage) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("imageId", thrift.STRING, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:imageId: ", p), err) - } - if err := oprot.WriteString(string(p.ImageId)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.imageId (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:imageId: ", p), err) - } - return err -} - -func (p *AppcImage) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AppcImage(%+v)", *p) -} - -// Describes an image to be used with the Mesos unified containerizer -// -// Attributes: -// - Docker -// - Appc -type Image struct { - Docker *DockerImage `thrift:"docker,1" json:"docker,omitempty"` - Appc *AppcImage `thrift:"appc,2" json:"appc,omitempty"` -} - -func NewImage() *Image { - return &Image{} -} - -var Image_Docker_DEFAULT *DockerImage - -func (p *Image) GetDocker() *DockerImage { - if !p.IsSetDocker() { - return Image_Docker_DEFAULT - } - return p.Docker -} - -var Image_Appc_DEFAULT *AppcImage - -func (p *Image) GetAppc() *AppcImage { - if !p.IsSetAppc() { - return Image_Appc_DEFAULT - } - return p.Appc -} -func (p *Image) CountSetFieldsImage() int { - count := 0 - if p.IsSetDocker() { - count++ - } - if p.IsSetAppc() { - count++ - } - return count - -} - -func (p *Image) IsSetDocker() bool { - return p.Docker != nil -} - -func (p *Image) IsSetAppc() bool { - return p.Appc != nil -} - -func (p *Image) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *Image) readField1(iprot thrift.TProtocol) error { - p.Docker = &DockerImage{} - if err := p.Docker.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Docker), err) - } - return nil -} - -func (p *Image) readField2(iprot thrift.TProtocol) error { - p.Appc = &AppcImage{} - if err := p.Appc.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Appc), err) - } - return nil -} - -func (p *Image) Write(oprot thrift.TProtocol) error { - if c := p.CountSetFieldsImage(); c != 1 { - return fmt.Errorf("%T write union: exactly one field must be set (%d set).", p, c) - } - if err := oprot.WriteStructBegin("Image"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *Image) writeField1(oprot thrift.TProtocol) (err error) { - if p.IsSetDocker() { - if err := oprot.WriteFieldBegin("docker", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:docker: ", p), err) - } - if err := p.Docker.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Docker), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:docker: ", p), err) - } - } - return err -} - -func (p *Image) writeField2(oprot thrift.TProtocol) (err error) { - if p.IsSetAppc() { - if err := oprot.WriteFieldBegin("appc", thrift.STRUCT, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:appc: ", p), err) - } - if err := p.Appc.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Appc), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:appc: ", p), err) - } - } - return err -} - -func (p *Image) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("Image(%+v)", *p) -} - -// Describes a mesos container, this is the default -// -// Attributes: -// - Image: the optional filesystem image to use when launching this task. -// - Volumes: the optional list of volumes to mount into the task. -type MesosContainer struct { - Image *Image `thrift:"image,1" json:"image,omitempty"` - Volumes []*Volume `thrift:"volumes,2" json:"volumes,omitempty"` -} - -func NewMesosContainer() *MesosContainer { - return &MesosContainer{} -} - -var MesosContainer_Image_DEFAULT *Image - -func (p *MesosContainer) GetImage() *Image { - if !p.IsSetImage() { - return MesosContainer_Image_DEFAULT - } - return p.Image -} - -var MesosContainer_Volumes_DEFAULT []*Volume - -func (p *MesosContainer) GetVolumes() []*Volume { - return p.Volumes -} -func (p *MesosContainer) IsSetImage() bool { - return p.Image != nil -} - -func (p *MesosContainer) IsSetVolumes() bool { - return p.Volumes != nil -} - -func (p *MesosContainer) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *MesosContainer) readField1(iprot thrift.TProtocol) error { - p.Image = &Image{} - if err := p.Image.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Image), err) - } - return nil -} - -func (p *MesosContainer) readField2(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadListBegin() - if err != nil { - return thrift.PrependError("error reading list begin: ", err) - } - tSlice := make([]*Volume, 0, size) - p.Volumes = tSlice - for i := 0; i < size; i++ { - _elem3 := &Volume{} - if err := _elem3.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem3), err) - } - p.Volumes = append(p.Volumes, _elem3) - } - if err := iprot.ReadListEnd(); err != nil { - return thrift.PrependError("error reading list end: ", err) - } - return nil -} - -func (p *MesosContainer) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("MesosContainer"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *MesosContainer) writeField1(oprot thrift.TProtocol) (err error) { - if p.IsSetImage() { - if err := oprot.WriteFieldBegin("image", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:image: ", p), err) - } - if err := p.Image.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Image), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:image: ", p), err) - } - } - return err -} - -func (p *MesosContainer) writeField2(oprot thrift.TProtocol) (err error) { - if p.IsSetVolumes() { - if err := oprot.WriteFieldBegin("volumes", thrift.LIST, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:volumes: ", p), err) - } - if err := oprot.WriteListBegin(thrift.STRUCT, len(p.Volumes)); err != nil { - return thrift.PrependError("error writing list begin: ", err) - } - for _, v := range p.Volumes { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteListEnd(); err != nil { - return thrift.PrependError("error writing list end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:volumes: ", p), err) - } - } - return err -} - -func (p *MesosContainer) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("MesosContainer(%+v)", *p) -} - -// Describes a parameter passed to docker cli -// -// Attributes: -// - Name: a parameter to pass to docker. (e.g. volume) -// - Value: the value to pass to a parameter (e.g. /src/webapp:/opt/webapp) -type DockerParameter struct { - Name string `thrift:"name,1" json:"name"` - Value string `thrift:"value,2" json:"value"` -} - -func NewDockerParameter() *DockerParameter { - return &DockerParameter{} -} - -func (p *DockerParameter) GetName() string { - return p.Name -} - -func (p *DockerParameter) GetValue() string { - return p.Value -} -func (p *DockerParameter) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *DockerParameter) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Name = v - } - return nil -} - -func (p *DockerParameter) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.Value = v - } - return nil -} - -func (p *DockerParameter) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("DockerParameter"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *DockerParameter) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("name", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:name: ", p), err) - } - if err := oprot.WriteString(string(p.Name)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.name (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:name: ", p), err) - } - return err -} - -func (p *DockerParameter) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("value", thrift.STRING, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:value: ", p), err) - } - if err := oprot.WriteString(string(p.Value)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.value (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:value: ", p), err) - } - return err -} - -func (p *DockerParameter) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("DockerParameter(%+v)", *p) -} - -// Describes a docker container -// -// Attributes: -// - Image: The container image to be run -// - Parameters: The arbitrary parameters to pass to container -type DockerContainer struct { - Image string `thrift:"image,1" json:"image"` - Parameters []*DockerParameter `thrift:"parameters,2" json:"parameters,omitempty"` -} - -func NewDockerContainer() *DockerContainer { - return &DockerContainer{} -} - -func (p *DockerContainer) GetImage() string { - return p.Image -} - -var DockerContainer_Parameters_DEFAULT []*DockerParameter - -func (p *DockerContainer) GetParameters() []*DockerParameter { - return p.Parameters -} -func (p *DockerContainer) IsSetParameters() bool { - return p.Parameters != nil -} - -func (p *DockerContainer) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *DockerContainer) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Image = v - } - return nil -} - -func (p *DockerContainer) readField2(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadListBegin() - if err != nil { - return thrift.PrependError("error reading list begin: ", err) - } - tSlice := make([]*DockerParameter, 0, size) - p.Parameters = tSlice - for i := 0; i < size; i++ { - _elem4 := &DockerParameter{} - if err := _elem4.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem4), err) - } - p.Parameters = append(p.Parameters, _elem4) - } - if err := iprot.ReadListEnd(); err != nil { - return thrift.PrependError("error reading list end: ", err) - } - return nil -} - -func (p *DockerContainer) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("DockerContainer"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *DockerContainer) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("image", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:image: ", p), err) - } - if err := oprot.WriteString(string(p.Image)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.image (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:image: ", p), err) - } - return err -} - -func (p *DockerContainer) writeField2(oprot thrift.TProtocol) (err error) { - if p.IsSetParameters() { - if err := oprot.WriteFieldBegin("parameters", thrift.LIST, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:parameters: ", p), err) - } - if err := oprot.WriteListBegin(thrift.STRUCT, len(p.Parameters)); err != nil { - return thrift.PrependError("error writing list begin: ", err) - } - for _, v := range p.Parameters { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteListEnd(); err != nil { - return thrift.PrependError("error writing list end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:parameters: ", p), err) - } - } - return err -} - -func (p *DockerContainer) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("DockerContainer(%+v)", *p) -} - -// Describes a container to be used in a task -// -// Attributes: -// - Mesos -// - Docker -type Container struct { - Mesos *MesosContainer `thrift:"mesos,1" json:"mesos,omitempty"` - Docker *DockerContainer `thrift:"docker,2" json:"docker,omitempty"` -} - -func NewContainer() *Container { - return &Container{} -} - -var Container_Mesos_DEFAULT *MesosContainer - -func (p *Container) GetMesos() *MesosContainer { - if !p.IsSetMesos() { - return Container_Mesos_DEFAULT - } - return p.Mesos -} - -var Container_Docker_DEFAULT *DockerContainer - -func (p *Container) GetDocker() *DockerContainer { - if !p.IsSetDocker() { - return Container_Docker_DEFAULT - } - return p.Docker -} -func (p *Container) CountSetFieldsContainer() int { - count := 0 - if p.IsSetMesos() { - count++ - } - if p.IsSetDocker() { - count++ - } - return count - -} - -func (p *Container) IsSetMesos() bool { - return p.Mesos != nil -} - -func (p *Container) IsSetDocker() bool { - return p.Docker != nil -} - -func (p *Container) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *Container) readField1(iprot thrift.TProtocol) error { - p.Mesos = &MesosContainer{} - if err := p.Mesos.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Mesos), err) - } - return nil -} - -func (p *Container) readField2(iprot thrift.TProtocol) error { - p.Docker = &DockerContainer{} - if err := p.Docker.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Docker), err) - } - return nil -} - -func (p *Container) Write(oprot thrift.TProtocol) error { - if c := p.CountSetFieldsContainer(); c != 1 { - return fmt.Errorf("%T write union: exactly one field must be set (%d set).", p, c) - } - if err := oprot.WriteStructBegin("Container"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *Container) writeField1(oprot thrift.TProtocol) (err error) { - if p.IsSetMesos() { - if err := oprot.WriteFieldBegin("mesos", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:mesos: ", p), err) - } - if err := p.Mesos.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Mesos), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:mesos: ", p), err) - } - } - return err -} - -func (p *Container) writeField2(oprot thrift.TProtocol) (err error) { - if p.IsSetDocker() { - if err := oprot.WriteFieldBegin("docker", thrift.STRUCT, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:docker: ", p), err) - } - if err := p.Docker.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Docker), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:docker: ", p), err) - } - } - return err -} - -func (p *Container) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("Container(%+v)", *p) -} - -// Describes resource value required to run a task. -// -// Attributes: -// - NumCpus -// - RamMb -// - DiskMb -// - NamedPort -// - NumGpus -type Resource struct { - NumCpus *float64 `thrift:"numCpus,1" json:"numCpus,omitempty"` - RamMb *int64 `thrift:"ramMb,2" json:"ramMb,omitempty"` - DiskMb *int64 `thrift:"diskMb,3" json:"diskMb,omitempty"` - NamedPort *string `thrift:"namedPort,4" json:"namedPort,omitempty"` - NumGpus *int64 `thrift:"numGpus,5" json:"numGpus,omitempty"` -} - -func NewResource() *Resource { - return &Resource{} -} - -var Resource_NumCpus_DEFAULT float64 - -func (p *Resource) GetNumCpus() float64 { - if !p.IsSetNumCpus() { - return Resource_NumCpus_DEFAULT - } - return *p.NumCpus -} - -var Resource_RamMb_DEFAULT int64 - -func (p *Resource) GetRamMb() int64 { - if !p.IsSetRamMb() { - return Resource_RamMb_DEFAULT - } - return *p.RamMb -} - -var Resource_DiskMb_DEFAULT int64 - -func (p *Resource) GetDiskMb() int64 { - if !p.IsSetDiskMb() { - return Resource_DiskMb_DEFAULT - } - return *p.DiskMb -} - -var Resource_NamedPort_DEFAULT string - -func (p *Resource) GetNamedPort() string { - if !p.IsSetNamedPort() { - return Resource_NamedPort_DEFAULT - } - return *p.NamedPort -} - -var Resource_NumGpus_DEFAULT int64 - -func (p *Resource) GetNumGpus() int64 { - if !p.IsSetNumGpus() { - return Resource_NumGpus_DEFAULT - } - return *p.NumGpus -} -func (p *Resource) CountSetFieldsResource() int { - count := 0 - if p.IsSetNumCpus() { - count++ - } - if p.IsSetRamMb() { - count++ - } - if p.IsSetDiskMb() { - count++ - } - if p.IsSetNamedPort() { - count++ - } - if p.IsSetNumGpus() { - count++ - } - return count - -} - -func (p *Resource) IsSetNumCpus() bool { - return p.NumCpus != nil -} - -func (p *Resource) IsSetRamMb() bool { - return p.RamMb != nil -} - -func (p *Resource) IsSetDiskMb() bool { - return p.DiskMb != nil -} - -func (p *Resource) IsSetNamedPort() bool { - return p.NamedPort != nil -} - -func (p *Resource) IsSetNumGpus() bool { - return p.NumGpus != nil -} - -func (p *Resource) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - case 5: - if err := p.readField5(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *Resource) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadDouble(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.NumCpus = &v - } - return nil -} - -func (p *Resource) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI64(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.RamMb = &v - } - return nil -} - -func (p *Resource) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI64(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.DiskMb = &v - } - return nil -} - -func (p *Resource) readField4(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 4: ", err) - } else { - p.NamedPort = &v - } - return nil -} - -func (p *Resource) readField5(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI64(); err != nil { - return thrift.PrependError("error reading field 5: ", err) - } else { - p.NumGpus = &v - } - return nil -} - -func (p *Resource) Write(oprot thrift.TProtocol) error { - if c := p.CountSetFieldsResource(); c != 1 { - return fmt.Errorf("%T write union: exactly one field must be set (%d set).", p, c) - } - if err := oprot.WriteStructBegin("Resource"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := p.writeField5(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *Resource) writeField1(oprot thrift.TProtocol) (err error) { - if p.IsSetNumCpus() { - if err := oprot.WriteFieldBegin("numCpus", thrift.DOUBLE, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:numCpus: ", p), err) - } - if err := oprot.WriteDouble(float64(*p.NumCpus)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.numCpus (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:numCpus: ", p), err) - } - } - return err -} - -func (p *Resource) writeField2(oprot thrift.TProtocol) (err error) { - if p.IsSetRamMb() { - if err := oprot.WriteFieldBegin("ramMb", thrift.I64, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:ramMb: ", p), err) - } - if err := oprot.WriteI64(int64(*p.RamMb)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.ramMb (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:ramMb: ", p), err) - } - } - return err -} - -func (p *Resource) writeField3(oprot thrift.TProtocol) (err error) { - if p.IsSetDiskMb() { - if err := oprot.WriteFieldBegin("diskMb", thrift.I64, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:diskMb: ", p), err) - } - if err := oprot.WriteI64(int64(*p.DiskMb)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.diskMb (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:diskMb: ", p), err) - } - } - return err -} - -func (p *Resource) writeField4(oprot thrift.TProtocol) (err error) { - if p.IsSetNamedPort() { - if err := oprot.WriteFieldBegin("namedPort", thrift.STRING, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:namedPort: ", p), err) - } - if err := oprot.WriteString(string(*p.NamedPort)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.namedPort (4) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:namedPort: ", p), err) - } - } - return err -} - -func (p *Resource) writeField5(oprot thrift.TProtocol) (err error) { - if p.IsSetNumGpus() { - if err := oprot.WriteFieldBegin("numGpus", thrift.I64, 5); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:numGpus: ", p), err) - } - if err := oprot.WriteI64(int64(*p.NumGpus)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.numGpus (5) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 5:numGpus: ", p), err) - } - } - return err -} - -func (p *Resource) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("Resource(%+v)", *p) -} - -// Attributes: -// - Reschedule -// - DelaySecs -type PartitionPolicy struct { - Reschedule bool `thrift:"reschedule,1" json:"reschedule"` - DelaySecs *int64 `thrift:"delaySecs,2" json:"delaySecs,omitempty"` -} - -func NewPartitionPolicy() *PartitionPolicy { - return &PartitionPolicy{} -} - -func (p *PartitionPolicy) GetReschedule() bool { - return p.Reschedule -} - -var PartitionPolicy_DelaySecs_DEFAULT int64 - -func (p *PartitionPolicy) GetDelaySecs() int64 { - if !p.IsSetDelaySecs() { - return PartitionPolicy_DelaySecs_DEFAULT - } - return *p.DelaySecs -} -func (p *PartitionPolicy) IsSetDelaySecs() bool { - return p.DelaySecs != nil -} - -func (p *PartitionPolicy) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *PartitionPolicy) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadBool(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Reschedule = v - } - return nil -} - -func (p *PartitionPolicy) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI64(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.DelaySecs = &v - } - return nil -} - -func (p *PartitionPolicy) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("PartitionPolicy"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *PartitionPolicy) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("reschedule", thrift.BOOL, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:reschedule: ", p), err) - } - if err := oprot.WriteBool(bool(p.Reschedule)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.reschedule (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:reschedule: ", p), err) - } - return err -} - -func (p *PartitionPolicy) writeField2(oprot thrift.TProtocol) (err error) { - if p.IsSetDelaySecs() { - if err := oprot.WriteFieldBegin("delaySecs", thrift.I64, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:delaySecs: ", p), err) - } - if err := oprot.WriteI64(int64(*p.DelaySecs)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.delaySecs (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:delaySecs: ", p), err) - } - } - return err -} - -func (p *PartitionPolicy) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("PartitionPolicy(%+v)", *p) -} - -// SLA requirements expressed as the percentage of instances to be RUNNING every durationSecs -// -// Attributes: -// - Percentage -// - DurationSecs: Minimum time duration a task needs to be `RUNNING` to be treated as active -type PercentageSlaPolicy struct { - Percentage float64 `thrift:"percentage,1" json:"percentage"` - DurationSecs int64 `thrift:"durationSecs,2" json:"durationSecs"` -} - -func NewPercentageSlaPolicy() *PercentageSlaPolicy { - return &PercentageSlaPolicy{} -} - -func (p *PercentageSlaPolicy) GetPercentage() float64 { - return p.Percentage -} - -func (p *PercentageSlaPolicy) GetDurationSecs() int64 { - return p.DurationSecs -} -func (p *PercentageSlaPolicy) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *PercentageSlaPolicy) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadDouble(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Percentage = v - } - return nil -} - -func (p *PercentageSlaPolicy) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI64(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.DurationSecs = v - } - return nil -} - -func (p *PercentageSlaPolicy) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("PercentageSlaPolicy"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *PercentageSlaPolicy) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("percentage", thrift.DOUBLE, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:percentage: ", p), err) - } - if err := oprot.WriteDouble(float64(p.Percentage)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.percentage (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:percentage: ", p), err) - } - return err -} - -func (p *PercentageSlaPolicy) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("durationSecs", thrift.I64, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:durationSecs: ", p), err) - } - if err := oprot.WriteI64(int64(p.DurationSecs)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.durationSecs (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:durationSecs: ", p), err) - } - return err -} - -func (p *PercentageSlaPolicy) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("PercentageSlaPolicy(%+v)", *p) -} - -// SLA requirements expressed as the number of instances to be RUNNING every durationSecs -// -// Attributes: -// - Count: The number of active instances required every `durationSecs` -// - DurationSecs: Minimum time duration a task needs to be `RUNNING` to be treated as active -type CountSlaPolicy struct { - Count int64 `thrift:"count,1" json:"count"` - DurationSecs int64 `thrift:"durationSecs,2" json:"durationSecs"` -} - -func NewCountSlaPolicy() *CountSlaPolicy { - return &CountSlaPolicy{} -} - -func (p *CountSlaPolicy) GetCount() int64 { - return p.Count -} - -func (p *CountSlaPolicy) GetDurationSecs() int64 { - return p.DurationSecs -} -func (p *CountSlaPolicy) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *CountSlaPolicy) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI64(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Count = v - } - return nil -} - -func (p *CountSlaPolicy) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI64(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.DurationSecs = v - } - return nil -} - -func (p *CountSlaPolicy) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("CountSlaPolicy"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *CountSlaPolicy) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("count", thrift.I64, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:count: ", p), err) - } - if err := oprot.WriteI64(int64(p.Count)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.count (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:count: ", p), err) - } - return err -} - -func (p *CountSlaPolicy) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("durationSecs", thrift.I64, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:durationSecs: ", p), err) - } - if err := oprot.WriteI64(int64(p.DurationSecs)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.durationSecs (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:durationSecs: ", p), err) - } - return err -} - -func (p *CountSlaPolicy) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("CountSlaPolicy(%+v)", *p) -} - -// SLA requirements to be delegated to an external coordinator -// -// Attributes: -// - CoordinatorUrl: URL for the coordinator service that needs to be contacted for SLA checks -// - StatusKey: Field in the Coordinator response json indicating if the action is allowed or not -type CoordinatorSlaPolicy struct { - CoordinatorUrl string `thrift:"coordinatorUrl,1" json:"coordinatorUrl"` - StatusKey string `thrift:"statusKey,2" json:"statusKey"` -} - -func NewCoordinatorSlaPolicy() *CoordinatorSlaPolicy { - return &CoordinatorSlaPolicy{} -} - -func (p *CoordinatorSlaPolicy) GetCoordinatorUrl() string { - return p.CoordinatorUrl -} - -func (p *CoordinatorSlaPolicy) GetStatusKey() string { - return p.StatusKey -} -func (p *CoordinatorSlaPolicy) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *CoordinatorSlaPolicy) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.CoordinatorUrl = v - } - return nil -} - -func (p *CoordinatorSlaPolicy) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.StatusKey = v - } - return nil -} - -func (p *CoordinatorSlaPolicy) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("CoordinatorSlaPolicy"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *CoordinatorSlaPolicy) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("coordinatorUrl", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:coordinatorUrl: ", p), err) - } - if err := oprot.WriteString(string(p.CoordinatorUrl)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.coordinatorUrl (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:coordinatorUrl: ", p), err) - } - return err -} - -func (p *CoordinatorSlaPolicy) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("statusKey", thrift.STRING, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:statusKey: ", p), err) - } - if err := oprot.WriteString(string(p.StatusKey)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.statusKey (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:statusKey: ", p), err) - } - return err -} - -func (p *CoordinatorSlaPolicy) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("CoordinatorSlaPolicy(%+v)", *p) -} - -// SLA requirements expressed in one of the many types -// -// Attributes: -// - PercentageSlaPolicy -// - CountSlaPolicy -// - CoordinatorSlaPolicy -type SlaPolicy struct { - PercentageSlaPolicy *PercentageSlaPolicy `thrift:"percentageSlaPolicy,1" json:"percentageSlaPolicy,omitempty"` - CountSlaPolicy *CountSlaPolicy `thrift:"countSlaPolicy,2" json:"countSlaPolicy,omitempty"` - CoordinatorSlaPolicy *CoordinatorSlaPolicy `thrift:"coordinatorSlaPolicy,3" json:"coordinatorSlaPolicy,omitempty"` -} - -func NewSlaPolicy() *SlaPolicy { - return &SlaPolicy{} -} - -var SlaPolicy_PercentageSlaPolicy_DEFAULT *PercentageSlaPolicy - -func (p *SlaPolicy) GetPercentageSlaPolicy() *PercentageSlaPolicy { - if !p.IsSetPercentageSlaPolicy() { - return SlaPolicy_PercentageSlaPolicy_DEFAULT - } - return p.PercentageSlaPolicy -} - -var SlaPolicy_CountSlaPolicy_DEFAULT *CountSlaPolicy - -func (p *SlaPolicy) GetCountSlaPolicy() *CountSlaPolicy { - if !p.IsSetCountSlaPolicy() { - return SlaPolicy_CountSlaPolicy_DEFAULT - } - return p.CountSlaPolicy -} - -var SlaPolicy_CoordinatorSlaPolicy_DEFAULT *CoordinatorSlaPolicy - -func (p *SlaPolicy) GetCoordinatorSlaPolicy() *CoordinatorSlaPolicy { - if !p.IsSetCoordinatorSlaPolicy() { - return SlaPolicy_CoordinatorSlaPolicy_DEFAULT - } - return p.CoordinatorSlaPolicy -} -func (p *SlaPolicy) CountSetFieldsSlaPolicy() int { - count := 0 - if p.IsSetPercentageSlaPolicy() { - count++ - } - if p.IsSetCountSlaPolicy() { - count++ - } - if p.IsSetCoordinatorSlaPolicy() { - count++ - } - return count - -} - -func (p *SlaPolicy) IsSetPercentageSlaPolicy() bool { - return p.PercentageSlaPolicy != nil -} - -func (p *SlaPolicy) IsSetCountSlaPolicy() bool { - return p.CountSlaPolicy != nil -} - -func (p *SlaPolicy) IsSetCoordinatorSlaPolicy() bool { - return p.CoordinatorSlaPolicy != nil -} - -func (p *SlaPolicy) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *SlaPolicy) readField1(iprot thrift.TProtocol) error { - p.PercentageSlaPolicy = &PercentageSlaPolicy{} - if err := p.PercentageSlaPolicy.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.PercentageSlaPolicy), err) - } - return nil -} - -func (p *SlaPolicy) readField2(iprot thrift.TProtocol) error { - p.CountSlaPolicy = &CountSlaPolicy{} - if err := p.CountSlaPolicy.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.CountSlaPolicy), err) - } - return nil -} - -func (p *SlaPolicy) readField3(iprot thrift.TProtocol) error { - p.CoordinatorSlaPolicy = &CoordinatorSlaPolicy{} - if err := p.CoordinatorSlaPolicy.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.CoordinatorSlaPolicy), err) - } - return nil -} - -func (p *SlaPolicy) Write(oprot thrift.TProtocol) error { - if c := p.CountSetFieldsSlaPolicy(); c != 1 { - return fmt.Errorf("%T write union: exactly one field must be set (%d set).", p, c) - } - if err := oprot.WriteStructBegin("SlaPolicy"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *SlaPolicy) writeField1(oprot thrift.TProtocol) (err error) { - if p.IsSetPercentageSlaPolicy() { - if err := oprot.WriteFieldBegin("percentageSlaPolicy", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:percentageSlaPolicy: ", p), err) - } - if err := p.PercentageSlaPolicy.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.PercentageSlaPolicy), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:percentageSlaPolicy: ", p), err) - } - } - return err -} - -func (p *SlaPolicy) writeField2(oprot thrift.TProtocol) (err error) { - if p.IsSetCountSlaPolicy() { - if err := oprot.WriteFieldBegin("countSlaPolicy", thrift.STRUCT, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:countSlaPolicy: ", p), err) - } - if err := p.CountSlaPolicy.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.CountSlaPolicy), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:countSlaPolicy: ", p), err) - } - } - return err -} - -func (p *SlaPolicy) writeField3(oprot thrift.TProtocol) (err error) { - if p.IsSetCoordinatorSlaPolicy() { - if err := oprot.WriteFieldBegin("coordinatorSlaPolicy", thrift.STRUCT, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:coordinatorSlaPolicy: ", p), err) - } - if err := p.CoordinatorSlaPolicy.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.CoordinatorSlaPolicy), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:coordinatorSlaPolicy: ", p), err) - } - } - return err -} - -func (p *SlaPolicy) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("SlaPolicy(%+v)", *p) -} - -// Description of the tasks contained within a job. -// -// Attributes: -// - Job: Job task belongs to. -// - Owner: contains the role component of JobKey -// - IsService -// - Priority -// - MaxTaskFailures -// - Production: Whether this is a production task, which can preempt. -// - Tier: Task tier type. -// - Resources: All resources required to run a task. -// - Constraints -// - MesosFetcherUris: Resources to retrieve with Mesos Fetcher -// - TaskLinks: Custom links to include when displaying this task on the scheduler dashboard. Keys are anchor -// text, values are URLs. Wildcards are supported for dynamic link crafting based on host, ports, -// instance, etc. -// - ContactEmail -// - ExecutorConfig: Executor configuration -// - Metadata: Used to display additional details in the UI. -// - PartitionPolicy: Policy for how to deal with task partitions -// - SlaPolicy: SLA requirements to be met during maintenance -// - Container: the container the task should use to execute -type TaskConfig struct { - // unused fields # 1 to 6 - IsService bool `thrift:"isService,7" json:"isService"` - // unused fields # 8 to 10 - Priority int32 `thrift:"priority,11" json:"priority"` - // unused field # 12 - MaxTaskFailures int32 `thrift:"maxTaskFailures,13" json:"maxTaskFailures"` - // unused fields # 14 to 16 - Owner *Identity `thrift:"owner,17" json:"owner"` - Production *bool `thrift:"production,18" json:"production,omitempty"` - // unused field # 19 - Constraints map[*Constraint]bool `thrift:"constraints,20" json:"constraints"` - // unused field # 21 - TaskLinks map[string]string `thrift:"taskLinks,22" json:"taskLinks,omitempty"` - ContactEmail *string `thrift:"contactEmail,23" json:"contactEmail,omitempty"` - // unused field # 24 - ExecutorConfig *ExecutorConfig `thrift:"executorConfig,25" json:"executorConfig,omitempty"` - // unused field # 26 - Metadata map[*Metadata]bool `thrift:"metadata,27" json:"metadata,omitempty"` - Job *JobKey `thrift:"job,28" json:"job"` - Container *Container `thrift:"container,29" json:"container"` - Tier *string `thrift:"tier,30" json:"tier,omitempty"` - // unused field # 31 - Resources map[*Resource]bool `thrift:"resources,32" json:"resources"` - MesosFetcherUris map[*MesosFetcherURI]bool `thrift:"mesosFetcherUris,33" json:"mesosFetcherUris,omitempty"` - PartitionPolicy *PartitionPolicy `thrift:"partitionPolicy,34" json:"partitionPolicy,omitempty"` - SlaPolicy *SlaPolicy `thrift:"slaPolicy,35" json:"slaPolicy,omitempty"` -} - -func NewTaskConfig() *TaskConfig { - return &TaskConfig{} -} - -var TaskConfig_Job_DEFAULT *JobKey - -func (p *TaskConfig) GetJob() *JobKey { - if !p.IsSetJob() { - return TaskConfig_Job_DEFAULT - } - return p.Job -} - -var TaskConfig_Owner_DEFAULT *Identity - -func (p *TaskConfig) GetOwner() *Identity { - if !p.IsSetOwner() { - return TaskConfig_Owner_DEFAULT - } - return p.Owner -} - -func (p *TaskConfig) GetIsService() bool { - return p.IsService -} - -func (p *TaskConfig) GetPriority() int32 { - return p.Priority -} - -func (p *TaskConfig) GetMaxTaskFailures() int32 { - return p.MaxTaskFailures -} - -var TaskConfig_Production_DEFAULT bool - -func (p *TaskConfig) GetProduction() bool { - if !p.IsSetProduction() { - return TaskConfig_Production_DEFAULT - } - return *p.Production -} - -var TaskConfig_Tier_DEFAULT string - -func (p *TaskConfig) GetTier() string { - if !p.IsSetTier() { - return TaskConfig_Tier_DEFAULT - } - return *p.Tier -} - -func (p *TaskConfig) GetResources() map[*Resource]bool { - return p.Resources -} - -func (p *TaskConfig) GetConstraints() map[*Constraint]bool { - return p.Constraints -} - -var TaskConfig_MesosFetcherUris_DEFAULT map[*MesosFetcherURI]bool - -func (p *TaskConfig) GetMesosFetcherUris() map[*MesosFetcherURI]bool { - return p.MesosFetcherUris -} - -var TaskConfig_TaskLinks_DEFAULT map[string]string - -func (p *TaskConfig) GetTaskLinks() map[string]string { - return p.TaskLinks -} - -var TaskConfig_ContactEmail_DEFAULT string - -func (p *TaskConfig) GetContactEmail() string { - if !p.IsSetContactEmail() { - return TaskConfig_ContactEmail_DEFAULT - } - return *p.ContactEmail -} - -var TaskConfig_ExecutorConfig_DEFAULT *ExecutorConfig - -func (p *TaskConfig) GetExecutorConfig() *ExecutorConfig { - if !p.IsSetExecutorConfig() { - return TaskConfig_ExecutorConfig_DEFAULT - } - return p.ExecutorConfig -} - -var TaskConfig_Metadata_DEFAULT map[*Metadata]bool - -func (p *TaskConfig) GetMetadata() map[*Metadata]bool { - return p.Metadata -} - -var TaskConfig_PartitionPolicy_DEFAULT *PartitionPolicy - -func (p *TaskConfig) GetPartitionPolicy() *PartitionPolicy { - if !p.IsSetPartitionPolicy() { - return TaskConfig_PartitionPolicy_DEFAULT - } - return p.PartitionPolicy -} - -var TaskConfig_SlaPolicy_DEFAULT *SlaPolicy - -func (p *TaskConfig) GetSlaPolicy() *SlaPolicy { - if !p.IsSetSlaPolicy() { - return TaskConfig_SlaPolicy_DEFAULT - } - return p.SlaPolicy -} - -var TaskConfig_Container_DEFAULT *Container = &Container{ - Mesos: &MesosContainer{}, -} - -func (p *TaskConfig) GetContainer() *Container { - if !p.IsSetContainer() { - return TaskConfig_Container_DEFAULT - } - return p.Container -} -func (p *TaskConfig) IsSetJob() bool { - return p.Job != nil -} - -func (p *TaskConfig) IsSetOwner() bool { - return p.Owner != nil -} - -func (p *TaskConfig) IsSetProduction() bool { - return p.Production != nil -} - -func (p *TaskConfig) IsSetTier() bool { - return p.Tier != nil -} - -func (p *TaskConfig) IsSetMesosFetcherUris() bool { - return p.MesosFetcherUris != nil -} - -func (p *TaskConfig) IsSetTaskLinks() bool { - return p.TaskLinks != nil -} - -func (p *TaskConfig) IsSetContactEmail() bool { - return p.ContactEmail != nil -} - -func (p *TaskConfig) IsSetExecutorConfig() bool { - return p.ExecutorConfig != nil -} - -func (p *TaskConfig) IsSetMetadata() bool { - return p.Metadata != nil -} - -func (p *TaskConfig) IsSetPartitionPolicy() bool { - return p.PartitionPolicy != nil -} - -func (p *TaskConfig) IsSetSlaPolicy() bool { - return p.SlaPolicy != nil -} - -func (p *TaskConfig) IsSetContainer() bool { - return p.Container != nil -} - -func (p *TaskConfig) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 28: - if err := p.readField28(iprot); err != nil { - return err - } - case 17: - if err := p.readField17(iprot); err != nil { - return err - } - case 7: - if err := p.readField7(iprot); err != nil { - return err - } - case 11: - if err := p.readField11(iprot); err != nil { - return err - } - case 13: - if err := p.readField13(iprot); err != nil { - return err - } - case 18: - if err := p.readField18(iprot); err != nil { - return err - } - case 30: - if err := p.readField30(iprot); err != nil { - return err - } - case 32: - if err := p.readField32(iprot); err != nil { - return err - } - case 20: - if err := p.readField20(iprot); err != nil { - return err - } - case 33: - if err := p.readField33(iprot); err != nil { - return err - } - case 22: - if err := p.readField22(iprot); err != nil { - return err - } - case 23: - if err := p.readField23(iprot); err != nil { - return err - } - case 25: - if err := p.readField25(iprot); err != nil { - return err - } - case 27: - if err := p.readField27(iprot); err != nil { - return err - } - case 34: - if err := p.readField34(iprot); err != nil { - return err - } - case 35: - if err := p.readField35(iprot); err != nil { - return err - } - case 29: - if err := p.readField29(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *TaskConfig) readField28(iprot thrift.TProtocol) error { - p.Job = &JobKey{} - if err := p.Job.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Job), err) - } - return nil -} - -func (p *TaskConfig) readField17(iprot thrift.TProtocol) error { - p.Owner = &Identity{} - if err := p.Owner.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Owner), err) - } - return nil -} - -func (p *TaskConfig) readField7(iprot thrift.TProtocol) error { - if v, err := iprot.ReadBool(); err != nil { - return thrift.PrependError("error reading field 7: ", err) - } else { - p.IsService = v - } - return nil -} - -func (p *TaskConfig) readField11(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 11: ", err) - } else { - p.Priority = v - } - return nil -} - -func (p *TaskConfig) readField13(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 13: ", err) - } else { - p.MaxTaskFailures = v - } - return nil -} - -func (p *TaskConfig) readField18(iprot thrift.TProtocol) error { - if v, err := iprot.ReadBool(); err != nil { - return thrift.PrependError("error reading field 18: ", err) - } else { - p.Production = &v - } - return nil -} - -func (p *TaskConfig) readField30(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 30: ", err) - } else { - p.Tier = &v - } - return nil -} - -func (p *TaskConfig) readField32(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*Resource]bool, size) - p.Resources = tSet - for i := 0; i < size; i++ { - _elem5 := &Resource{} - if err := _elem5.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem5), err) - } - p.Resources[_elem5] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *TaskConfig) readField20(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*Constraint]bool, size) - p.Constraints = tSet - for i := 0; i < size; i++ { - _elem6 := &Constraint{} - if err := _elem6.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem6), err) - } - p.Constraints[_elem6] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *TaskConfig) readField33(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*MesosFetcherURI]bool, size) - p.MesosFetcherUris = tSet - for i := 0; i < size; i++ { - _elem7 := &MesosFetcherURI{} - if err := _elem7.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem7), err) - } - p.MesosFetcherUris[_elem7] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *TaskConfig) readField22(iprot thrift.TProtocol) error { - _, _, size, err := iprot.ReadMapBegin() - if err != nil { - return thrift.PrependError("error reading map begin: ", err) - } - tMap := make(map[string]string, size) - p.TaskLinks = tMap - for i := 0; i < size; i++ { - var _key8 string - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 0: ", err) - } else { - _key8 = v - } - var _val9 string - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 0: ", err) - } else { - _val9 = v - } - p.TaskLinks[_key8] = _val9 - } - if err := iprot.ReadMapEnd(); err != nil { - return thrift.PrependError("error reading map end: ", err) - } - return nil -} - -func (p *TaskConfig) readField23(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 23: ", err) - } else { - p.ContactEmail = &v - } - return nil -} - -func (p *TaskConfig) readField25(iprot thrift.TProtocol) error { - p.ExecutorConfig = &ExecutorConfig{} - if err := p.ExecutorConfig.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.ExecutorConfig), err) - } - return nil -} - -func (p *TaskConfig) readField27(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*Metadata]bool, size) - p.Metadata = tSet - for i := 0; i < size; i++ { - _elem10 := &Metadata{} - if err := _elem10.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem10), err) - } - p.Metadata[_elem10] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *TaskConfig) readField34(iprot thrift.TProtocol) error { - p.PartitionPolicy = &PartitionPolicy{} - if err := p.PartitionPolicy.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.PartitionPolicy), err) - } - return nil -} - -func (p *TaskConfig) readField35(iprot thrift.TProtocol) error { - p.SlaPolicy = &SlaPolicy{} - if err := p.SlaPolicy.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.SlaPolicy), err) - } - return nil -} - -func (p *TaskConfig) readField29(iprot thrift.TProtocol) error { - p.Container = &Container{} - if err := p.Container.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Container), err) - } - return nil -} - -func (p *TaskConfig) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("TaskConfig"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField7(oprot); err != nil { - return err - } - if err := p.writeField11(oprot); err != nil { - return err - } - if err := p.writeField13(oprot); err != nil { - return err - } - if err := p.writeField17(oprot); err != nil { - return err - } - if err := p.writeField18(oprot); err != nil { - return err - } - if err := p.writeField20(oprot); err != nil { - return err - } - if err := p.writeField22(oprot); err != nil { - return err - } - if err := p.writeField23(oprot); err != nil { - return err - } - if err := p.writeField25(oprot); err != nil { - return err - } - if err := p.writeField27(oprot); err != nil { - return err - } - if err := p.writeField28(oprot); err != nil { - return err - } - if err := p.writeField29(oprot); err != nil { - return err - } - if err := p.writeField30(oprot); err != nil { - return err - } - if err := p.writeField32(oprot); err != nil { - return err - } - if err := p.writeField33(oprot); err != nil { - return err - } - if err := p.writeField34(oprot); err != nil { - return err - } - if err := p.writeField35(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *TaskConfig) writeField7(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("isService", thrift.BOOL, 7); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 7:isService: ", p), err) - } - if err := oprot.WriteBool(bool(p.IsService)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.isService (7) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 7:isService: ", p), err) - } - return err -} - -func (p *TaskConfig) writeField11(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("priority", thrift.I32, 11); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 11:priority: ", p), err) - } - if err := oprot.WriteI32(int32(p.Priority)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.priority (11) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 11:priority: ", p), err) - } - return err -} - -func (p *TaskConfig) writeField13(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("maxTaskFailures", thrift.I32, 13); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 13:maxTaskFailures: ", p), err) - } - if err := oprot.WriteI32(int32(p.MaxTaskFailures)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.maxTaskFailures (13) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 13:maxTaskFailures: ", p), err) - } - return err -} - -func (p *TaskConfig) writeField17(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("owner", thrift.STRUCT, 17); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 17:owner: ", p), err) - } - if err := p.Owner.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Owner), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 17:owner: ", p), err) - } - return err -} - -func (p *TaskConfig) writeField18(oprot thrift.TProtocol) (err error) { - if p.IsSetProduction() { - if err := oprot.WriteFieldBegin("production", thrift.BOOL, 18); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 18:production: ", p), err) - } - if err := oprot.WriteBool(bool(*p.Production)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.production (18) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 18:production: ", p), err) - } - } - return err -} - -func (p *TaskConfig) writeField20(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("constraints", thrift.SET, 20); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 20:constraints: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Constraints)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Constraints { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 20:constraints: ", p), err) - } - return err -} - -func (p *TaskConfig) writeField22(oprot thrift.TProtocol) (err error) { - if p.IsSetTaskLinks() { - if err := oprot.WriteFieldBegin("taskLinks", thrift.MAP, 22); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 22:taskLinks: ", p), err) - } - if err := oprot.WriteMapBegin(thrift.STRING, thrift.STRING, len(p.TaskLinks)); err != nil { - return thrift.PrependError("error writing map begin: ", err) - } - for k, v := range p.TaskLinks { - if err := oprot.WriteString(string(k)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) - } - if err := oprot.WriteString(string(v)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) - } - } - if err := oprot.WriteMapEnd(); err != nil { - return thrift.PrependError("error writing map end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 22:taskLinks: ", p), err) - } - } - return err -} - -func (p *TaskConfig) writeField23(oprot thrift.TProtocol) (err error) { - if p.IsSetContactEmail() { - if err := oprot.WriteFieldBegin("contactEmail", thrift.STRING, 23); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 23:contactEmail: ", p), err) - } - if err := oprot.WriteString(string(*p.ContactEmail)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.contactEmail (23) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 23:contactEmail: ", p), err) - } - } - return err -} - -func (p *TaskConfig) writeField25(oprot thrift.TProtocol) (err error) { - if p.IsSetExecutorConfig() { - if err := oprot.WriteFieldBegin("executorConfig", thrift.STRUCT, 25); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 25:executorConfig: ", p), err) - } - if err := p.ExecutorConfig.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.ExecutorConfig), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 25:executorConfig: ", p), err) - } - } - return err -} - -func (p *TaskConfig) writeField27(oprot thrift.TProtocol) (err error) { - if p.IsSetMetadata() { - if err := oprot.WriteFieldBegin("metadata", thrift.SET, 27); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 27:metadata: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Metadata)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Metadata { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 27:metadata: ", p), err) - } - } - return err -} - -func (p *TaskConfig) writeField28(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("job", thrift.STRUCT, 28); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 28:job: ", p), err) - } - if err := p.Job.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Job), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 28:job: ", p), err) - } - return err -} - -func (p *TaskConfig) writeField29(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("container", thrift.STRUCT, 29); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 29:container: ", p), err) - } - if err := p.Container.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Container), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 29:container: ", p), err) - } - return err -} - -func (p *TaskConfig) writeField30(oprot thrift.TProtocol) (err error) { - if p.IsSetTier() { - if err := oprot.WriteFieldBegin("tier", thrift.STRING, 30); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 30:tier: ", p), err) - } - if err := oprot.WriteString(string(*p.Tier)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.tier (30) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 30:tier: ", p), err) - } - } - return err -} - -func (p *TaskConfig) writeField32(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("resources", thrift.SET, 32); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 32:resources: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Resources)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Resources { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 32:resources: ", p), err) - } - return err -} - -func (p *TaskConfig) writeField33(oprot thrift.TProtocol) (err error) { - if p.IsSetMesosFetcherUris() { - if err := oprot.WriteFieldBegin("mesosFetcherUris", thrift.SET, 33); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 33:mesosFetcherUris: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.MesosFetcherUris)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.MesosFetcherUris { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 33:mesosFetcherUris: ", p), err) - } - } - return err -} - -func (p *TaskConfig) writeField34(oprot thrift.TProtocol) (err error) { - if p.IsSetPartitionPolicy() { - if err := oprot.WriteFieldBegin("partitionPolicy", thrift.STRUCT, 34); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 34:partitionPolicy: ", p), err) - } - if err := p.PartitionPolicy.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.PartitionPolicy), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 34:partitionPolicy: ", p), err) - } - } - return err -} - -func (p *TaskConfig) writeField35(oprot thrift.TProtocol) (err error) { - if p.IsSetSlaPolicy() { - if err := oprot.WriteFieldBegin("slaPolicy", thrift.STRUCT, 35); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 35:slaPolicy: ", p), err) - } - if err := p.SlaPolicy.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.SlaPolicy), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 35:slaPolicy: ", p), err) - } - } - return err -} - -func (p *TaskConfig) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("TaskConfig(%+v)", *p) -} - -// Attributes: -// - Resources: Aggregated resource values. -type ResourceAggregate struct { - // unused fields # 1 to 3 - Resources map[*Resource]bool `thrift:"resources,4" json:"resources"` -} - -func NewResourceAggregate() *ResourceAggregate { - return &ResourceAggregate{} -} - -func (p *ResourceAggregate) GetResources() map[*Resource]bool { - return p.Resources -} -func (p *ResourceAggregate) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ResourceAggregate) readField4(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*Resource]bool, size) - p.Resources = tSet - for i := 0; i < size; i++ { - _elem11 := &Resource{} - if err := _elem11.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem11), err) - } - p.Resources[_elem11] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *ResourceAggregate) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("ResourceAggregate"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ResourceAggregate) writeField4(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("resources", thrift.SET, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:resources: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Resources)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Resources { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:resources: ", p), err) - } - return err -} - -func (p *ResourceAggregate) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ResourceAggregate(%+v)", *p) -} - -// Description of an Aurora job. One task will be scheduled for each instance within the job. -// -// Attributes: -// - Key: Key for this job. If not specified name, owner.role, and a reasonable default environment are -// used to construct it server-side. -// - Owner: Owner of this job. -// - CronSchedule: If present, the job will be handled as a cron job with this crontab-syntax schedule. -// - CronCollisionPolicy: Collision policy to use when handling overlapping cron runs. Default is KILL_EXISTING. -// - TaskConfig: Task configuration for this job. -// - InstanceCount: The number of instances in the job. Generated instance IDs for tasks will be in the range -// [0, instances). -type JobConfiguration struct { - // unused fields # 1 to 3 - CronSchedule *string `thrift:"cronSchedule,4" json:"cronSchedule,omitempty"` - CronCollisionPolicy CronCollisionPolicy `thrift:"cronCollisionPolicy,5" json:"cronCollisionPolicy"` - TaskConfig *TaskConfig `thrift:"taskConfig,6" json:"taskConfig"` - Owner *Identity `thrift:"owner,7" json:"owner"` - InstanceCount int32 `thrift:"instanceCount,8" json:"instanceCount"` - Key *JobKey `thrift:"key,9" json:"key"` -} - -func NewJobConfiguration() *JobConfiguration { - return &JobConfiguration{} -} - -var JobConfiguration_Key_DEFAULT *JobKey - -func (p *JobConfiguration) GetKey() *JobKey { - if !p.IsSetKey() { - return JobConfiguration_Key_DEFAULT - } - return p.Key -} - -var JobConfiguration_Owner_DEFAULT *Identity - -func (p *JobConfiguration) GetOwner() *Identity { - if !p.IsSetOwner() { - return JobConfiguration_Owner_DEFAULT - } - return p.Owner -} - -var JobConfiguration_CronSchedule_DEFAULT string - -func (p *JobConfiguration) GetCronSchedule() string { - if !p.IsSetCronSchedule() { - return JobConfiguration_CronSchedule_DEFAULT - } - return *p.CronSchedule -} - -func (p *JobConfiguration) GetCronCollisionPolicy() CronCollisionPolicy { - return p.CronCollisionPolicy -} - -var JobConfiguration_TaskConfig_DEFAULT *TaskConfig - -func (p *JobConfiguration) GetTaskConfig() *TaskConfig { - if !p.IsSetTaskConfig() { - return JobConfiguration_TaskConfig_DEFAULT - } - return p.TaskConfig -} - -func (p *JobConfiguration) GetInstanceCount() int32 { - return p.InstanceCount -} -func (p *JobConfiguration) IsSetKey() bool { - return p.Key != nil -} - -func (p *JobConfiguration) IsSetOwner() bool { - return p.Owner != nil -} - -func (p *JobConfiguration) IsSetCronSchedule() bool { - return p.CronSchedule != nil -} - -func (p *JobConfiguration) IsSetTaskConfig() bool { - return p.TaskConfig != nil -} - -func (p *JobConfiguration) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 9: - if err := p.readField9(iprot); err != nil { - return err - } - case 7: - if err := p.readField7(iprot); err != nil { - return err - } - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - case 5: - if err := p.readField5(iprot); err != nil { - return err - } - case 6: - if err := p.readField6(iprot); err != nil { - return err - } - case 8: - if err := p.readField8(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *JobConfiguration) readField9(iprot thrift.TProtocol) error { - p.Key = &JobKey{} - if err := p.Key.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) - } - return nil -} - -func (p *JobConfiguration) readField7(iprot thrift.TProtocol) error { - p.Owner = &Identity{} - if err := p.Owner.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Owner), err) - } - return nil -} - -func (p *JobConfiguration) readField4(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 4: ", err) - } else { - p.CronSchedule = &v - } - return nil -} - -func (p *JobConfiguration) readField5(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 5: ", err) - } else { - temp := CronCollisionPolicy(v) - p.CronCollisionPolicy = temp - } - return nil -} - -func (p *JobConfiguration) readField6(iprot thrift.TProtocol) error { - p.TaskConfig = &TaskConfig{} - if err := p.TaskConfig.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.TaskConfig), err) - } - return nil -} - -func (p *JobConfiguration) readField8(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 8: ", err) - } else { - p.InstanceCount = v - } - return nil -} - -func (p *JobConfiguration) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("JobConfiguration"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := p.writeField5(oprot); err != nil { - return err - } - if err := p.writeField6(oprot); err != nil { - return err - } - if err := p.writeField7(oprot); err != nil { - return err - } - if err := p.writeField8(oprot); err != nil { - return err - } - if err := p.writeField9(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *JobConfiguration) writeField4(oprot thrift.TProtocol) (err error) { - if p.IsSetCronSchedule() { - if err := oprot.WriteFieldBegin("cronSchedule", thrift.STRING, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:cronSchedule: ", p), err) - } - if err := oprot.WriteString(string(*p.CronSchedule)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.cronSchedule (4) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:cronSchedule: ", p), err) - } - } - return err -} - -func (p *JobConfiguration) writeField5(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("cronCollisionPolicy", thrift.I32, 5); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:cronCollisionPolicy: ", p), err) - } - if err := oprot.WriteI32(int32(p.CronCollisionPolicy)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.cronCollisionPolicy (5) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 5:cronCollisionPolicy: ", p), err) - } - return err -} - -func (p *JobConfiguration) writeField6(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("taskConfig", thrift.STRUCT, 6); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 6:taskConfig: ", p), err) - } - if err := p.TaskConfig.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.TaskConfig), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 6:taskConfig: ", p), err) - } - return err -} - -func (p *JobConfiguration) writeField7(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("owner", thrift.STRUCT, 7); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 7:owner: ", p), err) - } - if err := p.Owner.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Owner), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 7:owner: ", p), err) - } - return err -} - -func (p *JobConfiguration) writeField8(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("instanceCount", thrift.I32, 8); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 8:instanceCount: ", p), err) - } - if err := oprot.WriteI32(int32(p.InstanceCount)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.instanceCount (8) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 8:instanceCount: ", p), err) - } - return err -} - -func (p *JobConfiguration) writeField9(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 9); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 9:key: ", p), err) - } - if err := p.Key.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 9:key: ", p), err) - } - return err -} - -func (p *JobConfiguration) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("JobConfiguration(%+v)", *p) -} - -// Attributes: -// - ActiveTaskCount: Number of tasks in active state for this job. -// - FinishedTaskCount: Number of tasks in finished state for this job. -// - FailedTaskCount: Number of failed tasks for this job. -// - PendingTaskCount: Number of tasks in pending state for this job. -type JobStats struct { - ActiveTaskCount int32 `thrift:"activeTaskCount,1" json:"activeTaskCount"` - FinishedTaskCount int32 `thrift:"finishedTaskCount,2" json:"finishedTaskCount"` - FailedTaskCount int32 `thrift:"failedTaskCount,3" json:"failedTaskCount"` - PendingTaskCount int32 `thrift:"pendingTaskCount,4" json:"pendingTaskCount"` -} - -func NewJobStats() *JobStats { - return &JobStats{} -} - -func (p *JobStats) GetActiveTaskCount() int32 { - return p.ActiveTaskCount -} - -func (p *JobStats) GetFinishedTaskCount() int32 { - return p.FinishedTaskCount -} - -func (p *JobStats) GetFailedTaskCount() int32 { - return p.FailedTaskCount -} - -func (p *JobStats) GetPendingTaskCount() int32 { - return p.PendingTaskCount -} -func (p *JobStats) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *JobStats) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.ActiveTaskCount = v - } - return nil -} - -func (p *JobStats) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.FinishedTaskCount = v - } - return nil -} - -func (p *JobStats) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.FailedTaskCount = v - } - return nil -} - -func (p *JobStats) readField4(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 4: ", err) - } else { - p.PendingTaskCount = v - } - return nil -} - -func (p *JobStats) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("JobStats"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *JobStats) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("activeTaskCount", thrift.I32, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:activeTaskCount: ", p), err) - } - if err := oprot.WriteI32(int32(p.ActiveTaskCount)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.activeTaskCount (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:activeTaskCount: ", p), err) - } - return err -} - -func (p *JobStats) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("finishedTaskCount", thrift.I32, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:finishedTaskCount: ", p), err) - } - if err := oprot.WriteI32(int32(p.FinishedTaskCount)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.finishedTaskCount (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:finishedTaskCount: ", p), err) - } - return err -} - -func (p *JobStats) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("failedTaskCount", thrift.I32, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:failedTaskCount: ", p), err) - } - if err := oprot.WriteI32(int32(p.FailedTaskCount)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.failedTaskCount (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:failedTaskCount: ", p), err) - } - return err -} - -func (p *JobStats) writeField4(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("pendingTaskCount", thrift.I32, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:pendingTaskCount: ", p), err) - } - if err := oprot.WriteI32(int32(p.PendingTaskCount)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.pendingTaskCount (4) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:pendingTaskCount: ", p), err) - } - return err -} - -func (p *JobStats) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("JobStats(%+v)", *p) -} - -// Attributes: -// - Job -// - Stats -// - NextCronRunMs: Timestamp of next cron run in ms since epoch, for a cron job -type JobSummary struct { - Job *JobConfiguration `thrift:"job,1" json:"job"` - Stats *JobStats `thrift:"stats,2" json:"stats"` - NextCronRunMs *int64 `thrift:"nextCronRunMs,3" json:"nextCronRunMs,omitempty"` -} - -func NewJobSummary() *JobSummary { - return &JobSummary{} -} - -var JobSummary_Job_DEFAULT *JobConfiguration - -func (p *JobSummary) GetJob() *JobConfiguration { - if !p.IsSetJob() { - return JobSummary_Job_DEFAULT - } - return p.Job -} - -var JobSummary_Stats_DEFAULT *JobStats - -func (p *JobSummary) GetStats() *JobStats { - if !p.IsSetStats() { - return JobSummary_Stats_DEFAULT - } - return p.Stats -} - -var JobSummary_NextCronRunMs_DEFAULT int64 - -func (p *JobSummary) GetNextCronRunMs() int64 { - if !p.IsSetNextCronRunMs() { - return JobSummary_NextCronRunMs_DEFAULT - } - return *p.NextCronRunMs -} -func (p *JobSummary) IsSetJob() bool { - return p.Job != nil -} - -func (p *JobSummary) IsSetStats() bool { - return p.Stats != nil -} - -func (p *JobSummary) IsSetNextCronRunMs() bool { - return p.NextCronRunMs != nil -} - -func (p *JobSummary) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *JobSummary) readField1(iprot thrift.TProtocol) error { - p.Job = &JobConfiguration{} - if err := p.Job.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Job), err) - } - return nil -} - -func (p *JobSummary) readField2(iprot thrift.TProtocol) error { - p.Stats = &JobStats{} - if err := p.Stats.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Stats), err) - } - return nil -} - -func (p *JobSummary) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI64(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.NextCronRunMs = &v - } - return nil -} - -func (p *JobSummary) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("JobSummary"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *JobSummary) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("job", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:job: ", p), err) - } - if err := p.Job.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Job), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:job: ", p), err) - } - return err -} - -func (p *JobSummary) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("stats", thrift.STRUCT, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:stats: ", p), err) - } - if err := p.Stats.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Stats), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:stats: ", p), err) - } - return err -} - -func (p *JobSummary) writeField3(oprot thrift.TProtocol) (err error) { - if p.IsSetNextCronRunMs() { - if err := oprot.WriteFieldBegin("nextCronRunMs", thrift.I64, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:nextCronRunMs: ", p), err) - } - if err := oprot.WriteI64(int64(*p.NextCronRunMs)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.nextCronRunMs (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:nextCronRunMs: ", p), err) - } - } - return err -} - -func (p *JobSummary) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("JobSummary(%+v)", *p) -} - -// Closed range of integers. -// -// Attributes: -// - First -// - Last -type Range struct { - First int32 `thrift:"first,1" json:"first"` - Last int32 `thrift:"last,2" json:"last"` -} - -func NewRange() *Range { - return &Range{} -} - -func (p *Range) GetFirst() int32 { - return p.First -} - -func (p *Range) GetLast() int32 { - return p.Last -} -func (p *Range) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *Range) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.First = v - } - return nil -} - -func (p *Range) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.Last = v - } - return nil -} - -func (p *Range) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("Range"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *Range) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("first", thrift.I32, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:first: ", p), err) - } - if err := oprot.WriteI32(int32(p.First)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.first (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:first: ", p), err) - } - return err -} - -func (p *Range) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("last", thrift.I32, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:last: ", p), err) - } - if err := oprot.WriteI32(int32(p.Last)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.last (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:last: ", p), err) - } - return err -} - -func (p *Range) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("Range(%+v)", *p) -} - -// Attributes: -// - Config -// - Instances -type ConfigGroup struct { - Config *TaskConfig `thrift:"config,1" json:"config"` - // unused field # 2 - Instances map[*Range]bool `thrift:"instances,3" json:"instances"` -} - -func NewConfigGroup() *ConfigGroup { - return &ConfigGroup{} -} - -var ConfigGroup_Config_DEFAULT *TaskConfig - -func (p *ConfigGroup) GetConfig() *TaskConfig { - if !p.IsSetConfig() { - return ConfigGroup_Config_DEFAULT - } - return p.Config -} - -func (p *ConfigGroup) GetInstances() map[*Range]bool { - return p.Instances -} -func (p *ConfigGroup) IsSetConfig() bool { - return p.Config != nil -} - -func (p *ConfigGroup) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ConfigGroup) readField1(iprot thrift.TProtocol) error { - p.Config = &TaskConfig{} - if err := p.Config.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Config), err) - } - return nil -} - -func (p *ConfigGroup) readField3(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*Range]bool, size) - p.Instances = tSet - for i := 0; i < size; i++ { - _elem12 := &Range{} - if err := _elem12.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem12), err) - } - p.Instances[_elem12] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *ConfigGroup) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("ConfigGroup"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ConfigGroup) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("config", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:config: ", p), err) - } - if err := p.Config.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Config), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:config: ", p), err) - } - return err -} - -func (p *ConfigGroup) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("instances", thrift.SET, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:instances: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Instances)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Instances { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:instances: ", p), err) - } - return err -} - -func (p *ConfigGroup) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ConfigGroup(%+v)", *p) -} - -// Attributes: -// - Key -// - Groups -type ConfigSummary struct { - Key *JobKey `thrift:"key,1" json:"key"` - Groups map[*ConfigGroup]bool `thrift:"groups,2" json:"groups"` -} - -func NewConfigSummary() *ConfigSummary { - return &ConfigSummary{} -} - -var ConfigSummary_Key_DEFAULT *JobKey - -func (p *ConfigSummary) GetKey() *JobKey { - if !p.IsSetKey() { - return ConfigSummary_Key_DEFAULT - } - return p.Key -} - -func (p *ConfigSummary) GetGroups() map[*ConfigGroup]bool { - return p.Groups -} -func (p *ConfigSummary) IsSetKey() bool { - return p.Key != nil -} - -func (p *ConfigSummary) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ConfigSummary) readField1(iprot thrift.TProtocol) error { - p.Key = &JobKey{} - if err := p.Key.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) - } - return nil -} - -func (p *ConfigSummary) readField2(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*ConfigGroup]bool, size) - p.Groups = tSet - for i := 0; i < size; i++ { - _elem13 := &ConfigGroup{} - if err := _elem13.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem13), err) - } - p.Groups[_elem13] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *ConfigSummary) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("ConfigSummary"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ConfigSummary) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:key: ", p), err) - } - if err := p.Key.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:key: ", p), err) - } - return err -} - -func (p *ConfigSummary) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("groups", thrift.SET, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:groups: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Groups)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Groups { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:groups: ", p), err) - } - return err -} - -func (p *ConfigSummary) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ConfigSummary(%+v)", *p) -} - -// Attributes: -// - TaskConfig -type PopulateJobResult_ struct { - // unused field # 1 - TaskConfig *TaskConfig `thrift:"taskConfig,2" json:"taskConfig"` -} - -func NewPopulateJobResult_() *PopulateJobResult_ { - return &PopulateJobResult_{} -} - -var PopulateJobResult__TaskConfig_DEFAULT *TaskConfig - -func (p *PopulateJobResult_) GetTaskConfig() *TaskConfig { - if !p.IsSetTaskConfig() { - return PopulateJobResult__TaskConfig_DEFAULT - } - return p.TaskConfig -} -func (p *PopulateJobResult_) IsSetTaskConfig() bool { - return p.TaskConfig != nil -} - -func (p *PopulateJobResult_) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *PopulateJobResult_) readField2(iprot thrift.TProtocol) error { - p.TaskConfig = &TaskConfig{} - if err := p.TaskConfig.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.TaskConfig), err) - } - return nil -} - -func (p *PopulateJobResult_) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("PopulateJobResult"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *PopulateJobResult_) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("taskConfig", thrift.STRUCT, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:taskConfig: ", p), err) - } - if err := p.TaskConfig.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.TaskConfig), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:taskConfig: ", p), err) - } - return err -} - -func (p *PopulateJobResult_) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("PopulateJobResult_(%+v)", *p) -} - -// Attributes: -// - Quota: Total allocated resource quota. -// - ProdSharedConsumption: Resources consumed by production jobs from a shared resource pool. -// - NonProdSharedConsumption: Resources consumed by non-production jobs from a shared resource pool. -// - ProdDedicatedConsumption: Resources consumed by production jobs from a dedicated resource pool. -// - NonProdDedicatedConsumption: Resources consumed by non-production jobs from a dedicated resource pool. -type GetQuotaResult_ struct { - Quota *ResourceAggregate `thrift:"quota,1" json:"quota"` - ProdSharedConsumption *ResourceAggregate `thrift:"prodSharedConsumption,2" json:"prodSharedConsumption,omitempty"` - NonProdSharedConsumption *ResourceAggregate `thrift:"nonProdSharedConsumption,3" json:"nonProdSharedConsumption,omitempty"` - ProdDedicatedConsumption *ResourceAggregate `thrift:"prodDedicatedConsumption,4" json:"prodDedicatedConsumption,omitempty"` - NonProdDedicatedConsumption *ResourceAggregate `thrift:"nonProdDedicatedConsumption,5" json:"nonProdDedicatedConsumption,omitempty"` -} - -func NewGetQuotaResult_() *GetQuotaResult_ { - return &GetQuotaResult_{} -} - -var GetQuotaResult__Quota_DEFAULT *ResourceAggregate - -func (p *GetQuotaResult_) GetQuota() *ResourceAggregate { - if !p.IsSetQuota() { - return GetQuotaResult__Quota_DEFAULT - } - return p.Quota -} - -var GetQuotaResult__ProdSharedConsumption_DEFAULT *ResourceAggregate - -func (p *GetQuotaResult_) GetProdSharedConsumption() *ResourceAggregate { - if !p.IsSetProdSharedConsumption() { - return GetQuotaResult__ProdSharedConsumption_DEFAULT - } - return p.ProdSharedConsumption -} - -var GetQuotaResult__NonProdSharedConsumption_DEFAULT *ResourceAggregate - -func (p *GetQuotaResult_) GetNonProdSharedConsumption() *ResourceAggregate { - if !p.IsSetNonProdSharedConsumption() { - return GetQuotaResult__NonProdSharedConsumption_DEFAULT - } - return p.NonProdSharedConsumption -} - -var GetQuotaResult__ProdDedicatedConsumption_DEFAULT *ResourceAggregate - -func (p *GetQuotaResult_) GetProdDedicatedConsumption() *ResourceAggregate { - if !p.IsSetProdDedicatedConsumption() { - return GetQuotaResult__ProdDedicatedConsumption_DEFAULT - } - return p.ProdDedicatedConsumption -} - -var GetQuotaResult__NonProdDedicatedConsumption_DEFAULT *ResourceAggregate - -func (p *GetQuotaResult_) GetNonProdDedicatedConsumption() *ResourceAggregate { - if !p.IsSetNonProdDedicatedConsumption() { - return GetQuotaResult__NonProdDedicatedConsumption_DEFAULT - } - return p.NonProdDedicatedConsumption -} -func (p *GetQuotaResult_) IsSetQuota() bool { - return p.Quota != nil -} - -func (p *GetQuotaResult_) IsSetProdSharedConsumption() bool { - return p.ProdSharedConsumption != nil -} - -func (p *GetQuotaResult_) IsSetNonProdSharedConsumption() bool { - return p.NonProdSharedConsumption != nil -} - -func (p *GetQuotaResult_) IsSetProdDedicatedConsumption() bool { - return p.ProdDedicatedConsumption != nil -} - -func (p *GetQuotaResult_) IsSetNonProdDedicatedConsumption() bool { - return p.NonProdDedicatedConsumption != nil -} - -func (p *GetQuotaResult_) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - case 5: - if err := p.readField5(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *GetQuotaResult_) readField1(iprot thrift.TProtocol) error { - p.Quota = &ResourceAggregate{} - if err := p.Quota.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Quota), err) - } - return nil -} - -func (p *GetQuotaResult_) readField2(iprot thrift.TProtocol) error { - p.ProdSharedConsumption = &ResourceAggregate{} - if err := p.ProdSharedConsumption.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.ProdSharedConsumption), err) - } - return nil -} - -func (p *GetQuotaResult_) readField3(iprot thrift.TProtocol) error { - p.NonProdSharedConsumption = &ResourceAggregate{} - if err := p.NonProdSharedConsumption.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.NonProdSharedConsumption), err) - } - return nil -} - -func (p *GetQuotaResult_) readField4(iprot thrift.TProtocol) error { - p.ProdDedicatedConsumption = &ResourceAggregate{} - if err := p.ProdDedicatedConsumption.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.ProdDedicatedConsumption), err) - } - return nil -} - -func (p *GetQuotaResult_) readField5(iprot thrift.TProtocol) error { - p.NonProdDedicatedConsumption = &ResourceAggregate{} - if err := p.NonProdDedicatedConsumption.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.NonProdDedicatedConsumption), err) - } - return nil -} - -func (p *GetQuotaResult_) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("GetQuotaResult"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := p.writeField5(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *GetQuotaResult_) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("quota", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:quota: ", p), err) - } - if err := p.Quota.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Quota), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:quota: ", p), err) - } - return err -} - -func (p *GetQuotaResult_) writeField2(oprot thrift.TProtocol) (err error) { - if p.IsSetProdSharedConsumption() { - if err := oprot.WriteFieldBegin("prodSharedConsumption", thrift.STRUCT, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:prodSharedConsumption: ", p), err) - } - if err := p.ProdSharedConsumption.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.ProdSharedConsumption), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:prodSharedConsumption: ", p), err) - } - } - return err -} - -func (p *GetQuotaResult_) writeField3(oprot thrift.TProtocol) (err error) { - if p.IsSetNonProdSharedConsumption() { - if err := oprot.WriteFieldBegin("nonProdSharedConsumption", thrift.STRUCT, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:nonProdSharedConsumption: ", p), err) - } - if err := p.NonProdSharedConsumption.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.NonProdSharedConsumption), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:nonProdSharedConsumption: ", p), err) - } - } - return err -} - -func (p *GetQuotaResult_) writeField4(oprot thrift.TProtocol) (err error) { - if p.IsSetProdDedicatedConsumption() { - if err := oprot.WriteFieldBegin("prodDedicatedConsumption", thrift.STRUCT, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:prodDedicatedConsumption: ", p), err) - } - if err := p.ProdDedicatedConsumption.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.ProdDedicatedConsumption), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:prodDedicatedConsumption: ", p), err) - } - } - return err -} - -func (p *GetQuotaResult_) writeField5(oprot thrift.TProtocol) (err error) { - if p.IsSetNonProdDedicatedConsumption() { - if err := oprot.WriteFieldBegin("nonProdDedicatedConsumption", thrift.STRUCT, 5); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:nonProdDedicatedConsumption: ", p), err) - } - if err := p.NonProdDedicatedConsumption.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.NonProdDedicatedConsumption), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 5:nonProdDedicatedConsumption: ", p), err) - } - } - return err -} - -func (p *GetQuotaResult_) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("GetQuotaResult_(%+v)", *p) -} - -// Event marking a state transition within a task's lifecycle. -// -// Attributes: -// - Timestamp: Epoch timestamp in milliseconds. -// - Status: New status of the task. -// - Message: Audit message that explains why a transition occurred. -// - Scheduler: Hostname of the scheduler machine that performed the event. -type TaskEvent struct { - Timestamp int64 `thrift:"timestamp,1" json:"timestamp"` - Status ScheduleStatus `thrift:"status,2" json:"status"` - Message *string `thrift:"message,3" json:"message,omitempty"` - Scheduler *string `thrift:"scheduler,4" json:"scheduler,omitempty"` -} - -func NewTaskEvent() *TaskEvent { - return &TaskEvent{} -} - -func (p *TaskEvent) GetTimestamp() int64 { - return p.Timestamp -} - -func (p *TaskEvent) GetStatus() ScheduleStatus { - return p.Status -} - -var TaskEvent_Message_DEFAULT string - -func (p *TaskEvent) GetMessage() string { - if !p.IsSetMessage() { - return TaskEvent_Message_DEFAULT - } - return *p.Message -} - -var TaskEvent_Scheduler_DEFAULT string - -func (p *TaskEvent) GetScheduler() string { - if !p.IsSetScheduler() { - return TaskEvent_Scheduler_DEFAULT - } - return *p.Scheduler -} -func (p *TaskEvent) IsSetMessage() bool { - return p.Message != nil -} - -func (p *TaskEvent) IsSetScheduler() bool { - return p.Scheduler != nil -} - -func (p *TaskEvent) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *TaskEvent) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI64(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Timestamp = v - } - return nil -} - -func (p *TaskEvent) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - temp := ScheduleStatus(v) - p.Status = temp - } - return nil -} - -func (p *TaskEvent) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.Message = &v - } - return nil -} - -func (p *TaskEvent) readField4(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 4: ", err) - } else { - p.Scheduler = &v - } - return nil -} - -func (p *TaskEvent) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("TaskEvent"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *TaskEvent) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("timestamp", thrift.I64, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:timestamp: ", p), err) - } - if err := oprot.WriteI64(int64(p.Timestamp)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.timestamp (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:timestamp: ", p), err) - } - return err -} - -func (p *TaskEvent) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("status", thrift.I32, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:status: ", p), err) - } - if err := oprot.WriteI32(int32(p.Status)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.status (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:status: ", p), err) - } - return err -} - -func (p *TaskEvent) writeField3(oprot thrift.TProtocol) (err error) { - if p.IsSetMessage() { - if err := oprot.WriteFieldBegin("message", thrift.STRING, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:message: ", p), err) - } - if err := oprot.WriteString(string(*p.Message)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.message (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:message: ", p), err) - } - } - return err -} - -func (p *TaskEvent) writeField4(oprot thrift.TProtocol) (err error) { - if p.IsSetScheduler() { - if err := oprot.WriteFieldBegin("scheduler", thrift.STRING, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:scheduler: ", p), err) - } - if err := oprot.WriteString(string(*p.Scheduler)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.scheduler (4) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:scheduler: ", p), err) - } - } - return err -} - -func (p *TaskEvent) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("TaskEvent(%+v)", *p) -} - -// A task assignment that is provided to an executor. -// -// Attributes: -// - TaskId: The mesos task ID for this task. Guaranteed to be globally unique -// - SlaveId: The mesos slave ID that this task has been assigned to. -// This will not be populated for a PENDING task. -// - SlaveHost: The name of the machine that this task has been assigned to. -// This will not be populated for a PENDING task. -// - Task: Information about how to run this task. -// - AssignedPorts: Ports reserved on the machine while this task is running. -// - InstanceId: The instance ID assigned to this task. Instance IDs must be unique and contiguous within a -// job, and will be in the range [0, N-1] (inclusive) for a job that has N instances. -type AssignedTask struct { - TaskId string `thrift:"taskId,1" json:"taskId"` - SlaveId string `thrift:"slaveId,2" json:"slaveId"` - SlaveHost string `thrift:"slaveHost,3" json:"slaveHost"` - Task *TaskConfig `thrift:"task,4" json:"task"` - AssignedPorts map[string]int32 `thrift:"assignedPorts,5" json:"assignedPorts"` - InstanceId int32 `thrift:"instanceId,6" json:"instanceId"` -} - -func NewAssignedTask() *AssignedTask { - return &AssignedTask{} -} - -func (p *AssignedTask) GetTaskId() string { - return p.TaskId -} - -func (p *AssignedTask) GetSlaveId() string { - return p.SlaveId -} - -func (p *AssignedTask) GetSlaveHost() string { - return p.SlaveHost -} - -var AssignedTask_Task_DEFAULT *TaskConfig - -func (p *AssignedTask) GetTask() *TaskConfig { - if !p.IsSetTask() { - return AssignedTask_Task_DEFAULT - } - return p.Task -} - -func (p *AssignedTask) GetAssignedPorts() map[string]int32 { - return p.AssignedPorts -} - -func (p *AssignedTask) GetInstanceId() int32 { - return p.InstanceId -} -func (p *AssignedTask) IsSetTask() bool { - return p.Task != nil -} - -func (p *AssignedTask) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - case 5: - if err := p.readField5(iprot); err != nil { - return err - } - case 6: - if err := p.readField6(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AssignedTask) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.TaskId = v - } - return nil -} - -func (p *AssignedTask) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.SlaveId = v - } - return nil -} - -func (p *AssignedTask) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.SlaveHost = v - } - return nil -} - -func (p *AssignedTask) readField4(iprot thrift.TProtocol) error { - p.Task = &TaskConfig{} - if err := p.Task.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Task), err) - } - return nil -} - -func (p *AssignedTask) readField5(iprot thrift.TProtocol) error { - _, _, size, err := iprot.ReadMapBegin() - if err != nil { - return thrift.PrependError("error reading map begin: ", err) - } - tMap := make(map[string]int32, size) - p.AssignedPorts = tMap - for i := 0; i < size; i++ { - var _key14 string - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 0: ", err) - } else { - _key14 = v - } - var _val15 int32 - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 0: ", err) - } else { - _val15 = v - } - p.AssignedPorts[_key14] = _val15 - } - if err := iprot.ReadMapEnd(); err != nil { - return thrift.PrependError("error reading map end: ", err) - } - return nil -} - -func (p *AssignedTask) readField6(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 6: ", err) - } else { - p.InstanceId = v - } - return nil -} - -func (p *AssignedTask) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("AssignedTask"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := p.writeField5(oprot); err != nil { - return err - } - if err := p.writeField6(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *AssignedTask) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("taskId", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:taskId: ", p), err) - } - if err := oprot.WriteString(string(p.TaskId)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.taskId (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:taskId: ", p), err) - } - return err -} - -func (p *AssignedTask) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("slaveId", thrift.STRING, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:slaveId: ", p), err) - } - if err := oprot.WriteString(string(p.SlaveId)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.slaveId (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:slaveId: ", p), err) - } - return err -} - -func (p *AssignedTask) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("slaveHost", thrift.STRING, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:slaveHost: ", p), err) - } - if err := oprot.WriteString(string(p.SlaveHost)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.slaveHost (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:slaveHost: ", p), err) - } - return err -} - -func (p *AssignedTask) writeField4(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("task", thrift.STRUCT, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:task: ", p), err) - } - if err := p.Task.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Task), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:task: ", p), err) - } - return err -} - -func (p *AssignedTask) writeField5(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("assignedPorts", thrift.MAP, 5); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:assignedPorts: ", p), err) - } - if err := oprot.WriteMapBegin(thrift.STRING, thrift.I32, len(p.AssignedPorts)); err != nil { - return thrift.PrependError("error writing map begin: ", err) - } - for k, v := range p.AssignedPorts { - if err := oprot.WriteString(string(k)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) - } - if err := oprot.WriteI32(int32(v)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) - } - } - if err := oprot.WriteMapEnd(); err != nil { - return thrift.PrependError("error writing map end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 5:assignedPorts: ", p), err) - } - return err -} - -func (p *AssignedTask) writeField6(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("instanceId", thrift.I32, 6); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 6:instanceId: ", p), err) - } - if err := oprot.WriteI32(int32(p.InstanceId)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.instanceId (6) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 6:instanceId: ", p), err) - } - return err -} - -func (p *AssignedTask) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AssignedTask(%+v)", *p) -} - -// A task that has been scheduled. -// -// Attributes: -// - AssignedTask: The task that was scheduled. -// - Status: The current status of this task. -// - FailureCount: The number of failures that this task has accumulated over the multi-generational history of -// this task. -// - TimesPartitioned: The number of partitions this task has accumulated over its lifetime. -// - TaskEvents: State change history for this task. -// - AncestorId: The task ID of the previous generation of this task. When a task is automatically rescheduled, -// a copy of the task is created and ancestor ID of the previous task's task ID. -type ScheduledTask struct { - AssignedTask *AssignedTask `thrift:"assignedTask,1" json:"assignedTask"` - Status ScheduleStatus `thrift:"status,2" json:"status"` - FailureCount int32 `thrift:"failureCount,3" json:"failureCount"` - TaskEvents []*TaskEvent `thrift:"taskEvents,4" json:"taskEvents"` - AncestorId string `thrift:"ancestorId,5" json:"ancestorId"` - TimesPartitioned int32 `thrift:"timesPartitioned,6" json:"timesPartitioned"` -} - -func NewScheduledTask() *ScheduledTask { - return &ScheduledTask{} -} - -var ScheduledTask_AssignedTask_DEFAULT *AssignedTask - -func (p *ScheduledTask) GetAssignedTask() *AssignedTask { - if !p.IsSetAssignedTask() { - return ScheduledTask_AssignedTask_DEFAULT - } - return p.AssignedTask -} - -func (p *ScheduledTask) GetStatus() ScheduleStatus { - return p.Status -} - -func (p *ScheduledTask) GetFailureCount() int32 { - return p.FailureCount -} - -func (p *ScheduledTask) GetTimesPartitioned() int32 { - return p.TimesPartitioned -} - -func (p *ScheduledTask) GetTaskEvents() []*TaskEvent { - return p.TaskEvents -} - -func (p *ScheduledTask) GetAncestorId() string { - return p.AncestorId -} -func (p *ScheduledTask) IsSetAssignedTask() bool { - return p.AssignedTask != nil -} - -func (p *ScheduledTask) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - case 6: - if err := p.readField6(iprot); err != nil { - return err - } - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - case 5: - if err := p.readField5(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ScheduledTask) readField1(iprot thrift.TProtocol) error { - p.AssignedTask = &AssignedTask{} - if err := p.AssignedTask.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.AssignedTask), err) - } - return nil -} - -func (p *ScheduledTask) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - temp := ScheduleStatus(v) - p.Status = temp - } - return nil -} - -func (p *ScheduledTask) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.FailureCount = v - } - return nil -} - -func (p *ScheduledTask) readField6(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 6: ", err) - } else { - p.TimesPartitioned = v - } - return nil -} - -func (p *ScheduledTask) readField4(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadListBegin() - if err != nil { - return thrift.PrependError("error reading list begin: ", err) - } - tSlice := make([]*TaskEvent, 0, size) - p.TaskEvents = tSlice - for i := 0; i < size; i++ { - _elem16 := &TaskEvent{} - if err := _elem16.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem16), err) - } - p.TaskEvents = append(p.TaskEvents, _elem16) - } - if err := iprot.ReadListEnd(); err != nil { - return thrift.PrependError("error reading list end: ", err) - } - return nil -} - -func (p *ScheduledTask) readField5(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 5: ", err) - } else { - p.AncestorId = v - } - return nil -} - -func (p *ScheduledTask) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("ScheduledTask"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := p.writeField5(oprot); err != nil { - return err - } - if err := p.writeField6(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ScheduledTask) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("assignedTask", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:assignedTask: ", p), err) - } - if err := p.AssignedTask.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.AssignedTask), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:assignedTask: ", p), err) - } - return err -} - -func (p *ScheduledTask) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("status", thrift.I32, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:status: ", p), err) - } - if err := oprot.WriteI32(int32(p.Status)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.status (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:status: ", p), err) - } - return err -} - -func (p *ScheduledTask) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("failureCount", thrift.I32, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:failureCount: ", p), err) - } - if err := oprot.WriteI32(int32(p.FailureCount)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.failureCount (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:failureCount: ", p), err) - } - return err -} - -func (p *ScheduledTask) writeField4(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("taskEvents", thrift.LIST, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:taskEvents: ", p), err) - } - if err := oprot.WriteListBegin(thrift.STRUCT, len(p.TaskEvents)); err != nil { - return thrift.PrependError("error writing list begin: ", err) - } - for _, v := range p.TaskEvents { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteListEnd(); err != nil { - return thrift.PrependError("error writing list end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:taskEvents: ", p), err) - } - return err -} - -func (p *ScheduledTask) writeField5(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("ancestorId", thrift.STRING, 5); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:ancestorId: ", p), err) - } - if err := oprot.WriteString(string(p.AncestorId)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.ancestorId (5) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 5:ancestorId: ", p), err) - } - return err -} - -func (p *ScheduledTask) writeField6(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("timesPartitioned", thrift.I32, 6); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 6:timesPartitioned: ", p), err) - } - if err := oprot.WriteI32(int32(p.TimesPartitioned)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.timesPartitioned (6) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 6:timesPartitioned: ", p), err) - } - return err -} - -func (p *ScheduledTask) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ScheduledTask(%+v)", *p) -} - -// Attributes: -// - Tasks -type ScheduleStatusResult_ struct { - Tasks []*ScheduledTask `thrift:"tasks,1" json:"tasks"` -} - -func NewScheduleStatusResult_() *ScheduleStatusResult_ { - return &ScheduleStatusResult_{} -} - -func (p *ScheduleStatusResult_) GetTasks() []*ScheduledTask { - return p.Tasks -} -func (p *ScheduleStatusResult_) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ScheduleStatusResult_) readField1(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadListBegin() - if err != nil { - return thrift.PrependError("error reading list begin: ", err) - } - tSlice := make([]*ScheduledTask, 0, size) - p.Tasks = tSlice - for i := 0; i < size; i++ { - _elem17 := &ScheduledTask{} - if err := _elem17.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem17), err) - } - p.Tasks = append(p.Tasks, _elem17) - } - if err := iprot.ReadListEnd(); err != nil { - return thrift.PrependError("error reading list end: ", err) - } - return nil -} - -func (p *ScheduleStatusResult_) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("ScheduleStatusResult"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ScheduleStatusResult_) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("tasks", thrift.LIST, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:tasks: ", p), err) - } - if err := oprot.WriteListBegin(thrift.STRUCT, len(p.Tasks)); err != nil { - return thrift.PrependError("error writing list begin: ", err) - } - for _, v := range p.Tasks { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteListEnd(); err != nil { - return thrift.PrependError("error writing list end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:tasks: ", p), err) - } - return err -} - -func (p *ScheduleStatusResult_) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ScheduleStatusResult_(%+v)", *p) -} - -// Attributes: -// - Configs -type GetJobsResult_ struct { - Configs map[*JobConfiguration]bool `thrift:"configs,1" json:"configs"` -} - -func NewGetJobsResult_() *GetJobsResult_ { - return &GetJobsResult_{} -} - -func (p *GetJobsResult_) GetConfigs() map[*JobConfiguration]bool { - return p.Configs -} -func (p *GetJobsResult_) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *GetJobsResult_) readField1(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*JobConfiguration]bool, size) - p.Configs = tSet - for i := 0; i < size; i++ { - _elem18 := &JobConfiguration{} - if err := _elem18.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem18), err) - } - p.Configs[_elem18] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *GetJobsResult_) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("GetJobsResult"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *GetJobsResult_) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("configs", thrift.SET, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:configs: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Configs)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Configs { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:configs: ", p), err) - } - return err -} - -func (p *GetJobsResult_) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("GetJobsResult_(%+v)", *p) -} - -// Contains a set of restrictions on matching tasks where all restrictions must be met -// (terms are AND'ed together). -// -// Attributes: -// - Role -// - Environment -// - JobName -// - TaskIds -// - Statuses -// - InstanceIds -// - SlaveHosts -// - JobKeys -// - Offset -// - Limit -type TaskQuery struct { - // unused field # 1 - JobName *string `thrift:"jobName,2" json:"jobName,omitempty"` - // unused field # 3 - TaskIds map[string]bool `thrift:"taskIds,4" json:"taskIds,omitempty"` - Statuses map[ScheduleStatus]bool `thrift:"statuses,5" json:"statuses,omitempty"` - // unused field # 6 - InstanceIds map[int32]bool `thrift:"instanceIds,7" json:"instanceIds,omitempty"` - // unused field # 8 - Environment *string `thrift:"environment,9" json:"environment,omitempty"` - SlaveHosts map[string]bool `thrift:"slaveHosts,10" json:"slaveHosts,omitempty"` - JobKeys map[*JobKey]bool `thrift:"jobKeys,11" json:"jobKeys,omitempty"` - Offset *int32 `thrift:"offset,12" json:"offset,omitempty"` - Limit *int32 `thrift:"limit,13" json:"limit,omitempty"` - Role *string `thrift:"role,14" json:"role,omitempty"` -} - -func NewTaskQuery() *TaskQuery { - return &TaskQuery{} -} - -var TaskQuery_Role_DEFAULT string - -func (p *TaskQuery) GetRole() string { - if !p.IsSetRole() { - return TaskQuery_Role_DEFAULT - } - return *p.Role -} - -var TaskQuery_Environment_DEFAULT string - -func (p *TaskQuery) GetEnvironment() string { - if !p.IsSetEnvironment() { - return TaskQuery_Environment_DEFAULT - } - return *p.Environment -} - -var TaskQuery_JobName_DEFAULT string - -func (p *TaskQuery) GetJobName() string { - if !p.IsSetJobName() { - return TaskQuery_JobName_DEFAULT - } - return *p.JobName -} - -var TaskQuery_TaskIds_DEFAULT map[string]bool - -func (p *TaskQuery) GetTaskIds() map[string]bool { - return p.TaskIds -} - -var TaskQuery_Statuses_DEFAULT map[ScheduleStatus]bool - -func (p *TaskQuery) GetStatuses() map[ScheduleStatus]bool { - return p.Statuses -} - -var TaskQuery_InstanceIds_DEFAULT map[int32]bool - -func (p *TaskQuery) GetInstanceIds() map[int32]bool { - return p.InstanceIds -} - -var TaskQuery_SlaveHosts_DEFAULT map[string]bool - -func (p *TaskQuery) GetSlaveHosts() map[string]bool { - return p.SlaveHosts -} - -var TaskQuery_JobKeys_DEFAULT map[*JobKey]bool - -func (p *TaskQuery) GetJobKeys() map[*JobKey]bool { - return p.JobKeys -} - -var TaskQuery_Offset_DEFAULT int32 - -func (p *TaskQuery) GetOffset() int32 { - if !p.IsSetOffset() { - return TaskQuery_Offset_DEFAULT - } - return *p.Offset -} - -var TaskQuery_Limit_DEFAULT int32 - -func (p *TaskQuery) GetLimit() int32 { - if !p.IsSetLimit() { - return TaskQuery_Limit_DEFAULT - } - return *p.Limit -} -func (p *TaskQuery) IsSetRole() bool { - return p.Role != nil -} - -func (p *TaskQuery) IsSetEnvironment() bool { - return p.Environment != nil -} - -func (p *TaskQuery) IsSetJobName() bool { - return p.JobName != nil -} - -func (p *TaskQuery) IsSetTaskIds() bool { - return p.TaskIds != nil -} - -func (p *TaskQuery) IsSetStatuses() bool { - return p.Statuses != nil -} - -func (p *TaskQuery) IsSetInstanceIds() bool { - return p.InstanceIds != nil -} - -func (p *TaskQuery) IsSetSlaveHosts() bool { - return p.SlaveHosts != nil -} - -func (p *TaskQuery) IsSetJobKeys() bool { - return p.JobKeys != nil -} - -func (p *TaskQuery) IsSetOffset() bool { - return p.Offset != nil -} - -func (p *TaskQuery) IsSetLimit() bool { - return p.Limit != nil -} - -func (p *TaskQuery) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 14: - if err := p.readField14(iprot); err != nil { - return err - } - case 9: - if err := p.readField9(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - case 5: - if err := p.readField5(iprot); err != nil { - return err - } - case 7: - if err := p.readField7(iprot); err != nil { - return err - } - case 10: - if err := p.readField10(iprot); err != nil { - return err - } - case 11: - if err := p.readField11(iprot); err != nil { - return err - } - case 12: - if err := p.readField12(iprot); err != nil { - return err - } - case 13: - if err := p.readField13(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *TaskQuery) readField14(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 14: ", err) - } else { - p.Role = &v - } - return nil -} - -func (p *TaskQuery) readField9(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 9: ", err) - } else { - p.Environment = &v - } - return nil -} - -func (p *TaskQuery) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.JobName = &v - } - return nil -} - -func (p *TaskQuery) readField4(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[string]bool, size) - p.TaskIds = tSet - for i := 0; i < size; i++ { - var _elem19 string - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 0: ", err) - } else { - _elem19 = v - } - p.TaskIds[_elem19] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *TaskQuery) readField5(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[ScheduleStatus]bool, size) - p.Statuses = tSet - for i := 0; i < size; i++ { - var _elem20 ScheduleStatus - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 0: ", err) - } else { - temp := ScheduleStatus(v) - _elem20 = temp - } - p.Statuses[_elem20] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *TaskQuery) readField7(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[int32]bool, size) - p.InstanceIds = tSet - for i := 0; i < size; i++ { - var _elem21 int32 - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 0: ", err) - } else { - _elem21 = v - } - p.InstanceIds[_elem21] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *TaskQuery) readField10(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[string]bool, size) - p.SlaveHosts = tSet - for i := 0; i < size; i++ { - var _elem22 string - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 0: ", err) - } else { - _elem22 = v - } - p.SlaveHosts[_elem22] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *TaskQuery) readField11(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*JobKey]bool, size) - p.JobKeys = tSet - for i := 0; i < size; i++ { - _elem23 := &JobKey{} - if err := _elem23.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem23), err) - } - p.JobKeys[_elem23] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *TaskQuery) readField12(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 12: ", err) - } else { - p.Offset = &v - } - return nil -} - -func (p *TaskQuery) readField13(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 13: ", err) - } else { - p.Limit = &v - } - return nil -} - -func (p *TaskQuery) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("TaskQuery"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := p.writeField5(oprot); err != nil { - return err - } - if err := p.writeField7(oprot); err != nil { - return err - } - if err := p.writeField9(oprot); err != nil { - return err - } - if err := p.writeField10(oprot); err != nil { - return err - } - if err := p.writeField11(oprot); err != nil { - return err - } - if err := p.writeField12(oprot); err != nil { - return err - } - if err := p.writeField13(oprot); err != nil { - return err - } - if err := p.writeField14(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *TaskQuery) writeField2(oprot thrift.TProtocol) (err error) { - if p.IsSetJobName() { - if err := oprot.WriteFieldBegin("jobName", thrift.STRING, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:jobName: ", p), err) - } - if err := oprot.WriteString(string(*p.JobName)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.jobName (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:jobName: ", p), err) - } - } - return err -} - -func (p *TaskQuery) writeField4(oprot thrift.TProtocol) (err error) { - if p.IsSetTaskIds() { - if err := oprot.WriteFieldBegin("taskIds", thrift.SET, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:taskIds: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRING, len(p.TaskIds)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.TaskIds { - if err := oprot.WriteString(string(v)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:taskIds: ", p), err) - } - } - return err -} - -func (p *TaskQuery) writeField5(oprot thrift.TProtocol) (err error) { - if p.IsSetStatuses() { - if err := oprot.WriteFieldBegin("statuses", thrift.SET, 5); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:statuses: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.I32, len(p.Statuses)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Statuses { - if err := oprot.WriteI32(int32(v)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 5:statuses: ", p), err) - } - } - return err -} - -func (p *TaskQuery) writeField7(oprot thrift.TProtocol) (err error) { - if p.IsSetInstanceIds() { - if err := oprot.WriteFieldBegin("instanceIds", thrift.SET, 7); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 7:instanceIds: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.I32, len(p.InstanceIds)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.InstanceIds { - if err := oprot.WriteI32(int32(v)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 7:instanceIds: ", p), err) - } - } - return err -} - -func (p *TaskQuery) writeField9(oprot thrift.TProtocol) (err error) { - if p.IsSetEnvironment() { - if err := oprot.WriteFieldBegin("environment", thrift.STRING, 9); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 9:environment: ", p), err) - } - if err := oprot.WriteString(string(*p.Environment)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.environment (9) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 9:environment: ", p), err) - } - } - return err -} - -func (p *TaskQuery) writeField10(oprot thrift.TProtocol) (err error) { - if p.IsSetSlaveHosts() { - if err := oprot.WriteFieldBegin("slaveHosts", thrift.SET, 10); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 10:slaveHosts: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRING, len(p.SlaveHosts)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.SlaveHosts { - if err := oprot.WriteString(string(v)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 10:slaveHosts: ", p), err) - } - } - return err -} - -func (p *TaskQuery) writeField11(oprot thrift.TProtocol) (err error) { - if p.IsSetJobKeys() { - if err := oprot.WriteFieldBegin("jobKeys", thrift.SET, 11); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 11:jobKeys: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.JobKeys)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.JobKeys { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 11:jobKeys: ", p), err) - } - } - return err -} - -func (p *TaskQuery) writeField12(oprot thrift.TProtocol) (err error) { - if p.IsSetOffset() { - if err := oprot.WriteFieldBegin("offset", thrift.I32, 12); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 12:offset: ", p), err) - } - if err := oprot.WriteI32(int32(*p.Offset)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.offset (12) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 12:offset: ", p), err) - } - } - return err -} - -func (p *TaskQuery) writeField13(oprot thrift.TProtocol) (err error) { - if p.IsSetLimit() { - if err := oprot.WriteFieldBegin("limit", thrift.I32, 13); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 13:limit: ", p), err) - } - if err := oprot.WriteI32(int32(*p.Limit)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.limit (13) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 13:limit: ", p), err) - } - } - return err -} - -func (p *TaskQuery) writeField14(oprot thrift.TProtocol) (err error) { - if p.IsSetRole() { - if err := oprot.WriteFieldBegin("role", thrift.STRING, 14); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 14:role: ", p), err) - } - if err := oprot.WriteString(string(*p.Role)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.role (14) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 14:role: ", p), err) - } - } - return err -} - -func (p *TaskQuery) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("TaskQuery(%+v)", *p) -} - -// Attributes: -// - Host -// - Mode -type HostStatus struct { - Host string `thrift:"host,1" json:"host"` - Mode MaintenanceMode `thrift:"mode,2" json:"mode"` -} - -func NewHostStatus() *HostStatus { - return &HostStatus{} -} - -func (p *HostStatus) GetHost() string { - return p.Host -} - -func (p *HostStatus) GetMode() MaintenanceMode { - return p.Mode -} -func (p *HostStatus) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *HostStatus) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Host = v - } - return nil -} - -func (p *HostStatus) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - temp := MaintenanceMode(v) - p.Mode = temp - } - return nil -} - -func (p *HostStatus) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("HostStatus"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *HostStatus) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("host", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:host: ", p), err) - } - if err := oprot.WriteString(string(p.Host)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.host (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:host: ", p), err) - } - return err -} - -func (p *HostStatus) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("mode", thrift.I32, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:mode: ", p), err) - } - if err := oprot.WriteI32(int32(p.Mode)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.mode (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:mode: ", p), err) - } - return err -} - -func (p *HostStatus) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("HostStatus(%+v)", *p) -} - -// Attributes: -// - Role -// - JobCount -// - CronJobCount -type RoleSummary struct { - Role string `thrift:"role,1" json:"role"` - JobCount int32 `thrift:"jobCount,2" json:"jobCount"` - CronJobCount int32 `thrift:"cronJobCount,3" json:"cronJobCount"` -} - -func NewRoleSummary() *RoleSummary { - return &RoleSummary{} -} - -func (p *RoleSummary) GetRole() string { - return p.Role -} - -func (p *RoleSummary) GetJobCount() int32 { - return p.JobCount -} - -func (p *RoleSummary) GetCronJobCount() int32 { - return p.CronJobCount -} -func (p *RoleSummary) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *RoleSummary) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Role = v - } - return nil -} - -func (p *RoleSummary) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.JobCount = v - } - return nil -} - -func (p *RoleSummary) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.CronJobCount = v - } - return nil -} - -func (p *RoleSummary) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("RoleSummary"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *RoleSummary) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("role", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:role: ", p), err) - } - if err := oprot.WriteString(string(p.Role)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.role (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:role: ", p), err) - } - return err -} - -func (p *RoleSummary) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("jobCount", thrift.I32, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:jobCount: ", p), err) - } - if err := oprot.WriteI32(int32(p.JobCount)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.jobCount (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:jobCount: ", p), err) - } - return err -} - -func (p *RoleSummary) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("cronJobCount", thrift.I32, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:cronJobCount: ", p), err) - } - if err := oprot.WriteI32(int32(p.CronJobCount)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.cronJobCount (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:cronJobCount: ", p), err) - } - return err -} - -func (p *RoleSummary) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("RoleSummary(%+v)", *p) -} - -// Attributes: -// - HostNames -type Hosts struct { - HostNames map[string]bool `thrift:"hostNames,1" json:"hostNames"` -} - -func NewHosts() *Hosts { - return &Hosts{} -} - -func (p *Hosts) GetHostNames() map[string]bool { - return p.HostNames -} -func (p *Hosts) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *Hosts) readField1(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[string]bool, size) - p.HostNames = tSet - for i := 0; i < size; i++ { - var _elem24 string - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 0: ", err) - } else { - _elem24 = v - } - p.HostNames[_elem24] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *Hosts) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("Hosts"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *Hosts) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("hostNames", thrift.SET, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:hostNames: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRING, len(p.HostNames)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.HostNames { - if err := oprot.WriteString(string(v)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:hostNames: ", p), err) - } - return err -} - -func (p *Hosts) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("Hosts(%+v)", *p) -} - -// Attributes: -// - TaskId -// - Reason -type PendingReason struct { - TaskId string `thrift:"taskId,1" json:"taskId"` - Reason string `thrift:"reason,2" json:"reason"` -} - -func NewPendingReason() *PendingReason { - return &PendingReason{} -} - -func (p *PendingReason) GetTaskId() string { - return p.TaskId -} - -func (p *PendingReason) GetReason() string { - return p.Reason -} -func (p *PendingReason) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *PendingReason) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.TaskId = v - } - return nil -} - -func (p *PendingReason) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.Reason = v - } - return nil -} - -func (p *PendingReason) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("PendingReason"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *PendingReason) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("taskId", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:taskId: ", p), err) - } - if err := oprot.WriteString(string(p.TaskId)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.taskId (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:taskId: ", p), err) - } - return err -} - -func (p *PendingReason) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("reason", thrift.STRING, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:reason: ", p), err) - } - if err := oprot.WriteString(string(p.Reason)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.reason (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:reason: ", p), err) - } - return err -} - -func (p *PendingReason) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("PendingReason(%+v)", *p) -} - -// Job update key. -// -// Attributes: -// - Job: Job being updated -// - ID: Update ID. -type JobUpdateKey struct { - Job *JobKey `thrift:"job,1" json:"job"` - ID string `thrift:"id,2" json:"id"` -} - -func NewJobUpdateKey() *JobUpdateKey { - return &JobUpdateKey{} -} - -var JobUpdateKey_Job_DEFAULT *JobKey - -func (p *JobUpdateKey) GetJob() *JobKey { - if !p.IsSetJob() { - return JobUpdateKey_Job_DEFAULT - } - return p.Job -} - -func (p *JobUpdateKey) GetID() string { - return p.ID -} -func (p *JobUpdateKey) IsSetJob() bool { - return p.Job != nil -} - -func (p *JobUpdateKey) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *JobUpdateKey) readField1(iprot thrift.TProtocol) error { - p.Job = &JobKey{} - if err := p.Job.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Job), err) - } - return nil -} - -func (p *JobUpdateKey) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.ID = v - } - return nil -} - -func (p *JobUpdateKey) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("JobUpdateKey"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *JobUpdateKey) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("job", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:job: ", p), err) - } - if err := p.Job.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Job), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:job: ", p), err) - } - return err -} - -func (p *JobUpdateKey) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("id", thrift.STRING, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:id: ", p), err) - } - if err := oprot.WriteString(string(p.ID)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.id (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:id: ", p), err) - } - return err -} - -func (p *JobUpdateKey) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("JobUpdateKey(%+v)", *p) -} - -// Job update thresholds and limits. -// -// Attributes: -// - UpdateGroupSize: Max number of instances being updated at any given moment. -// - MaxPerInstanceFailures: Max number of instance failures to tolerate before marking instance as FAILED. -// - MaxFailedInstances: Max number of FAILED instances to tolerate before terminating the update. -// - MinWaitInInstanceRunningMs: Min time to watch a RUNNING instance. -// - RollbackOnFailure: If true, enables failed update rollback. -// - UpdateOnlyTheseInstances: Instance IDs to act on. All instances will be affected if this is not set. -// - WaitForBatchCompletion: If true, use updateGroupSize as strict batching boundaries, and avoid proceeding to another -// batch until the preceding batch finishes updating. -// - BlockIfNoPulsesAfterMs: If set, requires external calls to pulseJobUpdate RPC within the specified rate for the -// update to make progress. If no pulses received within specified interval the update will -// block. A blocked update is unable to continue but retains its current status. It may only get -// unblocked by a fresh pulseJobUpdate call. -// - SlaAware: If true, updates will obey the SLA requirements of the tasks being updated. If the SLA policy -// differs between the old and new task configurations, updates will use the newest configuration. -type JobUpdateSettings struct { - UpdateGroupSize int32 `thrift:"updateGroupSize,1" json:"updateGroupSize"` - MaxPerInstanceFailures int32 `thrift:"maxPerInstanceFailures,2" json:"maxPerInstanceFailures"` - MaxFailedInstances int32 `thrift:"maxFailedInstances,3" json:"maxFailedInstances"` - // unused field # 4 - MinWaitInInstanceRunningMs int32 `thrift:"minWaitInInstanceRunningMs,5" json:"minWaitInInstanceRunningMs"` - RollbackOnFailure bool `thrift:"rollbackOnFailure,6" json:"rollbackOnFailure"` - UpdateOnlyTheseInstances map[*Range]bool `thrift:"updateOnlyTheseInstances,7" json:"updateOnlyTheseInstances"` - WaitForBatchCompletion bool `thrift:"waitForBatchCompletion,8" json:"waitForBatchCompletion"` - BlockIfNoPulsesAfterMs *int32 `thrift:"blockIfNoPulsesAfterMs,9" json:"blockIfNoPulsesAfterMs,omitempty"` - SlaAware *bool `thrift:"slaAware,10" json:"slaAware,omitempty"` -} - -func NewJobUpdateSettings() *JobUpdateSettings { - return &JobUpdateSettings{} -} - -func (p *JobUpdateSettings) GetUpdateGroupSize() int32 { - return p.UpdateGroupSize -} - -func (p *JobUpdateSettings) GetMaxPerInstanceFailures() int32 { - return p.MaxPerInstanceFailures -} - -func (p *JobUpdateSettings) GetMaxFailedInstances() int32 { - return p.MaxFailedInstances -} - -func (p *JobUpdateSettings) GetMinWaitInInstanceRunningMs() int32 { - return p.MinWaitInInstanceRunningMs -} - -func (p *JobUpdateSettings) GetRollbackOnFailure() bool { - return p.RollbackOnFailure -} - -func (p *JobUpdateSettings) GetUpdateOnlyTheseInstances() map[*Range]bool { - return p.UpdateOnlyTheseInstances -} - -func (p *JobUpdateSettings) GetWaitForBatchCompletion() bool { - return p.WaitForBatchCompletion -} - -var JobUpdateSettings_BlockIfNoPulsesAfterMs_DEFAULT int32 - -func (p *JobUpdateSettings) GetBlockIfNoPulsesAfterMs() int32 { - if !p.IsSetBlockIfNoPulsesAfterMs() { - return JobUpdateSettings_BlockIfNoPulsesAfterMs_DEFAULT - } - return *p.BlockIfNoPulsesAfterMs -} - -var JobUpdateSettings_SlaAware_DEFAULT bool - -func (p *JobUpdateSettings) GetSlaAware() bool { - if !p.IsSetSlaAware() { - return JobUpdateSettings_SlaAware_DEFAULT - } - return *p.SlaAware -} -func (p *JobUpdateSettings) IsSetBlockIfNoPulsesAfterMs() bool { - return p.BlockIfNoPulsesAfterMs != nil -} - -func (p *JobUpdateSettings) IsSetSlaAware() bool { - return p.SlaAware != nil -} - -func (p *JobUpdateSettings) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - case 5: - if err := p.readField5(iprot); err != nil { - return err - } - case 6: - if err := p.readField6(iprot); err != nil { - return err - } - case 7: - if err := p.readField7(iprot); err != nil { - return err - } - case 8: - if err := p.readField8(iprot); err != nil { - return err - } - case 9: - if err := p.readField9(iprot); err != nil { - return err - } - case 10: - if err := p.readField10(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *JobUpdateSettings) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.UpdateGroupSize = v - } - return nil -} - -func (p *JobUpdateSettings) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.MaxPerInstanceFailures = v - } - return nil -} - -func (p *JobUpdateSettings) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.MaxFailedInstances = v - } - return nil -} - -func (p *JobUpdateSettings) readField5(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 5: ", err) - } else { - p.MinWaitInInstanceRunningMs = v - } - return nil -} - -func (p *JobUpdateSettings) readField6(iprot thrift.TProtocol) error { - if v, err := iprot.ReadBool(); err != nil { - return thrift.PrependError("error reading field 6: ", err) - } else { - p.RollbackOnFailure = v - } - return nil -} - -func (p *JobUpdateSettings) readField7(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*Range]bool, size) - p.UpdateOnlyTheseInstances = tSet - for i := 0; i < size; i++ { - _elem25 := &Range{} - if err := _elem25.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem25), err) - } - p.UpdateOnlyTheseInstances[_elem25] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *JobUpdateSettings) readField8(iprot thrift.TProtocol) error { - if v, err := iprot.ReadBool(); err != nil { - return thrift.PrependError("error reading field 8: ", err) - } else { - p.WaitForBatchCompletion = v - } - return nil -} - -func (p *JobUpdateSettings) readField9(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 9: ", err) - } else { - p.BlockIfNoPulsesAfterMs = &v - } - return nil -} - -func (p *JobUpdateSettings) readField10(iprot thrift.TProtocol) error { - if v, err := iprot.ReadBool(); err != nil { - return thrift.PrependError("error reading field 10: ", err) - } else { - p.SlaAware = &v - } - return nil -} - -func (p *JobUpdateSettings) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("JobUpdateSettings"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := p.writeField5(oprot); err != nil { - return err - } - if err := p.writeField6(oprot); err != nil { - return err - } - if err := p.writeField7(oprot); err != nil { - return err - } - if err := p.writeField8(oprot); err != nil { - return err - } - if err := p.writeField9(oprot); err != nil { - return err - } - if err := p.writeField10(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *JobUpdateSettings) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("updateGroupSize", thrift.I32, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:updateGroupSize: ", p), err) - } - if err := oprot.WriteI32(int32(p.UpdateGroupSize)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.updateGroupSize (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:updateGroupSize: ", p), err) - } - return err -} - -func (p *JobUpdateSettings) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("maxPerInstanceFailures", thrift.I32, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:maxPerInstanceFailures: ", p), err) - } - if err := oprot.WriteI32(int32(p.MaxPerInstanceFailures)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.maxPerInstanceFailures (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:maxPerInstanceFailures: ", p), err) - } - return err -} - -func (p *JobUpdateSettings) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("maxFailedInstances", thrift.I32, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:maxFailedInstances: ", p), err) - } - if err := oprot.WriteI32(int32(p.MaxFailedInstances)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.maxFailedInstances (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:maxFailedInstances: ", p), err) - } - return err -} - -func (p *JobUpdateSettings) writeField5(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("minWaitInInstanceRunningMs", thrift.I32, 5); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:minWaitInInstanceRunningMs: ", p), err) - } - if err := oprot.WriteI32(int32(p.MinWaitInInstanceRunningMs)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.minWaitInInstanceRunningMs (5) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 5:minWaitInInstanceRunningMs: ", p), err) - } - return err -} - -func (p *JobUpdateSettings) writeField6(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("rollbackOnFailure", thrift.BOOL, 6); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 6:rollbackOnFailure: ", p), err) - } - if err := oprot.WriteBool(bool(p.RollbackOnFailure)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.rollbackOnFailure (6) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 6:rollbackOnFailure: ", p), err) - } - return err -} - -func (p *JobUpdateSettings) writeField7(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("updateOnlyTheseInstances", thrift.SET, 7); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 7:updateOnlyTheseInstances: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.UpdateOnlyTheseInstances)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.UpdateOnlyTheseInstances { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 7:updateOnlyTheseInstances: ", p), err) - } - return err -} - -func (p *JobUpdateSettings) writeField8(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("waitForBatchCompletion", thrift.BOOL, 8); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 8:waitForBatchCompletion: ", p), err) - } - if err := oprot.WriteBool(bool(p.WaitForBatchCompletion)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.waitForBatchCompletion (8) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 8:waitForBatchCompletion: ", p), err) - } - return err -} - -func (p *JobUpdateSettings) writeField9(oprot thrift.TProtocol) (err error) { - if p.IsSetBlockIfNoPulsesAfterMs() { - if err := oprot.WriteFieldBegin("blockIfNoPulsesAfterMs", thrift.I32, 9); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 9:blockIfNoPulsesAfterMs: ", p), err) - } - if err := oprot.WriteI32(int32(*p.BlockIfNoPulsesAfterMs)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.blockIfNoPulsesAfterMs (9) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 9:blockIfNoPulsesAfterMs: ", p), err) - } - } - return err -} - -func (p *JobUpdateSettings) writeField10(oprot thrift.TProtocol) (err error) { - if p.IsSetSlaAware() { - if err := oprot.WriteFieldBegin("slaAware", thrift.BOOL, 10); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 10:slaAware: ", p), err) - } - if err := oprot.WriteBool(bool(*p.SlaAware)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.slaAware (10) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 10:slaAware: ", p), err) - } - } - return err -} - -func (p *JobUpdateSettings) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("JobUpdateSettings(%+v)", *p) -} - -// Event marking a state transition in job update lifecycle. -// -// Attributes: -// - Status: Update status. -// - TimestampMs: Epoch timestamp in milliseconds. -// - User: User who performed this event (if user-initiated). -// - Message: Message from the user (for user-initiated transitions) or the scheduler about why the state was -// changed. -type JobUpdateEvent struct { - Status JobUpdateStatus `thrift:"status,1" json:"status"` - TimestampMs int64 `thrift:"timestampMs,2" json:"timestampMs"` - User *string `thrift:"user,3" json:"user,omitempty"` - Message *string `thrift:"message,4" json:"message,omitempty"` -} - -func NewJobUpdateEvent() *JobUpdateEvent { - return &JobUpdateEvent{} -} - -func (p *JobUpdateEvent) GetStatus() JobUpdateStatus { - return p.Status -} - -func (p *JobUpdateEvent) GetTimestampMs() int64 { - return p.TimestampMs -} - -var JobUpdateEvent_User_DEFAULT string - -func (p *JobUpdateEvent) GetUser() string { - if !p.IsSetUser() { - return JobUpdateEvent_User_DEFAULT - } - return *p.User -} - -var JobUpdateEvent_Message_DEFAULT string - -func (p *JobUpdateEvent) GetMessage() string { - if !p.IsSetMessage() { - return JobUpdateEvent_Message_DEFAULT - } - return *p.Message -} -func (p *JobUpdateEvent) IsSetUser() bool { - return p.User != nil -} - -func (p *JobUpdateEvent) IsSetMessage() bool { - return p.Message != nil -} - -func (p *JobUpdateEvent) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *JobUpdateEvent) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - temp := JobUpdateStatus(v) - p.Status = temp - } - return nil -} - -func (p *JobUpdateEvent) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI64(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.TimestampMs = v - } - return nil -} - -func (p *JobUpdateEvent) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.User = &v - } - return nil -} - -func (p *JobUpdateEvent) readField4(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 4: ", err) - } else { - p.Message = &v - } - return nil -} - -func (p *JobUpdateEvent) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("JobUpdateEvent"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *JobUpdateEvent) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("status", thrift.I32, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:status: ", p), err) - } - if err := oprot.WriteI32(int32(p.Status)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.status (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:status: ", p), err) - } - return err -} - -func (p *JobUpdateEvent) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("timestampMs", thrift.I64, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:timestampMs: ", p), err) - } - if err := oprot.WriteI64(int64(p.TimestampMs)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.timestampMs (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:timestampMs: ", p), err) - } - return err -} - -func (p *JobUpdateEvent) writeField3(oprot thrift.TProtocol) (err error) { - if p.IsSetUser() { - if err := oprot.WriteFieldBegin("user", thrift.STRING, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:user: ", p), err) - } - if err := oprot.WriteString(string(*p.User)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.user (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:user: ", p), err) - } - } - return err -} - -func (p *JobUpdateEvent) writeField4(oprot thrift.TProtocol) (err error) { - if p.IsSetMessage() { - if err := oprot.WriteFieldBegin("message", thrift.STRING, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:message: ", p), err) - } - if err := oprot.WriteString(string(*p.Message)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.message (4) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:message: ", p), err) - } - } - return err -} - -func (p *JobUpdateEvent) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("JobUpdateEvent(%+v)", *p) -} - -// Event marking a state transition in job instance update lifecycle. -// -// Attributes: -// - InstanceId: Job instance ID. -// - TimestampMs: Epoch timestamp in milliseconds. -// - Action: Job update action taken on the instance. -// - Message: Optional message explaining the instance update event. -type JobInstanceUpdateEvent struct { - InstanceId int32 `thrift:"instanceId,1" json:"instanceId"` - TimestampMs int64 `thrift:"timestampMs,2" json:"timestampMs"` - Action JobUpdateAction `thrift:"action,3" json:"action"` - Message *string `thrift:"message,4" json:"message,omitempty"` -} - -func NewJobInstanceUpdateEvent() *JobInstanceUpdateEvent { - return &JobInstanceUpdateEvent{} -} - -func (p *JobInstanceUpdateEvent) GetInstanceId() int32 { - return p.InstanceId -} - -func (p *JobInstanceUpdateEvent) GetTimestampMs() int64 { - return p.TimestampMs -} - -func (p *JobInstanceUpdateEvent) GetAction() JobUpdateAction { - return p.Action -} - -var JobInstanceUpdateEvent_Message_DEFAULT string - -func (p *JobInstanceUpdateEvent) GetMessage() string { - if !p.IsSetMessage() { - return JobInstanceUpdateEvent_Message_DEFAULT - } - return *p.Message -} -func (p *JobInstanceUpdateEvent) IsSetMessage() bool { - return p.Message != nil -} - -func (p *JobInstanceUpdateEvent) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *JobInstanceUpdateEvent) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.InstanceId = v - } - return nil -} - -func (p *JobInstanceUpdateEvent) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI64(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.TimestampMs = v - } - return nil -} - -func (p *JobInstanceUpdateEvent) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - temp := JobUpdateAction(v) - p.Action = temp - } - return nil -} - -func (p *JobInstanceUpdateEvent) readField4(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 4: ", err) - } else { - p.Message = &v - } - return nil -} - -func (p *JobInstanceUpdateEvent) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("JobInstanceUpdateEvent"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *JobInstanceUpdateEvent) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("instanceId", thrift.I32, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:instanceId: ", p), err) - } - if err := oprot.WriteI32(int32(p.InstanceId)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.instanceId (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:instanceId: ", p), err) - } - return err -} - -func (p *JobInstanceUpdateEvent) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("timestampMs", thrift.I64, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:timestampMs: ", p), err) - } - if err := oprot.WriteI64(int64(p.TimestampMs)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.timestampMs (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:timestampMs: ", p), err) - } - return err -} - -func (p *JobInstanceUpdateEvent) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("action", thrift.I32, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:action: ", p), err) - } - if err := oprot.WriteI32(int32(p.Action)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.action (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:action: ", p), err) - } - return err -} - -func (p *JobInstanceUpdateEvent) writeField4(oprot thrift.TProtocol) (err error) { - if p.IsSetMessage() { - if err := oprot.WriteFieldBegin("message", thrift.STRING, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:message: ", p), err) - } - if err := oprot.WriteString(string(*p.Message)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.message (4) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:message: ", p), err) - } - } - return err -} - -func (p *JobInstanceUpdateEvent) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("JobInstanceUpdateEvent(%+v)", *p) -} - -// Maps instance IDs to TaskConfigs it. -// -// Attributes: -// - Task: A TaskConfig associated with instances. -// - Instances: Instances associated with the TaskConfig. -type InstanceTaskConfig struct { - Task *TaskConfig `thrift:"task,1" json:"task"` - Instances map[*Range]bool `thrift:"instances,2" json:"instances"` -} - -func NewInstanceTaskConfig() *InstanceTaskConfig { - return &InstanceTaskConfig{} -} - -var InstanceTaskConfig_Task_DEFAULT *TaskConfig - -func (p *InstanceTaskConfig) GetTask() *TaskConfig { - if !p.IsSetTask() { - return InstanceTaskConfig_Task_DEFAULT - } - return p.Task -} - -func (p *InstanceTaskConfig) GetInstances() map[*Range]bool { - return p.Instances -} -func (p *InstanceTaskConfig) IsSetTask() bool { - return p.Task != nil -} - -func (p *InstanceTaskConfig) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *InstanceTaskConfig) readField1(iprot thrift.TProtocol) error { - p.Task = &TaskConfig{} - if err := p.Task.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Task), err) - } - return nil -} - -func (p *InstanceTaskConfig) readField2(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*Range]bool, size) - p.Instances = tSet - for i := 0; i < size; i++ { - _elem26 := &Range{} - if err := _elem26.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem26), err) - } - p.Instances[_elem26] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *InstanceTaskConfig) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("InstanceTaskConfig"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *InstanceTaskConfig) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("task", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:task: ", p), err) - } - if err := p.Task.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Task), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:task: ", p), err) - } - return err -} - -func (p *InstanceTaskConfig) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("instances", thrift.SET, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:instances: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Instances)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Instances { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:instances: ", p), err) - } - return err -} - -func (p *InstanceTaskConfig) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("InstanceTaskConfig(%+v)", *p) -} - -// Current job update state including status and created/modified timestamps. -// -// Attributes: -// - Status: Current status of the update. -// - CreatedTimestampMs: Created timestamp in milliseconds. -// - LastModifiedTimestampMs: Last modified timestamp in milliseconds. -type JobUpdateState struct { - Status JobUpdateStatus `thrift:"status,1" json:"status"` - CreatedTimestampMs int64 `thrift:"createdTimestampMs,2" json:"createdTimestampMs"` - LastModifiedTimestampMs int64 `thrift:"lastModifiedTimestampMs,3" json:"lastModifiedTimestampMs"` -} - -func NewJobUpdateState() *JobUpdateState { - return &JobUpdateState{} -} - -func (p *JobUpdateState) GetStatus() JobUpdateStatus { - return p.Status -} - -func (p *JobUpdateState) GetCreatedTimestampMs() int64 { - return p.CreatedTimestampMs -} - -func (p *JobUpdateState) GetLastModifiedTimestampMs() int64 { - return p.LastModifiedTimestampMs -} -func (p *JobUpdateState) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *JobUpdateState) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - temp := JobUpdateStatus(v) - p.Status = temp - } - return nil -} - -func (p *JobUpdateState) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI64(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.CreatedTimestampMs = v - } - return nil -} - -func (p *JobUpdateState) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI64(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.LastModifiedTimestampMs = v - } - return nil -} - -func (p *JobUpdateState) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("JobUpdateState"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *JobUpdateState) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("status", thrift.I32, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:status: ", p), err) - } - if err := oprot.WriteI32(int32(p.Status)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.status (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:status: ", p), err) - } - return err -} - -func (p *JobUpdateState) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("createdTimestampMs", thrift.I64, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:createdTimestampMs: ", p), err) - } - if err := oprot.WriteI64(int64(p.CreatedTimestampMs)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.createdTimestampMs (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:createdTimestampMs: ", p), err) - } - return err -} - -func (p *JobUpdateState) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("lastModifiedTimestampMs", thrift.I64, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:lastModifiedTimestampMs: ", p), err) - } - if err := oprot.WriteI64(int64(p.LastModifiedTimestampMs)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.lastModifiedTimestampMs (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:lastModifiedTimestampMs: ", p), err) - } - return err -} - -func (p *JobUpdateState) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("JobUpdateState(%+v)", *p) -} - -// Summary of the job update including job key, user and current state. -// -// Attributes: -// - Key: Unique identifier for the update. -// - User: User initiated an update. -// - State: Current job update state. -// - Metadata: Update metadata supplied by the client. -type JobUpdateSummary struct { - // unused fields # 1 to 2 - User string `thrift:"user,3" json:"user"` - State *JobUpdateState `thrift:"state,4" json:"state"` - Key *JobUpdateKey `thrift:"key,5" json:"key"` - Metadata map[*Metadata]bool `thrift:"metadata,6" json:"metadata,omitempty"` -} - -func NewJobUpdateSummary() *JobUpdateSummary { - return &JobUpdateSummary{} -} - -var JobUpdateSummary_Key_DEFAULT *JobUpdateKey - -func (p *JobUpdateSummary) GetKey() *JobUpdateKey { - if !p.IsSetKey() { - return JobUpdateSummary_Key_DEFAULT - } - return p.Key -} - -func (p *JobUpdateSummary) GetUser() string { - return p.User -} - -var JobUpdateSummary_State_DEFAULT *JobUpdateState - -func (p *JobUpdateSummary) GetState() *JobUpdateState { - if !p.IsSetState() { - return JobUpdateSummary_State_DEFAULT - } - return p.State -} - -var JobUpdateSummary_Metadata_DEFAULT map[*Metadata]bool - -func (p *JobUpdateSummary) GetMetadata() map[*Metadata]bool { - return p.Metadata -} -func (p *JobUpdateSummary) IsSetKey() bool { - return p.Key != nil -} - -func (p *JobUpdateSummary) IsSetState() bool { - return p.State != nil -} - -func (p *JobUpdateSummary) IsSetMetadata() bool { - return p.Metadata != nil -} - -func (p *JobUpdateSummary) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 5: - if err := p.readField5(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - case 6: - if err := p.readField6(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *JobUpdateSummary) readField5(iprot thrift.TProtocol) error { - p.Key = &JobUpdateKey{} - if err := p.Key.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) - } - return nil -} - -func (p *JobUpdateSummary) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.User = v - } - return nil -} - -func (p *JobUpdateSummary) readField4(iprot thrift.TProtocol) error { - p.State = &JobUpdateState{} - if err := p.State.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.State), err) - } - return nil -} - -func (p *JobUpdateSummary) readField6(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*Metadata]bool, size) - p.Metadata = tSet - for i := 0; i < size; i++ { - _elem27 := &Metadata{} - if err := _elem27.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem27), err) - } - p.Metadata[_elem27] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *JobUpdateSummary) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("JobUpdateSummary"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := p.writeField5(oprot); err != nil { - return err - } - if err := p.writeField6(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *JobUpdateSummary) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("user", thrift.STRING, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:user: ", p), err) - } - if err := oprot.WriteString(string(p.User)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.user (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:user: ", p), err) - } - return err -} - -func (p *JobUpdateSummary) writeField4(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("state", thrift.STRUCT, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:state: ", p), err) - } - if err := p.State.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.State), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:state: ", p), err) - } - return err -} - -func (p *JobUpdateSummary) writeField5(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 5); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:key: ", p), err) - } - if err := p.Key.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 5:key: ", p), err) - } - return err -} - -func (p *JobUpdateSummary) writeField6(oprot thrift.TProtocol) (err error) { - if p.IsSetMetadata() { - if err := oprot.WriteFieldBegin("metadata", thrift.SET, 6); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 6:metadata: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Metadata)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Metadata { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 6:metadata: ", p), err) - } - } - return err -} - -func (p *JobUpdateSummary) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("JobUpdateSummary(%+v)", *p) -} - -// Update configuration and setting details. -// -// Attributes: -// - InitialState: Actual InstanceId -> TaskConfig mapping when the update was requested. -// - DesiredState: Desired configuration when the update completes. -// - Settings: Update specific settings. -type JobUpdateInstructions struct { - InitialState map[*InstanceTaskConfig]bool `thrift:"initialState,1" json:"initialState"` - DesiredState *InstanceTaskConfig `thrift:"desiredState,2" json:"desiredState"` - Settings *JobUpdateSettings `thrift:"settings,3" json:"settings"` -} - -func NewJobUpdateInstructions() *JobUpdateInstructions { - return &JobUpdateInstructions{} -} - -func (p *JobUpdateInstructions) GetInitialState() map[*InstanceTaskConfig]bool { - return p.InitialState -} - -var JobUpdateInstructions_DesiredState_DEFAULT *InstanceTaskConfig - -func (p *JobUpdateInstructions) GetDesiredState() *InstanceTaskConfig { - if !p.IsSetDesiredState() { - return JobUpdateInstructions_DesiredState_DEFAULT - } - return p.DesiredState -} - -var JobUpdateInstructions_Settings_DEFAULT *JobUpdateSettings - -func (p *JobUpdateInstructions) GetSettings() *JobUpdateSettings { - if !p.IsSetSettings() { - return JobUpdateInstructions_Settings_DEFAULT - } - return p.Settings -} -func (p *JobUpdateInstructions) IsSetDesiredState() bool { - return p.DesiredState != nil -} - -func (p *JobUpdateInstructions) IsSetSettings() bool { - return p.Settings != nil -} - -func (p *JobUpdateInstructions) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *JobUpdateInstructions) readField1(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*InstanceTaskConfig]bool, size) - p.InitialState = tSet - for i := 0; i < size; i++ { - _elem28 := &InstanceTaskConfig{} - if err := _elem28.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem28), err) - } - p.InitialState[_elem28] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *JobUpdateInstructions) readField2(iprot thrift.TProtocol) error { - p.DesiredState = &InstanceTaskConfig{} - if err := p.DesiredState.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.DesiredState), err) - } - return nil -} - -func (p *JobUpdateInstructions) readField3(iprot thrift.TProtocol) error { - p.Settings = &JobUpdateSettings{} - if err := p.Settings.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Settings), err) - } - return nil -} - -func (p *JobUpdateInstructions) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("JobUpdateInstructions"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *JobUpdateInstructions) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("initialState", thrift.SET, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:initialState: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.InitialState)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.InitialState { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:initialState: ", p), err) - } - return err -} - -func (p *JobUpdateInstructions) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("desiredState", thrift.STRUCT, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:desiredState: ", p), err) - } - if err := p.DesiredState.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.DesiredState), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:desiredState: ", p), err) - } - return err -} - -func (p *JobUpdateInstructions) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("settings", thrift.STRUCT, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:settings: ", p), err) - } - if err := p.Settings.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Settings), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:settings: ", p), err) - } - return err -} - -func (p *JobUpdateInstructions) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("JobUpdateInstructions(%+v)", *p) -} - -// Full definition of the job update. -// -// Attributes: -// - Summary: Update summary. -// - Instructions: Update configuration. -type JobUpdate struct { - Summary *JobUpdateSummary `thrift:"summary,1" json:"summary"` - Instructions *JobUpdateInstructions `thrift:"instructions,2" json:"instructions"` -} - -func NewJobUpdate() *JobUpdate { - return &JobUpdate{} -} - -var JobUpdate_Summary_DEFAULT *JobUpdateSummary - -func (p *JobUpdate) GetSummary() *JobUpdateSummary { - if !p.IsSetSummary() { - return JobUpdate_Summary_DEFAULT - } - return p.Summary -} - -var JobUpdate_Instructions_DEFAULT *JobUpdateInstructions - -func (p *JobUpdate) GetInstructions() *JobUpdateInstructions { - if !p.IsSetInstructions() { - return JobUpdate_Instructions_DEFAULT - } - return p.Instructions -} -func (p *JobUpdate) IsSetSummary() bool { - return p.Summary != nil -} - -func (p *JobUpdate) IsSetInstructions() bool { - return p.Instructions != nil -} - -func (p *JobUpdate) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *JobUpdate) readField1(iprot thrift.TProtocol) error { - p.Summary = &JobUpdateSummary{} - if err := p.Summary.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Summary), err) - } - return nil -} - -func (p *JobUpdate) readField2(iprot thrift.TProtocol) error { - p.Instructions = &JobUpdateInstructions{} - if err := p.Instructions.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Instructions), err) - } - return nil -} - -func (p *JobUpdate) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("JobUpdate"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *JobUpdate) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("summary", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:summary: ", p), err) - } - if err := p.Summary.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Summary), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:summary: ", p), err) - } - return err -} - -func (p *JobUpdate) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("instructions", thrift.STRUCT, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:instructions: ", p), err) - } - if err := p.Instructions.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Instructions), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:instructions: ", p), err) - } - return err -} - -func (p *JobUpdate) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("JobUpdate(%+v)", *p) -} - -// Attributes: -// - Update: Update definition. -// - UpdateEvents: History for this update. -// - InstanceEvents: History for the individual instances updated. -type JobUpdateDetails struct { - Update *JobUpdate `thrift:"update,1" json:"update"` - UpdateEvents []*JobUpdateEvent `thrift:"updateEvents,2" json:"updateEvents"` - InstanceEvents []*JobInstanceUpdateEvent `thrift:"instanceEvents,3" json:"instanceEvents"` -} - -func NewJobUpdateDetails() *JobUpdateDetails { - return &JobUpdateDetails{} -} - -var JobUpdateDetails_Update_DEFAULT *JobUpdate - -func (p *JobUpdateDetails) GetUpdate() *JobUpdate { - if !p.IsSetUpdate() { - return JobUpdateDetails_Update_DEFAULT - } - return p.Update -} - -func (p *JobUpdateDetails) GetUpdateEvents() []*JobUpdateEvent { - return p.UpdateEvents -} - -func (p *JobUpdateDetails) GetInstanceEvents() []*JobInstanceUpdateEvent { - return p.InstanceEvents -} -func (p *JobUpdateDetails) IsSetUpdate() bool { - return p.Update != nil -} - -func (p *JobUpdateDetails) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *JobUpdateDetails) readField1(iprot thrift.TProtocol) error { - p.Update = &JobUpdate{} - if err := p.Update.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Update), err) - } - return nil -} - -func (p *JobUpdateDetails) readField2(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadListBegin() - if err != nil { - return thrift.PrependError("error reading list begin: ", err) - } - tSlice := make([]*JobUpdateEvent, 0, size) - p.UpdateEvents = tSlice - for i := 0; i < size; i++ { - _elem29 := &JobUpdateEvent{} - if err := _elem29.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem29), err) - } - p.UpdateEvents = append(p.UpdateEvents, _elem29) - } - if err := iprot.ReadListEnd(); err != nil { - return thrift.PrependError("error reading list end: ", err) - } - return nil -} - -func (p *JobUpdateDetails) readField3(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadListBegin() - if err != nil { - return thrift.PrependError("error reading list begin: ", err) - } - tSlice := make([]*JobInstanceUpdateEvent, 0, size) - p.InstanceEvents = tSlice - for i := 0; i < size; i++ { - _elem30 := &JobInstanceUpdateEvent{} - if err := _elem30.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem30), err) - } - p.InstanceEvents = append(p.InstanceEvents, _elem30) - } - if err := iprot.ReadListEnd(); err != nil { - return thrift.PrependError("error reading list end: ", err) - } - return nil -} - -func (p *JobUpdateDetails) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("JobUpdateDetails"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *JobUpdateDetails) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("update", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:update: ", p), err) - } - if err := p.Update.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Update), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:update: ", p), err) - } - return err -} - -func (p *JobUpdateDetails) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("updateEvents", thrift.LIST, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:updateEvents: ", p), err) - } - if err := oprot.WriteListBegin(thrift.STRUCT, len(p.UpdateEvents)); err != nil { - return thrift.PrependError("error writing list begin: ", err) - } - for _, v := range p.UpdateEvents { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteListEnd(); err != nil { - return thrift.PrependError("error writing list end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:updateEvents: ", p), err) - } - return err -} - -func (p *JobUpdateDetails) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("instanceEvents", thrift.LIST, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:instanceEvents: ", p), err) - } - if err := oprot.WriteListBegin(thrift.STRUCT, len(p.InstanceEvents)); err != nil { - return thrift.PrependError("error writing list begin: ", err) - } - for _, v := range p.InstanceEvents { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteListEnd(); err != nil { - return thrift.PrependError("error writing list end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:instanceEvents: ", p), err) - } - return err -} - -func (p *JobUpdateDetails) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("JobUpdateDetails(%+v)", *p) -} - -// A request to update the following instances of an existing job. Used by startUpdate. -// -// Attributes: -// - TaskConfig: Desired TaskConfig to apply. -// - InstanceCount: Desired number of instances of the task config. -// - Settings: Update settings and limits. -// - Metadata: Update metadata supplied by the client issuing the JobUpdateRequest. -type JobUpdateRequest struct { - TaskConfig *TaskConfig `thrift:"taskConfig,1" json:"taskConfig"` - InstanceCount int32 `thrift:"instanceCount,2" json:"instanceCount"` - Settings *JobUpdateSettings `thrift:"settings,3" json:"settings"` - Metadata map[*Metadata]bool `thrift:"metadata,4" json:"metadata,omitempty"` -} - -func NewJobUpdateRequest() *JobUpdateRequest { - return &JobUpdateRequest{} -} - -var JobUpdateRequest_TaskConfig_DEFAULT *TaskConfig - -func (p *JobUpdateRequest) GetTaskConfig() *TaskConfig { - if !p.IsSetTaskConfig() { - return JobUpdateRequest_TaskConfig_DEFAULT - } - return p.TaskConfig -} - -func (p *JobUpdateRequest) GetInstanceCount() int32 { - return p.InstanceCount -} - -var JobUpdateRequest_Settings_DEFAULT *JobUpdateSettings - -func (p *JobUpdateRequest) GetSettings() *JobUpdateSettings { - if !p.IsSetSettings() { - return JobUpdateRequest_Settings_DEFAULT - } - return p.Settings -} - -var JobUpdateRequest_Metadata_DEFAULT map[*Metadata]bool - -func (p *JobUpdateRequest) GetMetadata() map[*Metadata]bool { - return p.Metadata -} -func (p *JobUpdateRequest) IsSetTaskConfig() bool { - return p.TaskConfig != nil -} - -func (p *JobUpdateRequest) IsSetSettings() bool { - return p.Settings != nil -} - -func (p *JobUpdateRequest) IsSetMetadata() bool { - return p.Metadata != nil -} - -func (p *JobUpdateRequest) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *JobUpdateRequest) readField1(iprot thrift.TProtocol) error { - p.TaskConfig = &TaskConfig{} - if err := p.TaskConfig.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.TaskConfig), err) - } - return nil -} - -func (p *JobUpdateRequest) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.InstanceCount = v - } - return nil -} - -func (p *JobUpdateRequest) readField3(iprot thrift.TProtocol) error { - p.Settings = &JobUpdateSettings{} - if err := p.Settings.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Settings), err) - } - return nil -} - -func (p *JobUpdateRequest) readField4(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*Metadata]bool, size) - p.Metadata = tSet - for i := 0; i < size; i++ { - _elem31 := &Metadata{} - if err := _elem31.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem31), err) - } - p.Metadata[_elem31] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *JobUpdateRequest) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("JobUpdateRequest"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *JobUpdateRequest) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("taskConfig", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:taskConfig: ", p), err) - } - if err := p.TaskConfig.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.TaskConfig), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:taskConfig: ", p), err) - } - return err -} - -func (p *JobUpdateRequest) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("instanceCount", thrift.I32, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:instanceCount: ", p), err) - } - if err := oprot.WriteI32(int32(p.InstanceCount)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.instanceCount (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:instanceCount: ", p), err) - } - return err -} - -func (p *JobUpdateRequest) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("settings", thrift.STRUCT, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:settings: ", p), err) - } - if err := p.Settings.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Settings), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:settings: ", p), err) - } - return err -} - -func (p *JobUpdateRequest) writeField4(oprot thrift.TProtocol) (err error) { - if p.IsSetMetadata() { - if err := oprot.WriteFieldBegin("metadata", thrift.SET, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:metadata: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Metadata)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Metadata { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:metadata: ", p), err) - } - } - return err -} - -func (p *JobUpdateRequest) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("JobUpdateRequest(%+v)", *p) -} - -// Contains a set of restrictions on matching job updates where all restrictions must be met -// (terms are AND'ed together). -// -// Attributes: -// - Role: Job role. -// - Key: Unique identifier for a job update. -// - JobKey: Job key. -// - User: User who created the update. -// - UpdateStatuses: Set of update statuses. -// - Offset: Offset to serve data from. Used by pagination. -// - Limit: Number or records to serve. Used by pagination. -type JobUpdateQuery struct { - // unused field # 1 - Role *string `thrift:"role,2" json:"role,omitempty"` - JobKey *JobKey `thrift:"jobKey,3" json:"jobKey,omitempty"` - User *string `thrift:"user,4" json:"user,omitempty"` - UpdateStatuses map[JobUpdateStatus]bool `thrift:"updateStatuses,5" json:"updateStatuses,omitempty"` - Offset int32 `thrift:"offset,6" json:"offset"` - Limit int32 `thrift:"limit,7" json:"limit"` - Key *JobUpdateKey `thrift:"key,8" json:"key,omitempty"` -} - -func NewJobUpdateQuery() *JobUpdateQuery { - return &JobUpdateQuery{} -} - -var JobUpdateQuery_Role_DEFAULT string - -func (p *JobUpdateQuery) GetRole() string { - if !p.IsSetRole() { - return JobUpdateQuery_Role_DEFAULT - } - return *p.Role -} - -var JobUpdateQuery_Key_DEFAULT *JobUpdateKey - -func (p *JobUpdateQuery) GetKey() *JobUpdateKey { - if !p.IsSetKey() { - return JobUpdateQuery_Key_DEFAULT - } - return p.Key -} - -var JobUpdateQuery_JobKey_DEFAULT *JobKey - -func (p *JobUpdateQuery) GetJobKey() *JobKey { - if !p.IsSetJobKey() { - return JobUpdateQuery_JobKey_DEFAULT - } - return p.JobKey -} - -var JobUpdateQuery_User_DEFAULT string - -func (p *JobUpdateQuery) GetUser() string { - if !p.IsSetUser() { - return JobUpdateQuery_User_DEFAULT - } - return *p.User -} - -var JobUpdateQuery_UpdateStatuses_DEFAULT map[JobUpdateStatus]bool - -func (p *JobUpdateQuery) GetUpdateStatuses() map[JobUpdateStatus]bool { - return p.UpdateStatuses -} - -func (p *JobUpdateQuery) GetOffset() int32 { - return p.Offset -} - -func (p *JobUpdateQuery) GetLimit() int32 { - return p.Limit -} -func (p *JobUpdateQuery) IsSetRole() bool { - return p.Role != nil -} - -func (p *JobUpdateQuery) IsSetKey() bool { - return p.Key != nil -} - -func (p *JobUpdateQuery) IsSetJobKey() bool { - return p.JobKey != nil -} - -func (p *JobUpdateQuery) IsSetUser() bool { - return p.User != nil -} - -func (p *JobUpdateQuery) IsSetUpdateStatuses() bool { - return p.UpdateStatuses != nil -} - -func (p *JobUpdateQuery) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 8: - if err := p.readField8(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - case 5: - if err := p.readField5(iprot); err != nil { - return err - } - case 6: - if err := p.readField6(iprot); err != nil { - return err - } - case 7: - if err := p.readField7(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *JobUpdateQuery) readField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 2: ", err) - } else { - p.Role = &v - } - return nil -} - -func (p *JobUpdateQuery) readField8(iprot thrift.TProtocol) error { - p.Key = &JobUpdateKey{} - if err := p.Key.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) - } - return nil -} - -func (p *JobUpdateQuery) readField3(iprot thrift.TProtocol) error { - p.JobKey = &JobKey{} - if err := p.JobKey.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.JobKey), err) - } - return nil -} - -func (p *JobUpdateQuery) readField4(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 4: ", err) - } else { - p.User = &v - } - return nil -} - -func (p *JobUpdateQuery) readField5(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[JobUpdateStatus]bool, size) - p.UpdateStatuses = tSet - for i := 0; i < size; i++ { - var _elem32 JobUpdateStatus - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 0: ", err) - } else { - temp := JobUpdateStatus(v) - _elem32 = temp - } - p.UpdateStatuses[_elem32] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *JobUpdateQuery) readField6(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 6: ", err) - } else { - p.Offset = v - } - return nil -} - -func (p *JobUpdateQuery) readField7(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 7: ", err) - } else { - p.Limit = v - } - return nil -} - -func (p *JobUpdateQuery) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("JobUpdateQuery"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := p.writeField5(oprot); err != nil { - return err - } - if err := p.writeField6(oprot); err != nil { - return err - } - if err := p.writeField7(oprot); err != nil { - return err - } - if err := p.writeField8(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *JobUpdateQuery) writeField2(oprot thrift.TProtocol) (err error) { - if p.IsSetRole() { - if err := oprot.WriteFieldBegin("role", thrift.STRING, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:role: ", p), err) - } - if err := oprot.WriteString(string(*p.Role)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.role (2) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:role: ", p), err) - } - } - return err -} - -func (p *JobUpdateQuery) writeField3(oprot thrift.TProtocol) (err error) { - if p.IsSetJobKey() { - if err := oprot.WriteFieldBegin("jobKey", thrift.STRUCT, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:jobKey: ", p), err) - } - if err := p.JobKey.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.JobKey), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:jobKey: ", p), err) - } - } - return err -} - -func (p *JobUpdateQuery) writeField4(oprot thrift.TProtocol) (err error) { - if p.IsSetUser() { - if err := oprot.WriteFieldBegin("user", thrift.STRING, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:user: ", p), err) - } - if err := oprot.WriteString(string(*p.User)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.user (4) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:user: ", p), err) - } - } - return err -} - -func (p *JobUpdateQuery) writeField5(oprot thrift.TProtocol) (err error) { - if p.IsSetUpdateStatuses() { - if err := oprot.WriteFieldBegin("updateStatuses", thrift.SET, 5); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:updateStatuses: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.I32, len(p.UpdateStatuses)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.UpdateStatuses { - if err := oprot.WriteI32(int32(v)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 5:updateStatuses: ", p), err) - } - } - return err -} - -func (p *JobUpdateQuery) writeField6(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("offset", thrift.I32, 6); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 6:offset: ", p), err) - } - if err := oprot.WriteI32(int32(p.Offset)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.offset (6) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 6:offset: ", p), err) - } - return err -} - -func (p *JobUpdateQuery) writeField7(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("limit", thrift.I32, 7); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 7:limit: ", p), err) - } - if err := oprot.WriteI32(int32(p.Limit)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.limit (7) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 7:limit: ", p), err) - } - return err -} - -func (p *JobUpdateQuery) writeField8(oprot thrift.TProtocol) (err error) { - if p.IsSetKey() { - if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 8); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 8:key: ", p), err) - } - if err := p.Key.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 8:key: ", p), err) - } - } - return err -} - -func (p *JobUpdateQuery) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("JobUpdateQuery(%+v)", *p) -} - -// Attributes: -// - Host -// - DefaultSlaPolicy -// - TimeoutSecs -// - CreatedTimestampMs -type HostMaintenanceRequest struct { - Host string `thrift:"host,1" json:"host"` - DefaultSlaPolicy *SlaPolicy `thrift:"defaultSlaPolicy,2" json:"defaultSlaPolicy"` - TimeoutSecs int64 `thrift:"timeoutSecs,3" json:"timeoutSecs"` - CreatedTimestampMs int64 `thrift:"createdTimestampMs,4" json:"createdTimestampMs"` -} - -func NewHostMaintenanceRequest() *HostMaintenanceRequest { - return &HostMaintenanceRequest{} -} - -func (p *HostMaintenanceRequest) GetHost() string { - return p.Host -} - -var HostMaintenanceRequest_DefaultSlaPolicy_DEFAULT *SlaPolicy - -func (p *HostMaintenanceRequest) GetDefaultSlaPolicy() *SlaPolicy { - if !p.IsSetDefaultSlaPolicy() { - return HostMaintenanceRequest_DefaultSlaPolicy_DEFAULT - } - return p.DefaultSlaPolicy -} - -func (p *HostMaintenanceRequest) GetTimeoutSecs() int64 { - return p.TimeoutSecs -} - -func (p *HostMaintenanceRequest) GetCreatedTimestampMs() int64 { - return p.CreatedTimestampMs -} -func (p *HostMaintenanceRequest) IsSetDefaultSlaPolicy() bool { - return p.DefaultSlaPolicy != nil -} - -func (p *HostMaintenanceRequest) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *HostMaintenanceRequest) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Host = v - } - return nil -} - -func (p *HostMaintenanceRequest) readField2(iprot thrift.TProtocol) error { - p.DefaultSlaPolicy = &SlaPolicy{} - if err := p.DefaultSlaPolicy.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.DefaultSlaPolicy), err) - } - return nil -} - -func (p *HostMaintenanceRequest) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI64(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.TimeoutSecs = v - } - return nil -} - -func (p *HostMaintenanceRequest) readField4(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI64(); err != nil { - return thrift.PrependError("error reading field 4: ", err) - } else { - p.CreatedTimestampMs = v - } - return nil -} - -func (p *HostMaintenanceRequest) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("HostMaintenanceRequest"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *HostMaintenanceRequest) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("host", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:host: ", p), err) - } - if err := oprot.WriteString(string(p.Host)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.host (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:host: ", p), err) - } - return err -} - -func (p *HostMaintenanceRequest) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("defaultSlaPolicy", thrift.STRUCT, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:defaultSlaPolicy: ", p), err) - } - if err := p.DefaultSlaPolicy.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.DefaultSlaPolicy), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:defaultSlaPolicy: ", p), err) - } - return err -} - -func (p *HostMaintenanceRequest) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("timeoutSecs", thrift.I64, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:timeoutSecs: ", p), err) - } - if err := oprot.WriteI64(int64(p.TimeoutSecs)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.timeoutSecs (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:timeoutSecs: ", p), err) - } - return err -} - -func (p *HostMaintenanceRequest) writeField4(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("createdTimestampMs", thrift.I64, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:createdTimestampMs: ", p), err) - } - if err := oprot.WriteI64(int64(p.CreatedTimestampMs)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.createdTimestampMs (4) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:createdTimestampMs: ", p), err) - } - return err -} - -func (p *HostMaintenanceRequest) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("HostMaintenanceRequest(%+v)", *p) -} - -// Attributes: -// - Backups -type ListBackupsResult_ struct { - Backups map[string]bool `thrift:"backups,1" json:"backups"` -} - -func NewListBackupsResult_() *ListBackupsResult_ { - return &ListBackupsResult_{} -} - -func (p *ListBackupsResult_) GetBackups() map[string]bool { - return p.Backups -} -func (p *ListBackupsResult_) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ListBackupsResult_) readField1(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[string]bool, size) - p.Backups = tSet - for i := 0; i < size; i++ { - var _elem33 string - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 0: ", err) - } else { - _elem33 = v - } - p.Backups[_elem33] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *ListBackupsResult_) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("ListBackupsResult"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ListBackupsResult_) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("backups", thrift.SET, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:backups: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRING, len(p.Backups)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Backups { - if err := oprot.WriteString(string(v)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:backups: ", p), err) - } - return err -} - -func (p *ListBackupsResult_) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ListBackupsResult_(%+v)", *p) -} - -// Attributes: -// - Statuses -type StartMaintenanceResult_ struct { - Statuses map[*HostStatus]bool `thrift:"statuses,1" json:"statuses"` -} - -func NewStartMaintenanceResult_() *StartMaintenanceResult_ { - return &StartMaintenanceResult_{} -} - -func (p *StartMaintenanceResult_) GetStatuses() map[*HostStatus]bool { - return p.Statuses -} -func (p *StartMaintenanceResult_) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *StartMaintenanceResult_) readField1(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*HostStatus]bool, size) - p.Statuses = tSet - for i := 0; i < size; i++ { - _elem34 := &HostStatus{} - if err := _elem34.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem34), err) - } - p.Statuses[_elem34] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *StartMaintenanceResult_) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("StartMaintenanceResult"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *StartMaintenanceResult_) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("statuses", thrift.SET, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:statuses: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Statuses)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Statuses { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:statuses: ", p), err) - } - return err -} - -func (p *StartMaintenanceResult_) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("StartMaintenanceResult_(%+v)", *p) -} - -// Attributes: -// - Statuses -type DrainHostsResult_ struct { - Statuses map[*HostStatus]bool `thrift:"statuses,1" json:"statuses"` -} - -func NewDrainHostsResult_() *DrainHostsResult_ { - return &DrainHostsResult_{} -} - -func (p *DrainHostsResult_) GetStatuses() map[*HostStatus]bool { - return p.Statuses -} -func (p *DrainHostsResult_) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *DrainHostsResult_) readField1(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*HostStatus]bool, size) - p.Statuses = tSet - for i := 0; i < size; i++ { - _elem35 := &HostStatus{} - if err := _elem35.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem35), err) - } - p.Statuses[_elem35] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *DrainHostsResult_) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("DrainHostsResult"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *DrainHostsResult_) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("statuses", thrift.SET, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:statuses: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Statuses)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Statuses { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:statuses: ", p), err) - } - return err -} - -func (p *DrainHostsResult_) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("DrainHostsResult_(%+v)", *p) -} - -// Attributes: -// - Tasks -type QueryRecoveryResult_ struct { - Tasks map[*ScheduledTask]bool `thrift:"tasks,1" json:"tasks"` -} - -func NewQueryRecoveryResult_() *QueryRecoveryResult_ { - return &QueryRecoveryResult_{} -} - -func (p *QueryRecoveryResult_) GetTasks() map[*ScheduledTask]bool { - return p.Tasks -} -func (p *QueryRecoveryResult_) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *QueryRecoveryResult_) readField1(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*ScheduledTask]bool, size) - p.Tasks = tSet - for i := 0; i < size; i++ { - _elem36 := &ScheduledTask{} - if err := _elem36.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem36), err) - } - p.Tasks[_elem36] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *QueryRecoveryResult_) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("QueryRecoveryResult"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *QueryRecoveryResult_) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("tasks", thrift.SET, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:tasks: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Tasks)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Tasks { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:tasks: ", p), err) - } - return err -} - -func (p *QueryRecoveryResult_) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("QueryRecoveryResult_(%+v)", *p) -} - -// Attributes: -// - Statuses -type MaintenanceStatusResult_ struct { - Statuses map[*HostStatus]bool `thrift:"statuses,1" json:"statuses"` -} - -func NewMaintenanceStatusResult_() *MaintenanceStatusResult_ { - return &MaintenanceStatusResult_{} -} - -func (p *MaintenanceStatusResult_) GetStatuses() map[*HostStatus]bool { - return p.Statuses -} -func (p *MaintenanceStatusResult_) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *MaintenanceStatusResult_) readField1(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*HostStatus]bool, size) - p.Statuses = tSet - for i := 0; i < size; i++ { - _elem37 := &HostStatus{} - if err := _elem37.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem37), err) - } - p.Statuses[_elem37] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *MaintenanceStatusResult_) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("MaintenanceStatusResult"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *MaintenanceStatusResult_) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("statuses", thrift.SET, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:statuses: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Statuses)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Statuses { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:statuses: ", p), err) - } - return err -} - -func (p *MaintenanceStatusResult_) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("MaintenanceStatusResult_(%+v)", *p) -} - -// Attributes: -// - Statuses -type EndMaintenanceResult_ struct { - Statuses map[*HostStatus]bool `thrift:"statuses,1" json:"statuses"` -} - -func NewEndMaintenanceResult_() *EndMaintenanceResult_ { - return &EndMaintenanceResult_{} -} - -func (p *EndMaintenanceResult_) GetStatuses() map[*HostStatus]bool { - return p.Statuses -} -func (p *EndMaintenanceResult_) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *EndMaintenanceResult_) readField1(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*HostStatus]bool, size) - p.Statuses = tSet - for i := 0; i < size; i++ { - _elem38 := &HostStatus{} - if err := _elem38.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem38), err) - } - p.Statuses[_elem38] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *EndMaintenanceResult_) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("EndMaintenanceResult"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *EndMaintenanceResult_) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("statuses", thrift.SET, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:statuses: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Statuses)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Statuses { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:statuses: ", p), err) - } - return err -} - -func (p *EndMaintenanceResult_) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("EndMaintenanceResult_(%+v)", *p) -} - -// Attributes: -// - Summaries -type RoleSummaryResult_ struct { - Summaries map[*RoleSummary]bool `thrift:"summaries,1" json:"summaries"` -} - -func NewRoleSummaryResult_() *RoleSummaryResult_ { - return &RoleSummaryResult_{} -} - -func (p *RoleSummaryResult_) GetSummaries() map[*RoleSummary]bool { - return p.Summaries -} -func (p *RoleSummaryResult_) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *RoleSummaryResult_) readField1(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*RoleSummary]bool, size) - p.Summaries = tSet - for i := 0; i < size; i++ { - _elem39 := &RoleSummary{} - if err := _elem39.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem39), err) - } - p.Summaries[_elem39] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *RoleSummaryResult_) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("RoleSummaryResult"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *RoleSummaryResult_) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("summaries", thrift.SET, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:summaries: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Summaries)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Summaries { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:summaries: ", p), err) - } - return err -} - -func (p *RoleSummaryResult_) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("RoleSummaryResult_(%+v)", *p) -} - -// Attributes: -// - Summaries -type JobSummaryResult_ struct { - Summaries map[*JobSummary]bool `thrift:"summaries,1" json:"summaries"` -} - -func NewJobSummaryResult_() *JobSummaryResult_ { - return &JobSummaryResult_{} -} - -func (p *JobSummaryResult_) GetSummaries() map[*JobSummary]bool { - return p.Summaries -} -func (p *JobSummaryResult_) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *JobSummaryResult_) readField1(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*JobSummary]bool, size) - p.Summaries = tSet - for i := 0; i < size; i++ { - _elem40 := &JobSummary{} - if err := _elem40.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem40), err) - } - p.Summaries[_elem40] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *JobSummaryResult_) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("JobSummaryResult"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *JobSummaryResult_) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("summaries", thrift.SET, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:summaries: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Summaries)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Summaries { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:summaries: ", p), err) - } - return err -} - -func (p *JobSummaryResult_) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("JobSummaryResult_(%+v)", *p) -} - -// Attributes: -// - Summary -type ConfigSummaryResult_ struct { - Summary *ConfigSummary `thrift:"summary,1" json:"summary"` -} - -func NewConfigSummaryResult_() *ConfigSummaryResult_ { - return &ConfigSummaryResult_{} -} - -var ConfigSummaryResult__Summary_DEFAULT *ConfigSummary - -func (p *ConfigSummaryResult_) GetSummary() *ConfigSummary { - if !p.IsSetSummary() { - return ConfigSummaryResult__Summary_DEFAULT - } - return p.Summary -} -func (p *ConfigSummaryResult_) IsSetSummary() bool { - return p.Summary != nil -} - -func (p *ConfigSummaryResult_) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ConfigSummaryResult_) readField1(iprot thrift.TProtocol) error { - p.Summary = &ConfigSummary{} - if err := p.Summary.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Summary), err) - } - return nil -} - -func (p *ConfigSummaryResult_) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("ConfigSummaryResult"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ConfigSummaryResult_) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("summary", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:summary: ", p), err) - } - if err := p.Summary.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Summary), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:summary: ", p), err) - } - return err -} - -func (p *ConfigSummaryResult_) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ConfigSummaryResult_(%+v)", *p) -} - -// Attributes: -// - Reasons -type GetPendingReasonResult_ struct { - Reasons map[*PendingReason]bool `thrift:"reasons,1" json:"reasons"` -} - -func NewGetPendingReasonResult_() *GetPendingReasonResult_ { - return &GetPendingReasonResult_{} -} - -func (p *GetPendingReasonResult_) GetReasons() map[*PendingReason]bool { - return p.Reasons -} -func (p *GetPendingReasonResult_) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *GetPendingReasonResult_) readField1(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*PendingReason]bool, size) - p.Reasons = tSet - for i := 0; i < size; i++ { - _elem41 := &PendingReason{} - if err := _elem41.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem41), err) - } - p.Reasons[_elem41] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *GetPendingReasonResult_) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("GetPendingReasonResult"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *GetPendingReasonResult_) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("reasons", thrift.SET, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:reasons: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Reasons)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Reasons { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:reasons: ", p), err) - } - return err -} - -func (p *GetPendingReasonResult_) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("GetPendingReasonResult_(%+v)", *p) -} - -// Result of the startUpdate call. -// -// Attributes: -// - Key: Unique identifier for the job update. -// - UpdateSummary: Summary of the update that is in progress for the given JobKey. -type StartJobUpdateResult_ struct { - Key *JobUpdateKey `thrift:"key,1" json:"key"` - UpdateSummary *JobUpdateSummary `thrift:"updateSummary,2" json:"updateSummary,omitempty"` -} - -func NewStartJobUpdateResult_() *StartJobUpdateResult_ { - return &StartJobUpdateResult_{} -} - -var StartJobUpdateResult__Key_DEFAULT *JobUpdateKey - -func (p *StartJobUpdateResult_) GetKey() *JobUpdateKey { - if !p.IsSetKey() { - return StartJobUpdateResult__Key_DEFAULT - } - return p.Key -} - -var StartJobUpdateResult__UpdateSummary_DEFAULT *JobUpdateSummary - -func (p *StartJobUpdateResult_) GetUpdateSummary() *JobUpdateSummary { - if !p.IsSetUpdateSummary() { - return StartJobUpdateResult__UpdateSummary_DEFAULT - } - return p.UpdateSummary -} -func (p *StartJobUpdateResult_) IsSetKey() bool { - return p.Key != nil -} - -func (p *StartJobUpdateResult_) IsSetUpdateSummary() bool { - return p.UpdateSummary != nil -} - -func (p *StartJobUpdateResult_) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *StartJobUpdateResult_) readField1(iprot thrift.TProtocol) error { - p.Key = &JobUpdateKey{} - if err := p.Key.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Key), err) - } - return nil -} - -func (p *StartJobUpdateResult_) readField2(iprot thrift.TProtocol) error { - p.UpdateSummary = &JobUpdateSummary{} - if err := p.UpdateSummary.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.UpdateSummary), err) - } - return nil -} - -func (p *StartJobUpdateResult_) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("StartJobUpdateResult"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *StartJobUpdateResult_) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("key", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:key: ", p), err) - } - if err := p.Key.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Key), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:key: ", p), err) - } - return err -} - -func (p *StartJobUpdateResult_) writeField2(oprot thrift.TProtocol) (err error) { - if p.IsSetUpdateSummary() { - if err := oprot.WriteFieldBegin("updateSummary", thrift.STRUCT, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:updateSummary: ", p), err) - } - if err := p.UpdateSummary.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.UpdateSummary), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:updateSummary: ", p), err) - } - } - return err -} - -func (p *StartJobUpdateResult_) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("StartJobUpdateResult_(%+v)", *p) -} - -// Result of the getJobUpdateSummaries call. -// -// Attributes: -// - UpdateSummaries -type GetJobUpdateSummariesResult_ struct { - UpdateSummaries []*JobUpdateSummary `thrift:"updateSummaries,1" json:"updateSummaries"` -} - -func NewGetJobUpdateSummariesResult_() *GetJobUpdateSummariesResult_ { - return &GetJobUpdateSummariesResult_{} -} - -func (p *GetJobUpdateSummariesResult_) GetUpdateSummaries() []*JobUpdateSummary { - return p.UpdateSummaries -} -func (p *GetJobUpdateSummariesResult_) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *GetJobUpdateSummariesResult_) readField1(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadListBegin() - if err != nil { - return thrift.PrependError("error reading list begin: ", err) - } - tSlice := make([]*JobUpdateSummary, 0, size) - p.UpdateSummaries = tSlice - for i := 0; i < size; i++ { - _elem42 := &JobUpdateSummary{} - if err := _elem42.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem42), err) - } - p.UpdateSummaries = append(p.UpdateSummaries, _elem42) - } - if err := iprot.ReadListEnd(); err != nil { - return thrift.PrependError("error reading list end: ", err) - } - return nil -} - -func (p *GetJobUpdateSummariesResult_) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("GetJobUpdateSummariesResult"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *GetJobUpdateSummariesResult_) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("updateSummaries", thrift.LIST, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:updateSummaries: ", p), err) - } - if err := oprot.WriteListBegin(thrift.STRUCT, len(p.UpdateSummaries)); err != nil { - return thrift.PrependError("error writing list begin: ", err) - } - for _, v := range p.UpdateSummaries { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteListEnd(); err != nil { - return thrift.PrependError("error writing list end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:updateSummaries: ", p), err) - } - return err -} - -func (p *GetJobUpdateSummariesResult_) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("GetJobUpdateSummariesResult_(%+v)", *p) -} - -// Result of the getJobUpdateDetails call. -// -// Attributes: -// - Details -// - DetailsList -type GetJobUpdateDetailsResult_ struct { - Details *JobUpdateDetails `thrift:"details,1" json:"details"` - DetailsList []*JobUpdateDetails `thrift:"detailsList,2" json:"detailsList"` -} - -func NewGetJobUpdateDetailsResult_() *GetJobUpdateDetailsResult_ { - return &GetJobUpdateDetailsResult_{} -} - -var GetJobUpdateDetailsResult__Details_DEFAULT *JobUpdateDetails - -func (p *GetJobUpdateDetailsResult_) GetDetails() *JobUpdateDetails { - if !p.IsSetDetails() { - return GetJobUpdateDetailsResult__Details_DEFAULT - } - return p.Details -} - -func (p *GetJobUpdateDetailsResult_) GetDetailsList() []*JobUpdateDetails { - return p.DetailsList -} -func (p *GetJobUpdateDetailsResult_) IsSetDetails() bool { - return p.Details != nil -} - -func (p *GetJobUpdateDetailsResult_) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *GetJobUpdateDetailsResult_) readField1(iprot thrift.TProtocol) error { - p.Details = &JobUpdateDetails{} - if err := p.Details.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Details), err) - } - return nil -} - -func (p *GetJobUpdateDetailsResult_) readField2(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadListBegin() - if err != nil { - return thrift.PrependError("error reading list begin: ", err) - } - tSlice := make([]*JobUpdateDetails, 0, size) - p.DetailsList = tSlice - for i := 0; i < size; i++ { - _elem43 := &JobUpdateDetails{} - if err := _elem43.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem43), err) - } - p.DetailsList = append(p.DetailsList, _elem43) - } - if err := iprot.ReadListEnd(); err != nil { - return thrift.PrependError("error reading list end: ", err) - } - return nil -} - -func (p *GetJobUpdateDetailsResult_) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("GetJobUpdateDetailsResult"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *GetJobUpdateDetailsResult_) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("details", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:details: ", p), err) - } - if err := p.Details.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Details), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:details: ", p), err) - } - return err -} - -func (p *GetJobUpdateDetailsResult_) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("detailsList", thrift.LIST, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:detailsList: ", p), err) - } - if err := oprot.WriteListBegin(thrift.STRUCT, len(p.DetailsList)); err != nil { - return thrift.PrependError("error writing list begin: ", err) - } - for _, v := range p.DetailsList { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteListEnd(); err != nil { - return thrift.PrependError("error writing list end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:detailsList: ", p), err) - } - return err -} - -func (p *GetJobUpdateDetailsResult_) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("GetJobUpdateDetailsResult_(%+v)", *p) -} - -// Result of the pulseJobUpdate call. -// -// Attributes: -// - Status -type PulseJobUpdateResult_ struct { - Status JobUpdatePulseStatus `thrift:"status,1" json:"status"` -} - -func NewPulseJobUpdateResult_() *PulseJobUpdateResult_ { - return &PulseJobUpdateResult_{} -} - -func (p *PulseJobUpdateResult_) GetStatus() JobUpdatePulseStatus { - return p.Status -} -func (p *PulseJobUpdateResult_) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *PulseJobUpdateResult_) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - temp := JobUpdatePulseStatus(v) - p.Status = temp - } - return nil -} - -func (p *PulseJobUpdateResult_) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("PulseJobUpdateResult"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *PulseJobUpdateResult_) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("status", thrift.I32, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:status: ", p), err) - } - if err := oprot.WriteI32(int32(p.Status)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.status (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:status: ", p), err) - } - return err -} - -func (p *PulseJobUpdateResult_) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("PulseJobUpdateResult_(%+v)", *p) -} - -// Attributes: -// - Add: Instance addition diff details. -// - Remove: Instance removal diff details. -// - Update: Instance update diff details. -// - Unchanged: Instances unchanged by the update. -type GetJobUpdateDiffResult_ struct { - Add map[*ConfigGroup]bool `thrift:"add,1" json:"add"` - Remove map[*ConfigGroup]bool `thrift:"remove,2" json:"remove"` - Update map[*ConfigGroup]bool `thrift:"update,3" json:"update"` - Unchanged map[*ConfigGroup]bool `thrift:"unchanged,4" json:"unchanged"` -} - -func NewGetJobUpdateDiffResult_() *GetJobUpdateDiffResult_ { - return &GetJobUpdateDiffResult_{} -} - -func (p *GetJobUpdateDiffResult_) GetAdd() map[*ConfigGroup]bool { - return p.Add -} - -func (p *GetJobUpdateDiffResult_) GetRemove() map[*ConfigGroup]bool { - return p.Remove -} - -func (p *GetJobUpdateDiffResult_) GetUpdate() map[*ConfigGroup]bool { - return p.Update -} - -func (p *GetJobUpdateDiffResult_) GetUnchanged() map[*ConfigGroup]bool { - return p.Unchanged -} -func (p *GetJobUpdateDiffResult_) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *GetJobUpdateDiffResult_) readField1(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*ConfigGroup]bool, size) - p.Add = tSet - for i := 0; i < size; i++ { - _elem44 := &ConfigGroup{} - if err := _elem44.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem44), err) - } - p.Add[_elem44] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *GetJobUpdateDiffResult_) readField2(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*ConfigGroup]bool, size) - p.Remove = tSet - for i := 0; i < size; i++ { - _elem45 := &ConfigGroup{} - if err := _elem45.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem45), err) - } - p.Remove[_elem45] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *GetJobUpdateDiffResult_) readField3(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*ConfigGroup]bool, size) - p.Update = tSet - for i := 0; i < size; i++ { - _elem46 := &ConfigGroup{} - if err := _elem46.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem46), err) - } - p.Update[_elem46] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *GetJobUpdateDiffResult_) readField4(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*ConfigGroup]bool, size) - p.Unchanged = tSet - for i := 0; i < size; i++ { - _elem47 := &ConfigGroup{} - if err := _elem47.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem47), err) - } - p.Unchanged[_elem47] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *GetJobUpdateDiffResult_) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("GetJobUpdateDiffResult"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *GetJobUpdateDiffResult_) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("add", thrift.SET, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:add: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Add)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Add { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:add: ", p), err) - } - return err -} - -func (p *GetJobUpdateDiffResult_) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("remove", thrift.SET, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:remove: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Remove)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Remove { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:remove: ", p), err) - } - return err -} - -func (p *GetJobUpdateDiffResult_) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("update", thrift.SET, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:update: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Update)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Update { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:update: ", p), err) - } - return err -} - -func (p *GetJobUpdateDiffResult_) writeField4(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("unchanged", thrift.SET, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:unchanged: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Unchanged)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Unchanged { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:unchanged: ", p), err) - } - return err -} - -func (p *GetJobUpdateDiffResult_) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("GetJobUpdateDiffResult_(%+v)", *p) -} - -// Tier information. -// -// Attributes: -// - Name: Name of tier. -// - Settings: Tier attributes. -type TierConfig struct { - Name string `thrift:"name,1" json:"name"` - Settings map[string]string `thrift:"settings,2" json:"settings"` -} - -func NewTierConfig() *TierConfig { - return &TierConfig{} -} - -func (p *TierConfig) GetName() string { - return p.Name -} - -func (p *TierConfig) GetSettings() map[string]string { - return p.Settings -} -func (p *TierConfig) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *TierConfig) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Name = v - } - return nil -} - -func (p *TierConfig) readField2(iprot thrift.TProtocol) error { - _, _, size, err := iprot.ReadMapBegin() - if err != nil { - return thrift.PrependError("error reading map begin: ", err) - } - tMap := make(map[string]string, size) - p.Settings = tMap - for i := 0; i < size; i++ { - var _key48 string - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 0: ", err) - } else { - _key48 = v - } - var _val49 string - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 0: ", err) - } else { - _val49 = v - } - p.Settings[_key48] = _val49 - } - if err := iprot.ReadMapEnd(); err != nil { - return thrift.PrependError("error reading map end: ", err) - } - return nil -} - -func (p *TierConfig) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("TierConfig"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *TierConfig) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("name", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:name: ", p), err) - } - if err := oprot.WriteString(string(p.Name)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.name (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:name: ", p), err) - } - return err -} - -func (p *TierConfig) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("settings", thrift.MAP, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:settings: ", p), err) - } - if err := oprot.WriteMapBegin(thrift.STRING, thrift.STRING, len(p.Settings)); err != nil { - return thrift.PrependError("error writing map begin: ", err) - } - for k, v := range p.Settings { - if err := oprot.WriteString(string(k)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) - } - if err := oprot.WriteString(string(v)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err) - } - } - if err := oprot.WriteMapEnd(); err != nil { - return thrift.PrependError("error writing map end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:settings: ", p), err) - } - return err -} - -func (p *TierConfig) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("TierConfig(%+v)", *p) -} - -// Result of the getTierConfigResult call. -// -// Attributes: -// - DefaultTierName: Name of the default tier. -// - Tiers: Set of tier configurations. -type GetTierConfigResult_ struct { - DefaultTierName string `thrift:"defaultTierName,1" json:"defaultTierName"` - Tiers map[*TierConfig]bool `thrift:"tiers,2" json:"tiers"` -} - -func NewGetTierConfigResult_() *GetTierConfigResult_ { - return &GetTierConfigResult_{} -} - -func (p *GetTierConfigResult_) GetDefaultTierName() string { - return p.DefaultTierName -} - -func (p *GetTierConfigResult_) GetTiers() map[*TierConfig]bool { - return p.Tiers -} -func (p *GetTierConfigResult_) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 2: - if err := p.readField2(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *GetTierConfigResult_) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.DefaultTierName = v - } - return nil -} - -func (p *GetTierConfigResult_) readField2(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadSetBegin() - if err != nil { - return thrift.PrependError("error reading set begin: ", err) - } - tSet := make(map[*TierConfig]bool, size) - p.Tiers = tSet - for i := 0; i < size; i++ { - _elem50 := &TierConfig{} - if err := _elem50.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem50), err) - } - p.Tiers[_elem50] = true - } - if err := iprot.ReadSetEnd(); err != nil { - return thrift.PrependError("error reading set end: ", err) - } - return nil -} - -func (p *GetTierConfigResult_) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("GetTierConfigResult"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField2(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *GetTierConfigResult_) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("defaultTierName", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:defaultTierName: ", p), err) - } - if err := oprot.WriteString(string(p.DefaultTierName)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.defaultTierName (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:defaultTierName: ", p), err) - } - return err -} - -func (p *GetTierConfigResult_) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("tiers", thrift.SET, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:tiers: ", p), err) - } - if err := oprot.WriteSetBegin(thrift.STRUCT, len(p.Tiers)); err != nil { - return thrift.PrependError("error writing set begin: ", err) - } - for v, _ := range p.Tiers { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteSetEnd(); err != nil { - return thrift.PrependError("error writing set end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:tiers: ", p), err) - } - return err -} - -func (p *GetTierConfigResult_) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("GetTierConfigResult_(%+v)", *p) -} - -// Information about the scheduler. -// -// Attributes: -// - ClusterName -// - StatsUrlPrefix: A url prefix for job container stats. -type ServerInfo struct { - ClusterName string `thrift:"clusterName,1" json:"clusterName"` - // unused field # 2 - StatsUrlPrefix string `thrift:"statsUrlPrefix,3" json:"statsUrlPrefix"` -} - -func NewServerInfo() *ServerInfo { - return &ServerInfo{} -} - -func (p *ServerInfo) GetClusterName() string { - return p.ClusterName -} - -func (p *ServerInfo) GetStatsUrlPrefix() string { - return p.StatsUrlPrefix -} -func (p *ServerInfo) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ServerInfo) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.ClusterName = v - } - return nil -} - -func (p *ServerInfo) readField3(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 3: ", err) - } else { - p.StatsUrlPrefix = v - } - return nil -} - -func (p *ServerInfo) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("ServerInfo"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ServerInfo) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("clusterName", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:clusterName: ", p), err) - } - if err := oprot.WriteString(string(p.ClusterName)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.clusterName (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:clusterName: ", p), err) - } - return err -} - -func (p *ServerInfo) writeField3(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("statsUrlPrefix", thrift.STRING, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:statsUrlPrefix: ", p), err) - } - if err := oprot.WriteString(string(p.StatsUrlPrefix)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.statsUrlPrefix (3) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:statsUrlPrefix: ", p), err) - } - return err -} - -func (p *ServerInfo) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ServerInfo(%+v)", *p) -} - -// Attributes: -// - PopulateJobResult_ -// - ScheduleStatusResult_ -// - GetJobsResult_ -// - GetQuotaResult_ -// - ListBackupsResult_ -// - StartMaintenanceResult_ -// - DrainHostsResult_ -// - QueryRecoveryResult_ -// - MaintenanceStatusResult_ -// - EndMaintenanceResult_ -// - RoleSummaryResult_ -// - JobSummaryResult_ -// - ConfigSummaryResult_ -// - GetPendingReasonResult_ -// - StartJobUpdateResult_ -// - GetJobUpdateSummariesResult_ -// - GetJobUpdateDetailsResult_ -// - PulseJobUpdateResult_ -// - GetJobUpdateDiffResult_ -// - GetTierConfigResult_ -type Result_ struct { - PopulateJobResult_ *PopulateJobResult_ `thrift:"populateJobResult,1" json:"populateJobResult,omitempty"` - // unused field # 2 - ScheduleStatusResult_ *ScheduleStatusResult_ `thrift:"scheduleStatusResult,3" json:"scheduleStatusResult,omitempty"` - GetJobsResult_ *GetJobsResult_ `thrift:"getJobsResult,4" json:"getJobsResult,omitempty"` - GetQuotaResult_ *GetQuotaResult_ `thrift:"getQuotaResult,5" json:"getQuotaResult,omitempty"` - ListBackupsResult_ *ListBackupsResult_ `thrift:"listBackupsResult,6" json:"listBackupsResult,omitempty"` - StartMaintenanceResult_ *StartMaintenanceResult_ `thrift:"startMaintenanceResult,7" json:"startMaintenanceResult,omitempty"` - DrainHostsResult_ *DrainHostsResult_ `thrift:"drainHostsResult,8" json:"drainHostsResult,omitempty"` - QueryRecoveryResult_ *QueryRecoveryResult_ `thrift:"queryRecoveryResult,9" json:"queryRecoveryResult,omitempty"` - MaintenanceStatusResult_ *MaintenanceStatusResult_ `thrift:"maintenanceStatusResult,10" json:"maintenanceStatusResult,omitempty"` - EndMaintenanceResult_ *EndMaintenanceResult_ `thrift:"endMaintenanceResult,11" json:"endMaintenanceResult,omitempty"` - // unused fields # 12 to 16 - RoleSummaryResult_ *RoleSummaryResult_ `thrift:"roleSummaryResult,17" json:"roleSummaryResult,omitempty"` - JobSummaryResult_ *JobSummaryResult_ `thrift:"jobSummaryResult,18" json:"jobSummaryResult,omitempty"` - // unused field # 19 - ConfigSummaryResult_ *ConfigSummaryResult_ `thrift:"configSummaryResult,20" json:"configSummaryResult,omitempty"` - GetPendingReasonResult_ *GetPendingReasonResult_ `thrift:"getPendingReasonResult,21" json:"getPendingReasonResult,omitempty"` - StartJobUpdateResult_ *StartJobUpdateResult_ `thrift:"startJobUpdateResult,22" json:"startJobUpdateResult,omitempty"` - GetJobUpdateSummariesResult_ *GetJobUpdateSummariesResult_ `thrift:"getJobUpdateSummariesResult,23" json:"getJobUpdateSummariesResult,omitempty"` - GetJobUpdateDetailsResult_ *GetJobUpdateDetailsResult_ `thrift:"getJobUpdateDetailsResult,24" json:"getJobUpdateDetailsResult,omitempty"` - PulseJobUpdateResult_ *PulseJobUpdateResult_ `thrift:"pulseJobUpdateResult,25" json:"pulseJobUpdateResult,omitempty"` - GetJobUpdateDiffResult_ *GetJobUpdateDiffResult_ `thrift:"getJobUpdateDiffResult,26" json:"getJobUpdateDiffResult,omitempty"` - GetTierConfigResult_ *GetTierConfigResult_ `thrift:"getTierConfigResult,27" json:"getTierConfigResult,omitempty"` -} - -func NewResult_() *Result_ { - return &Result_{} -} - -var Result__PopulateJobResult__DEFAULT *PopulateJobResult_ - -func (p *Result_) GetPopulateJobResult_() *PopulateJobResult_ { - if !p.IsSetPopulateJobResult_() { - return Result__PopulateJobResult__DEFAULT - } - return p.PopulateJobResult_ -} - -var Result__ScheduleStatusResult__DEFAULT *ScheduleStatusResult_ - -func (p *Result_) GetScheduleStatusResult_() *ScheduleStatusResult_ { - if !p.IsSetScheduleStatusResult_() { - return Result__ScheduleStatusResult__DEFAULT - } - return p.ScheduleStatusResult_ -} - -var Result__GetJobsResult__DEFAULT *GetJobsResult_ - -func (p *Result_) GetGetJobsResult_() *GetJobsResult_ { - if !p.IsSetGetJobsResult_() { - return Result__GetJobsResult__DEFAULT - } - return p.GetJobsResult_ -} - -var Result__GetQuotaResult__DEFAULT *GetQuotaResult_ - -func (p *Result_) GetGetQuotaResult_() *GetQuotaResult_ { - if !p.IsSetGetQuotaResult_() { - return Result__GetQuotaResult__DEFAULT - } - return p.GetQuotaResult_ -} - -var Result__ListBackupsResult__DEFAULT *ListBackupsResult_ - -func (p *Result_) GetListBackupsResult_() *ListBackupsResult_ { - if !p.IsSetListBackupsResult_() { - return Result__ListBackupsResult__DEFAULT - } - return p.ListBackupsResult_ -} - -var Result__StartMaintenanceResult__DEFAULT *StartMaintenanceResult_ - -func (p *Result_) GetStartMaintenanceResult_() *StartMaintenanceResult_ { - if !p.IsSetStartMaintenanceResult_() { - return Result__StartMaintenanceResult__DEFAULT - } - return p.StartMaintenanceResult_ -} - -var Result__DrainHostsResult__DEFAULT *DrainHostsResult_ - -func (p *Result_) GetDrainHostsResult_() *DrainHostsResult_ { - if !p.IsSetDrainHostsResult_() { - return Result__DrainHostsResult__DEFAULT - } - return p.DrainHostsResult_ -} - -var Result__QueryRecoveryResult__DEFAULT *QueryRecoveryResult_ - -func (p *Result_) GetQueryRecoveryResult_() *QueryRecoveryResult_ { - if !p.IsSetQueryRecoveryResult_() { - return Result__QueryRecoveryResult__DEFAULT - } - return p.QueryRecoveryResult_ -} - -var Result__MaintenanceStatusResult__DEFAULT *MaintenanceStatusResult_ - -func (p *Result_) GetMaintenanceStatusResult_() *MaintenanceStatusResult_ { - if !p.IsSetMaintenanceStatusResult_() { - return Result__MaintenanceStatusResult__DEFAULT - } - return p.MaintenanceStatusResult_ -} - -var Result__EndMaintenanceResult__DEFAULT *EndMaintenanceResult_ - -func (p *Result_) GetEndMaintenanceResult_() *EndMaintenanceResult_ { - if !p.IsSetEndMaintenanceResult_() { - return Result__EndMaintenanceResult__DEFAULT - } - return p.EndMaintenanceResult_ -} - -var Result__RoleSummaryResult__DEFAULT *RoleSummaryResult_ - -func (p *Result_) GetRoleSummaryResult_() *RoleSummaryResult_ { - if !p.IsSetRoleSummaryResult_() { - return Result__RoleSummaryResult__DEFAULT - } - return p.RoleSummaryResult_ -} - -var Result__JobSummaryResult__DEFAULT *JobSummaryResult_ - -func (p *Result_) GetJobSummaryResult_() *JobSummaryResult_ { - if !p.IsSetJobSummaryResult_() { - return Result__JobSummaryResult__DEFAULT - } - return p.JobSummaryResult_ -} - -var Result__ConfigSummaryResult__DEFAULT *ConfigSummaryResult_ - -func (p *Result_) GetConfigSummaryResult_() *ConfigSummaryResult_ { - if !p.IsSetConfigSummaryResult_() { - return Result__ConfigSummaryResult__DEFAULT - } - return p.ConfigSummaryResult_ -} - -var Result__GetPendingReasonResult__DEFAULT *GetPendingReasonResult_ - -func (p *Result_) GetGetPendingReasonResult_() *GetPendingReasonResult_ { - if !p.IsSetGetPendingReasonResult_() { - return Result__GetPendingReasonResult__DEFAULT - } - return p.GetPendingReasonResult_ -} - -var Result__StartJobUpdateResult__DEFAULT *StartJobUpdateResult_ - -func (p *Result_) GetStartJobUpdateResult_() *StartJobUpdateResult_ { - if !p.IsSetStartJobUpdateResult_() { - return Result__StartJobUpdateResult__DEFAULT - } - return p.StartJobUpdateResult_ -} - -var Result__GetJobUpdateSummariesResult__DEFAULT *GetJobUpdateSummariesResult_ - -func (p *Result_) GetGetJobUpdateSummariesResult_() *GetJobUpdateSummariesResult_ { - if !p.IsSetGetJobUpdateSummariesResult_() { - return Result__GetJobUpdateSummariesResult__DEFAULT - } - return p.GetJobUpdateSummariesResult_ -} - -var Result__GetJobUpdateDetailsResult__DEFAULT *GetJobUpdateDetailsResult_ - -func (p *Result_) GetGetJobUpdateDetailsResult_() *GetJobUpdateDetailsResult_ { - if !p.IsSetGetJobUpdateDetailsResult_() { - return Result__GetJobUpdateDetailsResult__DEFAULT - } - return p.GetJobUpdateDetailsResult_ -} - -var Result__PulseJobUpdateResult__DEFAULT *PulseJobUpdateResult_ - -func (p *Result_) GetPulseJobUpdateResult_() *PulseJobUpdateResult_ { - if !p.IsSetPulseJobUpdateResult_() { - return Result__PulseJobUpdateResult__DEFAULT - } - return p.PulseJobUpdateResult_ -} - -var Result__GetJobUpdateDiffResult__DEFAULT *GetJobUpdateDiffResult_ - -func (p *Result_) GetGetJobUpdateDiffResult_() *GetJobUpdateDiffResult_ { - if !p.IsSetGetJobUpdateDiffResult_() { - return Result__GetJobUpdateDiffResult__DEFAULT - } - return p.GetJobUpdateDiffResult_ -} - -var Result__GetTierConfigResult__DEFAULT *GetTierConfigResult_ - -func (p *Result_) GetGetTierConfigResult_() *GetTierConfigResult_ { - if !p.IsSetGetTierConfigResult_() { - return Result__GetTierConfigResult__DEFAULT - } - return p.GetTierConfigResult_ -} -func (p *Result_) CountSetFieldsResult_() int { - count := 0 - if p.IsSetPopulateJobResult_() { - count++ - } - if p.IsSetScheduleStatusResult_() { - count++ - } - if p.IsSetGetJobsResult_() { - count++ - } - if p.IsSetGetQuotaResult_() { - count++ - } - if p.IsSetListBackupsResult_() { - count++ - } - if p.IsSetStartMaintenanceResult_() { - count++ - } - if p.IsSetDrainHostsResult_() { - count++ - } - if p.IsSetQueryRecoveryResult_() { - count++ - } - if p.IsSetMaintenanceStatusResult_() { - count++ - } - if p.IsSetEndMaintenanceResult_() { - count++ - } - if p.IsSetRoleSummaryResult_() { - count++ - } - if p.IsSetJobSummaryResult_() { - count++ - } - if p.IsSetConfigSummaryResult_() { - count++ - } - if p.IsSetGetPendingReasonResult_() { - count++ - } - if p.IsSetStartJobUpdateResult_() { - count++ - } - if p.IsSetGetJobUpdateSummariesResult_() { - count++ - } - if p.IsSetGetJobUpdateDetailsResult_() { - count++ - } - if p.IsSetPulseJobUpdateResult_() { - count++ - } - if p.IsSetGetJobUpdateDiffResult_() { - count++ - } - if p.IsSetGetTierConfigResult_() { - count++ - } - return count - -} - -func (p *Result_) IsSetPopulateJobResult_() bool { - return p.PopulateJobResult_ != nil -} - -func (p *Result_) IsSetScheduleStatusResult_() bool { - return p.ScheduleStatusResult_ != nil -} - -func (p *Result_) IsSetGetJobsResult_() bool { - return p.GetJobsResult_ != nil -} - -func (p *Result_) IsSetGetQuotaResult_() bool { - return p.GetQuotaResult_ != nil -} - -func (p *Result_) IsSetListBackupsResult_() bool { - return p.ListBackupsResult_ != nil -} - -func (p *Result_) IsSetStartMaintenanceResult_() bool { - return p.StartMaintenanceResult_ != nil -} - -func (p *Result_) IsSetDrainHostsResult_() bool { - return p.DrainHostsResult_ != nil -} - -func (p *Result_) IsSetQueryRecoveryResult_() bool { - return p.QueryRecoveryResult_ != nil -} - -func (p *Result_) IsSetMaintenanceStatusResult_() bool { - return p.MaintenanceStatusResult_ != nil -} - -func (p *Result_) IsSetEndMaintenanceResult_() bool { - return p.EndMaintenanceResult_ != nil -} - -func (p *Result_) IsSetRoleSummaryResult_() bool { - return p.RoleSummaryResult_ != nil -} - -func (p *Result_) IsSetJobSummaryResult_() bool { - return p.JobSummaryResult_ != nil -} - -func (p *Result_) IsSetConfigSummaryResult_() bool { - return p.ConfigSummaryResult_ != nil -} - -func (p *Result_) IsSetGetPendingReasonResult_() bool { - return p.GetPendingReasonResult_ != nil -} - -func (p *Result_) IsSetStartJobUpdateResult_() bool { - return p.StartJobUpdateResult_ != nil -} - -func (p *Result_) IsSetGetJobUpdateSummariesResult_() bool { - return p.GetJobUpdateSummariesResult_ != nil -} - -func (p *Result_) IsSetGetJobUpdateDetailsResult_() bool { - return p.GetJobUpdateDetailsResult_ != nil -} - -func (p *Result_) IsSetPulseJobUpdateResult_() bool { - return p.PulseJobUpdateResult_ != nil -} - -func (p *Result_) IsSetGetJobUpdateDiffResult_() bool { - return p.GetJobUpdateDiffResult_ != nil -} - -func (p *Result_) IsSetGetTierConfigResult_() bool { - return p.GetTierConfigResult_ != nil -} - -func (p *Result_) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - case 4: - if err := p.readField4(iprot); err != nil { - return err - } - case 5: - if err := p.readField5(iprot); err != nil { - return err - } - case 6: - if err := p.readField6(iprot); err != nil { - return err - } - case 7: - if err := p.readField7(iprot); err != nil { - return err - } - case 8: - if err := p.readField8(iprot); err != nil { - return err - } - case 9: - if err := p.readField9(iprot); err != nil { - return err - } - case 10: - if err := p.readField10(iprot); err != nil { - return err - } - case 11: - if err := p.readField11(iprot); err != nil { - return err - } - case 17: - if err := p.readField17(iprot); err != nil { - return err - } - case 18: - if err := p.readField18(iprot); err != nil { - return err - } - case 20: - if err := p.readField20(iprot); err != nil { - return err - } - case 21: - if err := p.readField21(iprot); err != nil { - return err - } - case 22: - if err := p.readField22(iprot); err != nil { - return err - } - case 23: - if err := p.readField23(iprot); err != nil { - return err - } - case 24: - if err := p.readField24(iprot); err != nil { - return err - } - case 25: - if err := p.readField25(iprot); err != nil { - return err - } - case 26: - if err := p.readField26(iprot); err != nil { - return err - } - case 27: - if err := p.readField27(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *Result_) readField1(iprot thrift.TProtocol) error { - p.PopulateJobResult_ = &PopulateJobResult_{} - if err := p.PopulateJobResult_.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.PopulateJobResult_), err) - } - return nil -} - -func (p *Result_) readField3(iprot thrift.TProtocol) error { - p.ScheduleStatusResult_ = &ScheduleStatusResult_{} - if err := p.ScheduleStatusResult_.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.ScheduleStatusResult_), err) - } - return nil -} - -func (p *Result_) readField4(iprot thrift.TProtocol) error { - p.GetJobsResult_ = &GetJobsResult_{} - if err := p.GetJobsResult_.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.GetJobsResult_), err) - } - return nil -} - -func (p *Result_) readField5(iprot thrift.TProtocol) error { - p.GetQuotaResult_ = &GetQuotaResult_{} - if err := p.GetQuotaResult_.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.GetQuotaResult_), err) - } - return nil -} - -func (p *Result_) readField6(iprot thrift.TProtocol) error { - p.ListBackupsResult_ = &ListBackupsResult_{} - if err := p.ListBackupsResult_.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.ListBackupsResult_), err) - } - return nil -} - -func (p *Result_) readField7(iprot thrift.TProtocol) error { - p.StartMaintenanceResult_ = &StartMaintenanceResult_{} - if err := p.StartMaintenanceResult_.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.StartMaintenanceResult_), err) - } - return nil -} - -func (p *Result_) readField8(iprot thrift.TProtocol) error { - p.DrainHostsResult_ = &DrainHostsResult_{} - if err := p.DrainHostsResult_.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.DrainHostsResult_), err) - } - return nil -} - -func (p *Result_) readField9(iprot thrift.TProtocol) error { - p.QueryRecoveryResult_ = &QueryRecoveryResult_{} - if err := p.QueryRecoveryResult_.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.QueryRecoveryResult_), err) - } - return nil -} - -func (p *Result_) readField10(iprot thrift.TProtocol) error { - p.MaintenanceStatusResult_ = &MaintenanceStatusResult_{} - if err := p.MaintenanceStatusResult_.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.MaintenanceStatusResult_), err) - } - return nil -} - -func (p *Result_) readField11(iprot thrift.TProtocol) error { - p.EndMaintenanceResult_ = &EndMaintenanceResult_{} - if err := p.EndMaintenanceResult_.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.EndMaintenanceResult_), err) - } - return nil -} - -func (p *Result_) readField17(iprot thrift.TProtocol) error { - p.RoleSummaryResult_ = &RoleSummaryResult_{} - if err := p.RoleSummaryResult_.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.RoleSummaryResult_), err) - } - return nil -} - -func (p *Result_) readField18(iprot thrift.TProtocol) error { - p.JobSummaryResult_ = &JobSummaryResult_{} - if err := p.JobSummaryResult_.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.JobSummaryResult_), err) - } - return nil -} - -func (p *Result_) readField20(iprot thrift.TProtocol) error { - p.ConfigSummaryResult_ = &ConfigSummaryResult_{} - if err := p.ConfigSummaryResult_.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.ConfigSummaryResult_), err) - } - return nil -} - -func (p *Result_) readField21(iprot thrift.TProtocol) error { - p.GetPendingReasonResult_ = &GetPendingReasonResult_{} - if err := p.GetPendingReasonResult_.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.GetPendingReasonResult_), err) - } - return nil -} - -func (p *Result_) readField22(iprot thrift.TProtocol) error { - p.StartJobUpdateResult_ = &StartJobUpdateResult_{} - if err := p.StartJobUpdateResult_.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.StartJobUpdateResult_), err) - } - return nil -} - -func (p *Result_) readField23(iprot thrift.TProtocol) error { - p.GetJobUpdateSummariesResult_ = &GetJobUpdateSummariesResult_{} - if err := p.GetJobUpdateSummariesResult_.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.GetJobUpdateSummariesResult_), err) - } - return nil -} - -func (p *Result_) readField24(iprot thrift.TProtocol) error { - p.GetJobUpdateDetailsResult_ = &GetJobUpdateDetailsResult_{} - if err := p.GetJobUpdateDetailsResult_.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.GetJobUpdateDetailsResult_), err) - } - return nil -} - -func (p *Result_) readField25(iprot thrift.TProtocol) error { - p.PulseJobUpdateResult_ = &PulseJobUpdateResult_{} - if err := p.PulseJobUpdateResult_.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.PulseJobUpdateResult_), err) - } - return nil -} - -func (p *Result_) readField26(iprot thrift.TProtocol) error { - p.GetJobUpdateDiffResult_ = &GetJobUpdateDiffResult_{} - if err := p.GetJobUpdateDiffResult_.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.GetJobUpdateDiffResult_), err) - } - return nil -} - -func (p *Result_) readField27(iprot thrift.TProtocol) error { - p.GetTierConfigResult_ = &GetTierConfigResult_{} - if err := p.GetTierConfigResult_.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.GetTierConfigResult_), err) - } - return nil -} - -func (p *Result_) Write(oprot thrift.TProtocol) error { - if c := p.CountSetFieldsResult_(); c != 1 { - return fmt.Errorf("%T write union: exactly one field must be set (%d set).", p, c) - } - if err := oprot.WriteStructBegin("Result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := p.writeField4(oprot); err != nil { - return err - } - if err := p.writeField5(oprot); err != nil { - return err - } - if err := p.writeField6(oprot); err != nil { - return err - } - if err := p.writeField7(oprot); err != nil { - return err - } - if err := p.writeField8(oprot); err != nil { - return err - } - if err := p.writeField9(oprot); err != nil { - return err - } - if err := p.writeField10(oprot); err != nil { - return err - } - if err := p.writeField11(oprot); err != nil { - return err - } - if err := p.writeField17(oprot); err != nil { - return err - } - if err := p.writeField18(oprot); err != nil { - return err - } - if err := p.writeField20(oprot); err != nil { - return err - } - if err := p.writeField21(oprot); err != nil { - return err - } - if err := p.writeField22(oprot); err != nil { - return err - } - if err := p.writeField23(oprot); err != nil { - return err - } - if err := p.writeField24(oprot); err != nil { - return err - } - if err := p.writeField25(oprot); err != nil { - return err - } - if err := p.writeField26(oprot); err != nil { - return err - } - if err := p.writeField27(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *Result_) writeField1(oprot thrift.TProtocol) (err error) { - if p.IsSetPopulateJobResult_() { - if err := oprot.WriteFieldBegin("populateJobResult", thrift.STRUCT, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:populateJobResult: ", p), err) - } - if err := p.PopulateJobResult_.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.PopulateJobResult_), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:populateJobResult: ", p), err) - } - } - return err -} - -func (p *Result_) writeField3(oprot thrift.TProtocol) (err error) { - if p.IsSetScheduleStatusResult_() { - if err := oprot.WriteFieldBegin("scheduleStatusResult", thrift.STRUCT, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:scheduleStatusResult: ", p), err) - } - if err := p.ScheduleStatusResult_.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.ScheduleStatusResult_), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:scheduleStatusResult: ", p), err) - } - } - return err -} - -func (p *Result_) writeField4(oprot thrift.TProtocol) (err error) { - if p.IsSetGetJobsResult_() { - if err := oprot.WriteFieldBegin("getJobsResult", thrift.STRUCT, 4); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:getJobsResult: ", p), err) - } - if err := p.GetJobsResult_.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.GetJobsResult_), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 4:getJobsResult: ", p), err) - } - } - return err -} - -func (p *Result_) writeField5(oprot thrift.TProtocol) (err error) { - if p.IsSetGetQuotaResult_() { - if err := oprot.WriteFieldBegin("getQuotaResult", thrift.STRUCT, 5); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:getQuotaResult: ", p), err) - } - if err := p.GetQuotaResult_.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.GetQuotaResult_), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 5:getQuotaResult: ", p), err) - } - } - return err -} - -func (p *Result_) writeField6(oprot thrift.TProtocol) (err error) { - if p.IsSetListBackupsResult_() { - if err := oprot.WriteFieldBegin("listBackupsResult", thrift.STRUCT, 6); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 6:listBackupsResult: ", p), err) - } - if err := p.ListBackupsResult_.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.ListBackupsResult_), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 6:listBackupsResult: ", p), err) - } - } - return err -} - -func (p *Result_) writeField7(oprot thrift.TProtocol) (err error) { - if p.IsSetStartMaintenanceResult_() { - if err := oprot.WriteFieldBegin("startMaintenanceResult", thrift.STRUCT, 7); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 7:startMaintenanceResult: ", p), err) - } - if err := p.StartMaintenanceResult_.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.StartMaintenanceResult_), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 7:startMaintenanceResult: ", p), err) - } - } - return err -} - -func (p *Result_) writeField8(oprot thrift.TProtocol) (err error) { - if p.IsSetDrainHostsResult_() { - if err := oprot.WriteFieldBegin("drainHostsResult", thrift.STRUCT, 8); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 8:drainHostsResult: ", p), err) - } - if err := p.DrainHostsResult_.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.DrainHostsResult_), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 8:drainHostsResult: ", p), err) - } - } - return err -} - -func (p *Result_) writeField9(oprot thrift.TProtocol) (err error) { - if p.IsSetQueryRecoveryResult_() { - if err := oprot.WriteFieldBegin("queryRecoveryResult", thrift.STRUCT, 9); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 9:queryRecoveryResult: ", p), err) - } - if err := p.QueryRecoveryResult_.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.QueryRecoveryResult_), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 9:queryRecoveryResult: ", p), err) - } - } - return err -} - -func (p *Result_) writeField10(oprot thrift.TProtocol) (err error) { - if p.IsSetMaintenanceStatusResult_() { - if err := oprot.WriteFieldBegin("maintenanceStatusResult", thrift.STRUCT, 10); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 10:maintenanceStatusResult: ", p), err) - } - if err := p.MaintenanceStatusResult_.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.MaintenanceStatusResult_), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 10:maintenanceStatusResult: ", p), err) - } - } - return err -} - -func (p *Result_) writeField11(oprot thrift.TProtocol) (err error) { - if p.IsSetEndMaintenanceResult_() { - if err := oprot.WriteFieldBegin("endMaintenanceResult", thrift.STRUCT, 11); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 11:endMaintenanceResult: ", p), err) - } - if err := p.EndMaintenanceResult_.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.EndMaintenanceResult_), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 11:endMaintenanceResult: ", p), err) - } - } - return err -} - -func (p *Result_) writeField17(oprot thrift.TProtocol) (err error) { - if p.IsSetRoleSummaryResult_() { - if err := oprot.WriteFieldBegin("roleSummaryResult", thrift.STRUCT, 17); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 17:roleSummaryResult: ", p), err) - } - if err := p.RoleSummaryResult_.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.RoleSummaryResult_), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 17:roleSummaryResult: ", p), err) - } - } - return err -} - -func (p *Result_) writeField18(oprot thrift.TProtocol) (err error) { - if p.IsSetJobSummaryResult_() { - if err := oprot.WriteFieldBegin("jobSummaryResult", thrift.STRUCT, 18); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 18:jobSummaryResult: ", p), err) - } - if err := p.JobSummaryResult_.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.JobSummaryResult_), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 18:jobSummaryResult: ", p), err) - } - } - return err -} - -func (p *Result_) writeField20(oprot thrift.TProtocol) (err error) { - if p.IsSetConfigSummaryResult_() { - if err := oprot.WriteFieldBegin("configSummaryResult", thrift.STRUCT, 20); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 20:configSummaryResult: ", p), err) - } - if err := p.ConfigSummaryResult_.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.ConfigSummaryResult_), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 20:configSummaryResult: ", p), err) - } - } - return err -} - -func (p *Result_) writeField21(oprot thrift.TProtocol) (err error) { - if p.IsSetGetPendingReasonResult_() { - if err := oprot.WriteFieldBegin("getPendingReasonResult", thrift.STRUCT, 21); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 21:getPendingReasonResult: ", p), err) - } - if err := p.GetPendingReasonResult_.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.GetPendingReasonResult_), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 21:getPendingReasonResult: ", p), err) - } - } - return err -} - -func (p *Result_) writeField22(oprot thrift.TProtocol) (err error) { - if p.IsSetStartJobUpdateResult_() { - if err := oprot.WriteFieldBegin("startJobUpdateResult", thrift.STRUCT, 22); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 22:startJobUpdateResult: ", p), err) - } - if err := p.StartJobUpdateResult_.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.StartJobUpdateResult_), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 22:startJobUpdateResult: ", p), err) - } - } - return err -} - -func (p *Result_) writeField23(oprot thrift.TProtocol) (err error) { - if p.IsSetGetJobUpdateSummariesResult_() { - if err := oprot.WriteFieldBegin("getJobUpdateSummariesResult", thrift.STRUCT, 23); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 23:getJobUpdateSummariesResult: ", p), err) - } - if err := p.GetJobUpdateSummariesResult_.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.GetJobUpdateSummariesResult_), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 23:getJobUpdateSummariesResult: ", p), err) - } - } - return err -} - -func (p *Result_) writeField24(oprot thrift.TProtocol) (err error) { - if p.IsSetGetJobUpdateDetailsResult_() { - if err := oprot.WriteFieldBegin("getJobUpdateDetailsResult", thrift.STRUCT, 24); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 24:getJobUpdateDetailsResult: ", p), err) - } - if err := p.GetJobUpdateDetailsResult_.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.GetJobUpdateDetailsResult_), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 24:getJobUpdateDetailsResult: ", p), err) - } - } - return err -} - -func (p *Result_) writeField25(oprot thrift.TProtocol) (err error) { - if p.IsSetPulseJobUpdateResult_() { - if err := oprot.WriteFieldBegin("pulseJobUpdateResult", thrift.STRUCT, 25); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 25:pulseJobUpdateResult: ", p), err) - } - if err := p.PulseJobUpdateResult_.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.PulseJobUpdateResult_), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 25:pulseJobUpdateResult: ", p), err) - } - } - return err -} - -func (p *Result_) writeField26(oprot thrift.TProtocol) (err error) { - if p.IsSetGetJobUpdateDiffResult_() { - if err := oprot.WriteFieldBegin("getJobUpdateDiffResult", thrift.STRUCT, 26); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 26:getJobUpdateDiffResult: ", p), err) - } - if err := p.GetJobUpdateDiffResult_.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.GetJobUpdateDiffResult_), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 26:getJobUpdateDiffResult: ", p), err) - } - } - return err -} - -func (p *Result_) writeField27(oprot thrift.TProtocol) (err error) { - if p.IsSetGetTierConfigResult_() { - if err := oprot.WriteFieldBegin("getTierConfigResult", thrift.STRUCT, 27); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 27:getTierConfigResult: ", p), err) - } - if err := p.GetTierConfigResult_.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.GetTierConfigResult_), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 27:getTierConfigResult: ", p), err) - } - } - return err -} - -func (p *Result_) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("Result_(%+v)", *p) -} - -// Attributes: -// - Message -type ResponseDetail struct { - Message string `thrift:"message,1" json:"message"` -} - -func NewResponseDetail() *ResponseDetail { - return &ResponseDetail{} -} - -func (p *ResponseDetail) GetMessage() string { - return p.Message -} -func (p *ResponseDetail) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ResponseDetail) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.Message = v - } - return nil -} - -func (p *ResponseDetail) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("ResponseDetail"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ResponseDetail) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("message", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:message: ", p), err) - } - if err := oprot.WriteString(string(p.Message)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.message (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:message: ", p), err) - } - return err -} - -func (p *ResponseDetail) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ResponseDetail(%+v)", *p) -} - -// Attributes: -// - ResponseCode -// - ServerInfo -// - Result_: Payload from the invoked RPC. -// - Details: Messages from the server relevant to the request, such as warnings or use of deprecated -// features. -type Response struct { - ResponseCode ResponseCode `thrift:"responseCode,1" json:"responseCode"` - // unused field # 2 - Result_ *Result_ `thrift:"result,3" json:"result,omitempty"` - // unused field # 4 - ServerInfo *ServerInfo `thrift:"serverInfo,5" json:"serverInfo"` - Details []*ResponseDetail `thrift:"details,6" json:"details"` -} - -func NewResponse() *Response { - return &Response{} -} - -func (p *Response) GetResponseCode() ResponseCode { - return p.ResponseCode -} - -var Response_ServerInfo_DEFAULT *ServerInfo - -func (p *Response) GetServerInfo() *ServerInfo { - if !p.IsSetServerInfo() { - return Response_ServerInfo_DEFAULT - } - return p.ServerInfo -} - -var Response_Result__DEFAULT *Result_ - -func (p *Response) GetResult_() *Result_ { - if !p.IsSetResult_() { - return Response_Result__DEFAULT - } - return p.Result_ -} - -func (p *Response) GetDetails() []*ResponseDetail { - return p.Details -} -func (p *Response) IsSetServerInfo() bool { - return p.ServerInfo != nil -} - -func (p *Response) IsSetResult_() bool { - return p.Result_ != nil -} - -func (p *Response) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - case 5: - if err := p.readField5(iprot); err != nil { - return err - } - case 3: - if err := p.readField3(iprot); err != nil { - return err - } - case 6: - if err := p.readField6(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *Response) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - temp := ResponseCode(v) - p.ResponseCode = temp - } - return nil -} - -func (p *Response) readField5(iprot thrift.TProtocol) error { - p.ServerInfo = &ServerInfo{} - if err := p.ServerInfo.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.ServerInfo), err) - } - return nil -} - -func (p *Response) readField3(iprot thrift.TProtocol) error { - p.Result_ = &Result_{} - if err := p.Result_.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Result_), err) - } - return nil -} - -func (p *Response) readField6(iprot thrift.TProtocol) error { - _, size, err := iprot.ReadListBegin() - if err != nil { - return thrift.PrependError("error reading list begin: ", err) - } - tSlice := make([]*ResponseDetail, 0, size) - p.Details = tSlice - for i := 0; i < size; i++ { - _elem51 := &ResponseDetail{} - if err := _elem51.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", _elem51), err) - } - p.Details = append(p.Details, _elem51) - } - if err := iprot.ReadListEnd(); err != nil { - return thrift.PrependError("error reading list end: ", err) - } - return nil -} - -func (p *Response) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("Response"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := p.writeField3(oprot); err != nil { - return err - } - if err := p.writeField5(oprot); err != nil { - return err - } - if err := p.writeField6(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *Response) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("responseCode", thrift.I32, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:responseCode: ", p), err) - } - if err := oprot.WriteI32(int32(p.ResponseCode)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.responseCode (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:responseCode: ", p), err) - } - return err -} - -func (p *Response) writeField3(oprot thrift.TProtocol) (err error) { - if p.IsSetResult_() { - if err := oprot.WriteFieldBegin("result", thrift.STRUCT, 3); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:result: ", p), err) - } - if err := p.Result_.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Result_), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 3:result: ", p), err) - } - } - return err -} - -func (p *Response) writeField5(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("serverInfo", thrift.STRUCT, 5); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:serverInfo: ", p), err) - } - if err := p.ServerInfo.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.ServerInfo), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 5:serverInfo: ", p), err) - } - return err -} - -func (p *Response) writeField6(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("details", thrift.LIST, 6); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 6:details: ", p), err) - } - if err := oprot.WriteListBegin(thrift.STRUCT, len(p.Details)); err != nil { - return thrift.PrependError("error writing list begin: ", err) - } - for _, v := range p.Details { - if err := v.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", v), err) - } - } - if err := oprot.WriteListEnd(); err != nil { - return thrift.PrependError("error writing list end: ", err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 6:details: ", p), err) - } - return err -} - -func (p *Response) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("Response(%+v)", *p) -} - -// Attributes: -// - BatchSize -type ExplicitReconciliationSettings struct { - BatchSize *int32 `thrift:"batchSize,1" json:"batchSize,omitempty"` -} - -func NewExplicitReconciliationSettings() *ExplicitReconciliationSettings { - return &ExplicitReconciliationSettings{} -} - -var ExplicitReconciliationSettings_BatchSize_DEFAULT int32 - -func (p *ExplicitReconciliationSettings) GetBatchSize() int32 { - if !p.IsSetBatchSize() { - return ExplicitReconciliationSettings_BatchSize_DEFAULT - } - return *p.BatchSize -} -func (p *ExplicitReconciliationSettings) IsSetBatchSize() bool { - return p.BatchSize != nil -} - -func (p *ExplicitReconciliationSettings) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { - break - } - switch fieldId { - case 1: - if err := p.readField1(iprot); err != nil { - return err - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ExplicitReconciliationSettings) readField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI32(); err != nil { - return thrift.PrependError("error reading field 1: ", err) - } else { - p.BatchSize = &v - } - return nil -} - -func (p *ExplicitReconciliationSettings) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("ExplicitReconciliationSettings"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) - } - if err := p.writeField1(oprot); err != nil { - return err - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) - } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) - } - return nil -} - -func (p *ExplicitReconciliationSettings) writeField1(oprot thrift.TProtocol) (err error) { - if p.IsSetBatchSize() { - if err := oprot.WriteFieldBegin("batchSize", thrift.I32, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:batchSize: ", p), err) - } - if err := oprot.WriteI32(int32(*p.BatchSize)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.batchSize (1) field write error: ", p), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:batchSize: ", p), err) - } - } - return err -} - -func (p *ExplicitReconciliationSettings) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ExplicitReconciliationSettings(%+v)", *p) -} diff --git a/vendor/github.com/paypal/gorealis/generateBindings.sh b/vendor/github.com/paypal/gorealis/generateBindings.sh index c876ef9..9ff0205 100755 --- a/vendor/github.com/paypal/gorealis/generateBindings.sh +++ b/vendor/github.com/paypal/gorealis/generateBindings.sh @@ -1,6 +1,6 @@ #! /bin/bash -THRIFT_VER=0.9.3 +THRIFT_VER=0.12.0 if [[ $(thrift -version | grep -e $THRIFT_VER -c) -ne 1 ]]; then echo "Warning: This wrapper has only been tested with version" $THRIFT_VER; diff --git a/vendor/github.com/paypal/gorealis/go.mod b/vendor/github.com/paypal/gorealis/go.mod new file mode 100644 index 0000000..c16fc63 --- /dev/null +++ b/vendor/github.com/paypal/gorealis/go.mod @@ -0,0 +1,10 @@ +module github.com/paypal/gorealis/v2 + +require ( + git.apache.org/thrift.git v0.0.0-20181016064013-5c1ecb67cde4 + github.com/davecgh/go-spew v1.1.0 + github.com/pkg/errors v0.0.0-20171216070316-e881fd58d78e + github.com/pmezard/go-difflib v1.0.0 + github.com/samuel/go-zookeeper v0.0.0-20171117190445-471cd4e61d7a + github.com/stretchr/testify v1.2.0 +) diff --git a/vendor/github.com/paypal/gorealis/go.sum b/vendor/github.com/paypal/gorealis/go.sum new file mode 100644 index 0000000..4a1be5a --- /dev/null +++ b/vendor/github.com/paypal/gorealis/go.sum @@ -0,0 +1,9 @@ +git.apache.org/thrift.git v0.0.0-20181016064013-5c1ecb67cde4 h1:crM1vBe07qSmh3hRVFXp4/TCfWaQkayD6ZOlNbQYtvw= +git.apache.org/thrift.git v0.0.0-20181016064013-5c1ecb67cde4/go.mod h1:fPE2ZNJGynbRyZ4dJvy6G277gSllfV2HJqblrnkyeyg= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pkg/errors v0.0.0-20171216070316-e881fd58d78e h1:+RHxT/gm0O3UF7nLJbdNzAmULvCFt4XfXHWzh3XI/zs= +github.com/pkg/errors v0.0.0-20171216070316-e881fd58d78e/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/samuel/go-zookeeper v0.0.0-20171117190445-471cd4e61d7a h1:EYL2xz/Zdo0hyqdZMXR4lmT2O11jDLTPCEqIe/FR6W4= +github.com/samuel/go-zookeeper v0.0.0-20171117190445-471cd4e61d7a/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= +github.com/stretchr/testify v1.2.0/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= diff --git a/vendor/github.com/paypal/gorealis/job.go b/vendor/github.com/paypal/gorealis/job.go index 0ff2aac..4798f37 100644 --- a/vendor/github.com/paypal/gorealis/job.go +++ b/vendor/github.com/paypal/gorealis/job.go @@ -15,180 +15,72 @@ package realis import ( - "strconv" - "github.com/paypal/gorealis/gen-go/apache/aurora" ) -type Job interface { - // Set Job Key environment. - Environment(env string) Job - Role(role string) Job - Name(name string) Job - CPU(cpus float64) Job - CronSchedule(cron string) Job - CronCollisionPolicy(policy aurora.CronCollisionPolicy) Job - Disk(disk int64) Job - RAM(ram int64) Job - ExecutorName(name string) Job - ExecutorData(data string) Job - AddPorts(num int) Job - AddLabel(key string, value string) Job - AddNamedPorts(names ...string) Job - AddLimitConstraint(name string, limit int32) Job - AddValueConstraint(name string, negated bool, values ...string) Job - - // From Aurora Docs: - // dedicated attribute. Aurora treats this specially, and only allows matching jobs - // to run on these machines, and will only schedule matching jobs on these machines. - // When a job is created, the scheduler requires that the $role component matches - // the role field in the job configuration, and will reject the job creation otherwise. - // A wildcard (*) may be used for the role portion of the dedicated attribute, which - // will allow any owner to elect for a job to run on the host(s) - AddDedicatedConstraint(role, name string) Job - AddURIs(extract bool, cache bool, values ...string) Job - JobKey() *aurora.JobKey - JobConfig() *aurora.JobConfiguration - TaskConfig() *aurora.TaskConfig - IsService(isService bool) Job - InstanceCount(instCount int32) Job - GetInstanceCount() int32 - MaxFailure(maxFail int32) Job - Container(container Container) Job -} - // Structure to collect all information pertaining to an Aurora job. type AuroraJob struct { jobConfig *aurora.JobConfiguration - resources map[string]*aurora.Resource - portCount int + task *AuroraTask } -// Create a Job object with everything initialized. -func NewJob() Job { - jobConfig := aurora.NewJobConfiguration() - taskConfig := aurora.NewTaskConfig() - jobKey := aurora.NewJobKey() +// Create a AuroraJob object with everything initialized. +func NewJob() *AuroraJob { - // Job Config - jobConfig.Key = jobKey - jobConfig.TaskConfig = taskConfig + jobKey := &aurora.JobKey{} - // Task Config - taskConfig.Job = jobKey - taskConfig.Container = aurora.NewContainer() - taskConfig.Container.Mesos = aurora.NewMesosContainer() - taskConfig.MesosFetcherUris = make(map[*aurora.MesosFetcherURI]bool) - taskConfig.Metadata = make(map[*aurora.Metadata]bool) - taskConfig.Constraints = make(map[*aurora.Constraint]bool) + // AuroraTask clientConfig + task := NewTask() + task.task.Job = jobKey - // Resources - numCpus := aurora.NewResource() - ramMb := aurora.NewResource() - diskMb := aurora.NewResource() - - resources := make(map[string]*aurora.Resource) - resources["cpu"] = numCpus - resources["ram"] = ramMb - resources["disk"] = diskMb - - taskConfig.Resources = make(map[*aurora.Resource]bool) - taskConfig.Resources[numCpus] = true - taskConfig.Resources[ramMb] = true - taskConfig.Resources[diskMb] = true - - numCpus.NumCpus = new(float64) - ramMb.RamMb = new(int64) - diskMb.DiskMb = new(int64) + // AuroraJob clientConfig + jobConfig := &aurora.JobConfiguration{ + Key: jobKey, + TaskConfig: task.TaskConfig(), + } return &AuroraJob{ jobConfig: jobConfig, - resources: resources, - portCount: 0, + task: task, } } -// Set Job Key environment. -func (j *AuroraJob) Environment(env string) Job { +// Set AuroraJob Key environment. Explicit changes to AuroraTask's job key are not needed +// because they share a pointer to the same JobKey. +func (j *AuroraJob) Environment(env string) *AuroraJob { j.jobConfig.Key.Environment = env return j } -// Set Job Key Role. -func (j *AuroraJob) Role(role string) Job { +// Set AuroraJob Key Role. +func (j *AuroraJob) Role(role string) *AuroraJob { j.jobConfig.Key.Role = role - //Will be deprecated + // Will be deprecated identity := &aurora.Identity{User: role} j.jobConfig.Owner = identity j.jobConfig.TaskConfig.Owner = identity return j } -// Set Job Key Name. -func (j *AuroraJob) Name(name string) Job { +// Set AuroraJob Key Name. +func (j *AuroraJob) Name(name string) *AuroraJob { j.jobConfig.Key.Name = name return j } -// Set name of the executor that will the task will be configured to. -func (j *AuroraJob) ExecutorName(name string) Job { - - if j.jobConfig.TaskConfig.ExecutorConfig == nil { - j.jobConfig.TaskConfig.ExecutorConfig = aurora.NewExecutorConfig() - } - - j.jobConfig.TaskConfig.ExecutorConfig.Name = name - return j -} - -// Will be included as part of entire task inside the scheduler that will be serialized. -func (j *AuroraJob) ExecutorData(data string) Job { - - if j.jobConfig.TaskConfig.ExecutorConfig == nil { - j.jobConfig.TaskConfig.ExecutorConfig = aurora.NewExecutorConfig() - } - - j.jobConfig.TaskConfig.ExecutorConfig.Data = data - return j -} - -func (j *AuroraJob) CPU(cpus float64) Job { - *j.resources["cpu"].NumCpus = cpus - - return j -} - -func (j *AuroraJob) RAM(ram int64) Job { - *j.resources["ram"].RamMb = ram - - return j -} - -func (j *AuroraJob) Disk(disk int64) Job { - *j.resources["disk"].DiskMb = disk - - return j -} - -// How many failures to tolerate before giving up. -func (j *AuroraJob) MaxFailure(maxFail int32) Job { - j.jobConfig.TaskConfig.MaxTaskFailures = maxFail - return j -} - // How many instances of the job to run -func (j *AuroraJob) InstanceCount(instCount int32) Job { +func (j *AuroraJob) InstanceCount(instCount int32) *AuroraJob { j.jobConfig.InstanceCount = instCount return j } -func (j *AuroraJob) CronSchedule(cron string) Job { +func (j *AuroraJob) CronSchedule(cron string) *AuroraJob { j.jobConfig.CronSchedule = &cron return j } -func (j *AuroraJob) CronCollisionPolicy(policy aurora.CronCollisionPolicy) Job { +func (j *AuroraJob) CronCollisionPolicy(policy aurora.CronCollisionPolicy) *AuroraJob { j.jobConfig.CronCollisionPolicy = policy return j } @@ -198,15 +90,9 @@ func (j *AuroraJob) GetInstanceCount() int32 { return j.jobConfig.InstanceCount } -// Restart the job's tasks if they fail -func (j *AuroraJob) IsService(isService bool) Job { - j.jobConfig.TaskConfig.IsService = isService - return j -} - // Get the current job configurations key to use for some realis calls. -func (j *AuroraJob) JobKey() *aurora.JobKey { - return j.jobConfig.Key +func (j *AuroraJob) JobKey() aurora.JobKey { + return *j.jobConfig.Key } // Get the current job configurations key to use for some realis calls. @@ -214,104 +100,90 @@ func (j *AuroraJob) JobConfig() *aurora.JobConfiguration { return j.jobConfig } +/* + AuroraTask specific API, see task.go for further documentation. + These functions are provided for the convenience of chaining API calls. +*/ + +func (j *AuroraJob) ExecutorName(name string) *AuroraJob { + j.task.ExecutorName(name) + return j +} + +func (j *AuroraJob) ExecutorData(data string) *AuroraJob { + j.task.ExecutorData(data) + return j +} + +func (j *AuroraJob) CPU(cpus float64) *AuroraJob { + j.task.CPU(cpus) + return j +} + +func (j *AuroraJob) RAM(ram int64) *AuroraJob { + j.task.RAM(ram) + return j +} + +func (j *AuroraJob) Disk(disk int64) *AuroraJob { + j.task.Disk(disk) + return j +} + +func (j *AuroraJob) Tier(tier string) *AuroraJob { + j.task.Tier(tier) + return j +} + +func (j *AuroraJob) MaxFailure(maxFail int32) *AuroraJob { + j.task.MaxFailure(maxFail) + return j +} + +func (j *AuroraJob) IsService(isService bool) *AuroraJob { + j.task.IsService(isService) + return j +} + func (j *AuroraJob) TaskConfig() *aurora.TaskConfig { - return j.jobConfig.TaskConfig + return j.task.TaskConfig() } -// Add a list of URIs with the same extract and cache configuration. Scheduler must have -// --enable_mesos_fetcher flag enabled. Currently there is no duplicate detection. -func (j *AuroraJob) AddURIs(extract bool, cache bool, values ...string) Job { - for _, value := range values { - j.jobConfig.TaskConfig.MesosFetcherUris[&aurora.MesosFetcherURI{ - Value: value, - Extract: &extract, - Cache: &cache, - }] = true - } +func (j *AuroraJob) AddURIs(extract bool, cache bool, values ...string) *AuroraJob { + j.task.AddURIs(extract, cache, values...) return j } -// Adds a Mesos label to the job. Note that Aurora will add the -// prefix "org.apache.aurora.metadata." to the beginning of each key. -func (j *AuroraJob) AddLabel(key string, value string) Job { - j.jobConfig.TaskConfig.Metadata[&aurora.Metadata{Key: key, Value: value}] = true +func (j *AuroraJob) AddLabel(key string, value string) *AuroraJob { + j.task.AddLabel(key, value) return j } -// Add a named port to the job configuration These are random ports as it's -// not currently possible to request specific ports using Aurora. -func (j *AuroraJob) AddNamedPorts(names ...string) Job { - j.portCount += len(names) - for _, name := range names { - j.jobConfig.TaskConfig.Resources[&aurora.Resource{NamedPort: &name}] = true - } - +func (j *AuroraJob) AddNamedPorts(names ...string) *AuroraJob { + j.task.AddNamedPorts(names...) return j } -// Adds a request for a number of ports to the job configuration. The names chosen for these ports -// will be org.apache.aurora.port.X, where X is the current port count for the job configuration -// starting at 0. These are random ports as it's not currently possible to request -// specific ports using Aurora. -func (j *AuroraJob) AddPorts(num int) Job { - start := j.portCount - j.portCount += num - for i := start; i < j.portCount; i++ { - portName := "org.apache.aurora.port." + strconv.Itoa(i) - j.jobConfig.TaskConfig.Resources[&aurora.Resource{NamedPort: &portName}] = true - } - +func (j *AuroraJob) AddPorts(num int) *AuroraJob { + j.task.AddPorts(num) + return j +} +func (j *AuroraJob) AddValueConstraint(name string, negated bool, values ...string) *AuroraJob { + j.task.AddValueConstraint(name, negated, values...) return j } -// From Aurora Docs: -// Add a Value constraint -// name - Mesos slave attribute that the constraint is matched against. -// If negated = true , treat this as a 'not' - to avoid specific values. -// Values - list of values we look for in attribute name -func (j *AuroraJob) AddValueConstraint(name string, negated bool, values ...string) Job { - constraintValues := make(map[string]bool) - for _, value := range values { - constraintValues[value] = true - } - j.jobConfig.TaskConfig.Constraints[&aurora.Constraint{ - Name: name, - Constraint: &aurora.TaskConstraint{ - Value: &aurora.ValueConstraint{ - Negated: negated, - Values: constraintValues, - }, - Limit: nil, - }, - }] = true - +func (j *AuroraJob) AddLimitConstraint(name string, limit int32) *AuroraJob { + j.task.AddLimitConstraint(name, limit) return j } -// From Aurora Docs: -// A constraint that specifies the maximum number of active tasks on a host with -// a matching attribute that may be scheduled simultaneously. -func (j *AuroraJob) AddLimitConstraint(name string, limit int32) Job { - j.jobConfig.TaskConfig.Constraints[&aurora.Constraint{ - Name: name, - Constraint: &aurora.TaskConstraint{ - Value: nil, - Limit: &aurora.LimitConstraint{Limit: limit}, - }, - }] = true - +func (j *AuroraJob) AddDedicatedConstraint(role, name string) *AuroraJob { + j.task.AddDedicatedConstraint(role, name) return j } -func (j *AuroraJob) AddDedicatedConstraint(role, name string) Job { - j.AddValueConstraint("dedicated", false, role+"/"+name) - - return j -} - -// Set a container to run for the job configuration to run. -func (j *AuroraJob) Container(container Container) Job { - j.jobConfig.TaskConfig.Container = container.Build() - +func (j *AuroraJob) Container(container Container) *AuroraJob { + j.task.Container(container) return j } diff --git a/vendor/github.com/paypal/gorealis/jobUpdate.go b/vendor/github.com/paypal/gorealis/jobUpdate.go new file mode 100644 index 0000000..bd25e79 --- /dev/null +++ b/vendor/github.com/paypal/gorealis/jobUpdate.go @@ -0,0 +1,232 @@ +/** + * 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. + */ + +package realis + +import ( + "time" + + "git.apache.org/thrift.git/lib/go/thrift" + "github.com/paypal/gorealis/gen-go/apache/aurora" +) + +// Structure to collect all information required to create job update +type JobUpdate struct { + task *AuroraTask + request *aurora.JobUpdateRequest +} + +// Create a default JobUpdate object with an empty task and no fields filled in. +func NewJobUpdate() *JobUpdate { + newTask := NewTask() + + req := aurora.JobUpdateRequest{} + req.TaskConfig = newTask.TaskConfig() + req.Settings = newUpdateSettings() + + return &JobUpdate{task: newTask, request: &req} +} + +func JobUpdateFromAuroraTask(task *AuroraTask) *JobUpdate { + newTask := task.Clone() + + req := aurora.JobUpdateRequest{} + req.TaskConfig = newTask.TaskConfig() + req.Settings = newUpdateSettings() + + return &JobUpdate{task: newTask, request: &req} +} + +func JobUpdateFromConfig(task *aurora.TaskConfig) *JobUpdate { + // Perform a deep copy to avoid unexpected behavior + newTask := TaskFromThrift(task) + + req := aurora.JobUpdateRequest{} + req.TaskConfig = newTask.TaskConfig() + req.Settings = newUpdateSettings() + + return &JobUpdate{task: newTask, request: &req} +} + +// Set instance count the job will have after the update. +func (j *JobUpdate) InstanceCount(inst int32) *JobUpdate { + j.request.InstanceCount = inst + return j +} + +// Max number of instances being updated at any given moment. +func (j *JobUpdate) BatchSize(size int32) *JobUpdate { + j.request.Settings.UpdateGroupSize = size + return j +} + +// Minimum number of seconds a shard must remain in RUNNING state before considered a success. +func (j *JobUpdate) WatchTime(timeout time.Duration) *JobUpdate { + j.request.Settings.MinWaitInInstanceRunningMs = int32(timeout.Seconds() * 1000) + return j +} + +// Wait for all instances in a group to be done before moving on. +func (j *JobUpdate) WaitForBatchCompletion(batchWait bool) *JobUpdate { + j.request.Settings.WaitForBatchCompletion = batchWait + return j +} + +// Max number of instance failures to tolerate before marking instance as FAILED. +func (j *JobUpdate) MaxPerInstanceFailures(inst int32) *JobUpdate { + j.request.Settings.MaxPerInstanceFailures = inst + return j +} + +// Max number of FAILED instances to tolerate before terminating the update. +func (j *JobUpdate) MaxFailedInstances(inst int32) *JobUpdate { + j.request.Settings.MaxFailedInstances = inst + return j +} + +// When False, prevents auto rollback of a failed update. +func (j *JobUpdate) RollbackOnFail(rollback bool) *JobUpdate { + j.request.Settings.RollbackOnFailure = rollback + return j +} + +// Sets the interval at which pulses should be received by the job update before timing out. +func (j *JobUpdate) PulseIntervalTimeout(timeout time.Duration) *JobUpdate { + j.request.Settings.BlockIfNoPulsesAfterMs = thrift.Int32Ptr(int32(timeout.Seconds() * 1000)) + return j +} + +func newUpdateSettings() *aurora.JobUpdateSettings { + + us := aurora.JobUpdateSettings{} + // Mirrors defaults set by Pystachio + us.UpdateOnlyTheseInstances = []*aurora.Range{} + us.UpdateGroupSize = 1 + us.WaitForBatchCompletion = false + us.MinWaitInInstanceRunningMs = 45000 + us.MaxPerInstanceFailures = 0 + us.MaxFailedInstances = 0 + us.RollbackOnFailure = true + + return &us +} + +/* + These methods are provided for user convenience in order to chain + calls for configuration. + API below here are wrappers around modifying an AuroraTask instance. + See task.go for further documentation. +*/ + +func (t *JobUpdate) Environment(env string) *JobUpdate { + t.task.Environment(env) + return t +} + +func (t *JobUpdate) Role(role string) *JobUpdate { + t.task.Role(role) + return t +} + +func (t *JobUpdate) Name(name string) *JobUpdate { + t.task.Name(name) + return t +} + +func (j *JobUpdate) ExecutorName(name string) *JobUpdate { + j.task.ExecutorName(name) + return j +} + +func (j *JobUpdate) ExecutorData(data string) *JobUpdate { + j.task.ExecutorData(data) + return j +} + +func (j *JobUpdate) CPU(cpus float64) *JobUpdate { + j.task.CPU(cpus) + return j +} + +func (j *JobUpdate) RAM(ram int64) *JobUpdate { + j.task.RAM(ram) + return j +} + +func (j *JobUpdate) Disk(disk int64) *JobUpdate { + j.task.Disk(disk) + return j +} + +func (j *JobUpdate) Tier(tier string) *JobUpdate { + j.task.Tier(tier) + return j +} + +func (j *JobUpdate) MaxFailure(maxFail int32) *JobUpdate { + j.task.MaxFailure(maxFail) + return j +} + +func (j *JobUpdate) IsService(isService bool) *JobUpdate { + j.task.IsService(isService) + return j +} + +func (j *JobUpdate) TaskConfig() *aurora.TaskConfig { + return j.task.TaskConfig() +} + +func (j *JobUpdate) AddURIs(extract bool, cache bool, values ...string) *JobUpdate { + j.task.AddURIs(extract, cache, values...) + return j +} + +func (j *JobUpdate) AddLabel(key string, value string) *JobUpdate { + j.task.AddLabel(key, value) + return j +} + +func (j *JobUpdate) AddNamedPorts(names ...string) *JobUpdate { + j.task.AddNamedPorts(names...) + return j +} + +func (j *JobUpdate) AddPorts(num int) *JobUpdate { + j.task.AddPorts(num) + return j +} +func (j *JobUpdate) AddValueConstraint(name string, negated bool, values ...string) *JobUpdate { + j.task.AddValueConstraint(name, negated, values...) + return j +} + +func (j *JobUpdate) AddLimitConstraint(name string, limit int32) *JobUpdate { + j.task.AddLimitConstraint(name, limit) + return j +} + +func (j *JobUpdate) AddDedicatedConstraint(role, name string) *JobUpdate { + j.task.AddDedicatedConstraint(role, name) + return j +} + +func (j *JobUpdate) Container(container Container) *JobUpdate { + j.task.Container(container) + return j +} + +func (j *JobUpdate) JobKey() aurora.JobKey { + return j.task.JobKey() +} diff --git a/vendor/github.com/paypal/gorealis/logger.go b/vendor/github.com/paypal/gorealis/logger.go index 05a3e85..54a901f 100644 --- a/vendor/github.com/paypal/gorealis/logger.go +++ b/vendor/github.com/paypal/gorealis/logger.go @@ -40,20 +40,20 @@ func (l *LevelLogger) EnableDebug(enable bool) { func (l LevelLogger) DebugPrintf(format string, a ...interface{}) { if l.debug { l.Print("[DEBUG] ") - l.Printf(format, a) + l.Printf(format, a...) } } func (l LevelLogger) DebugPrint(a ...interface{}) { if l.debug { l.Print("[DEBUG] ") - l.Print(a) + l.Print(a...) } } func (l LevelLogger) DebugPrintln(a ...interface{}) { if l.debug { l.Print("[DEBUG] ") - l.Println(a) + l.Println(a...) } } diff --git a/vendor/github.com/paypal/gorealis/monitors.go b/vendor/github.com/paypal/gorealis/monitors.go index ac5b3fa..0c024ad 100644 --- a/vendor/github.com/paypal/gorealis/monitors.go +++ b/vendor/github.com/paypal/gorealis/monitors.go @@ -19,87 +19,94 @@ import ( "time" "github.com/paypal/gorealis/gen-go/apache/aurora" - "github.com/paypal/gorealis/response" "github.com/pkg/errors" ) const ( UpdateFailed = "update failed" RolledBack = "update rolled back" - Timeout = "timeout" + Timedout = "timeout" ) -type Monitor struct { - Client Realis -} - // Polls the scheduler every certain amount of time to see if the update has succeeded -func (m *Monitor) JobUpdate(updateKey aurora.JobUpdateKey, interval int, timeout int) (bool, error) { +func (c *Client) JobUpdateMonitor(updateKey aurora.JobUpdateKey, interval, timeout time.Duration) (bool, error) { + if interval < 1*time.Second { + interval = interval * time.Second + } + + if timeout < 1*time.Second { + timeout = timeout * time.Second + } updateQ := aurora.JobUpdateQuery{ Key: &updateKey, Limit: 1, } - ticker := time.NewTicker(time.Second * time.Duration(interval)) + ticker := time.NewTicker(interval) defer ticker.Stop() - timer := time.NewTimer(time.Second * time.Duration(timeout)) + timer := time.NewTimer(timeout) defer timer.Stop() - var cliErr error - var respDetail *aurora.Response for { select { case <-ticker.C: - respDetail, cliErr = m.Client.JobUpdateDetails(updateQ) + updateDetail, cliErr := c.JobUpdateDetails(updateQ) if cliErr != nil { return false, cliErr } - updateDetail := response.JobUpdateDetails(respDetail) - if len(updateDetail) == 0 { - m.Client.RealisConfig().logger.Println("No update found") + c.RealisConfig().logger.Println("No update found") return false, errors.New("No update found for " + updateKey.String()) } + status := updateDetail[0].Update.Summary.State.Status - if _, ok := aurora.ACTIVE_JOB_UPDATE_STATES[status]; !ok { + // Convert Thrift Set to Golang map for quick lookup + if _, ok := ActiveJobUpdateStates[status]; !ok { // Rolled forward is the only state in which an update has been successfully updated // if we encounter an inactive state and it is not at rolled forward, update failed switch status { case aurora.JobUpdateStatus_ROLLED_FORWARD: - m.Client.RealisConfig().logger.Println("Update succeeded") + c.RealisConfig().logger.Println("Update succeeded") return true, nil case aurora.JobUpdateStatus_FAILED: - m.Client.RealisConfig().logger.Println("Update failed") + c.RealisConfig().logger.Println("Update failed") return false, errors.New(UpdateFailed) case aurora.JobUpdateStatus_ROLLED_BACK: - m.Client.RealisConfig().logger.Println("rolled back") + c.RealisConfig().logger.Println("rolled back") return false, errors.New(RolledBack) default: return false, nil } } case <-timer.C: - return false, errors.New(Timeout) + return false, errors.New(Timedout) } } } -// Monitor a Job until all instances enter one of the LIVE_STATES -func (m *Monitor) Instances(key *aurora.JobKey, instances int32, interval, timeout int) (bool, error) { - return m.ScheduleStatus(key, instances, aurora.LIVE_STATES, interval, timeout) +// Monitor a AuroraJob until all instances enter one of the LiveStates +func (c *Client) InstancesMonitor(key aurora.JobKey, instances int32, interval, timeout time.Duration) (bool, error) { + return c.ScheduleStatusMonitor(key, instances, aurora.LIVE_STATES, interval, timeout) } -// Monitor a Job until all instances enter a desired status. +// Monitor a AuroraJob until all instances enter a desired status. // Defaults sets of desired statuses provided by the thrift API include: -// ACTIVE_STATES, SLAVE_ASSIGNED_STATES, LIVE_STATES, and TERMINAL_STATES -func (m *Monitor) ScheduleStatus(key *aurora.JobKey, instanceCount int32, desiredStatuses map[aurora.ScheduleStatus]bool, interval, timeout int) (bool, error) { +// ActiveStates, SlaveAssignedStates, LiveStates, and TerminalStates +func (c *Client) ScheduleStatusMonitor(key aurora.JobKey, instanceCount int32, desiredStatuses []aurora.ScheduleStatus, interval, timeout time.Duration) (bool, error) { + if interval < 1*time.Second { + interval = interval * time.Second + } - ticker := time.NewTicker(time.Second * time.Duration(interval)) + if timeout < 1*time.Second { + timeout = timeout * time.Second + } + + ticker := time.NewTicker(interval) defer ticker.Stop() - timer := time.NewTimer(time.Second * time.Duration(timeout)) + timer := time.NewTimer(timeout) defer timer.Stop() for { @@ -107,7 +114,7 @@ func (m *Monitor) ScheduleStatus(key *aurora.JobKey, instanceCount int32, desire case <-ticker.C: // Query Aurora for the state of the job key ever interval - instCount, cliErr := m.Client.GetInstanceIds(key, desiredStatuses) + instCount, cliErr := c.GetInstanceIds(key, desiredStatuses) if cliErr != nil { return false, errors.Wrap(cliErr, "Unable to communicate with Aurora") } @@ -117,14 +124,21 @@ func (m *Monitor) ScheduleStatus(key *aurora.JobKey, instanceCount int32, desire case <-timer.C: // If the timer runs out, return a timeout error to user - return false, errors.New(Timeout) + return false, errors.New(Timedout) } } } // Monitor host status until all hosts match the status provided. Returns a map where the value is true if the host // is in one of the desired mode(s) or false if it is not as of the time when the monitor exited. -func (m *Monitor) HostMaintenance(hosts []string, modes []aurora.MaintenanceMode, interval, timeout int) (map[string]bool, error) { +func (c *Client) HostMaintenanceMonitor(hosts []string, modes []aurora.MaintenanceMode, interval, timeout time.Duration) (map[string]bool, error) { + if interval < 1*time.Second { + interval = interval * time.Second + } + + if timeout < 1*time.Second { + timeout = timeout * time.Second + } // Transform modes to monitor for into a set for easy lookup desiredMode := make(map[aurora.MaintenanceMode]struct{}) @@ -142,16 +156,16 @@ func (m *Monitor) HostMaintenance(hosts []string, modes []aurora.MaintenanceMode hostResult := make(map[string]bool) - ticker := time.NewTicker(time.Second * time.Duration(interval)) + ticker := time.NewTicker(interval) defer ticker.Stop() - timer := time.NewTimer(time.Second * time.Duration(timeout)) + timer := time.NewTimer(timeout) defer timer.Stop() for { select { case <-ticker.C: // Client call has multiple retries internally - _, result, err := m.Client.MaintenanceStatus(hosts...) + result, err := c.MaintenanceStatus(hosts...) if err != nil { // Error is either a payload error or a severe connection error for host := range remainingHosts { @@ -160,7 +174,7 @@ func (m *Monitor) HostMaintenance(hosts []string, modes []aurora.MaintenanceMode return hostResult, errors.Wrap(err, "client error in monitor") } - for status := range result.GetStatuses() { + for _, status := range result.GetStatuses() { if _, ok := desiredMode[status.GetMode()]; ok { hostResult[status.GetHost()] = true @@ -177,7 +191,7 @@ func (m *Monitor) HostMaintenance(hosts []string, modes []aurora.MaintenanceMode hostResult[host] = false } - return hostResult, errors.New(Timeout) + return hostResult, errors.New(Timedout) } } } diff --git a/vendor/github.com/paypal/gorealis/realis.go b/vendor/github.com/paypal/gorealis/realis.go index 8878b45..92ac5c1 100644 --- a/vendor/github.com/paypal/gorealis/realis.go +++ b/vendor/github.com/paypal/gorealis/realis.go @@ -26,6 +26,7 @@ import ( "net/http/cookiejar" "os" "path/filepath" + "sort" "strings" "sync" "time" @@ -36,71 +37,23 @@ import ( "github.com/pkg/errors" ) -const VERSION = "1.3.0" +const VERSION = "2.0.0" -// TODO(rdelvalle): Move documentation to interface in order to make godoc look better/more accessible -type Realis interface { - AbortJobUpdate(updateKey aurora.JobUpdateKey, message string) (*aurora.Response, error) - AddInstances(instKey aurora.InstanceKey, count int32) (*aurora.Response, error) - CreateJob(auroraJob Job) (*aurora.Response, error) - CreateService(auroraJob Job, settings *aurora.JobUpdateSettings) (*aurora.Response, *aurora.StartJobUpdateResult_, error) - DescheduleCronJob(key *aurora.JobKey) (*aurora.Response, error) - FetchTaskConfig(instKey aurora.InstanceKey) (*aurora.TaskConfig, error) - GetInstanceIds(key *aurora.JobKey, states map[aurora.ScheduleStatus]bool) (map[int32]bool, error) - GetJobUpdateSummaries(jobUpdateQuery *aurora.JobUpdateQuery) (*aurora.Response, error) - GetTaskStatus(query *aurora.TaskQuery) ([]*aurora.ScheduledTask, error) - GetTasksWithoutConfigs(query *aurora.TaskQuery) ([]*aurora.ScheduledTask, error) - GetJobs(role string) (*aurora.Response, *aurora.GetJobsResult_, error) - GetPendingReason(query *aurora.TaskQuery) (pendingReasons []*aurora.PendingReason, e error) - JobUpdateDetails(updateQuery aurora.JobUpdateQuery) (*aurora.Response, error) - KillJob(key *aurora.JobKey) (*aurora.Response, error) - KillInstances(key *aurora.JobKey, instances ...int32) (*aurora.Response, error) - RemoveInstances(key *aurora.JobKey, count int32) (*aurora.Response, error) - RestartInstances(key *aurora.JobKey, instances ...int32) (*aurora.Response, error) - RestartJob(key *aurora.JobKey) (*aurora.Response, error) - RollbackJobUpdate(key aurora.JobUpdateKey, message string) (*aurora.Response, error) - ScheduleCronJob(auroraJob Job) (*aurora.Response, error) - StartJobUpdate(updateJob *UpdateJob, message string) (*aurora.Response, error) - - PauseJobUpdate(key *aurora.JobUpdateKey, message string) (*aurora.Response, error) - ResumeJobUpdate(key *aurora.JobUpdateKey, message string) (*aurora.Response, error) - PulseJobUpdate(key *aurora.JobUpdateKey) (*aurora.Response, error) - StartCronJob(key *aurora.JobKey) (*aurora.Response, error) - // TODO: Remove this method and make it private to avoid race conditions - ReestablishConn() error - RealisConfig() *RealisConfig - Close() - - // Admin functions - DrainHosts(hosts ...string) (*aurora.Response, *aurora.DrainHostsResult_, error) - SLADrainHosts(policy *aurora.SlaPolicy, timeout int64, hosts ...string) (*aurora.DrainHostsResult_, error) - StartMaintenance(hosts ...string) (*aurora.Response, *aurora.StartMaintenanceResult_, error) - EndMaintenance(hosts ...string) (*aurora.Response, *aurora.EndMaintenanceResult_, error) - MaintenanceStatus(hosts ...string) (*aurora.Response, *aurora.MaintenanceStatusResult_, error) - SetQuota(role string, cpu *float64, ram *int64, disk *int64) (*aurora.Response, error) - GetQuota(role string) (*aurora.Response, error) - Snapshot() error - PerformBackup() error - // Force an Implicit reconciliation between Mesos and Aurora - ForceImplicitTaskReconciliation() error - // Force an Explicit reconciliation between Mesos and Aurora - ForceExplicitTaskReconciliation(batchSize *int32) error -} - -type realisClient struct { - config *RealisConfig +type Client struct { + config *clientConfig client *aurora.AuroraSchedulerManagerClient readonlyClient *aurora.ReadOnlySchedulerClient adminClient *aurora.AuroraAdminClient logger LevelLogger lock *sync.Mutex debug bool + transport thrift.TTransport } -type RealisConfig struct { +type clientConfig struct { username, password string url string - timeoutms int + timeout time.Duration binTransport, jsonTransport bool cluster *Cluster backoff Backoff @@ -108,8 +61,8 @@ type RealisConfig struct { protoFactory thrift.TProtocolFactory logger *LevelLogger InsecureSkipVerify bool - certspath string - clientkey, clientcert string + certsPath string + clientKey, clientCert string options []ClientOption debug bool zkOptions []ZKOpt @@ -122,30 +75,30 @@ var defaultBackoff = Backoff{ Jitter: 0.1, } -type ClientOption func(*RealisConfig) +type ClientOption func(*clientConfig) -//Config sets for options in RealisConfig. +// clientConfig sets for options in clientConfig. func BasicAuth(username, password string) ClientOption { - return func(config *RealisConfig) { + return func(config *clientConfig) { config.username = username config.password = password } } func SchedulerUrl(url string) ClientOption { - return func(config *RealisConfig) { + return func(config *clientConfig) { config.url = url } } -func TimeoutMS(timeout int) ClientOption { - return func(config *RealisConfig) { - config.timeoutms = timeout +func Timeout(timeout time.Duration) ClientOption { + return func(config *clientConfig) { + config.timeout = timeout } } func ZKCluster(cluster *Cluster) ClientOption { - return func(config *RealisConfig) { + return func(config *clientConfig) { config.cluster = cluster } } @@ -154,7 +107,7 @@ func ZKUrl(url string) ClientOption { opts := []ZKOpt{ZKEndpoints(strings.Split(url, ",")...), ZKPath("/aurora/scheduler")} - return func(config *RealisConfig) { + return func(config *clientConfig) { if config.zkOptions == nil { config.zkOptions = opts } else { @@ -163,82 +116,76 @@ func ZKUrl(url string) ClientOption { } } -func Retries(backoff Backoff) ClientOption { - return func(config *RealisConfig) { - config.backoff = backoff - } -} - func ThriftJSON() ClientOption { - return func(config *RealisConfig) { + return func(config *clientConfig) { config.jsonTransport = true } } func ThriftBinary() ClientOption { - return func(config *RealisConfig) { + return func(config *clientConfig) { config.binTransport = true } } func BackOff(b Backoff) ClientOption { - return func(config *RealisConfig) { + return func(config *clientConfig) { config.backoff = b } } func InsecureSkipVerify(InsecureSkipVerify bool) ClientOption { - return func(config *RealisConfig) { + return func(config *clientConfig) { config.InsecureSkipVerify = InsecureSkipVerify } } -func Certspath(certspath string) ClientOption { - return func(config *RealisConfig) { - config.certspath = certspath +func CertsPath(certspath string) ClientOption { + return func(config *clientConfig) { + config.certsPath = certspath } } func ClientCerts(clientKey, clientCert string) ClientOption { - return func(config *RealisConfig) { - config.clientkey, config.clientcert = clientKey, clientCert + return func(config *clientConfig) { + config.clientKey, config.clientCert = clientKey, clientCert } } // Use this option if you'd like to override default settings for connecting to Zookeeper. // See zk.go for what is possible to set as an option. func ZookeeperOptions(opts ...ZKOpt) ClientOption { - return func(config *RealisConfig) { + return func(config *clientConfig) { config.zkOptions = opts } } // Using the word set to avoid name collision with Interface. func SetLogger(l Logger) ClientOption { - return func(config *RealisConfig) { + return func(config *clientConfig) { config.logger = &LevelLogger{l, false} } } // Enable debug statements. func Debug() ClientOption { - return func(config *RealisConfig) { + return func(config *clientConfig) { config.debug = true } } -func newTJSONTransport(url string, timeout int, config *RealisConfig) (thrift.TTransport, error) { +func newTJSONTransport(url string, timeout time.Duration, config *clientConfig) (thrift.TTransport, error) { trans, err := defaultTTransport(url, timeout, config) if err != nil { return nil, errors.Wrap(err, "Error creating realis") } httpTrans := (trans).(*thrift.THttpClient) httpTrans.SetHeader("Content-Type", "application/x-thrift") - httpTrans.SetHeader("User-Agent", "GoRealis v"+VERSION) + httpTrans.SetHeader("User-Agent", "gorealis v"+VERSION) return trans, err } -func newTBinTransport(url string, timeout int, config *RealisConfig) (thrift.TTransport, error) { +func newTBinTransport(url string, timeout time.Duration, config *clientConfig) (thrift.TTransport, error) { trans, err := defaultTTransport(url, timeout, config) if err != nil { return nil, errors.Wrap(err, "Error creating realis") @@ -247,20 +194,20 @@ func newTBinTransport(url string, timeout int, config *RealisConfig) (thrift.TTr httpTrans.DelHeader("Content-Type") // Workaround for using thrift HttpPostClient httpTrans.SetHeader("Accept", "application/vnd.apache.thrift.binary") httpTrans.SetHeader("Content-Type", "application/vnd.apache.thrift.binary") - httpTrans.SetHeader("User-Agent", "GoRealis v"+VERSION) + httpTrans.SetHeader("User-Agent", "gorealis v"+VERSION) return trans, err } -// This client implementation of the realis interface uses a retry mechanism for all Thrift Calls. +// This client implementation uses a retry mechanism for all Thrift Calls. // It will retry all calls which result in a temporary failure as well as calls that fail due to an EOF // being returned by the http client. Most permanent failures are now being caught by the thriftCallWithRetries // function and not being retried but there may be corner cases not yet handled. -func NewRealisClient(options ...ClientOption) (Realis, error) { - config := &RealisConfig{} +func NewClient(options ...ClientOption) (*Client, error) { + config := &clientConfig{} // Default configs - config.timeoutms = 10000 + config.timeout = 10 * time.Second config.backoff = defaultBackoff config.logger = &LevelLogger{log.New(os.Stdout, "realis: ", log.Ltime|log.Ldate|log.LUTC), false} @@ -287,9 +234,9 @@ func NewRealisClient(options ...ClientOption) (Realis, error) { // Note, by this point, a LevelLogger should have been created. config.logger.EnableDebug(config.debug) - config.logger.DebugPrintln("Number of options applied to config: ", len(options)) + config.logger.DebugPrintln("Number of options applied to clientConfig: ", len(options)) - //Set default Transport to JSON if needed. + // Set default Transport to JSON if needed. if !config.jsonTransport && !config.binTransport { config.jsonTransport = true } @@ -320,8 +267,13 @@ func NewRealisClient(options ...ClientOption) (Realis, error) { return nil, errors.New("Incomplete Options -- url, cluster.json, or Zookeeper address required") } + url, err = validateAndPopulateAuroraURL(url) + if err != nil { + return nil, errors.Wrap(err, "unable to create realis object, invalid url") + } + if config.jsonTransport { - trans, err := newTJSONTransport(url, config.timeoutms, config) + trans, err := newTJSONTransport(url, config.timeout, config) if err != nil { return nil, NewTemporaryError(errors.Wrap(err, "Error creating realis")) } @@ -329,7 +281,7 @@ func NewRealisClient(options ...ClientOption) (Realis, error) { config.protoFactory = thrift.NewTJSONProtocolFactory() } else if config.binTransport { - trans, err := newTBinTransport(url, config.timeoutms, config) + trans, err := newTBinTransport(url, config.timeout, config) if err != nil { return nil, NewTemporaryError(errors.Wrap(err, "Error creating realis")) } @@ -337,7 +289,7 @@ func NewRealisClient(options ...ClientOption) (Realis, error) { config.protoFactory = thrift.NewTBinaryProtocolFactoryDefault() } - config.logger.Printf("gorealis config url: %+v\n", url) + config.logger.Printf("gorealis clientConfig url: %+v\n", url) // Adding Basic Authentication. if config.username != "" && config.password != "" { @@ -345,35 +297,26 @@ func NewRealisClient(options ...ClientOption) (Realis, error) { httpTrans.SetHeader("Authorization", "Basic "+basicAuth(config.username, config.password)) } - return &realisClient{ + return &Client{ config: config, client: aurora.NewAuroraSchedulerManagerClientFactory(config.transport, config.protoFactory), readonlyClient: aurora.NewReadOnlySchedulerClientFactory(config.transport, config.protoFactory), adminClient: aurora.NewAuroraAdminClientFactory(config.transport, config.protoFactory), logger: LevelLogger{config.logger, config.debug}, - lock: &sync.Mutex{}}, nil + lock: &sync.Mutex{}, + transport: config.transport, + }, nil } -func GetDefaultClusterFromZKUrl(zkurl string) *Cluster { - return &Cluster{ - Name: "defaultCluster", - AuthMechanism: "UNAUTHENTICATED", - ZK: zkurl, - SchedZKPath: "/aurora/scheduler", - AgentRunDir: "latest", - AgentRoot: "/var/lib/mesos", - } -} - -func GetCerts(certpath string) (*x509.CertPool, error) { +func GetCerts(certPath string) (*x509.CertPool, error) { globalRootCAs := x509.NewCertPool() - caFiles, err := ioutil.ReadDir(certpath) + caFiles, err := ioutil.ReadDir(certPath) if err != nil { return nil, err } for _, cert := range caFiles { - capathfile := filepath.Join(certpath, cert.Name()) - caCert, err := ioutil.ReadFile(capathfile) + caPathFile := filepath.Join(certPath, cert.Name()) + caCert, err := ioutil.ReadFile(caPathFile) if err != nil { return nil, err } @@ -383,35 +326,37 @@ func GetCerts(certpath string) (*x509.CertPool, error) { } // Creates a default Thrift Transport object for communications in gorealis using an HTTP Post Client -func defaultTTransport(urlstr string, timeoutms int, config *RealisConfig) (thrift.TTransport, error) { +func defaultTTransport(url string, timeout time.Duration, config *clientConfig) (thrift.TTransport, error) { + var transport http.Transport + jar, err := cookiejar.New(nil) if err != nil { - return &thrift.THttpClient{}, errors.Wrap(err, "Error creating Cookie Jar") + return nil, errors.Wrap(err, "Error creating Cookie Jar") } - var transport http.Transport + if config != nil { tlsConfig := &tls.Config{} if config.InsecureSkipVerify { tlsConfig.InsecureSkipVerify = true } - if config.certspath != "" { - rootCAs, err := GetCerts(config.certspath) + if config.certsPath != "" { + rootCAs, err := GetCerts(config.certsPath) if err != nil { - config.logger.Println("error occured couldn't fetch certs") + config.logger.Println("error occurred couldn't fetch certs") return nil, err } tlsConfig.RootCAs = rootCAs } - if config.clientkey != "" && config.clientcert == "" { + if config.clientKey != "" && config.clientCert == "" { return nil, fmt.Errorf("have to provide both client key,cert. Only client key provided ") } - if config.clientkey == "" && config.clientcert != "" { + if config.clientKey == "" && config.clientCert != "" { return nil, fmt.Errorf("have to provide both client key,cert. Only client cert provided ") } - if config.clientkey != "" && config.clientcert != "" { - cert, err := tls.LoadX509KeyPair(config.clientcert, config.clientkey) + if config.clientKey != "" && config.clientCert != "" { + cert, err := tls.LoadX509KeyPair(config.clientCert, config.clientKey) if err != nil { - config.logger.Println("error occured loading client certs and keys") + config.logger.Println("error occurred loading client certs and keys") return nil, err } tlsConfig.Certificates = []tls.Certificate{cert} @@ -419,15 +364,15 @@ func defaultTTransport(urlstr string, timeoutms int, config *RealisConfig) (thri transport.TLSClientConfig = tlsConfig } - trans, err := thrift.NewTHttpPostClientWithOptions(urlstr+"/api", - thrift.THttpClientOptions{Client: &http.Client{Timeout: time.Millisecond * time.Duration(timeoutms), Transport: &transport, Jar: jar}}) + trans, err := thrift.NewTHttpClientWithOptions(url, + thrift.THttpClientOptions{Client: &http.Client{Timeout: timeout, Transport: &transport, Jar: jar}}) if err != nil { - return &thrift.THttpClient{}, errors.Wrap(err, "Error creating transport") + return nil, errors.Wrap(err, "Error creating transport") } if err := trans.Open(); err != nil { - return &thrift.THttpClient{}, errors.Wrapf(err, "Error opening connection to %s", urlstr) + return nil, errors.Wrapf(err, "Error opening connection to %s", url) } return trans, nil @@ -435,29 +380,29 @@ func defaultTTransport(urlstr string, timeoutms int, config *RealisConfig) (thri // Create a default configuration of the transport layer, requires a URL to test connection with. // Uses HTTP Post as transport layer and Thrift JSON as the wire protocol by default. -func newDefaultConfig(url string, timeoutms int, config *RealisConfig) (*RealisConfig, error) { - return newTJSONConfig(url, timeoutms, config) +func newDefaultConfig(url string, timeout time.Duration, config *clientConfig) (*clientConfig, error) { + return newTJSONConfig(url, timeout, config) } -// Creates a realis config object using HTTP Post and Thrift JSON protocol to communicate with Aurora. -func newTJSONConfig(url string, timeoutms int, config *RealisConfig) (*RealisConfig, error) { - trans, err := defaultTTransport(url, timeoutms, config) +// Creates a realis clientConfig object using HTTP Post and Thrift JSON protocol to communicate with Aurora. +func newTJSONConfig(url string, timeout time.Duration, config *clientConfig) (*clientConfig, error) { + trans, err := defaultTTransport(url, timeout, config) if err != nil { - return &RealisConfig{}, errors.Wrap(err, "Error creating realis config") + return nil, errors.Wrap(err, "Error creating realis clientConfig") } httpTrans := (trans).(*thrift.THttpClient) httpTrans.SetHeader("Content-Type", "application/x-thrift") httpTrans.SetHeader("User-Agent", "gorealis v"+VERSION) - return &RealisConfig{transport: trans, protoFactory: thrift.NewTJSONProtocolFactory()}, nil + return &clientConfig{transport: trans, protoFactory: thrift.NewTJSONProtocolFactory()}, nil } -// Creates a realis config config using HTTP Post and Thrift Binary protocol to communicate with Aurora. -func newTBinaryConfig(url string, timeoutms int, config *RealisConfig) (*RealisConfig, error) { - trans, err := defaultTTransport(url, timeoutms, config) +// Creates a realis clientConfig clientConfig using HTTP Post and Thrift Binary protocol to communicate with Aurora. +func newTBinaryConfig(url string, timeout time.Duration, config *clientConfig) (*clientConfig, error) { + trans, err := defaultTTransport(url, timeout, config) if err != nil { - return &RealisConfig{}, errors.Wrap(err, "Error creating realis config") + return nil, errors.Wrap(err, "Error creating realis clientConfig") } httpTrans := (trans).(*thrift.THttpClient) @@ -467,7 +412,7 @@ func newTBinaryConfig(url string, timeoutms int, config *RealisConfig) (*RealisC httpTrans.SetHeader("Content-Type", "application/vnd.apache.thrift.binary") httpTrans.SetHeader("User-Agent", "gorealis v"+VERSION) - return &RealisConfig{transport: trans, protoFactory: thrift.NewTBinaryProtocolFactoryDefault()}, nil + return &clientConfig{transport: trans, protoFactory: thrift.NewTBinaryProtocolFactoryDefault()}, nil } @@ -476,16 +421,16 @@ func basicAuth(username, password string) string { return base64.StdEncoding.EncodeToString([]byte(auth)) } -func (r *realisClient) ReestablishConn() error { +func (c *Client) ReestablishConn() error { // Close existing connection - r.logger.Println("Re-establishing Connection to Aurora") - r.Close() + c.logger.Println("Re-establishing Connection to Aurora") + c.Close() - r.lock.Lock() - defer r.lock.Unlock() + c.lock.Lock() + defer c.lock.Unlock() // Recreate connection from scratch using original options - newRealis, err := NewRealisClient(r.config.options...) + newRealis, err := NewClient(c.config.options...) if err != nil { // This could be a temporary network hiccup return NewTemporaryError(err) @@ -493,30 +438,26 @@ func (r *realisClient) ReestablishConn() error { // If we are able to successfully re-connect, make receiver // point to newly established connections. - if newClient, ok := newRealis.(*realisClient); ok { - r.config = newClient.config - r.client = newClient.client - r.readonlyClient = newClient.readonlyClient - r.adminClient = newClient.adminClient - r.logger = newClient.logger - } + c.config = newRealis.config + c.client = newRealis.client + c.readonlyClient = newRealis.readonlyClient + c.adminClient = newRealis.adminClient + c.logger = newRealis.logger return nil } // Releases resources associated with the realis client. -func (r *realisClient) Close() { +func (c *Client) Close() { - r.lock.Lock() - defer r.lock.Unlock() + c.lock.Lock() + defer c.lock.Unlock() - r.client.Transport.Close() - r.readonlyClient.Transport.Close() - r.adminClient.Transport.Close() + c.transport.Close() } // Uses predefined set of states to retrieve a set of active jobs in Apache Aurora. -func (r *realisClient) GetInstanceIds(key *aurora.JobKey, states map[aurora.ScheduleStatus]bool) (map[int32]bool, error) { +func (c *Client) GetInstanceIds(key aurora.JobKey, states []aurora.ScheduleStatus) ([]int32, error) { taskQ := &aurora.TaskQuery{ Role: &key.Role, Environment: &key.Environment, @@ -524,10 +465,10 @@ func (r *realisClient) GetInstanceIds(key *aurora.JobKey, states map[aurora.Sche Statuses: states, } - r.logger.DebugPrintf("GetTasksWithoutConfigs Thrift Payload: %+v\n", taskQ) + c.logger.DebugPrintf("GetTasksWithoutConfigs Thrift Payload: %+v\n", taskQ) - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.client.GetTasksWithoutConfigs(taskQ) + resp, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.client.GetTasksWithoutConfigs(nil, taskQ) }) // If we encountered an error we couldn't recover from by retrying, return an error to the user @@ -537,336 +478,341 @@ func (r *realisClient) GetInstanceIds(key *aurora.JobKey, states map[aurora.Sche // Construct instance id map to stay in line with thrift's representation of sets tasks := response.ScheduleStatusResult(resp).GetTasks() - jobInstanceIds := make(map[int32]bool) + jobInstanceIds := make([]int32, 0, len(tasks)) for _, task := range tasks { - jobInstanceIds[task.GetAssignedTask().GetInstanceId()] = true + jobInstanceIds = append(jobInstanceIds, task.GetAssignedTask().GetInstanceId()) } return jobInstanceIds, nil } -func (r *realisClient) GetJobUpdateSummaries(jobUpdateQuery *aurora.JobUpdateQuery) (*aurora.Response, error) { - r.logger.DebugPrintf("GetJobUpdateSummaries Thrift Payload: %+v\n", jobUpdateQuery) +func (c *Client) GetJobUpdateSummaries(jobUpdateQuery *aurora.JobUpdateQuery) (*aurora.GetJobUpdateSummariesResult_, error) { + c.logger.DebugPrintf("GetJobUpdateSummaries Thrift Payload: %+v\n", jobUpdateQuery) - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.readonlyClient.GetJobUpdateSummaries(jobUpdateQuery) + resp, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.readonlyClient.GetJobUpdateSummaries(nil, jobUpdateQuery) }) if retryErr != nil { return nil, errors.Wrap(retryErr, "Error getting job update summaries from Aurora Scheduler") } - return resp, nil + return resp.GetResult_().GetGetJobUpdateSummariesResult_(), nil } -func (r *realisClient) GetJobs(role string) (*aurora.Response, *aurora.GetJobsResult_, error) { +func (c *Client) GetJobs(role string) (*aurora.GetJobsResult_, error) { var result *aurora.GetJobsResult_ - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.readonlyClient.GetJobs(role) + resp, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.readonlyClient.GetJobs(nil, role) }) if retryErr != nil { - return nil, result, errors.Wrap(retryErr, "Error getting Jobs from Aurora Scheduler") + return result, errors.Wrap(retryErr, "Error getting Jobs from Aurora Scheduler") } if resp.GetResult_() != nil { result = resp.GetResult_().GetJobsResult_ } - return resp, result, nil + return result, nil } -// Kill specific instances of a job. -func (r *realisClient) KillInstances(key *aurora.JobKey, instances ...int32) (*aurora.Response, error) { - r.logger.DebugPrintf("KillTasks Thrift Payload: %+v %v\n", key, instances) +// Kill specific instances of a job. Returns true, nil if a task was actually killed as a result of this API call. +// Returns false, nil if no tasks were killed as a result of this call but there was no error making the call. +func (c *Client) KillInstances(key aurora.JobKey, instances ...int32) (bool, error) { + c.logger.DebugPrintf("KillTasks Thrift Payload: %+v %v\n", key, instances) - instanceIds := make(map[int32]bool) - - for _, instId := range instances { - instanceIds[instId] = true - } - - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.client.KillTasks(key, instanceIds, "") + resp, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.client.KillTasks(nil, &key, instances, "") }) if retryErr != nil { - return nil, errors.Wrap(retryErr, "Error sending Kill command to Aurora Scheduler") + return false, errors.Wrap(retryErr, "Error sending Kill command to Aurora Scheduler") } - return resp, nil + + if len(resp.GetDetails()) > 0 { + c.logger.Println("KillTasks was called but no tasks killed as a result.") + return false, nil + } else { + return true, nil + } + } -func (r *realisClient) RealisConfig() *RealisConfig { - return r.config +func (c *Client) RealisConfig() *clientConfig { + return c.config } // Sends a kill message to the scheduler for all active tasks under a job. -func (r *realisClient) KillJob(key *aurora.JobKey) (*aurora.Response, error) { +func (c *Client) KillJob(key aurora.JobKey) error { - r.logger.DebugPrintf("KillTasks Thrift Payload: %+v\n", key) + c.logger.DebugPrintf("KillTasks Thrift Payload: %+v\n", key) - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { + _, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { // Giving the KillTasks thrift call an empty set tells the Aurora scheduler to kill all active shards - return r.client.KillTasks(key, nil, "") + return c.client.KillTasks(nil, &key, nil, "") }) if retryErr != nil { - return nil, errors.Wrap(retryErr, "Error sending Kill command to Aurora Scheduler") + return errors.Wrap(retryErr, "Error sending Kill command to Aurora Scheduler") } - return resp, nil + return nil } // Sends a create job message to the scheduler with a specific job configuration. // Although this API is able to create service jobs, it is better to use CreateService instead // as that API uses the update thrift call which has a few extra features available. // Use this API to create ad-hoc jobs. -func (r *realisClient) CreateJob(auroraJob Job) (*aurora.Response, error) { +func (c *Client) CreateJob(auroraJob *AuroraJob) error { - r.logger.DebugPrintf("CreateJob Thrift Payload: %+v\n", auroraJob.JobConfig()) + c.logger.DebugPrintf("CreateJob Thrift Payload: %+v\n", auroraJob.JobConfig()) - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.client.CreateJob(auroraJob.JobConfig()) + _, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.client.CreateJob(nil, auroraJob.JobConfig()) }) if retryErr != nil { - return resp, errors.Wrap(retryErr, "Error sending Create command to Aurora Scheduler") + return errors.Wrap(retryErr, "Error sending Create command to Aurora Scheduler") } - return resp, nil + + return nil } // This API uses an update thrift call to create the services giving a few more robust features. -func (r *realisClient) CreateService(auroraJob Job, settings *aurora.JobUpdateSettings) (*aurora.Response, *aurora.StartJobUpdateResult_, error) { - // Create a new job update object and ship it to the StartJobUpdate api - update := NewUpdateJob(auroraJob.TaskConfig(), settings) - update.InstanceCount(auroraJob.GetInstanceCount()) - - resp, err := r.StartJobUpdate(update, "") +func (c *Client) CreateService(update *JobUpdate) (*aurora.StartJobUpdateResult_, error) { + updateResult, err := c.StartJobUpdate(update, "") if err != nil { - return resp, nil, errors.Wrap(err, "unable to create service") + return nil, errors.Wrap(err, "unable to create service") } - if resp.GetResult_() != nil { - return resp, resp.GetResult_().GetStartJobUpdateResult_(), nil + if updateResult != nil { + return updateResult, nil } - return nil, nil, errors.New("results object is nil") + return nil, errors.New("results object is nil") } -func (r *realisClient) ScheduleCronJob(auroraJob Job) (*aurora.Response, error) { - r.logger.DebugPrintf("ScheduleCronJob Thrift Payload: %+v\n", auroraJob.JobConfig()) +func (c *Client) ScheduleCronJob(auroraJob *AuroraJob) error { + c.logger.DebugPrintf("ScheduleCronJob Thrift Payload: %+v\n", auroraJob.JobConfig()) - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.client.ScheduleCronJob(auroraJob.JobConfig()) + _, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.client.ScheduleCronJob(nil, auroraJob.JobConfig()) }) if retryErr != nil { - return nil, errors.Wrap(retryErr, "Error sending Cron Job Schedule message to Aurora Scheduler") + return errors.Wrap(retryErr, "Error sending Cron AuroraJob Schedule message to Aurora Scheduler") } - return resp, nil + return nil } -func (r *realisClient) DescheduleCronJob(key *aurora.JobKey) (*aurora.Response, error) { +func (c *Client) DescheduleCronJob(key aurora.JobKey) error { - r.logger.DebugPrintf("DescheduleCronJob Thrift Payload: %+v\n", key) + c.logger.DebugPrintf("DescheduleCronJob Thrift Payload: %+v\n", key) - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.client.DescheduleCronJob(key) + _, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.client.DescheduleCronJob(nil, &key) }) if retryErr != nil { - return nil, errors.Wrap(retryErr, "Error sending Cron Job De-schedule message to Aurora Scheduler") + return errors.Wrap(retryErr, "Error sending Cron AuroraJob De-schedule message to Aurora Scheduler") } - return resp, nil + return nil } -func (r *realisClient) StartCronJob(key *aurora.JobKey) (*aurora.Response, error) { +func (c *Client) StartCronJob(key aurora.JobKey) error { - r.logger.DebugPrintf("StartCronJob Thrift Payload: %+v\n", key) + c.logger.DebugPrintf("StartCronJob Thrift Payload: %+v\n", key) - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.client.StartCronJob(key) + _, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.client.StartCronJob(nil, &key) }) if retryErr != nil { - return nil, errors.Wrap(retryErr, "Error sending Start Cron Job message to Aurora Scheduler") + return errors.Wrap(retryErr, "Error sending Start Cron AuroraJob message to Aurora Scheduler") } - return resp, nil + return nil } // Restarts specific instances specified -func (r *realisClient) RestartInstances(key *aurora.JobKey, instances ...int32) (*aurora.Response, error) { - r.logger.DebugPrintf("RestartShards Thrift Payload: %+v %v\n", key, instances) +func (c *Client) RestartInstances(key aurora.JobKey, instances ...int32) error { + c.logger.DebugPrintf("RestartShards Thrift Payload: %+v %v\n", key, instances) - instanceIds := make(map[int32]bool) - - for _, instId := range instances { - instanceIds[instId] = true - } - - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.client.RestartShards(key, instanceIds) + _, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.client.RestartShards(nil, &key, instances) }) if retryErr != nil { - return nil, errors.Wrap(retryErr, "Error sending Restart command to Aurora Scheduler") + return errors.Wrap(retryErr, "Error sending Restart command to Aurora Scheduler") } - return resp, nil + return nil } // Restarts all active tasks under a job configuration. -func (r *realisClient) RestartJob(key *aurora.JobKey) (*aurora.Response, error) { +func (c *Client) RestartJob(key aurora.JobKey) error { - instanceIds, err1 := r.GetInstanceIds(key, aurora.ACTIVE_STATES) + instanceIds, err1 := c.GetInstanceIds(key, aurora.ACTIVE_STATES) if err1 != nil { - return nil, errors.Wrap(err1, "Could not retrieve relevant task instance IDs") + return errors.Wrap(err1, "Could not retrieve relevant task instance IDs") } - r.logger.DebugPrintf("RestartShards Thrift Payload: %+v %v\n", key, instanceIds) + c.logger.DebugPrintf("RestartShards Thrift Payload: %+v %v\n", key, instanceIds) if len(instanceIds) > 0 { - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.client.RestartShards(key, instanceIds) + _, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.client.RestartShards(nil, &key, instanceIds) }) if retryErr != nil { - return nil, errors.Wrap(retryErr, "Error sending Restart command to Aurora Scheduler") + return errors.Wrap(retryErr, "Error sending Restart command to Aurora Scheduler") } - return resp, nil + return nil } else { - return nil, errors.New("No tasks in the Active state") + return errors.New("No tasks in the Active state") } } // Update all tasks under a job configuration. Currently gorealis doesn't support for canary deployments. -func (r *realisClient) StartJobUpdate(updateJob *UpdateJob, message string) (*aurora.Response, error) { +func (c *Client) StartJobUpdate(updateJob *JobUpdate, message string) (*aurora.StartJobUpdateResult_, error) { - r.logger.DebugPrintf("StartJobUpdate Thrift Payload: %+v %v\n", updateJob, message) + c.logger.DebugPrintf("StartJobUpdate Thrift Payload: %+v %v\n", updateJob, message) - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.client.StartJobUpdate(updateJob.req, message) + resp, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.client.StartJobUpdate(nil, updateJob.request, message) }) if retryErr != nil { - return resp, errors.Wrap(retryErr, "Error sending StartJobUpdate command to Aurora Scheduler") + return nil, errors.Wrap(retryErr, "Error sending StartJobUpdate command to Aurora Scheduler") } - return resp, nil + return resp.GetResult_().GetStartJobUpdateResult_(), nil } -// Abort Job Update on Aurora. Requires the updateId which can be obtained on the Aurora web UI. -func (r *realisClient) AbortJobUpdate(updateKey aurora.JobUpdateKey, message string) (*aurora.Response, error) { +// Abort AuroraJob Update on Aurora. Requires the updateId which can be obtained on the Aurora web UI. +func (c *Client) AbortJobUpdate(updateKey aurora.JobUpdateKey, message string) error { - r.logger.DebugPrintf("AbortJobUpdate Thrift Payload: %+v %v\n", updateKey, message) + c.logger.DebugPrintf("AbortJobUpdate Thrift Payload: %+v %v\n", updateKey, message) - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.client.AbortJobUpdate(&updateKey, message) + _, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.client.AbortJobUpdate(nil, &updateKey, message) }) if retryErr != nil { - return nil, errors.Wrap(retryErr, "Error sending AbortJobUpdate command to Aurora Scheduler") + return errors.Wrap(retryErr, "Error sending AbortJobUpdate command to Aurora Scheduler") } - return resp, nil + return nil } -//Pause Job Update. UpdateID is returned from StartJobUpdate or the Aurora web UI. -func (r *realisClient) PauseJobUpdate(updateKey *aurora.JobUpdateKey, message string) (*aurora.Response, error) { +// Pause AuroraJob Update. UpdateID is returned from StartJobUpdate or the Aurora web UI. +func (c *Client) PauseJobUpdate(updateKey *aurora.JobUpdateKey, message string) error { - r.logger.DebugPrintf("PauseJobUpdate Thrift Payload: %+v %v\n", updateKey, message) + c.logger.DebugPrintf("PauseJobUpdate Thrift Payload: %+v %v\n", updateKey, message) - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.client.PauseJobUpdate(updateKey, message) + _, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.client.PauseJobUpdate(nil, updateKey, message) }) if retryErr != nil { - return nil, errors.Wrap(retryErr, "Error sending PauseJobUpdate command to Aurora Scheduler") + return errors.Wrap(retryErr, "Error sending PauseJobUpdate command to Aurora Scheduler") } - return resp, nil + return nil } -//Resume Paused Job Update. UpdateID is returned from StartJobUpdate or the Aurora web UI. -func (r *realisClient) ResumeJobUpdate(updateKey *aurora.JobUpdateKey, message string) (*aurora.Response, error) { +// Resume Paused AuroraJob Update. UpdateID is returned from StartJobUpdate or the Aurora web UI. +func (c *Client) ResumeJobUpdate(updateKey *aurora.JobUpdateKey, message string) error { - r.logger.DebugPrintf("ResumeJobUpdate Thrift Payload: %+v %v\n", updateKey, message) + c.logger.DebugPrintf("ResumeJobUpdate Thrift Payload: %+v %v\n", updateKey, message) - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.client.ResumeJobUpdate(updateKey, message) + _, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.client.ResumeJobUpdate(nil, updateKey, message) }) if retryErr != nil { - return nil, errors.Wrap(retryErr, "Error sending ResumeJobUpdate command to Aurora Scheduler") + return errors.Wrap(retryErr, "Error sending ResumeJobUpdate command to Aurora Scheduler") } - return resp, nil + return nil } -//Pulse Job Update on Aurora. UpdateID is returned from StartJobUpdate or the Aurora web UI. -func (r *realisClient) PulseJobUpdate(updateKey *aurora.JobUpdateKey) (*aurora.Response, error) { +// Pulse AuroraJob Update on Aurora. UpdateID is returned from StartJobUpdate or the Aurora web UI. +func (c *Client) PulseJobUpdate(updateKey *aurora.JobUpdateKey) (aurora.JobUpdatePulseStatus, error) { - r.logger.DebugPrintf("PulseJobUpdate Thrift Payload: %+v\n", updateKey) + c.logger.DebugPrintf("PulseJobUpdate Thrift Payload: %+v\n", updateKey) - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.client.PulseJobUpdate(updateKey) + resp, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.client.PulseJobUpdate(nil, updateKey) }) if retryErr != nil { - return nil, errors.Wrap(retryErr, "Error sending PulseJobUpdate command to Aurora Scheduler") + return aurora.JobUpdatePulseStatus(0), errors.Wrap(retryErr, "Error sending PulseJobUpdate command to Aurora Scheduler") + } + + if resp.GetResult_() != nil && resp.GetResult_().GetPulseJobUpdateResult_() != nil { + return resp.GetResult_().GetPulseJobUpdateResult_().GetStatus(), nil + } else { + return aurora.JobUpdatePulseStatus(0), errors.New("Thrift error, field was nil unexpectedly") } - return resp, nil } // Scale up the number of instances under a job configuration using the configuration for specific // instance to scale up. -func (r *realisClient) AddInstances(instKey aurora.InstanceKey, count int32) (*aurora.Response, error) { +func (c *Client) AddInstances(instKey aurora.InstanceKey, count int32) error { - r.logger.DebugPrintf("AddInstances Thrift Payload: %+v %v\n", instKey, count) + c.logger.DebugPrintf("AddInstances Thrift Payload: %+v %v\n", instKey, count) - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.client.AddInstances(&instKey, count) + _, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.client.AddInstances(nil, &instKey, count) }) if retryErr != nil { - return nil, errors.Wrap(retryErr, "Error sending AddInstances command to Aurora Scheduler") + return errors.Wrap(retryErr, "Error sending AddInstances command to Aurora Scheduler") } - return resp, nil + return nil } -//Scale down the number of instances under a job configuration using the configuration of a specific instance -func (r *realisClient) RemoveInstances(key *aurora.JobKey, count int32) (*aurora.Response, error) { - instanceIds, err := r.GetInstanceIds(key, aurora.ACTIVE_STATES) +// Scale down the number of instances under a job configuration using the configuration of a specific instance +// Instances with a higher instance ID will be removed first. For example, if our instance ID list is [0,1,2,3] +// and we want to remove 2 instances, 2 and 3 will always be picked. +func (c *Client) RemoveInstances(key aurora.JobKey, count int) error { + instanceIds, err := c.GetInstanceIds(key, aurora.ACTIVE_STATES) if err != nil { - return nil, errors.Wrap(err, "RemoveInstances: Could not retrieve relevant instance IDs") + return errors.Wrap(err, "RemoveInstances: Could not retrieve relevant instance IDs") } - if len(instanceIds) < int(count) { - return nil, errors.New(fmt.Sprintf("RemoveInstances: No sufficient instances to Kill - "+ - "Instances to kill %d Total Instances %d", count, len(instanceIds))) + if len(instanceIds) < count { + return errors.Errorf("Insufficient active instances available for killing: "+ + " Instances to be killed %d Active instances %d", count, len(instanceIds)) } - instanceList := make([]int32, count) - i := 0 - for k := range instanceIds { - instanceList[i] = k - i += 1 - if i == int(count) { - break - } + + // Sort instanceIds in decreasing order + sort.Slice(instanceIds, func(i, j int) bool { + return instanceIds[i] > instanceIds[j] + }) + + // Get the last count instance ids to kill + instanceIds = instanceIds[:count] + killed, err := c.KillInstances(key, instanceIds...) + + if !killed { + return errors.New("Flex down was not able to reduce the number of instances running.") } - return r.KillInstances(key, instanceList...) + + return nil } // Get information about task including a fully hydrated task configuration object -func (r *realisClient) GetTaskStatus(query *aurora.TaskQuery) (tasks []*aurora.ScheduledTask, e error) { +func (c *Client) GetTaskStatus(query *aurora.TaskQuery) ([]*aurora.ScheduledTask, error) { - r.logger.DebugPrintf("GetTasksStatus Thrift Payload: %+v\n", query) + c.logger.DebugPrintf("GetTasksStatus Thrift Payload: %+v\n", query) - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.client.GetTasksStatus(query) + resp, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.client.GetTasksStatus(nil, query) }) if retryErr != nil { @@ -877,36 +823,34 @@ func (r *realisClient) GetTaskStatus(query *aurora.TaskQuery) (tasks []*aurora.S } // Get pending reason -func (r *realisClient) GetPendingReason(query *aurora.TaskQuery) (pendingReasons []*aurora.PendingReason, e error) { +func (c *Client) GetPendingReason(query *aurora.TaskQuery) ([]*aurora.PendingReason, error) { - r.logger.DebugPrintf("GetPendingReason Thrift Payload: %+v\n", query) + c.logger.DebugPrintf("GetPendingReason Thrift Payload: %+v\n", query) - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.client.GetPendingReason(query) + resp, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.client.GetPendingReason(nil, query) }) if retryErr != nil { return nil, errors.Wrap(retryErr, "Error querying Aurora Scheduler for pending Reasons") } - var result map[*aurora.PendingReason]bool + var result []*aurora.PendingReason if resp.GetResult_() != nil { result = resp.GetResult_().GetGetPendingReasonResult_().GetReasons() } - for reason := range result { - pendingReasons = append(pendingReasons, reason) - } - return pendingReasons, nil + + return result, nil } // Get information about task including without a task configuration object -func (r *realisClient) GetTasksWithoutConfigs(query *aurora.TaskQuery) (tasks []*aurora.ScheduledTask, e error) { +func (c *Client) GetTasksWithoutConfigs(query *aurora.TaskQuery) ([]*aurora.ScheduledTask, error) { - r.logger.DebugPrintf("GetTasksWithoutConfigs Thrift Payload: %+v\n", query) + c.logger.DebugPrintf("GetTasksWithoutConfigs Thrift Payload: %+v\n", query) - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.client.GetTasksWithoutConfigs(query) + resp, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.client.GetTasksWithoutConfigs(nil, query) }) if retryErr != nil { @@ -918,11 +862,10 @@ func (r *realisClient) GetTasksWithoutConfigs(query *aurora.TaskQuery) (tasks [] } // Get the task configuration from the aurora scheduler for a job -func (r *realisClient) FetchTaskConfig(instKey aurora.InstanceKey) (*aurora.TaskConfig, error) { +func (c *Client) FetchTaskConfig(instKey aurora.InstanceKey) (*aurora.TaskConfig, error) { - ids := make(map[int32]bool) + ids := []int32{instKey.GetInstanceId()} - ids[instKey.InstanceId] = true taskQ := &aurora.TaskQuery{ Role: &instKey.JobKey.Role, Environment: &instKey.JobKey.Environment, @@ -931,10 +874,10 @@ func (r *realisClient) FetchTaskConfig(instKey aurora.InstanceKey) (*aurora.Task Statuses: aurora.ACTIVE_STATES, } - r.logger.DebugPrintf("GetTasksStatus Thrift Payload: %+v\n", taskQ) + c.logger.DebugPrintf("GetTasksStatus Thrift Payload: %+v\n", taskQ) - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.client.GetTasksStatus(taskQ) + resp, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.client.GetTasksStatus(nil, taskQ) }) if retryErr != nil { @@ -955,33 +898,37 @@ func (r *realisClient) FetchTaskConfig(instKey aurora.InstanceKey) (*aurora.Task return tasks[0].AssignedTask.Task, nil } -func (r *realisClient) JobUpdateDetails(updateQuery aurora.JobUpdateQuery) (*aurora.Response, error) { +func (c *Client) JobUpdateDetails(updateQuery aurora.JobUpdateQuery) ([]*aurora.JobUpdateDetails, error) { - r.logger.DebugPrintf("GetJobUpdateDetails Thrift Payload: %+v\n", updateQuery) + c.logger.DebugPrintf("GetJobUpdateDetails Thrift Payload: %+v\n", updateQuery) - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.client.GetJobUpdateDetails(&updateQuery) + resp, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.client.GetJobUpdateDetails(nil, &updateQuery) }) if retryErr != nil { return nil, errors.Wrap(retryErr, "Unable to get job update details") } - return resp, nil + if resp.GetResult_() != nil && resp.GetResult_().GetGetJobUpdateDetailsResult_() != nil { + return resp.GetResult_().GetGetJobUpdateDetailsResult_().GetDetailsList(), nil + } else { + return nil, errors.New("Unknown Thrift error, field is nil.") + } } -func (r *realisClient) RollbackJobUpdate(key aurora.JobUpdateKey, message string) (*aurora.Response, error) { +func (c *Client) RollbackJobUpdate(key aurora.JobUpdateKey, message string) error { - r.logger.DebugPrintf("RollbackJobUpdate Thrift Payload: %+v %v\n", key, message) + c.logger.DebugPrintf("RollbackJobUpdate Thrift Payload: %+v %v\n", key, message) - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.client.RollbackJobUpdate(&key, message) + _, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.client.RollbackJobUpdate(nil, &key, message) }) if retryErr != nil { - return nil, errors.Wrap(retryErr, "Unable to roll back job update") + return errors.Wrap(retryErr, "Unable to roll back job update") } - return resp, nil + return nil } /* Admin functions */ @@ -991,57 +938,131 @@ func (r *realisClient) RollbackJobUpdate(key aurora.JobUpdateKey, message string // Set a list of nodes to DRAINING. This means nothing will be able to be scheduled on them and any existing // tasks will be killed and re-scheduled elsewhere in the cluster. Tasks from DRAINING nodes are not guaranteed // to return to running unless there is enough capacity in the cluster to run them. -func (r *realisClient) DrainHosts(hosts ...string) (*aurora.Response, *aurora.DrainHostsResult_, error) { - - var result *aurora.DrainHostsResult_ - - if len(hosts) == 0 { - return nil, nil, errors.New("no hosts provided to drain") - } - - drainList := aurora.NewHosts() - drainList.HostNames = make(map[string]bool) - for _, host := range hosts { - drainList.HostNames[host] = true - } - - r.logger.DebugPrintf("DrainHosts Thrift Payload: %v\n", drainList) - - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.adminClient.DrainHosts(drainList) - }) - - if retryErr != nil { - return resp, result, errors.Wrap(retryErr, "Unable to recover connection") - } - - if resp.GetResult_() != nil { - result = resp.GetResult_().GetDrainHostsResult_() - } - - return resp, result, nil -} - -// Start SLA Aware Drain. -// defaultSlaPolicy is the fallback SlaPolicy to use if a task does not have an SlaPolicy. -// After timeoutSecs, tasks will be forcefully drained without checking SLA. -func (r *realisClient) SLADrainHosts(policy *aurora.SlaPolicy, timeout int64, hosts ...string) (*aurora.DrainHostsResult_, error) { - var result *aurora.DrainHostsResult_ +func (c *Client) DrainHosts(hosts ...string) ([]*aurora.HostStatus, error) { if len(hosts) == 0 { return nil, errors.New("no hosts provided to drain") } drainList := aurora.NewHosts() - drainList.HostNames = make(map[string]bool) - for _, host := range hosts { - drainList.HostNames[host] = true + drainList.HostNames = hosts + + c.logger.DebugPrintf("DrainHosts Thrift Payload: %v\n", drainList) + + resp, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.adminClient.DrainHosts(nil, drainList) + }) + + if retryErr != nil { + return nil, errors.Wrap(retryErr, "Unable to recover connection") } - r.logger.DebugPrintf("SLADrainHosts Thrift Payload: %v\n", drainList) + if resp.GetResult_() != nil && resp.GetResult_().GetDrainHostsResult_() != nil { + return resp.GetResult_().GetDrainHostsResult_().GetStatuses(), nil + } else { + return nil, errors.New("Thrift error: Field in response is nil unexpectedly.") + } +} - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.adminClient.SlaDrainHosts(drainList, policy, timeout) +// Start SLA Aware Drain. +// defaultSlaPolicy is the fallback SlaPolicy to use if a task does not have an SlaPolicy. +// After timeoutSecs, tasks will be forcefully drained without checking SLA. +func (c *Client) SLADrainHosts(policy *aurora.SlaPolicy, timeout int64, hosts ...string) ([]*aurora.HostStatus, error) { + + if len(hosts) == 0 { + return nil, errors.New("no hosts provided to drain") + } + + drainList := aurora.NewHosts() + drainList.HostNames = hosts + + c.logger.DebugPrintf("SLADrainHosts Thrift Payload: %v\n", drainList) + + resp, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.adminClient.SlaDrainHosts(nil, drainList, policy, timeout) + }) + + if retryErr != nil { + return nil, errors.Wrap(retryErr, "Unable to recover connection") + } + + if resp.GetResult_() != nil && resp.GetResult_().GetDrainHostsResult_() != nil { + return resp.GetResult_().GetDrainHostsResult_().GetStatuses(), nil + } else { + return nil, errors.New("Thrift error: Field in response is nil unexpectedly.") + } +} + +func (c *Client) StartMaintenance(hosts ...string) ([]*aurora.HostStatus, error) { + + if len(hosts) == 0 { + return nil, errors.New("no hosts provided to start maintenance on") + } + + hostList := aurora.NewHosts() + hostList.HostNames = hosts + + c.logger.DebugPrintf("StartMaintenance Thrift Payload: %v\n", hostList) + + resp, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.adminClient.StartMaintenance(nil, hostList) + }) + + if retryErr != nil { + return nil, errors.Wrap(retryErr, "Unable to recover connection") + } + + if resp.GetResult_() != nil && resp.GetResult_().GetStartMaintenanceResult_() != nil { + return resp.GetResult_().GetStartMaintenanceResult_().GetStatuses(), nil + } else { + return nil, errors.New("Thrift error: Field in response is nil unexpectedly.") + } +} + +func (c *Client) EndMaintenance(hosts ...string) ([]*aurora.HostStatus, error) { + + if len(hosts) == 0 { + return nil, errors.New("no hosts provided to end maintenance on") + } + + hostList := aurora.NewHosts() + hostList.HostNames = hosts + + c.logger.DebugPrintf("EndMaintenance Thrift Payload: %v\n", hostList) + + resp, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.adminClient.EndMaintenance(nil, hostList) + }) + + if retryErr != nil { + return nil, errors.Wrap(retryErr, "Unable to recover connection") + } + + if resp.GetResult_() != nil && resp.GetResult_().GetEndMaintenanceResult_() != nil { + return resp.GetResult_().GetEndMaintenanceResult_().GetStatuses(), nil + } else { + return nil, errors.New("Thrift error: Field in response is nil unexpectedly.") + } + +} + +func (c *Client) MaintenanceStatus(hosts ...string) (*aurora.MaintenanceStatusResult_, error) { + + var result *aurora.MaintenanceStatusResult_ + + if len(hosts) == 0 { + return nil, errors.New("no hosts provided to get maintenance status from") + } + + hostList := aurora.NewHosts() + hostList.HostNames = hosts + + c.logger.DebugPrintf("MaintenanceStatus Thrift Payload: %v\n", hostList) + + // Make thrift call. If we encounter an error sending the call, attempt to reconnect + // and continue trying to resend command until we run out of retries. + resp, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.adminClient.MaintenanceStatus(nil, hostList) }) if retryErr != nil { @@ -1049,150 +1070,59 @@ func (r *realisClient) SLADrainHosts(policy *aurora.SlaPolicy, timeout int64, ho } if resp.GetResult_() != nil { - result = resp.GetResult_().GetDrainHostsResult_() + result = resp.GetResult_().GetMaintenanceStatusResult_() } return result, nil } -func (r *realisClient) StartMaintenance(hosts ...string) (*aurora.Response, *aurora.StartMaintenanceResult_, error) { - - var result *aurora.StartMaintenanceResult_ - - if len(hosts) == 0 { - return nil, nil, errors.New("no hosts provided to start maintenance on") - } - - hostList := aurora.NewHosts() - hostList.HostNames = make(map[string]bool) - for _, host := range hosts { - hostList.HostNames[host] = true - } - - r.logger.DebugPrintf("StartMaintenance Thrift Payload: %v\n", hostList) - - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.adminClient.StartMaintenance(hostList) - }) - - if retryErr != nil { - return resp, result, errors.Wrap(retryErr, "Unable to recover connection") - } - - if resp.GetResult_() != nil { - result = resp.GetResult_().GetStartMaintenanceResult_() - } - - return resp, result, nil -} - -func (r *realisClient) EndMaintenance(hosts ...string) (*aurora.Response, *aurora.EndMaintenanceResult_, error) { - - var result *aurora.EndMaintenanceResult_ - - if len(hosts) == 0 { - return nil, nil, errors.New("no hosts provided to end maintenance on") - } - - hostList := aurora.NewHosts() - hostList.HostNames = make(map[string]bool) - for _, host := range hosts { - hostList.HostNames[host] = true - } - - r.logger.DebugPrintf("EndMaintenance Thrift Payload: %v\n", hostList) - - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.adminClient.EndMaintenance(hostList) - }) - - if retryErr != nil { - return resp, result, errors.Wrap(retryErr, "Unable to recover connection") - } - - if resp.GetResult_() != nil { - result = resp.GetResult_().GetEndMaintenanceResult_() - } - - return resp, result, nil -} - -func (r *realisClient) MaintenanceStatus(hosts ...string) (*aurora.Response, *aurora.MaintenanceStatusResult_, error) { - - var result *aurora.MaintenanceStatusResult_ - - if len(hosts) == 0 { - return nil, nil, errors.New("no hosts provided to get maintenance status from") - } - - hostList := aurora.NewHosts() - hostList.HostNames = make(map[string]bool) - for _, host := range hosts { - hostList.HostNames[host] = true - } - - r.logger.DebugPrintf("MaintenanceStatus Thrift Payload: %v\n", hostList) - - // Make thrift call. If we encounter an error sending the call, attempt to reconnect - // and continue trying to resend command until we run out of retries. - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.adminClient.MaintenanceStatus(hostList) - }) - - if retryErr != nil { - return resp, result, errors.Wrap(retryErr, "Unable to recover connection") - } - - if resp.GetResult_() != nil { - result = resp.GetResult_().GetMaintenanceStatusResult_() - } - - return resp, result, nil -} - // SetQuota sets a quota aggregate for the given role // TODO(zircote) Currently investigating an error that is returned from thrift calls that include resources for `NamedPort` and `NumGpu` -func (r *realisClient) SetQuota(role string, cpu *float64, ramMb *int64, diskMb *int64) (*aurora.Response, error) { - ram := aurora.NewResource() - ram.RamMb = ramMb - c := aurora.NewResource() - c.NumCpus = cpu - d := aurora.NewResource() - d.DiskMb = diskMb +func (c *Client) SetQuota(role string, cpu *float64, ramMb *int64, diskMb *int64) error { + ramResource := aurora.NewResource() + ramResource.RamMb = ramMb + cpuResource := aurora.NewResource() + cpuResource.NumCpus = cpu + diskResource := aurora.NewResource() + diskResource.DiskMb = diskMb + quota := aurora.NewResourceAggregate() - quota.Resources = make(map[*aurora.Resource]bool) - quota.Resources[ram] = true - quota.Resources[c] = true - quota.Resources[d] = true - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.adminClient.SetQuota(role, quota) + quota.Resources = []*aurora.Resource{ramResource, cpuResource, diskResource} + + _, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.adminClient.SetQuota(nil, role, quota) }) if retryErr != nil { - return resp, errors.Wrap(retryErr, "Unable to set role quota") + return errors.Wrap(retryErr, "Unable to set role quota") } - return resp, retryErr + return retryErr } // GetQuota returns the resource aggregate for the given role -func (r *realisClient) GetQuota(role string) (*aurora.Response, error) { +func (c *Client) GetQuota(role string) (*aurora.GetQuotaResult_, error) { - resp, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.adminClient.GetQuota(role) + resp, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.adminClient.GetQuota(nil, role) }) if retryErr != nil { - return resp, errors.Wrap(retryErr, "Unable to get role quota") + return nil, errors.Wrap(retryErr, "Unable to get role quota") + } + + if resp.GetResult_() != nil { + return resp.GetResult_().GetGetQuotaResult_(), nil + } else { + return nil, errors.New("Thrift error: Field in response is nil unexpectedly.") } - return resp, retryErr } // Force Aurora Scheduler to perform a snapshot and write to Mesos log -func (r *realisClient) Snapshot() error { +func (c *Client) Snapshot() error { - _, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.adminClient.Snapshot() + _, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.adminClient.Snapshot(nil) }) if retryErr != nil { @@ -1203,10 +1133,10 @@ func (r *realisClient) Snapshot() error { } // Force Aurora Scheduler to write backup file to a file in the backup directory -func (r *realisClient) PerformBackup() error { +func (c *Client) PerformBackup() error { - _, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.adminClient.PerformBackup() + _, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.adminClient.PerformBackup(nil) }) if retryErr != nil { @@ -1216,10 +1146,11 @@ func (r *realisClient) PerformBackup() error { return nil } -func (r *realisClient) ForceImplicitTaskReconciliation() error { +// Force an Implicit reconciliation between Mesos and Aurora +func (c *Client) ForceImplicitTaskReconciliation() error { - _, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.adminClient.TriggerImplicitTaskReconciliation() + _, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.adminClient.TriggerImplicitTaskReconciliation(nil) }) if retryErr != nil { @@ -1229,7 +1160,8 @@ func (r *realisClient) ForceImplicitTaskReconciliation() error { return nil } -func (r *realisClient) ForceExplicitTaskReconciliation(batchSize *int32) error { +// Force an Explicit reconciliation between Mesos and Aurora +func (c *Client) ForceExplicitTaskReconciliation(batchSize *int32) error { if batchSize != nil && *batchSize < 1 { return errors.New("Invalid batch size.") @@ -1238,8 +1170,8 @@ func (r *realisClient) ForceExplicitTaskReconciliation(batchSize *int32) error { settings.BatchSize = batchSize - _, retryErr := r.thriftCallWithRetries(func() (*aurora.Response, error) { - return r.adminClient.TriggerExplicitTaskReconciliation(settings) + _, retryErr := c.thriftCallWithRetries(func() (*aurora.Response, error) { + return c.adminClient.TriggerExplicitTaskReconciliation(nil, settings) }) if retryErr != nil { diff --git a/vendor/github.com/paypal/gorealis/realis_e2e_test.go b/vendor/github.com/paypal/gorealis/realis_e2e_test.go index 9108903..2cc79b8 100644 --- a/vendor/github.com/paypal/gorealis/realis_e2e_test.go +++ b/vendor/github.com/paypal/gorealis/realis_e2e_test.go @@ -22,24 +22,22 @@ import ( "testing" "time" - "github.com/paypal/gorealis" + realis "github.com/paypal/gorealis" "github.com/paypal/gorealis/gen-go/apache/aurora" - "github.com/paypal/gorealis/response" "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) -var r realis.Realis -var monitor *realis.Monitor +var r *realis.Client var thermosPayload []byte func TestMain(m *testing.M) { var err error // New configuration to connect to docker container - r, err = realis.NewRealisClient(realis.SchedulerUrl("http://192.168.33.7:8081"), + r, err = realis.NewClient(realis.SchedulerUrl("http://192.168.33.7:8081"), realis.BasicAuth("aurora", "secret"), - realis.TimeoutMS(20000)) + realis.Timeout(20*time.Second)) if err != nil { fmt.Println("Please run docker-compose up -d before running test suite") @@ -48,9 +46,6 @@ func TestMain(m *testing.M) { defer r.Close() - // Create monitor - monitor = &realis.Monitor{Client: r} - thermosPayload, err = ioutil.ReadFile("examples/thermos_payload.json") if err != nil { fmt.Println("Error reading thermos payload file: ", err) @@ -68,8 +63,8 @@ func TestNonExistentEndpoint(t *testing.T) { Jitter: 0.1} // Attempt to connect to a bad endpoint - r, err := realis.NewRealisClient(realis.SchedulerUrl("http://192.168.33.7:8081/doesntexist/"), - realis.TimeoutMS(200), + r, err := realis.NewClient(realis.SchedulerUrl("http://doesntexist.com:8081/api"), + realis.Timeout(200*time.Millisecond), realis.BackOff(backoff), ) defer r.Close() @@ -90,13 +85,38 @@ func TestNonExistentEndpoint(t *testing.T) { } +func TestBadCredentials(t *testing.T) { + r, err := realis.NewClient(realis.SchedulerUrl("http://192.168.33.7:8081"), + realis.BasicAuth("incorrect", "password"), + realis.Debug()) + defer r.Close() + + assert.NoError(t, err) + + job := realis.NewJob(). + Environment("prod"). + Role("vagrant"). + Name("create_thermos_job_test"). + ExecutorName(aurora.AURORA_EXECUTOR_NAME). + ExecutorData(string(thermosPayload)). + CPU(.5). + RAM(64). + Disk(100). + IsService(true). + InstanceCount(2). + AddPorts(1) + + assert.Error(t, r.CreateJob(job)) +} + func TestThriftBinary(t *testing.T) { - r, err := realis.NewRealisClient(realis.SchedulerUrl("http://192.168.33.7:8081"), + r, err := realis.NewClient(realis.SchedulerUrl("http://192.168.33.7:8081"), realis.BasicAuth("aurora", "secret"), - realis.TimeoutMS(20000), + realis.Timeout(20*time.Second), realis.ThriftBinary()) assert.NoError(t, err) + defer r.Close() role := "all" taskQ := &aurora.TaskQuery{ @@ -108,14 +128,12 @@ func TestThriftBinary(t *testing.T) { assert.NoError(t, err) - r.Close() - } func TestThriftJSON(t *testing.T) { - r, err := realis.NewRealisClient(realis.SchedulerUrl("http://192.168.33.7:8081"), + r, err := realis.NewClient(realis.SchedulerUrl("http://192.168.33.7:8081"), realis.BasicAuth("aurora", "secret"), - realis.TimeoutMS(20000), + realis.Timeout(20*time.Second), realis.ThriftJSON()) assert.NoError(t, err) @@ -135,7 +153,7 @@ func TestThriftJSON(t *testing.T) { } func TestNoopLogger(t *testing.T) { - r, err := realis.NewRealisClient(realis.SchedulerUrl("http://192.168.33.7:8081"), + r, err := realis.NewClient(realis.SchedulerUrl("http://192.168.33.7:8081"), realis.BasicAuth("aurora", "secret"), realis.SetLogger(realis.NoopLogger{})) @@ -160,6 +178,34 @@ func TestLeaderFromZK(t *testing.T) { assert.NoError(t, err) assert.Equal(t, "http://192.168.33.7:8081", url) + +} +func TestInvalidAuroraURL(t *testing.T) { + for _, url := range []string{ + "http://doesntexist.com:8081/apitest", + "test://doesntexist.com:8081", + "https://doesntexist.com:8081/testing/api", + } { + r, err := realis.NewClient(realis.SchedulerUrl(url)) + assert.Error(t, err) + assert.Nil(t, r) + } +} + +func TestValidAuroraURL(t *testing.T) { + for _, url := range []string{ + "http://domain.com:8081/api", + "https://domain.com:8081/api", + "domain.com:8081", + "domain.com", + "192.168.33.7", + "192.168.33.7:8081", + "192.168.33.7:8081/api", + } { + r, err := realis.NewClient(realis.SchedulerUrl(url)) + assert.NoError(t, err) + assert.NotNil(t, r) + } } func TestRealisClient_ReestablishConn(t *testing.T) { @@ -193,23 +239,21 @@ func TestRealisClient_CreateJob_Thermos(t *testing.T) { InstanceCount(2). AddPorts(1) - resp, err := r.CreateJob(job) + err := r.CreateJob(job) assert.NoError(t, err) - assert.Equal(t, aurora.ResponseCode_OK, resp.ResponseCode) - // Test Instances Monitor - success, err := monitor.Instances(job.JobKey(), job.GetInstanceCount(), 1, 50) + success, err := r.InstancesMonitor(job.JobKey(), job.GetInstanceCount(), 1*time.Second, 50*time.Second) assert.True(t, success) assert.NoError(t, err) - //Fetch all Jobs - _, result, err := r.GetJobs(role) + // Fetch all Jobs + result, err := r.GetJobs(role) fmt.Printf("GetJobs length: %+v \n", len(result.Configs)) assert.Len(t, result.Configs, 1) assert.NoError(t, err) - // Test asking the scheduler to perform a Snpshot + // Test asking the scheduler to perform a Snapshot t.Run("TestRealisClient_Snapshot", func(t *testing.T) { err := r.Snapshot() assert.NoError(t, err) @@ -223,12 +267,10 @@ func TestRealisClient_CreateJob_Thermos(t *testing.T) { // Tasks must exist for it to, be killed t.Run("TestRealisClient_KillJob_Thermos", func(t *testing.T) { - resp, err := r.KillJob(job.JobKey()) + err := r.KillJob(job.JobKey()) assert.NoError(t, err) - assert.Equal(t, aurora.ResponseCode_OK, resp.ResponseCode) - - success, err := monitor.Instances(job.JobKey(), 0, 1, 50) + success, err := r.InstancesMonitor(job.JobKey(), 0, 1*time.Second, 50*time.Second) assert.True(t, success) assert.NoError(t, err) }) @@ -249,9 +291,8 @@ func TestRealisClient_CreateJob_ExecutorDoesNotExist(t *testing.T) { Disk(10). InstanceCount(1) - resp, err := r.CreateJob(job) + err := r.CreateJob(job) assert.Error(t, err) - assert.Equal(t, aurora.ResponseCode_INVALID_REQUEST, resp.GetResponseCode()) } // Test configuring an executor that doesn't exist for CreateJob API @@ -273,9 +314,8 @@ func TestRealisClient_GetPendingReason(t *testing.T) { Disk(100). InstanceCount(1) - resp, err := r.CreateJob(job) + err := r.CreateJob(job) assert.NoError(t, err) - assert.Equal(t, aurora.ResponseCode_OK, resp.ResponseCode) taskQ := &aurora.TaskQuery{ Role: &role, @@ -287,7 +327,7 @@ func TestRealisClient_GetPendingReason(t *testing.T) { assert.NoError(t, err) assert.Len(t, reasons, 1) - resp, err = r.KillJob(job.JobKey()) + err = r.KillJob(job.JobKey()) assert.NoError(t, err) } @@ -295,7 +335,7 @@ func TestRealisClient_CreateService_WithPulse_Thermos(t *testing.T) { fmt.Println("Creating service") role := "vagrant" - job := realis.NewJob(). + job := realis.NewJobUpdate(). Environment("prod"). Role(role). Name("create_thermos_job_test"). @@ -305,72 +345,61 @@ func TestRealisClient_CreateService_WithPulse_Thermos(t *testing.T) { RAM(64). Disk(100). IsService(true). - InstanceCount(1). + InstanceCount(2). AddPorts(1). - AddLabel("currentTime", time.Now().String()) + AddLabel("currentTime", time.Now().String()). + PulseIntervalTimeout(30 * time.Millisecond). + BatchSize(1).WaitForBatchCompletion(true) pulse := int32(30) timeout := 300 - settings := realis.NewUpdateSettings() - settings.BlockIfNoPulsesAfterMs = &pulse - settings.UpdateGroupSize = 1 - settings.WaitForBatchCompletion = true - job.InstanceCount(2) - resp, result, err := r.CreateService(job, settings) + result, err := r.CreateService(job) fmt.Println(result.String()) assert.NoError(t, err) - assert.Equal(t, aurora.ResponseCode_OK, resp.ResponseCode) updateQ := aurora.JobUpdateQuery{ Key: result.GetKey(), Limit: 1, } - start := time.Now() + var updateDetails []*aurora.JobUpdateDetails + for i := 0; i*int(pulse) <= timeout; i++ { - fmt.Println("sending PulseJobUpdate....") - resp, err = r.PulseJobUpdate(result.GetKey()) - assert.NotNil(t, resp) - assert.Nil(t, err) + pulseStatus, err := r.PulseJobUpdate(result.GetKey()) - respDetail, err := r.JobUpdateDetails(updateQ) assert.Nil(t, err) - - updateDetail := response.JobUpdateDetails(respDetail) - if len(updateDetail) == 0 { - fmt.Println("No update found") - assert.NotEqual(t, len(updateDetail), 0) + if pulseStatus != aurora.JobUpdatePulseStatus_OK && pulseStatus != aurora.JobUpdatePulseStatus_FINISHED { + assert.Fail(t, "Pulse update status received doesn't exist") } - status := updateDetail[0].Update.Summary.State.Status - if _, ok := aurora.ACTIVE_JOB_UPDATE_STATES[status]; !ok { + updateDetails, err = r.JobUpdateDetails(updateQ) + assert.Nil(t, err) + + assert.Equal(t, len(updateDetails), 1, "No update matching query found") + status := updateDetails[0].Update.Summary.State.Status + + if _, ok := realis.ActiveJobUpdateStates[status]; !ok { // Rolled forward is the only state in which an update has been successfully updated // if we encounter an inactive state and it is not at rolled forward, update failed if status == aurora.JobUpdateStatus_ROLLED_FORWARD { - fmt.Println("Update succeded") + fmt.Println("Update succeeded") break } else { fmt.Println("Update failed") break } } - fmt.Println("Polling, update still active...") - time.Sleep(time.Duration(pulse) * time.Second) } - end := time.Now() - fmt.Printf("Update call took %d ns\n", (end.UnixNano() - start.UnixNano())) t.Run("TestRealisClient_KillJob_Thermos", func(t *testing.T) { - start := time.Now() - resp, err := r.KillJob(job.JobKey()) - end := time.Now() + err := r.AbortJobUpdate(*updateDetails[0].GetUpdate().GetSummary().GetKey(), "") + assert.NoError(t, err) + err = r.KillJob(job.JobKey()) assert.NoError(t, err) - assert.Equal(t, aurora.ResponseCode_OK, resp.ResponseCode) - fmt.Printf("Kill call took %d ns\n", (end.UnixNano() - start.UnixNano())) }) } @@ -379,7 +408,7 @@ func TestRealisClient_CreateService_WithPulse_Thermos(t *testing.T) { func TestRealisClient_CreateService(t *testing.T) { // Create a single job - job := realis.NewJob(). + job := realis.NewJobUpdate(). Environment("prod"). Role("vagrant"). Name("create_service_test"). @@ -389,25 +418,23 @@ func TestRealisClient_CreateService(t *testing.T) { RAM(4). Disk(10). InstanceCount(3). - IsService(true) + WatchTime(20 * time.Second). + IsService(true). + BatchSize(2) - settings := realis.NewUpdateSettings() - settings.UpdateGroupSize = 2 - job.InstanceCount(3) - resp, result, err := r.CreateService(job, settings) + result, err := r.CreateService(job) assert.NoError(t, err) assert.NotNil(t, result) - assert.Equal(t, aurora.ResponseCode_OK, resp.GetResponseCode()) var ok bool var mErr error - if ok, mErr = monitor.JobUpdate(*result.GetKey(), 5, 180); !ok || mErr != nil { + if ok, mErr = r.JobUpdateMonitor(*result.GetKey(), 5*time.Second, 4*time.Minute); !ok || mErr != nil { // Update may already be in a terminal state so don't check for error - _, err := r.AbortJobUpdate(*result.GetKey(), "Monitor timed out.") + err := r.AbortJobUpdate(*result.GetKey(), "Monitor timed out.") - _, err = r.KillJob(job.JobKey()) + err = r.KillJob(job.JobKey()) assert.NoError(t, err) } @@ -416,7 +443,7 @@ func TestRealisClient_CreateService(t *testing.T) { assert.NoError(t, mErr) // Kill task test task after confirming it came up fine - _, err = r.KillJob(job.JobKey()) + err = r.KillJob(job.JobKey()) assert.NoError(t, err) } @@ -425,7 +452,7 @@ func TestRealisClient_CreateService(t *testing.T) { func TestRealisClient_CreateService_ExecutorDoesNotExist(t *testing.T) { // Create a single job - job := realis.NewJob(). + jobUpdate := realis.NewJobUpdate(). Environment("prod"). Role("vagrant"). Name("executordoesntexist"). @@ -434,15 +461,12 @@ func TestRealisClient_CreateService_ExecutorDoesNotExist(t *testing.T) { CPU(.25). RAM(4). Disk(10). - InstanceCount(1) + InstanceCount(3) - settings := realis.NewUpdateSettings() - job.InstanceCount(3) - resp, result, err := r.CreateService(job, settings) + result, err := r.CreateService(jobUpdate) assert.Error(t, err) assert.Nil(t, result) - assert.Equal(t, aurora.ResponseCode_INVALID_REQUEST, resp.GetResponseCode()) } func TestRealisClient_ScheduleCronJob_Thermos(t *testing.T) { @@ -465,87 +489,66 @@ func TestRealisClient_ScheduleCronJob_Thermos(t *testing.T) { CronSchedule("* * * * *"). IsService(false) - resp, err := r.ScheduleCronJob(job) - if err != nil { - fmt.Println(err) - os.Exit(1) - } - - assert.Equal(t, aurora.ResponseCode_OK, resp.ResponseCode) + err = r.ScheduleCronJob(job) + assert.NoError(t, err) t.Run("TestRealisClient_StartCronJob_Thermos", func(t *testing.T) { - start := time.Now() - resp, err := r.StartCronJob(job.JobKey()) - end := time.Now() - + err := r.StartCronJob(job.JobKey()) assert.NoError(t, err) - assert.Equal(t, aurora.ResponseCode_OK, resp.ResponseCode) - fmt.Printf("Schedule cron call took %d ns\n", (end.UnixNano() - start.UnixNano())) }) t.Run("TestRealisClient_DeschedulerCronJob_Thermos", func(t *testing.T) { - start := time.Now() - resp, err := r.DescheduleCronJob(job.JobKey()) - end := time.Now() - + err := r.DescheduleCronJob(job.JobKey()) assert.NoError(t, err) - assert.Equal(t, aurora.ResponseCode_OK, resp.ResponseCode) - fmt.Printf("Deschedule cron call took %d ns\n", (end.UnixNano() - start.UnixNano())) }) } func TestRealisClient_StartMaintenance(t *testing.T) { hosts := []string{"localhost"} - _, _, err := r.StartMaintenance(hosts...) - if err != nil { - fmt.Printf("error: %+v\n", err.Error()) - os.Exit(1) - } + _, err := r.StartMaintenance(hosts...) + assert.NoError(t, err) // Monitor change to DRAINING and DRAINED mode - hostResults, err := monitor.HostMaintenance( + hostResults, err := r.HostMaintenanceMonitor( hosts, []aurora.MaintenanceMode{aurora.MaintenanceMode_SCHEDULED}, - 1, - 50) + 1*time.Second, + 50*time.Second) assert.Equal(t, map[string]bool{"localhost": true}, hostResults) assert.NoError(t, err) - _, _, err = r.EndMaintenance(hosts...) + _, err = r.EndMaintenance(hosts...) assert.NoError(t, err) // Monitor change to DRAINING and DRAINED mode - _, err = monitor.HostMaintenance( + _, err = r.HostMaintenanceMonitor( hosts, []aurora.MaintenanceMode{aurora.MaintenanceMode_NONE}, - 5, - 10) + 5*time.Second, + 10*time.Second) assert.NoError(t, err) } func TestRealisClient_DrainHosts(t *testing.T) { hosts := []string{"localhost"} - _, _, err := r.DrainHosts(hosts...) - if err != nil { - fmt.Printf("error: %+v\n", err.Error()) - os.Exit(1) - } + _, err := r.DrainHosts(hosts...) + assert.NoError(t, err) // Monitor change to DRAINING and DRAINED mode - hostResults, err := monitor.HostMaintenance( + hostResults, err := r.HostMaintenanceMonitor( hosts, []aurora.MaintenanceMode{aurora.MaintenanceMode_DRAINED, aurora.MaintenanceMode_DRAINING}, - 1, - 50) + 1*time.Second, + 50*time.Second) assert.Equal(t, map[string]bool{"localhost": true}, hostResults) assert.NoError(t, err) t.Run("TestRealisClient_MonitorNontransitioned", func(t *testing.T) { // Monitor change to DRAINING and DRAINED mode - hostResults, err := monitor.HostMaintenance( + hostResults, err := r.HostMaintenanceMonitor( append(hosts, "IMAGINARY_HOST"), []aurora.MaintenanceMode{aurora.MaintenanceMode_DRAINED, aurora.MaintenanceMode_DRAINING}, - 1, - 1) + 1*time.Second, + 1*time.Second) // Assert monitor returned an error that was not nil, and also a list of the non-transitioned hosts assert.Error(t, err) @@ -553,15 +556,15 @@ func TestRealisClient_DrainHosts(t *testing.T) { }) t.Run("TestRealisClient_EndMaintenance", func(t *testing.T) { - _, _, err := r.EndMaintenance(hosts...) + _, err := r.EndMaintenance(hosts...) assert.NoError(t, err) // Monitor change to DRAINING and DRAINED mode - _, err = monitor.HostMaintenance( + _, err = r.HostMaintenanceMonitor( hosts, []aurora.MaintenanceMode{aurora.MaintenanceMode_NONE}, - 5, - 10) + 5*time.Second, + 10*time.Second) assert.NoError(t, err) }) @@ -578,23 +581,23 @@ func TestRealisClient_SLADrainHosts(t *testing.T) { } // Monitor change to DRAINING and DRAINED mode - hostResults, err := monitor.HostMaintenance( + hostResults, err := r.HostMaintenanceMonitor( hosts, []aurora.MaintenanceMode{aurora.MaintenanceMode_DRAINED, aurora.MaintenanceMode_DRAINING}, - 1, - 50) + 1*time.Second, + 50*time.Second) assert.Equal(t, map[string]bool{"localhost": true}, hostResults) assert.NoError(t, err) - _, _, err = r.EndMaintenance(hosts...) + _, err = r.EndMaintenance(hosts...) assert.NoError(t, err) // Monitor change to DRAINING and DRAINED mode - _, err = monitor.HostMaintenance( + _, err = r.HostMaintenanceMonitor( hosts, []aurora.MaintenanceMode{aurora.MaintenanceMode_NONE}, - 5, - 10) + 5*time.Second, + 10*time.Second) assert.NoError(t, err) } @@ -613,11 +616,9 @@ func TestRealisClient_SessionThreadSafety(t *testing.T) { Disk(10). InstanceCount(1000) // Impossible amount to go live in any sane machine - resp, err := r.CreateJob(job) + err := r.CreateJob(job) assert.NoError(t, err) - assert.Equal(t, aurora.ResponseCode_OK, resp.ResponseCode) - wg := sync.WaitGroup{} for i := 0; i < 20; i++ { @@ -628,15 +629,13 @@ func TestRealisClient_SessionThreadSafety(t *testing.T) { defer wg.Done() // Test Schedule status monitor for terminal state and timing out after 30 seconds - success, err := monitor.ScheduleStatus(job.JobKey(), job.GetInstanceCount(), aurora.LIVE_STATES, 1, 30) + success, err := r.ScheduleStatusMonitor(job.JobKey(), job.GetInstanceCount(), aurora.LIVE_STATES, 1, 30) assert.False(t, success) assert.Error(t, err) - resp, err := r.KillJob(job.JobKey()) + err = r.KillJob(job.JobKey()) assert.NoError(t, err) - assert.Equal(t, aurora.ResponseCode_OK, resp.ResponseCode) - }() } @@ -648,19 +647,15 @@ func TestRealisClient_SetQuota(t *testing.T) { var cpu = 3.5 var ram int64 = 20480 var disk int64 = 10240 - resp, err := r.SetQuota("vagrant", &cpu, &ram, &disk) + err := r.SetQuota("vagrant", &cpu, &ram, &disk) assert.NoError(t, err) - assert.Equal(t, aurora.ResponseCode_OK, resp.ResponseCode) t.Run("TestRealisClient_GetQuota", func(t *testing.T) { // Test GetQuota based on previously set values var result *aurora.GetQuotaResult_ - resp, err = r.GetQuota("vagrant") - if resp.GetResult_() != nil { - result = resp.GetResult_().GetQuotaResult_ - } + quotaResult, err := r.GetQuota("vagrant") + assert.NoError(t, err) - assert.Equal(t, aurora.ResponseCode_OK, resp.ResponseCode) - for res := range result.Quota.GetResources() { + for _, res := range quotaResult.GetQuota().GetResources() { switch true { case res.DiskMb != nil: assert.Equal(t, disk, *res.DiskMb) diff --git a/vendor/github.com/paypal/gorealis/response/response.go b/vendor/github.com/paypal/gorealis/response/response.go index b77348d..2eb1d5e 100644 --- a/vendor/github.com/paypal/gorealis/response/response.go +++ b/vendor/github.com/paypal/gorealis/response/response.go @@ -17,7 +17,6 @@ package response import ( "bytes" - "errors" "github.com/paypal/gorealis/gen-go/apache/aurora" ) @@ -39,18 +38,6 @@ func JobUpdateSummaries(resp *aurora.Response) []*aurora.JobUpdateSummary { return resp.GetResult_().GetGetJobUpdateSummariesResult_().GetUpdateSummaries() } -// Deprecated: Replaced by checks done inside of thriftCallHelper -func ResponseCodeCheck(resp *aurora.Response) (*aurora.Response, error) { - if resp == nil { - return resp, errors.New("Response is nil") - } - if resp.GetResponseCode() != aurora.ResponseCode_OK { - return resp, errors.New(CombineMessage(resp)) - } - - return resp, nil -} - // Based on aurora client: src/main/python/apache/aurora/client/base.py func CombineMessage(resp *aurora.Response) string { var buffer bytes.Buffer diff --git a/vendor/github.com/paypal/gorealis/retry.go b/vendor/github.com/paypal/gorealis/retry.go index 17b5c1a..59d0aa0 100644 --- a/vendor/github.com/paypal/gorealis/retry.go +++ b/vendor/github.com/paypal/gorealis/retry.go @@ -17,7 +17,10 @@ package realis import ( "io" "math/rand" + "net/http" "net/url" + "strconv" + "strings" "time" "git.apache.org/thrift.git/lib/go/thrift" @@ -116,12 +119,12 @@ func ExponentialBackoff(backoff Backoff, logger Logger, condition ConditionFunc) type auroraThriftCall func() (resp *aurora.Response, err error) // Duplicates the functionality of ExponentialBackoff but is specifically targeted towards ThriftCalls. -func (r *realisClient) thriftCallWithRetries(thriftCall auroraThriftCall) (*aurora.Response, error) { +func (c *Client) thriftCallWithRetries(thriftCall auroraThriftCall) (*aurora.Response, error) { var resp *aurora.Response var clientErr error var curStep int - backoff := r.config.backoff + backoff := c.config.backoff duration := backoff.Duration for curStep = 0; curStep < backoff.Steps; curStep++ { @@ -133,7 +136,7 @@ func (r *realisClient) thriftCallWithRetries(thriftCall auroraThriftCall) (*auro adjusted = Jitter(duration, backoff.Jitter) } - r.logger.Printf("A retriable error occurred during thrift call, backing off for %v before retry %v\n", adjusted, curStep) + c.logger.Printf("A retriable error occurred during thrift call, backing off for %v before retry %v\n", adjusted, curStep) time.Sleep(adjusted) duration = time.Duration(float64(duration) * backoff.Factor) @@ -143,12 +146,12 @@ func (r *realisClient) thriftCallWithRetries(thriftCall auroraThriftCall) (*auro // Placing this in an anonymous function in order to create a new, short-lived stack allowing unlock // to be run in case of a panic inside of thriftCall. func() { - r.lock.Lock() - defer r.lock.Unlock() + c.lock.Lock() + defer c.lock.Unlock() resp, clientErr = thriftCall() - r.logger.DebugPrintf("Aurora Thrift Call ended resp: %v clientErr: %v\n", resp, clientErr) + c.logger.DebugPrintf("Aurora Thrift Call ended resp: %v clientErr: %v\n", resp, clientErr) }() // Check if our thrift call is returning an error. This is a retriable event as we don't know @@ -156,12 +159,18 @@ func (r *realisClient) thriftCallWithRetries(thriftCall auroraThriftCall) (*auro if clientErr != nil { // Print out the error to the user - r.logger.Printf("Client Error: %v\n", clientErr) + c.logger.Printf("Client Error: %v\n", clientErr) // Determine if error is a temporary URL error by going up the stack e, ok := clientErr.(thrift.TTransportException) if ok { - r.logger.DebugPrint("Encountered a transport exception") + c.logger.DebugPrint("Encountered a transport exception") + + // TODO(rdelvalle): Figure out a better way to obtain the error code as this is a very brittle solution + // 401 Unauthorized means the wrong username and password were provided + if strings.Contains(e.Error(), strconv.Itoa(http.StatusUnauthorized)) { + return nil, errors.Wrap(clientErr, "wrong username or password provided") + } e, ok := e.Err().(*url.Error) if ok { @@ -176,7 +185,7 @@ func (r *realisClient) thriftCallWithRetries(thriftCall auroraThriftCall) (*auro // In the future, reestablish connection should be able to check if it is actually possible // to make a thrift call to Aurora. For now, a reconnect should always lead to a retry. - r.ReestablishConn() + c.ReestablishConn() } else { @@ -195,31 +204,31 @@ func (r *realisClient) thriftCallWithRetries(thriftCall auroraThriftCall) (*auro // If the response code is transient, continue retrying case aurora.ResponseCode_ERROR_TRANSIENT: - r.logger.Println("Aurora replied with Transient error code, retrying") + c.logger.Println("Aurora replied with Transient error code, retrying") continue - // Failure scenarios, these indicate a bad payload or a bad config. Stop retrying. + // Failure scenarios, these indicate a bad payload or a bad clientConfig. Stop retrying. case aurora.ResponseCode_INVALID_REQUEST, aurora.ResponseCode_ERROR, aurora.ResponseCode_AUTH_FAILED, aurora.ResponseCode_JOB_UPDATING_ERROR: - r.logger.Printf("Terminal Response Code %v from Aurora, won't retry\n", resp.GetResponseCode().String()) + c.logger.Printf("Terminal Response Code %v from Aurora, won't retry\n", resp.GetResponseCode().String()) return resp, errors.New(response.CombineMessage(resp)) // The only case that should fall down to here is a WARNING response code. // It is currently not used as a response in the scheduler so it is unknown how to handle it. default: - r.logger.DebugPrintf("unhandled response code %v received from Aurora\n", responseCode) + c.logger.DebugPrintf("unhandled response code %v received from Aurora\n", responseCode) return nil, errors.Errorf("unhandled response code from Aurora %v\n", responseCode.String()) } } } - r.logger.DebugPrintf("it took %v retries to complete this operation\n", curStep) + c.logger.DebugPrintf("it took %v retries to complete this operation\n", curStep) if curStep > 1 { - r.config.logger.Printf("retried this thrift call %d time(s)", curStep) + c.config.logger.Printf("retried this thrift call %d time(s)", curStep) } // Provide more information to the user wherever possible. diff --git a/vendor/github.com/paypal/gorealis/runTestsMac.sh b/vendor/github.com/paypal/gorealis/runTestsMac.sh index fcc17b1..bdadd8d 100755 --- a/vendor/github.com/paypal/gorealis/runTestsMac.sh +++ b/vendor/github.com/paypal/gorealis/runTestsMac.sh @@ -1,4 +1,4 @@ #!/bin/bash # Since we run our docker compose setup in bridge mode to be able to run on MacOS, we have to launch a Docker container within the bridge network in order to avoid any routing issues. -docker run -t -v $(pwd):/go/src/github.com/paypal/gorealis --network gorealis_aurora_cluster golang:1.10.3-stretch go test -v github.com/paypal/gorealis +docker run -t -v $(pwd):/go/src/github.com/paypal/gorealis --network gorealis_aurora_cluster golang:1.11.3-stretch go test -v github.com/paypal/gorealis diff --git a/vendor/github.com/paypal/gorealis/task.go b/vendor/github.com/paypal/gorealis/task.go new file mode 100644 index 0000000..c097a11 --- /dev/null +++ b/vendor/github.com/paypal/gorealis/task.go @@ -0,0 +1,367 @@ +/** + * 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. + */ + +package realis + +import ( + "strconv" + + "git.apache.org/thrift.git/lib/go/thrift" + "github.com/paypal/gorealis/gen-go/apache/aurora" +) + +type ResourceType int + +const ( + CPU ResourceType = iota + RAM + DISK +) + +const ( + dedicated = "dedicated" + portPrefix = "org.apache.aurora.port." +) + +type AuroraTask struct { + task *aurora.TaskConfig + resources map[ResourceType]*aurora.Resource + portCount int +} + +func NewTask() *AuroraTask { + numCpus := &aurora.Resource{} + ramMb := &aurora.Resource{} + diskMb := &aurora.Resource{} + + numCpus.NumCpus = new(float64) + ramMb.RamMb = new(int64) + diskMb.DiskMb = new(int64) + + resources := make(map[ResourceType]*aurora.Resource) + resources[CPU] = numCpus + resources[RAM] = ramMb + resources[DISK] = diskMb + + return &AuroraTask{task: &aurora.TaskConfig{ + Job: &aurora.JobKey{}, + MesosFetcherUris: make([]*aurora.MesosFetcherURI, 0), + Metadata: make([]*aurora.Metadata, 0), + Constraints: make([]*aurora.Constraint, 0), + // Container is a Union so one container field must be set. Set Mesos by default. + Container: NewMesosContainer().Build(), + Resources: []*aurora.Resource{numCpus, ramMb, diskMb}, + }, + resources: resources, + portCount: 0} +} + +// Helper method to convert aurora.TaskConfig to gorealis AuroraTask type +func TaskFromThrift(config *aurora.TaskConfig) *AuroraTask { + + newTask := NewTask() + + // Pass values using receivers as much as possible + newTask. + Environment(config.Job.Environment). + Role(config.Job.Role). + Name(config.Job.Name). + MaxFailure(config.MaxTaskFailures). + IsService(config.IsService) + + if config.Tier != nil { + newTask.Tier(*config.Tier) + } + + if config.ExecutorConfig != nil { + newTask. + ExecutorName(config.ExecutorConfig.Name). + ExecutorData(config.ExecutorConfig.Data) + } + + // Make a deep copy of the task's container + if config.Container != nil { + if config.Container.Mesos != nil { + mesosContainer := NewMesosContainer() + + if config.Container.Mesos.Image != nil { + if config.Container.Mesos.Image.Appc != nil { + mesosContainer.AppcImage(config.Container.Mesos.Image.Appc.Name, config.Container.Mesos.Image.Appc.ImageId) + } else if config.Container.Mesos.Image.Docker != nil { + mesosContainer.DockerImage(config.Container.Mesos.Image.Docker.Name, config.Container.Mesos.Image.Docker.Tag) + } + } + + for _, vol := range config.Container.Mesos.Volumes { + mesosContainer.AddVolume(vol.ContainerPath, vol.HostPath, vol.Mode) + } + + newTask.Container(mesosContainer) + } else if config.Container.Docker != nil { + dockerContainer := NewDockerContainer() + dockerContainer.Image(config.Container.Docker.Image) + + for _, param := range config.Container.Docker.Parameters { + dockerContainer.AddParameter(param.Name, param.Value) + } + + newTask.Container(dockerContainer) + } + } + + // Copy all ports + for _, resource := range config.Resources { + // Copy only ports, skip CPU, RAM, and DISK + if resource != nil { + if resource.NamedPort != nil { + newTask.task.Resources = append(newTask.task.Resources, &aurora.Resource{NamedPort: thrift.StringPtr(*resource.NamedPort)}) + newTask.portCount++ + } + + if resource.RamMb != nil { + newTask.RAM(*resource.RamMb) + } + + if resource.NumCpus != nil { + newTask.CPU(*resource.NumCpus) + } + + if resource.DiskMb != nil { + newTask.Disk(*resource.DiskMb) + } + } + } + + // Copy constraints + for _, constraint := range config.Constraints { + if constraint != nil && constraint.Constraint != nil { + + newConstraint := aurora.Constraint{Name: constraint.Name} + + taskConstraint := constraint.Constraint + if taskConstraint.Limit != nil { + newConstraint.Constraint = &aurora.TaskConstraint{Limit: &aurora.LimitConstraint{Limit: taskConstraint.Limit.Limit}} + newTask.task.Constraints = append(newTask.task.Constraints, &newConstraint) + + } else if taskConstraint.Value != nil { + + values := make([]string, 0) + for _, val := range taskConstraint.Value.Values { + values = append(values, val) + } + + newConstraint.Constraint = &aurora.TaskConstraint{ + Value: &aurora.ValueConstraint{Negated: taskConstraint.Value.Negated, Values: values}} + + newTask.task.Constraints = append(newTask.task.Constraints, &newConstraint) + } + } + } + + // Copy labels + for _, label := range config.Metadata { + newTask.task.Metadata = append(newTask.task.Metadata, &aurora.Metadata{Key: label.Key, Value: label.Value}) + } + + // Copy Mesos fetcher URIs + for _, uri := range config.MesosFetcherUris { + newTask.task.MesosFetcherUris = append( + newTask.task.MesosFetcherUris, + &aurora.MesosFetcherURI{Value: uri.Value, Extract: thrift.BoolPtr(*uri.Extract), Cache: thrift.BoolPtr(*uri.Cache)}) + } + + return newTask +} + +// Set AuroraTask Key environment. +func (t *AuroraTask) Environment(env string) *AuroraTask { + t.task.Job.Environment = env + return t +} + +// Set AuroraTask Key Role. +func (t *AuroraTask) Role(role string) *AuroraTask { + t.task.Job.Role = role + return t +} + +// Set AuroraTask Key Name. +func (t *AuroraTask) Name(name string) *AuroraTask { + t.task.Job.Name = name + return t +} + +// Set name of the executor that will the task will be configured to. +func (t *AuroraTask) ExecutorName(name string) *AuroraTask { + if t.task.ExecutorConfig == nil { + t.task.ExecutorConfig = aurora.NewExecutorConfig() + } + + t.task.ExecutorConfig.Name = name + return t +} + +// Will be included as part of entire task inside the scheduler that will be serialized. +func (t *AuroraTask) ExecutorData(data string) *AuroraTask { + if t.task.ExecutorConfig == nil { + t.task.ExecutorConfig = aurora.NewExecutorConfig() + } + + t.task.ExecutorConfig.Data = data + return t +} + +func (t *AuroraTask) CPU(cpus float64) *AuroraTask { + *t.resources[CPU].NumCpus = cpus + return t +} + +func (t *AuroraTask) RAM(ram int64) *AuroraTask { + *t.resources[RAM].RamMb = ram + return t +} + +func (t *AuroraTask) Disk(disk int64) *AuroraTask { + *t.resources[DISK].DiskMb = disk + return t +} + +func (t *AuroraTask) Tier(tier string) *AuroraTask { + t.task.Tier = &tier + return t +} + +// How many failures to tolerate before giving up. +func (t *AuroraTask) MaxFailure(maxFail int32) *AuroraTask { + t.task.MaxTaskFailures = maxFail + return t +} + +// Restart the job's tasks if they fail +func (t *AuroraTask) IsService(isService bool) *AuroraTask { + t.task.IsService = isService + return t +} + +// Add a list of URIs with the same extract and cache configuration. Scheduler must have +// --enable_mesos_fetcher flag enabled. Currently there is no duplicate detection. +func (t *AuroraTask) AddURIs(extract bool, cache bool, values ...string) *AuroraTask { + for _, value := range values { + t.task.MesosFetcherUris = append( + t.task.MesosFetcherUris, + &aurora.MesosFetcherURI{Value: value, Extract: &extract, Cache: &cache}) + } + return t +} + +// Adds a Mesos label to the job. Note that Aurora will add the +// prefix "org.apache.aurora.metadata." to the beginning of each key. +func (t *AuroraTask) AddLabel(key string, value string) *AuroraTask { + t.task.Metadata = append(t.task.Metadata, &aurora.Metadata{Key: key, Value: value}) + return t +} + +// Add a named port to the job configuration These are random ports as it's +// not currently possible to request specific ports using Aurora. +func (t *AuroraTask) AddNamedPorts(names ...string) *AuroraTask { + t.portCount += len(names) + for _, name := range names { + t.task.Resources = append(t.task.Resources, &aurora.Resource{NamedPort: &name}) + } + + return t +} + +// Adds a request for a number of ports to the job configuration. The names chosen for these ports +// will be org.apache.aurora.port.X, where X is the current port count for the job configuration +// starting at 0. These are random ports as it's not currently possible to request +// specific ports using Aurora. +func (t *AuroraTask) AddPorts(num int) *AuroraTask { + start := t.portCount + t.portCount += num + for i := start; i < t.portCount; i++ { + portName := portPrefix + strconv.Itoa(i) + t.task.Resources = append(t.task.Resources, &aurora.Resource{NamedPort: &portName}) + } + + return t +} + +// From Aurora Docs: +// Add a Value constraint +// name - Mesos slave attribute that the constraint is matched against. +// If negated = true , treat this as a 'not' - to avoid specific values. +// Values - list of values we look for in attribute name +func (t *AuroraTask) AddValueConstraint(name string, negated bool, values ...string) *AuroraTask { + t.task.Constraints = append(t.task.Constraints, + &aurora.Constraint{ + Name: name, + Constraint: &aurora.TaskConstraint{ + Value: &aurora.ValueConstraint{ + Negated: negated, + Values: values, + }, + Limit: nil, + }, + }) + + return t +} + +// From Aurora Docs: +// A constraint that specifies the maximum number of active tasks on a host with +// a matching attribute that may be scheduled simultaneously. +func (t *AuroraTask) AddLimitConstraint(name string, limit int32) *AuroraTask { + t.task.Constraints = append(t.task.Constraints, + &aurora.Constraint{ + Name: name, + Constraint: &aurora.TaskConstraint{ + Value: nil, + Limit: &aurora.LimitConstraint{Limit: limit}, + }, + }) + + return t +} + +// From Aurora Docs: +// dedicated attribute. Aurora treats this specially, and only allows matching jobs +// to run on these machines, and will only schedule matching jobs on these machines. +// When a job is created, the scheduler requires that the $role component matches +// the role field in the job configuration, and will reject the job creation otherwise. +// A wildcard (*) may be used for the role portion of the dedicated attribute, which +// will allow any owner to elect for a job to run on the host(s) +func (t *AuroraTask) AddDedicatedConstraint(role, name string) *AuroraTask { + t.AddValueConstraint(dedicated, false, role+"/"+name) + return t +} + +// Set a container to run for the job configuration to run. +func (t *AuroraTask) Container(container Container) *AuroraTask { + t.task.Container = container.Build() + return t +} + +func (t *AuroraTask) TaskConfig() *aurora.TaskConfig { + return t.task +} + +func (t *AuroraTask) JobKey() aurora.JobKey { + return *t.task.Job +} + +func (t *AuroraTask) Clone() *AuroraTask { + newTask := TaskFromThrift(t.task) + return newTask +} diff --git a/vendor/github.com/paypal/gorealis/task_test.go b/vendor/github.com/paypal/gorealis/task_test.go new file mode 100644 index 0000000..a2efa39 --- /dev/null +++ b/vendor/github.com/paypal/gorealis/task_test.go @@ -0,0 +1,57 @@ +/** + * 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. + */ + +package realis_test + +import ( + "testing" + + realis "github.com/paypal/gorealis" + "github.com/paypal/gorealis/gen-go/apache/aurora" + "github.com/stretchr/testify/assert" +) + +func TestAuroraTask_Clone(t *testing.T) { + + task0 := realis.NewTask(). + Environment("development"). + Role("ubuntu"). + Name("this_is_a_test"). + ExecutorName(aurora.AURORA_EXECUTOR_NAME). + ExecutorData("{fake:payload}"). + CPU(10). + RAM(643). + Disk(1000). + IsService(true). + AddPorts(10). + Tier("preferred"). + MaxFailure(23). + AddURIs(true, true, "testURI"). + AddLabel("Test", "Value"). + AddNamedPorts("test"). + AddValueConstraint("test", false, "testing"). + AddLimitConstraint("test_limit", 1). + AddDedicatedConstraint("ubuntu", "name"). + Container(realis.NewDockerContainer().AddParameter("hello", "world").Image("testImg")) + + task1 := task0.Clone() + + assert.EqualValues(t, task0, task1, "Clone does not return the correct deep copy of AuroraTask") + + task0.Container(realis.NewMesosContainer(). + AppcImage("test", "testing"). + AddVolume("test", "test", aurora.Mode_RW)) + task2 := task0.Clone() + assert.EqualValues(t, task0, task2, "Clone does not return the correct deep copy of AuroraTask") +} diff --git a/vendor/github.com/paypal/gorealis/updatejob.go b/vendor/github.com/paypal/gorealis/updatejob.go deleted file mode 100644 index 4ee4f14..0000000 --- a/vendor/github.com/paypal/gorealis/updatejob.go +++ /dev/null @@ -1,154 +0,0 @@ -/** - * 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. - */ - -package realis - -import ( - "github.com/paypal/gorealis/gen-go/apache/aurora" -) - -// Structure to collect all information required to create job update -type UpdateJob struct { - Job // SetInstanceCount for job is hidden, access via full qualifier - req *aurora.JobUpdateRequest -} - -// Create a default UpdateJob object. -func NewDefaultUpdateJob(config *aurora.TaskConfig) *UpdateJob { - - req := aurora.NewJobUpdateRequest() - req.TaskConfig = config - req.Settings = NewUpdateSettings() - - job := NewJob().(*AuroraJob) - job.jobConfig.TaskConfig = config - - // Rebuild resource map from TaskConfig - for ptr := range config.Resources { - if ptr.NumCpus != nil { - job.resources["cpu"].NumCpus = ptr.NumCpus - continue // Guard against Union violations that Go won't enforce - } - - if ptr.RamMb != nil { - job.resources["ram"].RamMb = ptr.RamMb - continue - } - - if ptr.DiskMb != nil { - job.resources["disk"].DiskMb = ptr.DiskMb - continue - } - } - - // Mirrors defaults set by Pystachio - req.Settings.UpdateOnlyTheseInstances = make(map[*aurora.Range]bool) - req.Settings.UpdateGroupSize = 1 - req.Settings.WaitForBatchCompletion = false - req.Settings.MinWaitInInstanceRunningMs = 45000 - req.Settings.MaxPerInstanceFailures = 0 - req.Settings.MaxFailedInstances = 0 - req.Settings.RollbackOnFailure = true - - //TODO(rdelvalle): Deep copy job struct to avoid unexpected behavior - return &UpdateJob{Job: job, req: req} -} - -func NewUpdateJob(config *aurora.TaskConfig, settings *aurora.JobUpdateSettings) *UpdateJob { - - req := aurora.NewJobUpdateRequest() - req.TaskConfig = config - req.Settings = settings - - job := NewJob().(*AuroraJob) - job.jobConfig.TaskConfig = config - - // Rebuild resource map from TaskConfig - for ptr := range config.Resources { - if ptr.NumCpus != nil { - job.resources["cpu"].NumCpus = ptr.NumCpus - continue // Guard against Union violations that Go won't enforce - } - - if ptr.RamMb != nil { - job.resources["ram"].RamMb = ptr.RamMb - continue - } - - if ptr.DiskMb != nil { - job.resources["disk"].DiskMb = ptr.DiskMb - continue - } - } - - //TODO(rdelvalle): Deep copy job struct to avoid unexpected behavior - return &UpdateJob{Job: job, req: req} -} - -// Set instance count the job will have after the update. -func (u *UpdateJob) InstanceCount(inst int32) *UpdateJob { - u.req.InstanceCount = inst - return u -} - -// Max number of instances being updated at any given moment. -func (u *UpdateJob) BatchSize(size int32) *UpdateJob { - u.req.Settings.UpdateGroupSize = size - return u -} - -// Minimum number of seconds a shard must remain in RUNNING state before considered a success. -func (u *UpdateJob) WatchTime(ms int32) *UpdateJob { - u.req.Settings.MinWaitInInstanceRunningMs = ms - return u -} - -// Wait for all instances in a group to be done before moving on. -func (u *UpdateJob) WaitForBatchCompletion(batchWait bool) *UpdateJob { - u.req.Settings.WaitForBatchCompletion = batchWait - return u -} - -// Max number of instance failures to tolerate before marking instance as FAILED. -func (u *UpdateJob) MaxPerInstanceFailures(inst int32) *UpdateJob { - u.req.Settings.MaxPerInstanceFailures = inst - return u -} - -// Max number of FAILED instances to tolerate before terminating the update. -func (u *UpdateJob) MaxFailedInstances(inst int32) *UpdateJob { - u.req.Settings.MaxFailedInstances = inst - return u -} - -// When False, prevents auto rollback of a failed update. -func (u *UpdateJob) RollbackOnFail(rollback bool) *UpdateJob { - u.req.Settings.RollbackOnFailure = rollback - return u -} - -func NewUpdateSettings() *aurora.JobUpdateSettings { - - us := new(aurora.JobUpdateSettings) - // Mirrors defaults set by Pystachio - us.UpdateOnlyTheseInstances = make(map[*aurora.Range]bool) - us.UpdateGroupSize = 1 - us.WaitForBatchCompletion = false - us.MinWaitInInstanceRunningMs = 45000 - us.MaxPerInstanceFailures = 0 - us.MaxFailedInstances = 0 - us.RollbackOnFailure = true - - return us -} diff --git a/vendor/github.com/paypal/gorealis/util.go b/vendor/github.com/paypal/gorealis/util.go new file mode 100644 index 0000000..324b12f --- /dev/null +++ b/vendor/github.com/paypal/gorealis/util.go @@ -0,0 +1,75 @@ +package realis + +import ( + "net/url" + "strings" + + "github.com/paypal/gorealis/gen-go/apache/aurora" + "github.com/pkg/errors" +) + +var ActiveStates = make(map[aurora.ScheduleStatus]bool) +var SlaveAssignedStates = make(map[aurora.ScheduleStatus]bool) +var LiveStates = make(map[aurora.ScheduleStatus]bool) +var TerminalStates = make(map[aurora.ScheduleStatus]bool) +var ActiveJobUpdateStates = make(map[aurora.JobUpdateStatus]bool) +var AwaitingPulseJobUpdateStates = make(map[aurora.JobUpdateStatus]bool) + +func init() { + for _, status := range aurora.ACTIVE_STATES { + ActiveStates[status] = true + } + + for _, status := range aurora.SLAVE_ASSIGNED_STATES { + SlaveAssignedStates[status] = true + } + + for _, status := range aurora.LIVE_STATES { + LiveStates[status] = true + } + + for _, status := range aurora.TERMINAL_STATES { + TerminalStates[status] = true + } + + for _, status := range aurora.ACTIVE_JOB_UPDATE_STATES { + ActiveJobUpdateStates[status] = true + } + for _, status := range aurora.AWAITNG_PULSE_JOB_UPDATE_STATES { + AwaitingPulseJobUpdateStates[status] = true + } +} + +func validateAndPopulateAuroraURL(urlStr string) (string, error) { + + // If no protocol defined, assume http + if !strings.Contains(urlStr, "://") { + urlStr = "http://" + urlStr + } + + u, err := url.Parse(urlStr) + + if err != nil { + return "", errors.Wrap(err, "error parsing url") + } + + // If no path provided assume /api + if u.Path == "" { + u.Path = "/api" + } + + // If no port provided, assume default 8081 + if u.Port() == "" { + u.Host = u.Host + ":8081" + } + + if !(u.Scheme == "http" || u.Scheme == "https") { + return "", errors.Errorf("only protocols http and https are supported %v\n", u.Scheme) + } + + if u.Path != "/api" { + return "", errors.Errorf("expected /api path %v\n", u.Path) + } + + return u.String(), nil +} diff --git a/vendor/github.com/paypal/gorealis/zk_test.go b/vendor/github.com/paypal/gorealis/zk_test.go index 4f05b46..c23ff75 100644 --- a/vendor/github.com/paypal/gorealis/zk_test.go +++ b/vendor/github.com/paypal/gorealis/zk_test.go @@ -20,7 +20,7 @@ import ( "testing" "time" - "github.com/paypal/gorealis" + realis "github.com/paypal/gorealis" "github.com/stretchr/testify/assert" )