commit
7461407ad0
444 changed files with 15543 additions and 8637 deletions
@ -0,0 +1,41 @@ |
||||
# gRPC Versioning Guide |
||||
|
||||
## Versioning Overview |
||||
|
||||
All gRPC implementations use a three-part version number (`vX.Y.Z`) and strictly follow [semantic versioning](https://semver.org/), which defines the semantics of major, minor and patch components of the version number. In addition to that, gRPC versions evolve according to these rules: |
||||
- **Major version bumps** only happen on rare occasions. In order to qualify for a major version bump, certain criteria described later in this document need to be met. Most importantly, a major version increase must not break wire compatibility with other gRPC implementations so that existing gRPC libraries remain fully interoperable. |
||||
- **Minor version bumps** happen approx. every 6 weeks as part of the normal release cycle as defined by the gRPC release process. A new release branch named vMAJOR.MINOR.PATCH) is cut every 6 weeks based on the [release schedule](https://github.com/grpc/grpc/blob/master/doc/grpc_release_schedule.md). |
||||
- **Patch version bump** corresponds to bugfixes done on release branch. |
||||
|
||||
There are also a few extra rules regarding adding new gRPC implementations (e.g. adding support for a new language) |
||||
- New implementations start at v0.x.y version and until they reach 1.0, they are considered not ready for production workloads. Breaking API changes are allowed in the 0.x releases as the library is not considered stable yet. |
||||
- The "1.0" release has semantics of GA (generally available) and being production ready. Requirements to reach this milestone are at least these |
||||
- basic RPC features are feature complete and tested |
||||
- implementation is tested for interoperability with other languages |
||||
- Public API is declared stable |
||||
- Once a gRPC library reaches 1.0 (or higher version), the normal rules for versioning apply. |
||||
|
||||
## Policy for updating the major version number |
||||
|
||||
To avoid user confusion and simplify reasoning, the gRPC releases in different languages try to stay synchronized in terms of major and minor version (all languages follow the same release schedule). Nevertheless, because we also strictly follow semantic versioning, there are circumstances in which a gRPC implementation needs to break the version synchronicity and do a major version bump independently of other languages. |
||||
|
||||
### Situations when it's ok to do a major version bump |
||||
- **change forced by the language ecosystem:** when the language itself or its standard libraries that we depend on make a breaking change (something which is out of our control), reacting with updating gRPC APIs may be the only adequate response. |
||||
- **voluntary change:** Even in non-forced situations, there might be circumstances in which a breaking API change makes sense and represents a net win, but as a rule of thumb breaking changes are very disruptive for users, cause user fragmentation and incur high maintenance costs. Therefore, breaking API changes should be very rare events that need to be considered with extreme care and the bar for accepting such changes is intentionally set very high. |
||||
Example scenarios where a breaking API change might be adequate: |
||||
- fixing a security problem which requires changes to API (need to consider the non-breaking alternatives first) |
||||
- the change leads to very significant gains to security, usability or development velocity. These gains need to be clearly documented and claims need to be supported by evidence (ideally by numbers). Costs to the ecosystem (impact on users, dev team etc.) need to be taken into account and the change still needs to be a net positive after subtracting the costs. |
||||
|
||||
All proposals to make a breaking change need to be documented as a gRFC document (in the grpc/proposal repository) that covers at least these areas: |
||||
- Description of the proposal including an explanation why the proposed change is one of the very rare events where a breaking change is introduced. |
||||
- Migration costs (= what does it mean for the users to migrate to the new API, what are the costs and risks associated with it) |
||||
- Pros of the change (what is gained and how) |
||||
- Cons of the change (e.g. user confusion, lost users and user trust, work needed, added maintenance costs) |
||||
- Plan for supporting users still using the old major version (in case migration to the new major version is not trivial or not everyone can migrate easily) |
||||
|
||||
Note that while major version bump allows changing APIs used by the users, it must not impact the interoperability of the implementation with other gRPC implementations and the previous major version released. That means that **no backward incompatible protocol changes are allowed**: old clients must continue interoperating correctly with new servers and new servers with old clients. |
||||
|
||||
### Situations that DON'T warrant a major version bump |
||||
- Because other languages do so. This is not a good enough reason because |
||||
doing a major version bump has high potential for disturbing and confusing the users of that language and fragmenting the user base and that is a bigger threat than having language implementations at different major version (provided the state is well documented). Having some languages at different major version seems to be unavoidable anyway (due to forced version bumps), unless we bump some languages artificially. |
||||
- "I don't like this API": In retrospect, some API decisions made in the past necessarily turn out more lucky than others, but without strong reasons that would be in favor of changing the API and without enough supporting evidence (see previous section), other strategy than making a breaking API change needs to be used. Possible options: Expand the API to make it useful again; mark API as deprecated while keeping its functionality and providing a new better API. |
@ -0,0 +1,65 @@ |
||||
# Copyright 2019 The gRPC Authors |
||||
# |
||||
# Licensed under the Apache License, Version 2.0 (the "License"); |
||||
# you may not use this file except in compliance with the License. |
||||
# You may obtain a copy of the License at |
||||
# |
||||
# http://www.apache.org/licenses/LICENSE-2.0 |
||||
# |
||||
# Unless required by applicable law or agreed to in writing, software |
||||
# distributed under the License is distributed on an "AS IS" BASIS, |
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
# See the License for the specific language governing permissions and |
||||
# limitations under the License. |
||||
|
||||
filegroup( |
||||
name = "_credentials_files", |
||||
testonly = 1, |
||||
srcs = [ |
||||
"credentials/localhost.key", |
||||
"credentials/localhost.crt", |
||||
"credentials/root.crt", |
||||
], |
||||
) |
||||
|
||||
py_library( |
||||
name = "_credentials", |
||||
testonly = 1, |
||||
srcs = ["_credentials.py"], |
||||
data = [":_credentials_files"], |
||||
) |
||||
|
||||
py_binary( |
||||
name = "customized_auth_client", |
||||
testonly = 1, |
||||
srcs = ["customized_auth_client.py"], |
||||
deps = [ |
||||
":_credentials", |
||||
"//src/python/grpcio/grpc:grpcio", |
||||
"//examples:py_helloworld", |
||||
], |
||||
) |
||||
|
||||
py_binary( |
||||
name = "customized_auth_server", |
||||
testonly = 1, |
||||
srcs = ["customized_auth_server.py"], |
||||
deps = [ |
||||
":_credentials", |
||||
"//src/python/grpcio/grpc:grpcio", |
||||
"//examples:py_helloworld", |
||||
|
||||
], |
||||
) |
||||
|
||||
py_test( |
||||
name = "_auth_example_test", |
||||
srcs = ["test/_auth_example_test.py"], |
||||
deps = [ |
||||
"//src/python/grpcio/grpc:grpcio", |
||||
"//examples:py_helloworld", |
||||
":customized_auth_client", |
||||
":customized_auth_server", |
||||
":_credentials", |
||||
], |
||||
) |
@ -0,0 +1,112 @@ |
||||
# Authentication Extension Example in gRPC Python |
||||
|
||||
## Check Our Guide First |
||||
|
||||
For most common usage of authentication in gRPC Python, please see our |
||||
[Authentication](https://grpc.io/docs/guides/auth/) guide's Python section. The |
||||
Guide includes following scenarios: |
||||
|
||||
1. Server SSL credential setup |
||||
2. Client SSL credential setup |
||||
3. Authenticate with Google using a JWT |
||||
4. Authenticate with Google using an Oauth2 token |
||||
|
||||
Also, the guide talks about gRPC specific credential types. |
||||
|
||||
### Channel credentials |
||||
|
||||
Channel credentials are attached to a `Channel` object, the most common use case |
||||
are SSL credentials. |
||||
|
||||
### Call credentials |
||||
|
||||
Call credentials are attached to a `Call` object (corresponding to an RPC). |
||||
Under the hood, the call credentials is a function that takes in information of |
||||
the RPC and modify metadata through callback. |
||||
|
||||
## About This Example |
||||
|
||||
This example focuses on extending gRPC authentication mechanism: |
||||
1) Customize authentication plugin; |
||||
2) Composite client side credentials; |
||||
3) Validation through interceptor on server side. |
||||
|
||||
## AuthMetadataPlugin: Manipulate metadata for each call |
||||
|
||||
Unlike TLS/SSL based authentication, the authentication extension in gRPC Python |
||||
lives at a much higher level of networking. It relies on the transmission of |
||||
metadata (HTTP Header) between client and server, instead of alternating the |
||||
transport protocol. |
||||
|
||||
gRPC Python provides a way to intercept an RPC and append authentication related |
||||
metadata through |
||||
[`AuthMetadataPlugin`](https://grpc.github.io/grpc/python/grpc.html#grpc.AuthMetadataPlugin). |
||||
Those in need of a custom authentication method may simply provide a concrete |
||||
implementation of the following interface: |
||||
|
||||
```Python |
||||
class AuthMetadataPlugin: |
||||
"""A specification for custom authentication.""" |
||||
|
||||
def __call__(self, context, callback): |
||||
"""Implements authentication by passing metadata to a callback. |
||||
|
||||
Implementations of this method must not block. |
||||
|
||||
Args: |
||||
context: An AuthMetadataContext providing information on the RPC that |
||||
the plugin is being called to authenticate. |
||||
callback: An AuthMetadataPluginCallback to be invoked either |
||||
synchronously or asynchronously. |
||||
""" |
||||
``` |
||||
|
||||
Then pass the instance of the concrete implementation to |
||||
`grpc.metadata_call_credentials` function to be converted into a |
||||
`CallCredentials` object. Please NOTE that it is possible to pass a Python |
||||
function object directly, but we recommend to inherit from the base class to |
||||
ensure implementation correctness. |
||||
|
||||
|
||||
```Python |
||||
def metadata_call_credentials(metadata_plugin, name=None): |
||||
"""Construct CallCredentials from an AuthMetadataPlugin. |
||||
|
||||
Args: |
||||
metadata_plugin: An AuthMetadataPlugin to use for authentication. |
||||
name: An optional name for the plugin. |
||||
|
||||
Returns: |
||||
A CallCredentials. |
||||
""" |
||||
``` |
||||
|
||||
The `CallCredentials` object can be passed directly into an RPC like: |
||||
|
||||
```Python |
||||
call_credentials = grpc.metadata_call_credentials(my_foo_plugin) |
||||
stub.FooRpc(request, credentials=call_credentials) |
||||
``` |
||||
|
||||
Or you can use `ChannelCredentials` and `CallCredentials` at the same time by |
||||
combining them: |
||||
|
||||
```Python |
||||
channel_credentials = ... |
||||
call_credentials = ... |
||||
composite_credentials = grpc.composite_channel_credentials( |
||||
channel_credential, |
||||
call_credentials) |
||||
channel = grpc.secure_channel(server_address, composite_credentials) |
||||
``` |
||||
|
||||
It is also possible to apply multiple `CallCredentials` to a single RPC: |
||||
|
||||
```Python |
||||
call_credentials_foo = ... |
||||
call_credentials_bar = ... |
||||
call_credentials = grpc.composite_call_credentials( |
||||
call_credentials_foo, |
||||
call_credentials_bar) |
||||
stub.FooRpc(request, credentials=call_credentials) |
||||
``` |
@ -0,0 +1,31 @@ |
||||
# Copyright 2019 The gRPC Authors |
||||
# |
||||
# Licensed under the Apache License, Version 2.0 (the "License"); |
||||
# you may not use this file except in compliance with the License. |
||||
# You may obtain a copy of the License at |
||||
# |
||||
# http://www.apache.org/licenses/LICENSE-2.0 |
||||
# |
||||
# Unless required by applicable law or agreed to in writing, software |
||||
# distributed under the License is distributed on an "AS IS" BASIS, |
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
# See the License for the specific language governing permissions and |
||||
# limitations under the License. |
||||
"""Loading SSL credentials for gRPC Python authentication example.""" |
||||
|
||||
from __future__ import absolute_import |
||||
from __future__ import division |
||||
from __future__ import print_function |
||||
|
||||
import os |
||||
|
||||
|
||||
def _load_credential_from_file(filepath): |
||||
real_path = os.path.join(os.path.dirname(__file__), filepath) |
||||
with open(real_path, 'rb') as f: |
||||
return f.read() |
||||
|
||||
|
||||
SERVER_CERTIFICATE = _load_credential_from_file('credentials/localhost.crt') |
||||
SERVER_CERTIFICATE_KEY = _load_credential_from_file('credentials/localhost.key') |
||||
ROOT_CERTIFICATE = _load_credential_from_file('credentials/root.crt') |
@ -0,0 +1,19 @@ |
||||
-----BEGIN CERTIFICATE----- |
||||
MIIDFjCCAf4CCQCzrLIhrWa55zANBgkqhkiG9w0BAQsFADBCMQswCQYDVQQGEwJV |
||||
UzETMBEGA1UECAwKQ2FsaWZvcm5pYTEPMA0GA1UECgwGR29vZ2xlMQ0wCwYDVQQL |
||||
DARnUlBDMCAXDTE5MDYyNDIyMjIzM1oYDzIxMTkwNTMxMjIyMjMzWjBWMQswCQYD |
||||
VQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEPMA0GA1UECgwGR29vZ2xlMQ0w |
||||
CwYDVQQLDARnUlBDMRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEB |
||||
AQUAA4IBDwAwggEKAoIBAQCtCW0TjugnIUu8BEVIYvdMP+/2GENQDjZhZ8eKR5C6 |
||||
toDGbgjsDtt/GxISAg4cg70fIvy0XolnGPZodvfHDM4lJ7yHBOdZD8TXQoE6okR7 |
||||
HZuLUJ20M0pXgWqtRewKRUjuYsSDXBnzLiZw1dcv9nGpo+Bqa8NonpiGRRpEkshF |
||||
D6T9KU9Ts/x+wMQBIra2Gj0UMh79jPhUuxcYAQA0JQGivnOtdwuPiumpnUT8j8h6 |
||||
tWg5l01EsCZWJecCF85KnGpJEVYPyPqBqGsy0nGS9plGotOWF87+jyUQt+KD63xA |
||||
aBmTro86mKDDKEK4JvzjVeMGz2UbVcLPiiZnErTFaiXJAgMBAAEwDQYJKoZIhvcN |
||||
AQELBQADggEBAKsDgOPCWp5WCy17vJbRlgfgk05sVNIHZtzrmdswjBmvSg8MUpep |
||||
XqcPNUpsljAXsf9UM5IFEMRdilUsFGWvHjBEtNAW8WUK9UV18WRuU//0w1Mp5HAN |
||||
xUEKb4BoyZr65vlCnTR+AR5c9FfPvLibhr5qHs2RA8Y3GyLOcGqBWed87jhdQLCc |
||||
P1bxB+96le5JeXq0tw215lxonI2/3ZYVK4/ok9gwXrQoWm8YieJqitk/ZQ4S17/4 |
||||
pynHtDfdxLn23EXeGx+UTxJGfpRmhEZdJ+MN7QGYoomzx5qS5XoYKxRNrDlirJpr |
||||
OqXIn8E1it+6d5gOZfuHawcNGhRLplE/pfA= |
||||
-----END CERTIFICATE----- |
@ -0,0 +1,27 @@ |
||||
-----BEGIN RSA PRIVATE KEY----- |
||||
MIIEogIBAAKCAQEArQltE47oJyFLvARFSGL3TD/v9hhDUA42YWfHikeQuraAxm4I |
||||
7A7bfxsSEgIOHIO9HyL8tF6JZxj2aHb3xwzOJSe8hwTnWQ/E10KBOqJEex2bi1Cd |
||||
tDNKV4FqrUXsCkVI7mLEg1wZ8y4mcNXXL/ZxqaPgamvDaJ6YhkUaRJLIRQ+k/SlP |
||||
U7P8fsDEASK2tho9FDIe/Yz4VLsXGAEANCUBor5zrXcLj4rpqZ1E/I/IerVoOZdN |
||||
RLAmViXnAhfOSpxqSRFWD8j6gahrMtJxkvaZRqLTlhfO/o8lELfig+t8QGgZk66P |
||||
OpigwyhCuCb841XjBs9lG1XCz4omZxK0xWolyQIDAQABAoIBADeq/Kh6JT3RfGf0 |
||||
h8WN8TlaqHxnueAbcmtL0+oss+cdp7gu1jf7X6o4r0uT1a5ew40s2Fe+wj2kzkE1 |
||||
ZOlouTlC22gkr7j7Vbxa7PBMG/Pvxoa/XL0IczZLsGImSJXVTG1E4SvRiZeulTdf |
||||
1GbdxhtpWV1jZe5Wd4Na3+SHxF5S7m3PrHiZlYdz1ND+8XZs1NlL9+ej72qSFul9 |
||||
t/QjMWJ9pky/Wad5abnRLRyOsg+BsgnXbkUy2rD89ZxFMLda9pzXo3TPyAlBHonr |
||||
mkEsE4eRMWMpjBM79JbeyDdHn/cs/LjAZrzeDf7ugXr2CHQpKaM5O0PsNHezJII9 |
||||
L5kCfzECgYEA4M/rz1UP1/BJoSqigUlSs0tPAg8a5UlkVsh6Osuq72IPNo8qg/Fw |
||||
oV/IiIS+q+obRcFj1Od3PGdTpCJwW5dzd2fXBQGmGdj0HucnCrs13RtBh91JiF5i |
||||
y/YYI9KfgOG2ZT9gG68T0gTs6jRrS3Qd83npqjrkJqMOd7s00MK9tUcCgYEAxQq7 |
||||
T541oCYHSBRIIb0IrR25krZy9caxzCqPDwOcuuhaCqCiaq+ATvOWlSfgecm4eH0K |
||||
PCH0xlWxG0auPEwm4pA8+/WR/XJwscPZMuoht1EoKy1his4eKx/s7hHNeO6KOF0V |
||||
Y/zqIiuZnEwUoKbn7EqqNFSTT65PJKyGsICJFG8CgYAfaw9yl1myfQNdQb8aQGwN |
||||
YJ33FLNWje427qeeZe5KrDKiFloDvI9YDjHRWnPnRL1w/zj7fSm9yFb5HlMDieP6 |
||||
MQnsyjEzdY2QcA+VwVoiv3dmDHgFVeOKy6bOAtaFxYWfGr9MvygO9t9BT/gawGyb |
||||
JVORlc9i0vDnrMMR1dV7awKBgBpTWLtGc/u1mPt0Wj7HtsUKV6TWY32a0l5owTxM |
||||
S0BdksogtBJ06DukJ9Y9wawD23WdnyRxlPZ6tHLkeprrwbY7dypioOKvy4a0l+xJ |
||||
g7+uRCOgqIuXBkjUtx8HmeAyXp0xMo5tWArAsIFFWOwt4IadYygitJvMuh44PraO |
||||
NcJZAoGADEiV0dheXUCVr8DrtSom8DQMj92/G/FIYjXL8OUhh0+F+YlYP0+F8PEU |
||||
yYIWEqL/S5tVKYshimUXQa537JcRKsTVJBG/ZKD2kuqgOc72zQy3oplimXeJDCXY |
||||
h2eAQ0u8GN6tN9C4t8Kp4a3y6FGsxgu+UTxdnL3YQ+yHAVhtCzo= |
||||
-----END RSA PRIVATE KEY----- |
@ -0,0 +1,20 @@ |
||||
-----BEGIN CERTIFICATE----- |
||||
MIIDWTCCAkGgAwIBAgIJAPOConZMwykwMA0GCSqGSIb3DQEBCwUAMEIxCzAJBgNV |
||||
BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMQ8wDQYDVQQKDAZHb29nbGUxDTAL |
||||
BgNVBAsMBGdSUEMwIBcNMTkwNjI0MjIyMDA3WhgPMjExOTA1MzEyMjIwMDdaMEIx |
||||
CzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMQ8wDQYDVQQKDAZHb29n |
||||
bGUxDTALBgNVBAsMBGdSUEMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB |
||||
AQCwqei3TfyLidnQNDJ2lierMYo229K92DuORni7nSjJQ59Jc3dNMsmqGQJjCD8o |
||||
6mTlKM/oCbs27Wpx+OxcOLvT95j2kiDGca1fCvaMdguIod09SWiyMpv/hp0trLv7 |
||||
NJIKHznath6rHYX2Ii3fZ1yCPzyQbEPSAA+GNpoNm1v1ZWmWKke9v7vLlS3inNlW |
||||
Mt9jepK7DrtbNZnVDjeItnppBSbVYRMxIyNHkepFbqXx5TpkCvl4M4XQZw9bfSxQ |
||||
i3WZ3q+T1Tw//OUdPNc+OfMhu0MA0QoMwikskP0NaIC3dbJZ5Ogx0RcnaB4E+9C6 |
||||
O/znUEh3WuKVl5HXBF+UwWoFAgMBAAGjUDBOMB0GA1UdDgQWBBRm3JIgzgK4G97J |
||||
fbMGatWMZc7V3jAfBgNVHSMEGDAWgBRm3JIgzgK4G97JfbMGatWMZc7V3jAMBgNV |
||||
HRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQCNiV8x41if094ry2srS0YucpiN |
||||
3rTPk08FOLsENTMYai524TGXJti1P6ofGr5KXCL0uxTByHE3fEiMMud2TIY5iHQo |
||||
Y4mzDTTcb+Q7yKHwYZMlcp6nO8W+NeY5t+S0JPHhb8deKWepcN2UpXBUYQLw7AiE |
||||
l96T9Gi+vC9h/XE5IVwHFQXTxf5UYzXtW1nfapvrOONg/ms41dgmrRKIi+knWfiJ |
||||
FdHpHX2sfDAoJtnpEISX+nxRGNVTLY64utXWm4yxaZJshvy2s8zWJgRg7rtwAhTT |
||||
Np9E9MnihXLEmDI4Co9XlLPJyZFmqImsbmVuKFeQOCiLAoPJaMI2lbi7fiTo |
||||
-----END CERTIFICATE----- |
@ -0,0 +1,105 @@ |
||||
# Copyright 2019 The gRPC Authors |
||||
# |
||||
# Licensed under the Apache License, Version 2.0 (the "License"); |
||||
# you may not use this file except in compliance with the License. |
||||
# You may obtain a copy of the License at |
||||
# |
||||
# http://www.apache.org/licenses/LICENSE-2.0 |
||||
# |
||||
# Unless required by applicable law or agreed to in writing, software |
||||
# distributed under the License is distributed on an "AS IS" BASIS, |
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
# See the License for the specific language governing permissions and |
||||
# limitations under the License. |
||||
"""Client of the Python example of customizing authentication mechanism.""" |
||||
|
||||
from __future__ import absolute_import |
||||
from __future__ import division |
||||
from __future__ import print_function |
||||
|
||||
import argparse |
||||
import contextlib |
||||
import logging |
||||
|
||||
import grpc |
||||
from examples import helloworld_pb2 |
||||
from examples import helloworld_pb2_grpc |
||||
from examples.python.auth import _credentials |
||||
|
||||
_LOGGER = logging.getLogger(__name__) |
||||
_LOGGER.setLevel(logging.INFO) |
||||
|
||||
_ONE_DAY_IN_SECONDS = 60 * 60 * 24 |
||||
|
||||
_SERVER_ADDR_TEMPLATE = 'localhost:%d' |
||||
_SIGNATURE_HEADER_KEY = 'x-signature' |
||||
|
||||
|
||||
class AuthGateway(grpc.AuthMetadataPlugin): |
||||
|
||||
def __call__(self, context, callback): |
||||
"""Implements authentication by passing metadata to a callback. |
||||
|
||||
Implementations of this method must not block. |
||||
|
||||
Args: |
||||
context: An AuthMetadataContext providing information on the RPC that |
||||
the plugin is being called to authenticate. |
||||
callback: An AuthMetadataPluginCallback to be invoked either |
||||
synchronously or asynchronously. |
||||
""" |
||||
# Example AuthMetadataContext object: |
||||
# AuthMetadataContext( |
||||
# service_url=u'https://localhost:50051/helloworld.Greeter', |
||||
# method_name=u'SayHello') |
||||
signature = context.method_name[::-1] |
||||
callback(((_SIGNATURE_HEADER_KEY, signature),), None) |
||||
|
||||
|
||||
@contextlib.contextmanager |
||||
def create_client_channel(addr): |
||||
# Call credential object will be invoked for every single RPC |
||||
call_credentials = grpc.metadata_call_credentials( |
||||
AuthGateway(), name='auth gateway') |
||||
# Channel credential will be valid for the entire channel |
||||
channel_credential = grpc.ssl_channel_credentials( |
||||
_credentials.ROOT_CERTIFICATE) |
||||
# Combining channel credentials and call credentials together |
||||
composite_credentials = grpc.composite_channel_credentials( |
||||
channel_credential, |
||||
call_credentials, |
||||
) |
||||
channel = grpc.secure_channel(addr, composite_credentials) |
||||
yield channel |
||||
|
||||
|
||||
def send_rpc(channel): |
||||
stub = helloworld_pb2_grpc.GreeterStub(channel) |
||||
request = helloworld_pb2.HelloRequest(name='you') |
||||
try: |
||||
response = stub.SayHello(request) |
||||
except grpc.RpcError as rpc_error: |
||||
_LOGGER.error('Received error: %s', rpc_error) |
||||
return rpc_error |
||||
else: |
||||
_LOGGER.info('Received message: %s', response) |
||||
return response |
||||
|
||||
|
||||
def main(): |
||||
parser = argparse.ArgumentParser() |
||||
parser.add_argument( |
||||
'--port', |
||||
nargs='?', |
||||
type=int, |
||||
default=50051, |
||||
help='the address of server') |
||||
args = parser.parse_args() |
||||
|
||||
with create_client_channel(_SERVER_ADDR_TEMPLATE % args.port) as channel: |
||||
send_rpc(channel) |
||||
|
||||
|
||||
if __name__ == '__main__': |
||||
logging.basicConfig(level=logging.INFO) |
||||
main() |
@ -0,0 +1,110 @@ |
||||
# Copyright 2019 The gRPC Authors |
||||
# |
||||
# Licensed under the Apache License, Version 2.0 (the "License"); |
||||
# you may not use this file except in compliance with the License. |
||||
# You may obtain a copy of the License at |
||||
# |
||||
# http://www.apache.org/licenses/LICENSE-2.0 |
||||
# |
||||
# Unless required by applicable law or agreed to in writing, software |
||||
# distributed under the License is distributed on an "AS IS" BASIS, |
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
# See the License for the specific language governing permissions and |
||||
# limitations under the License. |
||||
"""Server of the Python example of customizing authentication mechanism.""" |
||||
|
||||
from __future__ import absolute_import |
||||
from __future__ import division |
||||
from __future__ import print_function |
||||
|
||||
import argparse |
||||
import contextlib |
||||
import logging |
||||
import time |
||||
from concurrent import futures |
||||
|
||||
import grpc |
||||
from examples import helloworld_pb2 |
||||
from examples import helloworld_pb2_grpc |
||||
from examples.python.auth import _credentials |
||||
|
||||
_LOGGER = logging.getLogger(__name__) |
||||
_LOGGER.setLevel(logging.INFO) |
||||
|
||||
_ONE_DAY_IN_SECONDS = 60 * 60 * 24 |
||||
|
||||
_LISTEN_ADDRESS_TEMPLATE = 'localhost:%d' |
||||
_SIGNATURE_HEADER_KEY = 'x-signature' |
||||
|
||||
|
||||
class SignatureValidationInterceptor(grpc.ServerInterceptor): |
||||
|
||||
def __init__(self): |
||||
|
||||
def abort(ignored_request, context): |
||||
context.abort(grpc.StatusCode.UNAUTHENTICATED, 'Invalid signature') |
||||
|
||||
self._abortion = grpc.unary_unary_rpc_method_handler(abort) |
||||
|
||||
def intercept_service(self, continuation, handler_call_details): |
||||
# Example HandlerCallDetails object: |
||||
# _HandlerCallDetails( |
||||
# method=u'/helloworld.Greeter/SayHello', |
||||
# invocation_metadata=...) |
||||
method_name = handler_call_details.method.split('/')[-1] |
||||
expected_metadata = (_SIGNATURE_HEADER_KEY, method_name[::-1]) |
||||
if expected_metadata in handler_call_details.invocation_metadata: |
||||
return continuation(handler_call_details) |
||||
else: |
||||
return self._abortion |
||||
|
||||
|
||||
class SimpleGreeter(helloworld_pb2_grpc.GreeterServicer): |
||||
|
||||
def SayHello(self, request, unused_context): |
||||
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) |
||||
|
||||
|
||||
@contextlib.contextmanager |
||||
def run_server(port): |
||||
# Bind interceptor to server |
||||
server = grpc.server( |
||||
futures.ThreadPoolExecutor(), |
||||
interceptors=(SignatureValidationInterceptor(),)) |
||||
helloworld_pb2_grpc.add_GreeterServicer_to_server(SimpleGreeter(), server) |
||||
|
||||
# Loading credentials |
||||
server_credentials = grpc.ssl_server_credentials((( |
||||
_credentials.SERVER_CERTIFICATE_KEY, |
||||
_credentials.SERVER_CERTIFICATE, |
||||
),)) |
||||
|
||||
# Pass down credentials |
||||
port = server.add_secure_port(_LISTEN_ADDRESS_TEMPLATE % port, |
||||
server_credentials) |
||||
|
||||
server.start() |
||||
try: |
||||
yield port |
||||
finally: |
||||
server.stop(0) |
||||
|
||||
|
||||
def main(): |
||||
parser = argparse.ArgumentParser() |
||||
parser.add_argument( |
||||
'--port', nargs='?', type=int, default=50051, help='the listening port') |
||||
args = parser.parse_args() |
||||
|
||||
with run_server(args.port) as port: |
||||
logging.info('Server is listening at port :%d', port) |
||||
try: |
||||
while True: |
||||
time.sleep(_ONE_DAY_IN_SECONDS) |
||||
except KeyboardInterrupt: |
||||
pass |
||||
|
||||
|
||||
if __name__ == '__main__': |
||||
logging.basicConfig(level=logging.INFO) |
||||
main() |
@ -0,0 +1,56 @@ |
||||
# Copyright 2019 The gRPC Authors |
||||
# |
||||
# Licensed under the Apache License, Version 2.0 (the "License"); |
||||
# you may not use this file except in compliance with the License. |
||||
# You may obtain a copy of the License at |
||||
# |
||||
# http://www.apache.org/licenses/LICENSE-2.0 |
||||
# |
||||
# Unless required by applicable law or agreed to in writing, software |
||||
# distributed under the License is distributed on an "AS IS" BASIS, |
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
# See the License for the specific language governing permissions and |
||||
# limitations under the License. |
||||
"""Test for gRPC Python authentication example.""" |
||||
|
||||
from __future__ import absolute_import |
||||
from __future__ import division |
||||
from __future__ import print_function |
||||
|
||||
import unittest |
||||
|
||||
import grpc |
||||
from examples.python.auth import _credentials |
||||
from examples.python.auth import customized_auth_client |
||||
from examples.python.auth import customized_auth_server |
||||
|
||||
_SERVER_ADDR_TEMPLATE = 'localhost:%d' |
||||
|
||||
|
||||
class AuthExampleTest(unittest.TestCase): |
||||
|
||||
def test_successful_call(self): |
||||
with customized_auth_server.run_server(0) as port: |
||||
with customized_auth_client.create_client_channel( |
||||
_SERVER_ADDR_TEMPLATE % port) as channel: |
||||
customized_auth_client.send_rpc(channel) |
||||
# No unhandled exception raised, test passed! |
||||
|
||||
def test_no_channel_credential(self): |
||||
with customized_auth_server.run_server(0) as port: |
||||
with grpc.insecure_channel(_SERVER_ADDR_TEMPLATE % port) as channel: |
||||
resp = customized_auth_client.send_rpc(channel) |
||||
self.assertEqual(resp.code(), grpc.StatusCode.UNAVAILABLE) |
||||
|
||||
def test_no_call_credential(self): |
||||
with customized_auth_server.run_server(0) as port: |
||||
channel_credential = grpc.ssl_channel_credentials( |
||||
_credentials.ROOT_CERTIFICATE) |
||||
with grpc.secure_channel(_SERVER_ADDR_TEMPLATE % port, |
||||
channel_credential) as channel: |
||||
resp = customized_auth_client.send_rpc(channel) |
||||
self.assertEqual(resp.code(), grpc.StatusCode.UNAUTHENTICATED) |
||||
|
||||
|
||||
if __name__ == '__main__': |
||||
unittest.main(verbosity=2) |
@ -0,0 +1,44 @@ |
||||
# Copyright 2019 The gRPC Authors |
||||
# |
||||
# Licensed under the Apache License, Version 2.0 (the "License"); |
||||
# you may not use this file except in compliance with the License. |
||||
# You may obtain a copy of the License at |
||||
# |
||||
# http://www.apache.org/licenses/LICENSE-2.0 |
||||
# |
||||
# Unless required by applicable law or agreed to in writing, software |
||||
# distributed under the License is distributed on an "AS IS" BASIS, |
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
# See the License for the specific language governing permissions and |
||||
# limitations under the License. |
||||
|
||||
py_binary( |
||||
name = "server", |
||||
srcs = ["server.py"], |
||||
deps = [ |
||||
"//src/python/grpcio/grpc:grpcio", |
||||
"//examples:py_helloworld", |
||||
], |
||||
srcs_version = "PY2AND3", |
||||
) |
||||
|
||||
py_binary( |
||||
name = "client", |
||||
srcs = ["client.py"], |
||||
deps = [ |
||||
"//src/python/grpcio/grpc:grpcio", |
||||
"//examples:py_helloworld", |
||||
], |
||||
srcs_version = "PY2AND3", |
||||
) |
||||
|
||||
py_test( |
||||
name = "test/compression_example_test", |
||||
srcs = ["test/compression_example_test.py"], |
||||
srcs_version = "PY2AND3", |
||||
data = [ |
||||
":client", |
||||
":server", |
||||
], |
||||
size = "small", |
||||
) |
@ -0,0 +1,58 @@ |
||||
## Compression with gRPC Python |
||||
|
||||
gRPC offers lossless compression options in order to decrease the number of bits |
||||
transferred over the wire. Three levels of compression are available: |
||||
|
||||
- `grpc.Compression.NoCompression` - No compression is applied to the payload. (default) |
||||
- `grpc.Compression.Deflate` - The "Deflate" algorithm is applied to the payload. |
||||
- `grpc.Compression.Gzip` - The Gzip algorithm is applied to the payload. |
||||
|
||||
The default option on both clients and servers is `grpc.Compression.NoCompression`. |
||||
|
||||
See [the gRPC Compression Spec](https://github.com/grpc/grpc/blob/master/doc/compression.md) |
||||
for more information. |
||||
|
||||
### Client Side Compression |
||||
|
||||
Compression may be set at two levels on the client side. |
||||
|
||||
#### At the channel level |
||||
|
||||
```python |
||||
with grpc.insecure_channel('foo.bar:1234', compression=grpc.Compression.Gzip) as channel: |
||||
use_channel(channel) |
||||
``` |
||||
|
||||
#### At the call level |
||||
|
||||
Setting the compression method at the call level will override any settings on |
||||
the channel level. |
||||
|
||||
```python |
||||
stub = helloworld_pb2_grpc.GreeterStub(channel) |
||||
response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'), |
||||
compression=grpc.Compression.Deflate) |
||||
``` |
||||
|
||||
|
||||
### Server Side Compression |
||||
|
||||
Additionally, compression may be set at two levels on the server side. |
||||
|
||||
#### On the entire server |
||||
|
||||
```python |
||||
server = grpc.server(futures.ThreadPoolExecutor(), |
||||
compression=grpc.Compression.Gzip) |
||||
``` |
||||
|
||||
#### For an individual RPC |
||||
|
||||
```python |
||||
def SayHello(self, request, context): |
||||
context.set_response_compression(grpc.Compression.NoCompression) |
||||
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) |
||||
``` |
||||
|
||||
Setting the compression method for an individual RPC will override any setting |
||||
supplied at server creation time. |
@ -0,0 +1,76 @@ |
||||
# Copyright 2019 the gRPC authors. |
||||
# |
||||
# Licensed under the Apache License, Version 2.0 (the "License"); |
||||
# you may not use this file except in compliance with the License. |
||||
# You may obtain a copy of the License at |
||||
# |
||||
# http://www.apache.org/licenses/LICENSE-2.0 |
||||
# |
||||
# Unless required by applicable law or agreed to in writing, software |
||||
# distributed under the License is distributed on an "AS IS" BASIS, |
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
# See the License for the specific language governing permissions and |
||||
# limitations under the License. |
||||
"""An example of compression on the client side with gRPC.""" |
||||
|
||||
from __future__ import absolute_import |
||||
from __future__ import division |
||||
from __future__ import print_function |
||||
|
||||
import argparse |
||||
import logging |
||||
import grpc |
||||
|
||||
from examples import helloworld_pb2 |
||||
from examples import helloworld_pb2_grpc |
||||
|
||||
_DESCRIPTION = 'A client capable of compression.' |
||||
_COMPRESSION_OPTIONS = { |
||||
"none": grpc.Compression.NoCompression, |
||||
"deflate": grpc.Compression.Deflate, |
||||
"gzip": grpc.Compression.Gzip, |
||||
} |
||||
|
||||
_LOGGER = logging.getLogger(__name__) |
||||
|
||||
|
||||
def run_client(channel_compression, call_compression, target): |
||||
with grpc.insecure_channel( |
||||
target, compression=channel_compression) as channel: |
||||
stub = helloworld_pb2_grpc.GreeterStub(channel) |
||||
response = stub.SayHello( |
||||
helloworld_pb2.HelloRequest(name='you'), |
||||
compression=call_compression, |
||||
wait_for_ready=True) |
||||
print("Response: {}".format(response)) |
||||
|
||||
|
||||
def main(): |
||||
parser = argparse.ArgumentParser(description=_DESCRIPTION) |
||||
parser.add_argument( |
||||
'--channel_compression', |
||||
default='none', |
||||
nargs='?', |
||||
choices=_COMPRESSION_OPTIONS.keys(), |
||||
help='The compression method to use for the channel.') |
||||
parser.add_argument( |
||||
'--call_compression', |
||||
default='none', |
||||
nargs='?', |
||||
choices=_COMPRESSION_OPTIONS.keys(), |
||||
help='The compression method to use for an individual call.') |
||||
parser.add_argument( |
||||
'--server', |
||||
default='localhost:50051', |
||||
type=str, |
||||
nargs='?', |
||||
help='The host-port pair at which to reach the server.') |
||||
args = parser.parse_args() |
||||
channel_compression = _COMPRESSION_OPTIONS[args.channel_compression] |
||||
call_compression = _COMPRESSION_OPTIONS[args.call_compression] |
||||
run_client(channel_compression, call_compression, args.server) |
||||
|
||||
|
||||
if __name__ == "__main__": |
||||
logging.basicConfig() |
||||
main() |
@ -0,0 +1,109 @@ |
||||
# Copyright 2019 the gRPC authors. |
||||
# |
||||
# Licensed under the Apache License, Version 2.0 (the "License"); |
||||
# you may not use this file except in compliance with the License. |
||||
# You may obtain a copy of the License at |
||||
# |
||||
# http://www.apache.org/licenses/LICENSE-2.0 |
||||
# |
||||
# Unless required by applicable law or agreed to in writing, software |
||||
# distributed under the License is distributed on an "AS IS" BASIS, |
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
# See the License for the specific language governing permissions and |
||||
# limitations under the License. |
||||
"""An example of compression on the server side with gRPC.""" |
||||
|
||||
from __future__ import absolute_import |
||||
from __future__ import division |
||||
from __future__ import print_function |
||||
|
||||
from concurrent import futures |
||||
import argparse |
||||
import logging |
||||
import threading |
||||
import time |
||||
import grpc |
||||
|
||||
from examples import helloworld_pb2 |
||||
from examples import helloworld_pb2_grpc |
||||
|
||||
_DESCRIPTION = 'A server capable of compression.' |
||||
_COMPRESSION_OPTIONS = { |
||||
"none": grpc.Compression.NoCompression, |
||||
"deflate": grpc.Compression.Deflate, |
||||
"gzip": grpc.Compression.Gzip, |
||||
} |
||||
_LOGGER = logging.getLogger(__name__) |
||||
|
||||
_SERVER_HOST = 'localhost' |
||||
_ONE_DAY_IN_SECONDS = 60 * 60 * 24 |
||||
|
||||
|
||||
class Greeter(helloworld_pb2_grpc.GreeterServicer): |
||||
|
||||
def __init__(self, no_compress_every_n): |
||||
super(Greeter, self).__init__() |
||||
self._no_compress_every_n = 0 |
||||
self._request_counter = 0 |
||||
self._counter_lock = threading.RLock() |
||||
|
||||
def _should_suppress_compression(self): |
||||
suppress_compression = False |
||||
with self._counter_lock: |
||||
if self._no_compress_every_n and self._request_counter % self._no_compress_every_n == 0: |
||||
suppress_compression = True |
||||
self._request_counter += 1 |
||||
return suppress_compression |
||||
|
||||
def SayHello(self, request, context): |
||||
if self._should_suppress_compression(): |
||||
context.set_response_compression(grpc.Compression.NoCompression) |
||||
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) |
||||
|
||||
|
||||
def run_server(server_compression, no_compress_every_n, port): |
||||
server = grpc.server( |
||||
futures.ThreadPoolExecutor(), |
||||
compression=server_compression, |
||||
options=(('grpc.so_reuseport', 1),)) |
||||
helloworld_pb2_grpc.add_GreeterServicer_to_server( |
||||
Greeter(no_compress_every_n), server) |
||||
address = '{}:{}'.format(_SERVER_HOST, port) |
||||
server.add_insecure_port(address) |
||||
server.start() |
||||
print("Server listening at '{}'".format(address)) |
||||
try: |
||||
while True: |
||||
time.sleep(_ONE_DAY_IN_SECONDS) |
||||
except KeyboardInterrupt: |
||||
server.stop(None) |
||||
|
||||
|
||||
def main(): |
||||
parser = argparse.ArgumentParser(description=_DESCRIPTION) |
||||
parser.add_argument( |
||||
'--server_compression', |
||||
default='none', |
||||
nargs='?', |
||||
choices=_COMPRESSION_OPTIONS.keys(), |
||||
help='The default compression method for the server.') |
||||
parser.add_argument( |
||||
'--no_compress_every_n', |
||||
type=int, |
||||
default=0, |
||||
nargs='?', |
||||
help='If set, every nth reply will be uncompressed.') |
||||
parser.add_argument( |
||||
'--port', |
||||
type=int, |
||||
default=50051, |
||||
nargs='?', |
||||
help='The port on which the server will listen.') |
||||
args = parser.parse_args() |
||||
run_server(_COMPRESSION_OPTIONS[args.server_compression], |
||||
args.no_compress_every_n, args.port) |
||||
|
||||
|
||||
if __name__ == "__main__": |
||||
logging.basicConfig() |
||||
main() |
@ -0,0 +1,62 @@ |
||||
# Copyright 2019 the gRPC authors. |
||||
# |
||||
# Licensed under the Apache License, Version 2.0 (the "License"); |
||||
# you may not use this file except in compliance with the License. |
||||
# You may obtain a copy of the License at |
||||
# |
||||
# http://www.apache.org/licenses/LICENSE-2.0 |
||||
# |
||||
# Unless required by applicable law or agreed to in writing, software |
||||
# distributed under the License is distributed on an "AS IS" BASIS, |
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
# See the License for the specific language governing permissions and |
||||
# limitations under the License. |
||||
"""Test for compression example.""" |
||||
|
||||
import contextlib |
||||
import os |
||||
import socket |
||||
import subprocess |
||||
import unittest |
||||
|
||||
_BINARY_DIR = os.path.realpath( |
||||
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) |
||||
_SERVER_PATH = os.path.join(_BINARY_DIR, 'server') |
||||
_CLIENT_PATH = os.path.join(_BINARY_DIR, 'client') |
||||
|
||||
|
||||
@contextlib.contextmanager |
||||
def _get_port(): |
||||
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) |
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) |
||||
if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 0: |
||||
raise RuntimeError("Failed to set SO_REUSEPORT.") |
||||
sock.bind(('', 0)) |
||||
try: |
||||
yield sock.getsockname()[1] |
||||
finally: |
||||
sock.close() |
||||
|
||||
|
||||
class CompressionExampleTest(unittest.TestCase): |
||||
|
||||
def test_compression_example(self): |
||||
with _get_port() as test_port: |
||||
server_process = subprocess.Popen((_SERVER_PATH, '--port', |
||||
str(test_port), |
||||
'--server_compression', 'gzip')) |
||||
try: |
||||
server_target = 'localhost:{}'.format(test_port) |
||||
client_process = subprocess.Popen( |
||||
(_CLIENT_PATH, '--server', server_target, |
||||
'--channel_compression', 'gzip')) |
||||
client_return_code = client_process.wait() |
||||
self.assertEqual(0, client_return_code) |
||||
self.assertIsNone(server_process.poll()) |
||||
finally: |
||||
server_process.kill() |
||||
server_process.wait() |
||||
|
||||
|
||||
if __name__ == '__main__': |
||||
unittest.main(verbosity=2) |
@ -0,0 +1,24 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2019 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_COMPLETION_QUEUE_IMPL_H |
||||
#define GRPCPP_COMPLETION_QUEUE_IMPL_H |
||||
|
||||
#include <grpcpp/impl/codegen/completion_queue_impl.h> |
||||
|
||||
#endif // GRPCPP_COMPLETION_QUEUE_IMPL_H
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,315 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2015 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_IMPL_CODEGEN_ASYNC_UNARY_CALL_IMPL_H |
||||
#define GRPCPP_IMPL_CODEGEN_ASYNC_UNARY_CALL_IMPL_H |
||||
|
||||
#include <assert.h> |
||||
#include <grpcpp/impl/codegen/call.h> |
||||
#include <grpcpp/impl/codegen/channel_interface.h> |
||||
#include <grpcpp/impl/codegen/client_context_impl.h> |
||||
#include <grpcpp/impl/codegen/server_context_impl.h> |
||||
#include <grpcpp/impl/codegen/service_type.h> |
||||
#include <grpcpp/impl/codegen/status.h> |
||||
|
||||
namespace grpc_impl { |
||||
|
||||
/// An interface relevant for async client side unary RPCs (which send
|
||||
/// one request message to a server and receive one response message).
|
||||
template <class R> |
||||
class ClientAsyncResponseReaderInterface { |
||||
public: |
||||
virtual ~ClientAsyncResponseReaderInterface() {} |
||||
|
||||
/// Start the call that was set up by the constructor, but only if the
|
||||
/// constructor was invoked through the "Prepare" API which doesn't actually
|
||||
/// start the call
|
||||
virtual void StartCall() = 0; |
||||
|
||||
/// Request notification of the reading of initial metadata. Completion
|
||||
/// will be notified by \a tag on the associated completion queue.
|
||||
/// This call is optional, but if it is used, it cannot be used concurrently
|
||||
/// with or after the \a Finish method.
|
||||
///
|
||||
/// \param[in] tag Tag identifying this request.
|
||||
virtual void ReadInitialMetadata(void* tag) = 0; |
||||
|
||||
/// Request to receive the server's response \a msg and final \a status for
|
||||
/// the call, and to notify \a tag on this call's completion queue when
|
||||
/// finished.
|
||||
///
|
||||
/// This function will return when either:
|
||||
/// - when the server's response message and status have been received.
|
||||
/// - when the server has returned a non-OK status (no message expected in
|
||||
/// this case).
|
||||
/// - when the call failed for some reason and the library generated a
|
||||
/// non-OK status.
|
||||
///
|
||||
/// \param[in] tag Tag identifying this request.
|
||||
/// \param[out] status To be updated with the operation status.
|
||||
/// \param[out] msg To be filled in with the server's response message.
|
||||
virtual void Finish(R* msg, ::grpc::Status* status, void* tag) = 0; |
||||
}; |
||||
|
||||
namespace internal { |
||||
template <class R> |
||||
class ClientAsyncResponseReaderFactory { |
||||
public: |
||||
/// Start a call and write the request out if \a start is set.
|
||||
/// \a tag will be notified on \a cq when the call has been started (i.e.
|
||||
/// intitial metadata sent) and \a request has been written out.
|
||||
/// If \a start is not set, the actual call must be initiated by StartCall
|
||||
/// Note that \a context will be used to fill in custom initial metadata
|
||||
/// used to send to the server when starting the call.
|
||||
template <class W> |
||||
static ClientAsyncResponseReader<R>* Create( |
||||
::grpc::ChannelInterface* channel, ::grpc_impl::CompletionQueue* cq, |
||||
const ::grpc::internal::RpcMethod& method, |
||||
::grpc_impl::ClientContext* context, const W& request, bool start) { |
||||
::grpc::internal::Call call = channel->CreateCall(method, context, cq); |
||||
return new (::grpc::g_core_codegen_interface->grpc_call_arena_alloc( |
||||
call.call(), sizeof(ClientAsyncResponseReader<R>))) |
||||
ClientAsyncResponseReader<R>(call, context, request, start); |
||||
} |
||||
}; |
||||
} // namespace internal
|
||||
|
||||
/// Async API for client-side unary RPCs, where the message response
|
||||
/// received from the server is of type \a R.
|
||||
template <class R> |
||||
class ClientAsyncResponseReader final |
||||
: public ClientAsyncResponseReaderInterface<R> { |
||||
public: |
||||
// always allocated against a call arena, no memory free required
|
||||
static void operator delete(void* ptr, std::size_t size) { |
||||
assert(size == sizeof(ClientAsyncResponseReader)); |
||||
} |
||||
|
||||
// This operator should never be called as the memory should be freed as part
|
||||
// of the arena destruction. It only exists to provide a matching operator
|
||||
// delete to the operator new so that some compilers will not complain (see
|
||||
// https://github.com/grpc/grpc/issues/11301) Note at the time of adding this
|
||||
// there are no tests catching the compiler warning.
|
||||
static void operator delete(void*, void*) { assert(0); } |
||||
|
||||
void StartCall() override { |
||||
assert(!started_); |
||||
started_ = true; |
||||
StartCallInternal(); |
||||
} |
||||
|
||||
/// See \a ClientAsyncResponseReaderInterface::ReadInitialMetadata for
|
||||
/// semantics.
|
||||
///
|
||||
/// Side effect:
|
||||
/// - the \a ClientContext associated with this call is updated with
|
||||
/// possible initial and trailing metadata sent from the server.
|
||||
void ReadInitialMetadata(void* tag) override { |
||||
assert(started_); |
||||
GPR_CODEGEN_ASSERT(!context_->initial_metadata_received_); |
||||
|
||||
single_buf.set_output_tag(tag); |
||||
single_buf.RecvInitialMetadata(context_); |
||||
call_.PerformOps(&single_buf); |
||||
initial_metadata_read_ = true; |
||||
} |
||||
|
||||
/// See \a ClientAysncResponseReaderInterface::Finish for semantics.
|
||||
///
|
||||
/// Side effect:
|
||||
/// - the \a ClientContext associated with this call is updated with
|
||||
/// possible initial and trailing metadata sent from the server.
|
||||
void Finish(R* msg, ::grpc::Status* status, void* tag) override { |
||||
assert(started_); |
||||
if (initial_metadata_read_) { |
||||
finish_buf.set_output_tag(tag); |
||||
finish_buf.RecvMessage(msg); |
||||
finish_buf.AllowNoMessage(); |
||||
finish_buf.ClientRecvStatus(context_, status); |
||||
call_.PerformOps(&finish_buf); |
||||
} else { |
||||
single_buf.set_output_tag(tag); |
||||
single_buf.RecvInitialMetadata(context_); |
||||
single_buf.RecvMessage(msg); |
||||
single_buf.AllowNoMessage(); |
||||
single_buf.ClientRecvStatus(context_, status); |
||||
call_.PerformOps(&single_buf); |
||||
} |
||||
} |
||||
|
||||
private: |
||||
friend class internal::ClientAsyncResponseReaderFactory<R>; |
||||
::grpc_impl::ClientContext* const context_; |
||||
::grpc::internal::Call call_; |
||||
bool started_; |
||||
bool initial_metadata_read_ = false; |
||||
|
||||
template <class W> |
||||
ClientAsyncResponseReader(::grpc::internal::Call call, |
||||
::grpc_impl::ClientContext* context, |
||||
const W& request, bool start) |
||||
: context_(context), call_(call), started_(start) { |
||||
// Bind the metadata at time of StartCallInternal but set up the rest here
|
||||
// TODO(ctiller): don't assert
|
||||
GPR_CODEGEN_ASSERT(single_buf.SendMessage(request).ok()); |
||||
single_buf.ClientSendClose(); |
||||
if (start) StartCallInternal(); |
||||
} |
||||
|
||||
void StartCallInternal() { |
||||
single_buf.SendInitialMetadata(&context_->send_initial_metadata_, |
||||
context_->initial_metadata_flags()); |
||||
} |
||||
|
||||
// disable operator new
|
||||
static void* operator new(std::size_t size); |
||||
static void* operator new(std::size_t size, void* p) { return p; } |
||||
|
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata, |
||||
::grpc::internal::CallOpSendMessage, |
||||
::grpc::internal::CallOpClientSendClose, |
||||
::grpc::internal::CallOpRecvInitialMetadata, |
||||
::grpc::internal::CallOpRecvMessage<R>, |
||||
::grpc::internal::CallOpClientRecvStatus> |
||||
single_buf; |
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpRecvMessage<R>, |
||||
::grpc::internal::CallOpClientRecvStatus> |
||||
finish_buf; |
||||
}; |
||||
|
||||
/// Async server-side API for handling unary calls, where the single
|
||||
/// response message sent to the client is of type \a W.
|
||||
template <class W> |
||||
class ServerAsyncResponseWriter final |
||||
: public ::grpc::internal::ServerAsyncStreamingInterface { |
||||
public: |
||||
explicit ServerAsyncResponseWriter(::grpc_impl::ServerContext* ctx) |
||||
: call_(nullptr, nullptr, nullptr), ctx_(ctx) {} |
||||
|
||||
/// See \a ServerAsyncStreamingInterface::SendInitialMetadata for semantics.
|
||||
///
|
||||
/// Side effect:
|
||||
/// The initial metadata that will be sent to the client from this op will
|
||||
/// be taken from the \a ServerContext associated with the call.
|
||||
///
|
||||
/// \param[in] tag Tag identifying this request.
|
||||
void SendInitialMetadata(void* tag) override { |
||||
GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_); |
||||
|
||||
meta_buf_.set_output_tag(tag); |
||||
meta_buf_.SendInitialMetadata(&ctx_->initial_metadata_, |
||||
ctx_->initial_metadata_flags()); |
||||
if (ctx_->compression_level_set()) { |
||||
meta_buf_.set_compression_level(ctx_->compression_level()); |
||||
} |
||||
ctx_->sent_initial_metadata_ = true; |
||||
call_.PerformOps(&meta_buf_); |
||||
} |
||||
|
||||
/// Indicate that the stream is to be finished and request notification
|
||||
/// when the server has sent the appropriate signals to the client to
|
||||
/// end the call. Should not be used concurrently with other operations.
|
||||
///
|
||||
/// \param[in] tag Tag identifying this request.
|
||||
/// \param[in] status To be sent to the client as the result of the call.
|
||||
/// \param[in] msg Message to be sent to the client.
|
||||
///
|
||||
/// Side effect:
|
||||
/// - also sends initial metadata if not already sent (using the
|
||||
/// \a ServerContext associated with this call).
|
||||
///
|
||||
/// Note: if \a status has a non-OK code, then \a msg will not be sent,
|
||||
/// and the client will receive only the status with possible trailing
|
||||
/// metadata.
|
||||
void Finish(const W& msg, const ::grpc::Status& status, void* tag) { |
||||
finish_buf_.set_output_tag(tag); |
||||
finish_buf_.set_core_cq_tag(&finish_buf_); |
||||
if (!ctx_->sent_initial_metadata_) { |
||||
finish_buf_.SendInitialMetadata(&ctx_->initial_metadata_, |
||||
ctx_->initial_metadata_flags()); |
||||
if (ctx_->compression_level_set()) { |
||||
finish_buf_.set_compression_level(ctx_->compression_level()); |
||||
} |
||||
ctx_->sent_initial_metadata_ = true; |
||||
} |
||||
// The response is dropped if the status is not OK.
|
||||
if (status.ok()) { |
||||
finish_buf_.ServerSendStatus(&ctx_->trailing_metadata_, |
||||
finish_buf_.SendMessage(msg)); |
||||
} else { |
||||
finish_buf_.ServerSendStatus(&ctx_->trailing_metadata_, status); |
||||
} |
||||
call_.PerformOps(&finish_buf_); |
||||
} |
||||
|
||||
/// Indicate that the stream is to be finished with a non-OK status,
|
||||
/// and request notification for when the server has finished sending the
|
||||
/// appropriate signals to the client to end the call.
|
||||
/// Should not be used concurrently with other operations.
|
||||
///
|
||||
/// \param[in] tag Tag identifying this request.
|
||||
/// \param[in] status To be sent to the client as the result of the call.
|
||||
/// - Note: \a status must have a non-OK code.
|
||||
///
|
||||
/// Side effect:
|
||||
/// - also sends initial metadata if not already sent (using the
|
||||
/// \a ServerContext associated with this call).
|
||||
void FinishWithError(const ::grpc::Status& status, void* tag) { |
||||
GPR_CODEGEN_ASSERT(!status.ok()); |
||||
finish_buf_.set_output_tag(tag); |
||||
if (!ctx_->sent_initial_metadata_) { |
||||
finish_buf_.SendInitialMetadata(&ctx_->initial_metadata_, |
||||
ctx_->initial_metadata_flags()); |
||||
if (ctx_->compression_level_set()) { |
||||
finish_buf_.set_compression_level(ctx_->compression_level()); |
||||
} |
||||
ctx_->sent_initial_metadata_ = true; |
||||
} |
||||
finish_buf_.ServerSendStatus(&ctx_->trailing_metadata_, status); |
||||
call_.PerformOps(&finish_buf_); |
||||
} |
||||
|
||||
private: |
||||
void BindCall(::grpc::internal::Call* call) override { call_ = *call; } |
||||
|
||||
::grpc::internal::Call call_; |
||||
::grpc_impl::ServerContext* ctx_; |
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata> |
||||
meta_buf_; |
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata, |
||||
::grpc::internal::CallOpSendMessage, |
||||
::grpc::internal::CallOpServerSendStatus> |
||||
finish_buf_; |
||||
}; |
||||
|
||||
} // namespace grpc_impl
|
||||
|
||||
namespace std { |
||||
template <class R> |
||||
class default_delete<::grpc_impl::ClientAsyncResponseReader<R>> { |
||||
public: |
||||
void operator()(void* p) {} |
||||
}; |
||||
template <class R> |
||||
class default_delete<::grpc_impl::ClientAsyncResponseReaderInterface<R>> { |
||||
public: |
||||
void operator()(void* p) {} |
||||
}; |
||||
} // namespace std
|
||||
|
||||
#endif // GRPCPP_IMPL_CODEGEN_ASYNC_UNARY_CALL_IMPL_H
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,944 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2019 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_IMPL_CODEGEN_SYNC_STREAM_IMPL_H |
||||
#define GRPCPP_IMPL_CODEGEN_SYNC_STREAM_IMPL_H |
||||
|
||||
#include <grpcpp/impl/codegen/call.h> |
||||
#include <grpcpp/impl/codegen/channel_interface.h> |
||||
#include <grpcpp/impl/codegen/client_context_impl.h> |
||||
#include <grpcpp/impl/codegen/completion_queue_impl.h> |
||||
#include <grpcpp/impl/codegen/core_codegen_interface.h> |
||||
#include <grpcpp/impl/codegen/server_context_impl.h> |
||||
#include <grpcpp/impl/codegen/service_type.h> |
||||
#include <grpcpp/impl/codegen/status.h> |
||||
|
||||
namespace grpc_impl { |
||||
|
||||
namespace internal { |
||||
/// Common interface for all synchronous client side streaming.
|
||||
class ClientStreamingInterface { |
||||
public: |
||||
virtual ~ClientStreamingInterface() {} |
||||
|
||||
/// Block waiting until the stream finishes and a final status of the call is
|
||||
/// available.
|
||||
///
|
||||
/// It is appropriate to call this method when both:
|
||||
/// * the calling code (client-side) has no more message to send
|
||||
/// (this can be declared implicitly by calling this method, or
|
||||
/// explicitly through an earlier call to <i>WritesDone</i> method of the
|
||||
/// class in use, e.g. \a ClientWriterInterface::WritesDone or
|
||||
/// \a ClientReaderWriterInterface::WritesDone).
|
||||
/// * there are no more messages to be received from the server (which can
|
||||
/// be known implicitly, or explicitly from an earlier call to \a
|
||||
/// ReaderInterface::Read that returned "false").
|
||||
///
|
||||
/// This function will return either:
|
||||
/// - when all incoming messages have been read and the server has
|
||||
/// returned status.
|
||||
/// - when the server has returned a non-OK status.
|
||||
/// - OR when the call failed for some reason and the library generated a
|
||||
/// status.
|
||||
///
|
||||
/// Return values:
|
||||
/// - \a Status contains the status code, message and details for the call
|
||||
/// - the \a ClientContext associated with this call is updated with
|
||||
/// possible trailing metadata sent from the server.
|
||||
virtual ::grpc::Status Finish() = 0; |
||||
}; |
||||
|
||||
/// Common interface for all synchronous server side streaming.
|
||||
class ServerStreamingInterface { |
||||
public: |
||||
virtual ~ServerStreamingInterface() {} |
||||
|
||||
/// Block to send initial metadata to client.
|
||||
/// This call is optional, but if it is used, it cannot be used concurrently
|
||||
/// with or after the \a Finish method.
|
||||
///
|
||||
/// The initial metadata that will be sent to the client will be
|
||||
/// taken from the \a ServerContext associated with the call.
|
||||
virtual void SendInitialMetadata() = 0; |
||||
}; |
||||
|
||||
/// An interface that yields a sequence of messages of type \a R.
|
||||
template <class R> |
||||
class ReaderInterface { |
||||
public: |
||||
virtual ~ReaderInterface() {} |
||||
|
||||
/// Get an upper bound on the next message size available for reading on this
|
||||
/// stream.
|
||||
virtual bool NextMessageSize(uint32_t* sz) = 0; |
||||
|
||||
/// Block to read a message and parse to \a msg. Returns \a true on success.
|
||||
/// This is thread-safe with respect to \a Write or \WritesDone methods on
|
||||
/// the same stream. It should not be called concurrently with another \a
|
||||
/// Read on the same stream as the order of delivery will not be defined.
|
||||
///
|
||||
/// \param[out] msg The read message.
|
||||
///
|
||||
/// \return \a false when there will be no more incoming messages, either
|
||||
/// because the other side has called \a WritesDone() or the stream has failed
|
||||
/// (or been cancelled).
|
||||
virtual bool Read(R* msg) = 0; |
||||
}; |
||||
|
||||
/// An interface that can be fed a sequence of messages of type \a W.
|
||||
template <class W> |
||||
class WriterInterface { |
||||
public: |
||||
virtual ~WriterInterface() {} |
||||
|
||||
/// Block to write \a msg to the stream with WriteOptions \a options.
|
||||
/// This is thread-safe with respect to \a ReaderInterface::Read
|
||||
///
|
||||
/// \param msg The message to be written to the stream.
|
||||
/// \param options The WriteOptions affecting the write operation.
|
||||
///
|
||||
/// \return \a true on success, \a false when the stream has been closed.
|
||||
virtual bool Write(const W& msg, ::grpc::WriteOptions options) = 0; |
||||
|
||||
/// Block to write \a msg to the stream with default write options.
|
||||
/// This is thread-safe with respect to \a ReaderInterface::Read
|
||||
///
|
||||
/// \param msg The message to be written to the stream.
|
||||
///
|
||||
/// \return \a true on success, \a false when the stream has been closed.
|
||||
inline bool Write(const W& msg) { return Write(msg, ::grpc::WriteOptions()); } |
||||
|
||||
/// Write \a msg and coalesce it with the writing of trailing metadata, using
|
||||
/// WriteOptions \a options.
|
||||
///
|
||||
/// For client, WriteLast is equivalent of performing Write and WritesDone in
|
||||
/// a single step. \a msg and trailing metadata are coalesced and sent on wire
|
||||
/// by calling this function. For server, WriteLast buffers the \a msg.
|
||||
/// The writing of \a msg is held until the service handler returns,
|
||||
/// where \a msg and trailing metadata are coalesced and sent on wire.
|
||||
/// Note that WriteLast can only buffer \a msg up to the flow control window
|
||||
/// size. If \a msg size is larger than the window size, it will be sent on
|
||||
/// wire without buffering.
|
||||
///
|
||||
/// \param[in] msg The message to be written to the stream.
|
||||
/// \param[in] options The WriteOptions to be used to write this message.
|
||||
void WriteLast(const W& msg, ::grpc::WriteOptions options) { |
||||
Write(msg, options.set_last_message()); |
||||
} |
||||
}; |
||||
|
||||
} // namespace internal
|
||||
|
||||
/// Client-side interface for streaming reads of message of type \a R.
|
||||
template <class R> |
||||
class ClientReaderInterface : public internal::ClientStreamingInterface, |
||||
public internal::ReaderInterface<R> { |
||||
public: |
||||
/// Block to wait for initial metadata from server. The received metadata
|
||||
/// can only be accessed after this call returns. Should only be called before
|
||||
/// the first read. Calling this method is optional, and if it is not called
|
||||
/// the metadata will be available in ClientContext after the first read.
|
||||
virtual void WaitForInitialMetadata() = 0; |
||||
}; |
||||
|
||||
namespace internal { |
||||
template <class R> |
||||
class ClientReaderFactory { |
||||
public: |
||||
template <class W> |
||||
static ClientReader<R>* Create(::grpc::ChannelInterface* channel, |
||||
const ::grpc::internal::RpcMethod& method, |
||||
::grpc_impl::ClientContext* context, |
||||
const W& request) { |
||||
return new ClientReader<R>(channel, method, context, request); |
||||
} |
||||
}; |
||||
} // namespace internal
|
||||
|
||||
/// Synchronous (blocking) client-side API for doing server-streaming RPCs,
|
||||
/// where the stream of messages coming from the server has messages
|
||||
/// of type \a R.
|
||||
template <class R> |
||||
class ClientReader final : public ClientReaderInterface<R> { |
||||
public: |
||||
/// See the \a ClientStreamingInterface.WaitForInitialMetadata method for
|
||||
/// semantics.
|
||||
///
|
||||
// Side effect:
|
||||
/// Once complete, the initial metadata read from
|
||||
/// the server will be accessible through the \a ClientContext used to
|
||||
/// construct this object.
|
||||
void WaitForInitialMetadata() override { |
||||
GPR_CODEGEN_ASSERT(!context_->initial_metadata_received_); |
||||
|
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpRecvInitialMetadata> |
||||
ops; |
||||
ops.RecvInitialMetadata(context_); |
||||
call_.PerformOps(&ops); |
||||
cq_.Pluck(&ops); /// status ignored
|
||||
} |
||||
|
||||
bool NextMessageSize(uint32_t* sz) override { |
||||
*sz = call_.max_receive_message_size(); |
||||
return true; |
||||
} |
||||
|
||||
/// See the \a ReaderInterface.Read method for semantics.
|
||||
/// Side effect:
|
||||
/// This also receives initial metadata from the server, if not
|
||||
/// already received (if initial metadata is received, it can be then
|
||||
/// accessed through the \a ClientContext associated with this call).
|
||||
bool Read(R* msg) override { |
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpRecvInitialMetadata, |
||||
::grpc::internal::CallOpRecvMessage<R>> |
||||
ops; |
||||
if (!context_->initial_metadata_received_) { |
||||
ops.RecvInitialMetadata(context_); |
||||
} |
||||
ops.RecvMessage(msg); |
||||
call_.PerformOps(&ops); |
||||
return cq_.Pluck(&ops) && ops.got_message; |
||||
} |
||||
|
||||
/// See the \a ClientStreamingInterface.Finish method for semantics.
|
||||
///
|
||||
/// Side effect:
|
||||
/// The \a ClientContext associated with this call is updated with
|
||||
/// possible metadata received from the server.
|
||||
::grpc::Status Finish() override { |
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpClientRecvStatus> ops; |
||||
::grpc::Status status; |
||||
ops.ClientRecvStatus(context_, &status); |
||||
call_.PerformOps(&ops); |
||||
GPR_CODEGEN_ASSERT(cq_.Pluck(&ops)); |
||||
return status; |
||||
} |
||||
|
||||
private: |
||||
friend class internal::ClientReaderFactory<R>; |
||||
::grpc_impl::ClientContext* context_; |
||||
::grpc_impl::CompletionQueue cq_; |
||||
::grpc::internal::Call call_; |
||||
|
||||
/// Block to create a stream and write the initial metadata and \a request
|
||||
/// out. Note that \a context will be used to fill in custom initial
|
||||
/// metadata used to send to the server when starting the call.
|
||||
template <class W> |
||||
ClientReader(::grpc::ChannelInterface* channel, |
||||
const ::grpc::internal::RpcMethod& method, |
||||
::grpc_impl::ClientContext* context, const W& request) |
||||
: context_(context), |
||||
cq_(grpc_completion_queue_attributes{ |
||||
GRPC_CQ_CURRENT_VERSION, GRPC_CQ_PLUCK, GRPC_CQ_DEFAULT_POLLING, |
||||
nullptr}), // Pluckable cq
|
||||
call_(channel->CreateCall(method, context, &cq_)) { |
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata, |
||||
::grpc::internal::CallOpSendMessage, |
||||
::grpc::internal::CallOpClientSendClose> |
||||
ops; |
||||
ops.SendInitialMetadata(&context->send_initial_metadata_, |
||||
context->initial_metadata_flags()); |
||||
// TODO(ctiller): don't assert
|
||||
GPR_CODEGEN_ASSERT(ops.SendMessagePtr(&request).ok()); |
||||
ops.ClientSendClose(); |
||||
call_.PerformOps(&ops); |
||||
cq_.Pluck(&ops); |
||||
} |
||||
}; |
||||
|
||||
/// Client-side interface for streaming writes of message type \a W.
|
||||
template <class W> |
||||
class ClientWriterInterface : public internal::ClientStreamingInterface, |
||||
public internal::WriterInterface<W> { |
||||
public: |
||||
/// Half close writing from the client. (signal that the stream of messages
|
||||
/// coming from the client is complete).
|
||||
/// Blocks until currently-pending writes are completed.
|
||||
/// Thread safe with respect to \a ReaderInterface::Read operations only
|
||||
///
|
||||
/// \return Whether the writes were successful.
|
||||
virtual bool WritesDone() = 0; |
||||
}; |
||||
|
||||
namespace internal { |
||||
template <class W> |
||||
class ClientWriterFactory { |
||||
public: |
||||
template <class R> |
||||
static ClientWriter<W>* Create(::grpc::ChannelInterface* channel, |
||||
const ::grpc::internal::RpcMethod& method, |
||||
::grpc_impl::ClientContext* context, |
||||
R* response) { |
||||
return new ClientWriter<W>(channel, method, context, response); |
||||
} |
||||
}; |
||||
} // namespace internal
|
||||
|
||||
/// Synchronous (blocking) client-side API for doing client-streaming RPCs,
|
||||
/// where the outgoing message stream coming from the client has messages of
|
||||
/// type \a W.
|
||||
template <class W> |
||||
class ClientWriter : public ClientWriterInterface<W> { |
||||
public: |
||||
/// See the \a ClientStreamingInterface.WaitForInitialMetadata method for
|
||||
/// semantics.
|
||||
///
|
||||
// Side effect:
|
||||
/// Once complete, the initial metadata read from the server will be
|
||||
/// accessible through the \a ClientContext used to construct this object.
|
||||
void WaitForInitialMetadata() { |
||||
GPR_CODEGEN_ASSERT(!context_->initial_metadata_received_); |
||||
|
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpRecvInitialMetadata> |
||||
ops; |
||||
ops.RecvInitialMetadata(context_); |
||||
call_.PerformOps(&ops); |
||||
cq_.Pluck(&ops); // status ignored
|
||||
} |
||||
|
||||
/// See the WriterInterface.Write(const W& msg, WriteOptions options) method
|
||||
/// for semantics.
|
||||
///
|
||||
/// Side effect:
|
||||
/// Also sends initial metadata if not already sent (using the
|
||||
/// \a ClientContext associated with this call).
|
||||
using internal::WriterInterface<W>::Write; |
||||
bool Write(const W& msg, ::grpc::WriteOptions options) override { |
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata, |
||||
::grpc::internal::CallOpSendMessage, |
||||
::grpc::internal::CallOpClientSendClose> |
||||
ops; |
||||
|
||||
if (options.is_last_message()) { |
||||
options.set_buffer_hint(); |
||||
ops.ClientSendClose(); |
||||
} |
||||
if (context_->initial_metadata_corked_) { |
||||
ops.SendInitialMetadata(&context_->send_initial_metadata_, |
||||
context_->initial_metadata_flags()); |
||||
context_->set_initial_metadata_corked(false); |
||||
} |
||||
if (!ops.SendMessagePtr(&msg, options).ok()) { |
||||
return false; |
||||
} |
||||
|
||||
call_.PerformOps(&ops); |
||||
return cq_.Pluck(&ops); |
||||
} |
||||
|
||||
bool WritesDone() override { |
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpClientSendClose> ops; |
||||
ops.ClientSendClose(); |
||||
call_.PerformOps(&ops); |
||||
return cq_.Pluck(&ops); |
||||
} |
||||
|
||||
/// See the ClientStreamingInterface.Finish method for semantics.
|
||||
/// Side effects:
|
||||
/// - Also receives initial metadata if not already received.
|
||||
/// - Attempts to fill in the \a response parameter passed
|
||||
/// to the constructor of this instance with the response
|
||||
/// message from the server.
|
||||
::grpc::Status Finish() override { |
||||
::grpc::Status status; |
||||
if (!context_->initial_metadata_received_) { |
||||
finish_ops_.RecvInitialMetadata(context_); |
||||
} |
||||
finish_ops_.ClientRecvStatus(context_, &status); |
||||
call_.PerformOps(&finish_ops_); |
||||
GPR_CODEGEN_ASSERT(cq_.Pluck(&finish_ops_)); |
||||
return status; |
||||
} |
||||
|
||||
private: |
||||
friend class internal::ClientWriterFactory<W>; |
||||
|
||||
/// Block to create a stream (i.e. send request headers and other initial
|
||||
/// metadata to the server). Note that \a context will be used to fill
|
||||
/// in custom initial metadata. \a response will be filled in with the
|
||||
/// single expected response message from the server upon a successful
|
||||
/// call to the \a Finish method of this instance.
|
||||
template <class R> |
||||
ClientWriter(::grpc::ChannelInterface* channel, |
||||
const ::grpc::internal::RpcMethod& method, |
||||
::grpc_impl::ClientContext* context, R* response) |
||||
: context_(context), |
||||
cq_(grpc_completion_queue_attributes{ |
||||
GRPC_CQ_CURRENT_VERSION, GRPC_CQ_PLUCK, GRPC_CQ_DEFAULT_POLLING, |
||||
nullptr}), // Pluckable cq
|
||||
call_(channel->CreateCall(method, context, &cq_)) { |
||||
finish_ops_.RecvMessage(response); |
||||
finish_ops_.AllowNoMessage(); |
||||
|
||||
if (!context_->initial_metadata_corked_) { |
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata> |
||||
ops; |
||||
ops.SendInitialMetadata(&context->send_initial_metadata_, |
||||
context->initial_metadata_flags()); |
||||
call_.PerformOps(&ops); |
||||
cq_.Pluck(&ops); |
||||
} |
||||
} |
||||
|
||||
::grpc_impl::ClientContext* context_; |
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpRecvInitialMetadata, |
||||
::grpc::internal::CallOpGenericRecvMessage, |
||||
::grpc::internal::CallOpClientRecvStatus> |
||||
finish_ops_; |
||||
::grpc_impl::CompletionQueue cq_; |
||||
::grpc::internal::Call call_; |
||||
}; |
||||
|
||||
/// Client-side interface for bi-directional streaming with
|
||||
/// client-to-server stream messages of type \a W and
|
||||
/// server-to-client stream messages of type \a R.
|
||||
template <class W, class R> |
||||
class ClientReaderWriterInterface : public internal::ClientStreamingInterface, |
||||
public internal::WriterInterface<W>, |
||||
public internal::ReaderInterface<R> { |
||||
public: |
||||
/// Block to wait for initial metadata from server. The received metadata
|
||||
/// can only be accessed after this call returns. Should only be called before
|
||||
/// the first read. Calling this method is optional, and if it is not called
|
||||
/// the metadata will be available in ClientContext after the first read.
|
||||
virtual void WaitForInitialMetadata() = 0; |
||||
|
||||
/// Half close writing from the client. (signal that the stream of messages
|
||||
/// coming from the clinet is complete).
|
||||
/// Blocks until currently-pending writes are completed.
|
||||
/// Thread-safe with respect to \a ReaderInterface::Read
|
||||
///
|
||||
/// \return Whether the writes were successful.
|
||||
virtual bool WritesDone() = 0; |
||||
}; |
||||
|
||||
namespace internal { |
||||
template <class W, class R> |
||||
class ClientReaderWriterFactory { |
||||
public: |
||||
static ClientReaderWriter<W, R>* Create( |
||||
::grpc::ChannelInterface* channel, |
||||
const ::grpc::internal::RpcMethod& method, |
||||
::grpc_impl::ClientContext* context) { |
||||
return new ClientReaderWriter<W, R>(channel, method, context); |
||||
} |
||||
}; |
||||
} // namespace internal
|
||||
|
||||
/// Synchronous (blocking) client-side API for bi-directional streaming RPCs,
|
||||
/// where the outgoing message stream coming from the client has messages of
|
||||
/// type \a W, and the incoming messages stream coming from the server has
|
||||
/// messages of type \a R.
|
||||
template <class W, class R> |
||||
class ClientReaderWriter final : public ClientReaderWriterInterface<W, R> { |
||||
public: |
||||
/// Block waiting to read initial metadata from the server.
|
||||
/// This call is optional, but if it is used, it cannot be used concurrently
|
||||
/// with or after the \a Finish method.
|
||||
///
|
||||
/// Once complete, the initial metadata read from the server will be
|
||||
/// accessible through the \a ClientContext used to construct this object.
|
||||
void WaitForInitialMetadata() override { |
||||
GPR_CODEGEN_ASSERT(!context_->initial_metadata_received_); |
||||
|
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpRecvInitialMetadata> |
||||
ops; |
||||
ops.RecvInitialMetadata(context_); |
||||
call_.PerformOps(&ops); |
||||
cq_.Pluck(&ops); // status ignored
|
||||
} |
||||
|
||||
bool NextMessageSize(uint32_t* sz) override { |
||||
*sz = call_.max_receive_message_size(); |
||||
return true; |
||||
} |
||||
|
||||
/// See the \a ReaderInterface.Read method for semantics.
|
||||
/// Side effect:
|
||||
/// Also receives initial metadata if not already received (updates the \a
|
||||
/// ClientContext associated with this call in that case).
|
||||
bool Read(R* msg) override { |
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpRecvInitialMetadata, |
||||
::grpc::internal::CallOpRecvMessage<R>> |
||||
ops; |
||||
if (!context_->initial_metadata_received_) { |
||||
ops.RecvInitialMetadata(context_); |
||||
} |
||||
ops.RecvMessage(msg); |
||||
call_.PerformOps(&ops); |
||||
return cq_.Pluck(&ops) && ops.got_message; |
||||
} |
||||
|
||||
/// See the \a WriterInterface.Write method for semantics.
|
||||
///
|
||||
/// Side effect:
|
||||
/// Also sends initial metadata if not already sent (using the
|
||||
/// \a ClientContext associated with this call to fill in values).
|
||||
using internal::WriterInterface<W>::Write; |
||||
bool Write(const W& msg, ::grpc::WriteOptions options) override { |
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata, |
||||
::grpc::internal::CallOpSendMessage, |
||||
::grpc::internal::CallOpClientSendClose> |
||||
ops; |
||||
|
||||
if (options.is_last_message()) { |
||||
options.set_buffer_hint(); |
||||
ops.ClientSendClose(); |
||||
} |
||||
if (context_->initial_metadata_corked_) { |
||||
ops.SendInitialMetadata(&context_->send_initial_metadata_, |
||||
context_->initial_metadata_flags()); |
||||
context_->set_initial_metadata_corked(false); |
||||
} |
||||
if (!ops.SendMessagePtr(&msg, options).ok()) { |
||||
return false; |
||||
} |
||||
|
||||
call_.PerformOps(&ops); |
||||
return cq_.Pluck(&ops); |
||||
} |
||||
|
||||
bool WritesDone() override { |
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpClientSendClose> ops; |
||||
ops.ClientSendClose(); |
||||
call_.PerformOps(&ops); |
||||
return cq_.Pluck(&ops); |
||||
} |
||||
|
||||
/// See the ClientStreamingInterface.Finish method for semantics.
|
||||
///
|
||||
/// Side effect:
|
||||
/// - the \a ClientContext associated with this call is updated with
|
||||
/// possible trailing metadata sent from the server.
|
||||
::grpc::Status Finish() override { |
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpRecvInitialMetadata, |
||||
::grpc::internal::CallOpClientRecvStatus> |
||||
ops; |
||||
if (!context_->initial_metadata_received_) { |
||||
ops.RecvInitialMetadata(context_); |
||||
} |
||||
::grpc::Status status; |
||||
ops.ClientRecvStatus(context_, &status); |
||||
call_.PerformOps(&ops); |
||||
GPR_CODEGEN_ASSERT(cq_.Pluck(&ops)); |
||||
return status; |
||||
} |
||||
|
||||
private: |
||||
friend class internal::ClientReaderWriterFactory<W, R>; |
||||
|
||||
::grpc_impl::ClientContext* context_; |
||||
::grpc_impl::CompletionQueue cq_; |
||||
::grpc::internal::Call call_; |
||||
|
||||
/// Block to create a stream and write the initial metadata and \a request
|
||||
/// out. Note that \a context will be used to fill in custom initial metadata
|
||||
/// used to send to the server when starting the call.
|
||||
ClientReaderWriter(::grpc::ChannelInterface* channel, |
||||
const ::grpc::internal::RpcMethod& method, |
||||
::grpc_impl::ClientContext* context) |
||||
: context_(context), |
||||
cq_(grpc_completion_queue_attributes{ |
||||
GRPC_CQ_CURRENT_VERSION, GRPC_CQ_PLUCK, GRPC_CQ_DEFAULT_POLLING, |
||||
nullptr}), // Pluckable cq
|
||||
call_(channel->CreateCall(method, context, &cq_)) { |
||||
if (!context_->initial_metadata_corked_) { |
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata> |
||||
ops; |
||||
ops.SendInitialMetadata(&context->send_initial_metadata_, |
||||
context->initial_metadata_flags()); |
||||
call_.PerformOps(&ops); |
||||
cq_.Pluck(&ops); |
||||
} |
||||
} |
||||
}; |
||||
|
||||
/// Server-side interface for streaming reads of message of type \a R.
|
||||
template <class R> |
||||
class ServerReaderInterface : public internal::ServerStreamingInterface, |
||||
public internal::ReaderInterface<R> {}; |
||||
|
||||
/// Synchronous (blocking) server-side API for doing client-streaming RPCs,
|
||||
/// where the incoming message stream coming from the client has messages of
|
||||
/// type \a R.
|
||||
template <class R> |
||||
class ServerReader final : public ServerReaderInterface<R> { |
||||
public: |
||||
/// See the \a ServerStreamingInterface.SendInitialMetadata method
|
||||
/// for semantics. Note that initial metadata will be affected by the
|
||||
/// \a ServerContext associated with this call.
|
||||
void SendInitialMetadata() override { |
||||
GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_); |
||||
|
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata> |
||||
ops; |
||||
ops.SendInitialMetadata(&ctx_->initial_metadata_, |
||||
ctx_->initial_metadata_flags()); |
||||
if (ctx_->compression_level_set()) { |
||||
ops.set_compression_level(ctx_->compression_level()); |
||||
} |
||||
ctx_->sent_initial_metadata_ = true; |
||||
call_->PerformOps(&ops); |
||||
call_->cq()->Pluck(&ops); |
||||
} |
||||
|
||||
bool NextMessageSize(uint32_t* sz) override { |
||||
*sz = call_->max_receive_message_size(); |
||||
return true; |
||||
} |
||||
|
||||
bool Read(R* msg) override { |
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpRecvMessage<R>> ops; |
||||
ops.RecvMessage(msg); |
||||
call_->PerformOps(&ops); |
||||
return call_->cq()->Pluck(&ops) && ops.got_message; |
||||
} |
||||
|
||||
private: |
||||
::grpc::internal::Call* const call_; |
||||
ServerContext* const ctx_; |
||||
|
||||
template <class ServiceType, class RequestType, class ResponseType> |
||||
friend class ::grpc::internal::ClientStreamingHandler; |
||||
|
||||
ServerReader(::grpc::internal::Call* call, ::grpc_impl::ServerContext* ctx) |
||||
: call_(call), ctx_(ctx) {} |
||||
}; |
||||
|
||||
/// Server-side interface for streaming writes of message of type \a W.
|
||||
template <class W> |
||||
class ServerWriterInterface : public internal::ServerStreamingInterface, |
||||
public internal::WriterInterface<W> {}; |
||||
|
||||
/// Synchronous (blocking) server-side API for doing for doing a
|
||||
/// server-streaming RPCs, where the outgoing message stream coming from the
|
||||
/// server has messages of type \a W.
|
||||
template <class W> |
||||
class ServerWriter final : public ServerWriterInterface<W> { |
||||
public: |
||||
/// See the \a ServerStreamingInterface.SendInitialMetadata method
|
||||
/// for semantics.
|
||||
/// Note that initial metadata will be affected by the
|
||||
/// \a ServerContext associated with this call.
|
||||
void SendInitialMetadata() override { |
||||
GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_); |
||||
|
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata> |
||||
ops; |
||||
ops.SendInitialMetadata(&ctx_->initial_metadata_, |
||||
ctx_->initial_metadata_flags()); |
||||
if (ctx_->compression_level_set()) { |
||||
ops.set_compression_level(ctx_->compression_level()); |
||||
} |
||||
ctx_->sent_initial_metadata_ = true; |
||||
call_->PerformOps(&ops); |
||||
call_->cq()->Pluck(&ops); |
||||
} |
||||
|
||||
/// See the \a WriterInterface.Write method for semantics.
|
||||
///
|
||||
/// Side effect:
|
||||
/// Also sends initial metadata if not already sent (using the
|
||||
/// \a ClientContext associated with this call to fill in values).
|
||||
using internal::WriterInterface<W>::Write; |
||||
bool Write(const W& msg, ::grpc::WriteOptions options) override { |
||||
if (options.is_last_message()) { |
||||
options.set_buffer_hint(); |
||||
} |
||||
|
||||
if (!ctx_->pending_ops_.SendMessagePtr(&msg, options).ok()) { |
||||
return false; |
||||
} |
||||
if (!ctx_->sent_initial_metadata_) { |
||||
ctx_->pending_ops_.SendInitialMetadata(&ctx_->initial_metadata_, |
||||
ctx_->initial_metadata_flags()); |
||||
if (ctx_->compression_level_set()) { |
||||
ctx_->pending_ops_.set_compression_level(ctx_->compression_level()); |
||||
} |
||||
ctx_->sent_initial_metadata_ = true; |
||||
} |
||||
call_->PerformOps(&ctx_->pending_ops_); |
||||
// if this is the last message we defer the pluck until AFTER we start
|
||||
// the trailing md op. This prevents hangs. See
|
||||
// https://github.com/grpc/grpc/issues/11546
|
||||
if (options.is_last_message()) { |
||||
ctx_->has_pending_ops_ = true; |
||||
return true; |
||||
} |
||||
ctx_->has_pending_ops_ = false; |
||||
return call_->cq()->Pluck(&ctx_->pending_ops_); |
||||
} |
||||
|
||||
private: |
||||
::grpc::internal::Call* const call_; |
||||
::grpc_impl::ServerContext* const ctx_; |
||||
|
||||
template <class ServiceType, class RequestType, class ResponseType> |
||||
friend class ::grpc::internal::ServerStreamingHandler; |
||||
|
||||
ServerWriter(::grpc::internal::Call* call, ::grpc_impl::ServerContext* ctx) |
||||
: call_(call), ctx_(ctx) {} |
||||
}; |
||||
|
||||
/// Server-side interface for bi-directional streaming.
|
||||
template <class W, class R> |
||||
class ServerReaderWriterInterface : public internal::ServerStreamingInterface, |
||||
public internal::WriterInterface<W>, |
||||
public internal::ReaderInterface<R> {}; |
||||
|
||||
/// Actual implementation of bi-directional streaming
|
||||
namespace internal { |
||||
template <class W, class R> |
||||
class ServerReaderWriterBody final { |
||||
public: |
||||
ServerReaderWriterBody(grpc::internal::Call* call, |
||||
::grpc_impl::ServerContext* ctx) |
||||
: call_(call), ctx_(ctx) {} |
||||
|
||||
void SendInitialMetadata() { |
||||
GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_); |
||||
|
||||
grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata> ops; |
||||
ops.SendInitialMetadata(&ctx_->initial_metadata_, |
||||
ctx_->initial_metadata_flags()); |
||||
if (ctx_->compression_level_set()) { |
||||
ops.set_compression_level(ctx_->compression_level()); |
||||
} |
||||
ctx_->sent_initial_metadata_ = true; |
||||
call_->PerformOps(&ops); |
||||
call_->cq()->Pluck(&ops); |
||||
} |
||||
|
||||
bool NextMessageSize(uint32_t* sz) { |
||||
*sz = call_->max_receive_message_size(); |
||||
return true; |
||||
} |
||||
|
||||
bool Read(R* msg) { |
||||
::grpc::internal::CallOpSet<::grpc::internal::CallOpRecvMessage<R>> ops; |
||||
ops.RecvMessage(msg); |
||||
call_->PerformOps(&ops); |
||||
return call_->cq()->Pluck(&ops) && ops.got_message; |
||||
} |
||||
|
||||
bool Write(const W& msg, ::grpc::WriteOptions options) { |
||||
if (options.is_last_message()) { |
||||
options.set_buffer_hint(); |
||||
} |
||||
if (!ctx_->pending_ops_.SendMessagePtr(&msg, options).ok()) { |
||||
return false; |
||||
} |
||||
if (!ctx_->sent_initial_metadata_) { |
||||
ctx_->pending_ops_.SendInitialMetadata(&ctx_->initial_metadata_, |
||||
ctx_->initial_metadata_flags()); |
||||
if (ctx_->compression_level_set()) { |
||||
ctx_->pending_ops_.set_compression_level(ctx_->compression_level()); |
||||
} |
||||
ctx_->sent_initial_metadata_ = true; |
||||
} |
||||
call_->PerformOps(&ctx_->pending_ops_); |
||||
// if this is the last message we defer the pluck until AFTER we start
|
||||
// the trailing md op. This prevents hangs. See
|
||||
// https://github.com/grpc/grpc/issues/11546
|
||||
if (options.is_last_message()) { |
||||
ctx_->has_pending_ops_ = true; |
||||
return true; |
||||
} |
||||
ctx_->has_pending_ops_ = false; |
||||
return call_->cq()->Pluck(&ctx_->pending_ops_); |
||||
} |
||||
|
||||
private: |
||||
grpc::internal::Call* const call_; |
||||
::grpc_impl::ServerContext* const ctx_; |
||||
}; |
||||
|
||||
} // namespace internal
|
||||
|
||||
/// Synchronous (blocking) server-side API for a bidirectional
|
||||
/// streaming call, where the incoming message stream coming from the client has
|
||||
/// messages of type \a R, and the outgoing message streaming coming from
|
||||
/// the server has messages of type \a W.
|
||||
template <class W, class R> |
||||
class ServerReaderWriter final : public ServerReaderWriterInterface<W, R> { |
||||
public: |
||||
/// See the \a ServerStreamingInterface.SendInitialMetadata method
|
||||
/// for semantics. Note that initial metadata will be affected by the
|
||||
/// \a ServerContext associated with this call.
|
||||
void SendInitialMetadata() override { body_.SendInitialMetadata(); } |
||||
|
||||
bool NextMessageSize(uint32_t* sz) override { |
||||
return body_.NextMessageSize(sz); |
||||
} |
||||
|
||||
bool Read(R* msg) override { return body_.Read(msg); } |
||||
|
||||
/// See the \a WriterInterface.Write(const W& msg, WriteOptions options)
|
||||
/// method for semantics.
|
||||
/// Side effect:
|
||||
/// Also sends initial metadata if not already sent (using the \a
|
||||
/// ServerContext associated with this call).
|
||||
using internal::WriterInterface<W>::Write; |
||||
bool Write(const W& msg, ::grpc::WriteOptions options) override { |
||||
return body_.Write(msg, options); |
||||
} |
||||
|
||||
private: |
||||
internal::ServerReaderWriterBody<W, R> body_; |
||||
|
||||
friend class ::grpc::internal::TemplatedBidiStreamingHandler< |
||||
ServerReaderWriter<W, R>, false>; |
||||
ServerReaderWriter(::grpc::internal::Call* call, |
||||
::grpc_impl::ServerContext* ctx) |
||||
: body_(call, ctx) {} |
||||
}; |
||||
|
||||
/// A class to represent a flow-controlled unary call. This is something
|
||||
/// of a hybrid between conventional unary and streaming. This is invoked
|
||||
/// through a unary call on the client side, but the server responds to it
|
||||
/// as though it were a single-ping-pong streaming call. The server can use
|
||||
/// the \a NextMessageSize method to determine an upper-bound on the size of
|
||||
/// the message. A key difference relative to streaming: ServerUnaryStreamer
|
||||
/// must have exactly 1 Read and exactly 1 Write, in that order, to function
|
||||
/// correctly. Otherwise, the RPC is in error.
|
||||
template <class RequestType, class ResponseType> |
||||
class ServerUnaryStreamer final |
||||
: public ServerReaderWriterInterface<ResponseType, RequestType> { |
||||
public: |
||||
/// Block to send initial metadata to client.
|
||||
/// Implicit input parameter:
|
||||
/// - the \a ServerContext associated with this call will be used for
|
||||
/// sending initial metadata.
|
||||
void SendInitialMetadata() override { body_.SendInitialMetadata(); } |
||||
|
||||
/// Get an upper bound on the request message size from the client.
|
||||
bool NextMessageSize(uint32_t* sz) override { |
||||
return body_.NextMessageSize(sz); |
||||
} |
||||
|
||||
/// Read a message of type \a R into \a msg. Completion will be notified by \a
|
||||
/// tag on the associated completion queue.
|
||||
/// This is thread-safe with respect to \a Write or \a WritesDone methods. It
|
||||
/// should not be called concurrently with other streaming APIs
|
||||
/// on the same stream. It is not meaningful to call it concurrently
|
||||
/// with another \a ReaderInterface::Read on the same stream since reads on
|
||||
/// the same stream are delivered in order.
|
||||
///
|
||||
/// \param[out] msg Where to eventually store the read message.
|
||||
/// \param[in] tag The tag identifying the operation.
|
||||
bool Read(RequestType* request) override { |
||||
if (read_done_) { |
||||
return false; |
||||
} |
||||
read_done_ = true; |
||||
return body_.Read(request); |
||||
} |
||||
|
||||
/// Block to write \a msg to the stream with WriteOptions \a options.
|
||||
/// This is thread-safe with respect to \a ReaderInterface::Read
|
||||
///
|
||||
/// \param msg The message to be written to the stream.
|
||||
/// \param options The WriteOptions affecting the write operation.
|
||||
///
|
||||
/// \return \a true on success, \a false when the stream has been closed.
|
||||
using internal::WriterInterface<ResponseType>::Write; |
||||
bool Write(const ResponseType& response, |
||||
::grpc::WriteOptions options) override { |
||||
if (write_done_ || !read_done_) { |
||||
return false; |
||||
} |
||||
write_done_ = true; |
||||
return body_.Write(response, options); |
||||
} |
||||
|
||||
private: |
||||
internal::ServerReaderWriterBody<ResponseType, RequestType> body_; |
||||
bool read_done_; |
||||
bool write_done_; |
||||
|
||||
friend class ::grpc::internal::TemplatedBidiStreamingHandler< |
||||
ServerUnaryStreamer<RequestType, ResponseType>, true>; |
||||
ServerUnaryStreamer(::grpc::internal::Call* call, |
||||
::grpc_impl::ServerContext* ctx) |
||||
: body_(call, ctx), read_done_(false), write_done_(false) {} |
||||
}; |
||||
|
||||
/// A class to represent a flow-controlled server-side streaming call.
|
||||
/// This is something of a hybrid between server-side and bidi streaming.
|
||||
/// This is invoked through a server-side streaming call on the client side,
|
||||
/// but the server responds to it as though it were a bidi streaming call that
|
||||
/// must first have exactly 1 Read and then any number of Writes.
|
||||
template <class RequestType, class ResponseType> |
||||
class ServerSplitStreamer final |
||||
: public ServerReaderWriterInterface<ResponseType, RequestType> { |
||||
public: |
||||
/// Block to send initial metadata to client.
|
||||
/// Implicit input parameter:
|
||||
/// - the \a ServerContext associated with this call will be used for
|
||||
/// sending initial metadata.
|
||||
void SendInitialMetadata() override { body_.SendInitialMetadata(); } |
||||
|
||||
/// Get an upper bound on the request message size from the client.
|
||||
bool NextMessageSize(uint32_t* sz) override { |
||||
return body_.NextMessageSize(sz); |
||||
} |
||||
|
||||
/// Read a message of type \a R into \a msg. Completion will be notified by \a
|
||||
/// tag on the associated completion queue.
|
||||
/// This is thread-safe with respect to \a Write or \a WritesDone methods. It
|
||||
/// should not be called concurrently with other streaming APIs
|
||||
/// on the same stream. It is not meaningful to call it concurrently
|
||||
/// with another \a ReaderInterface::Read on the same stream since reads on
|
||||
/// the same stream are delivered in order.
|
||||
///
|
||||
/// \param[out] msg Where to eventually store the read message.
|
||||
/// \param[in] tag The tag identifying the operation.
|
||||
bool Read(RequestType* request) override { |
||||
if (read_done_) { |
||||
return false; |
||||
} |
||||
read_done_ = true; |
||||
return body_.Read(request); |
||||
} |
||||
|
||||
/// Block to write \a msg to the stream with WriteOptions \a options.
|
||||
/// This is thread-safe with respect to \a ReaderInterface::Read
|
||||
///
|
||||
/// \param msg The message to be written to the stream.
|
||||
/// \param options The WriteOptions affecting the write operation.
|
||||
///
|
||||
/// \return \a true on success, \a false when the stream has been closed.
|
||||
using internal::WriterInterface<ResponseType>::Write; |
||||
bool Write(const ResponseType& response, |
||||
::grpc::WriteOptions options) override { |
||||
return read_done_ && body_.Write(response, options); |
||||
} |
||||
|
||||
private: |
||||
internal::ServerReaderWriterBody<ResponseType, RequestType> body_; |
||||
bool read_done_; |
||||
|
||||
friend class ::grpc::internal::TemplatedBidiStreamingHandler< |
||||
ServerSplitStreamer<RequestType, ResponseType>, false>; |
||||
ServerSplitStreamer(::grpc::internal::Call* call, |
||||
::grpc_impl::ServerContext* ctx) |
||||
: body_(call, ctx), read_done_(false) {} |
||||
}; |
||||
|
||||
} // namespace grpc_impl
|
||||
|
||||
#endif // GRPCPP_IMPL_CODEGEN_SYNC_STREAM_IMPL_H
|
@ -0,0 +1,24 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2019 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_SUPPORT_ASYNC_STREAM_IMPL_H |
||||
#define GRPCPP_SUPPORT_ASYNC_STREAM_IMPL_H |
||||
|
||||
#include <grpcpp/impl/codegen/async_stream_impl.h> |
||||
|
||||
#endif // GRPCPP_SUPPORT_ASYNC_STREAM_IMPL_H
|
@ -0,0 +1,24 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2019 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_SUPPORT_ASYNC_UNARY_CALL_IMPL_H |
||||
#define GRPCPP_SUPPORT_ASYNC_UNARY_CALL_IMPL_H |
||||
|
||||
#include <grpcpp/impl/codegen/async_unary_call_impl.h> |
||||
|
||||
#endif // GRPCPP_SUPPORT_ASYNC_UNARY_CALL_IMPL_H
|
@ -0,0 +1,24 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2019 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_SUPPORT_CLIENT_CALLBACK_IMPL_H |
||||
#define GRPCPP_SUPPORT_CLIENT_CALLBACK_IMPL_H |
||||
|
||||
#include <grpcpp/impl/codegen/client_callback_impl.h> |
||||
|
||||
#endif // GRPCPP_SUPPORT_CLIENT_CALLBACK_IMPL_H
|
@ -0,0 +1,24 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2019 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_SUPPORT_SERVER_CALLBACK_IMPL_H |
||||
#define GRPCPP_SUPPORT_SERVER_CALLBACK_IMPL_H |
||||
|
||||
#include <grpcpp/impl/codegen/server_callback_impl.h> |
||||
|
||||
#endif // GRPCPP_SUPPORT_SERVER_CALLBACK_IMPL_H
|
@ -0,0 +1,24 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2019 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_SUPPORT_SYNC_STREAM_IMPL_H |
||||
#define GRPCPP_SUPPORT_SYNC_STREAM_IMPL_H |
||||
|
||||
#include <grpcpp/impl/codegen/sync_stream_impl.h> |
||||
|
||||
#endif // GRPCPP_SUPPORT_SYNC_STREAM_IMPL_H
|
@ -0,0 +1,120 @@ |
||||
# gRPC Bazel BUILD file. |
||||
# |
||||
# Copyright 2016 gRPC authors. |
||||
# |
||||
# Licensed under the Apache License, Version 2.0 (the "License"); |
||||
# you may not use this file except in compliance with the License. |
||||
# You may obtain a copy of the License at |
||||
# |
||||
# http://www.apache.org/licenses/LICENSE-2.0 |
||||
# |
||||
# Unless required by applicable law or agreed to in writing, software |
||||
# distributed under the License is distributed on an "AS IS" BASIS, |
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
# See the License for the specific language governing permissions and |
||||
# limitations under the License. |
||||
|
||||
licenses(["notice"]) # Apache v2 |
||||
|
||||
exports_files(["LICENSE"]) |
||||
|
||||
package( |
||||
default_visibility = ["//visibility:public"], |
||||
features = [ |
||||
"-layering_check", |
||||
"-parse_headers", |
||||
], |
||||
) |
||||
|
||||
load( |
||||
"//bazel:grpc_build_system.bzl", |
||||
"grpc_cc_library", |
||||
"grpc_proto_plugin", |
||||
) |
||||
|
||||
grpc_cc_library( |
||||
name = "grpc_plugin_support", |
||||
srcs = [ |
||||
"cpp_generator.cc", |
||||
"csharp_generator.cc", |
||||
"node_generator.cc", |
||||
"objective_c_generator.cc", |
||||
"php_generator.cc", |
||||
"python_generator.cc", |
||||
"ruby_generator.cc", |
||||
], |
||||
hdrs = [ |
||||
"config_protobuf.h", |
||||
"config.h", |
||||
"cpp_generator.h", |
||||
"cpp_generator_helpers.h", |
||||
"cpp_plugin.h", |
||||
"csharp_generator.h", |
||||
"csharp_generator_helpers.h", |
||||
"generator_helpers.h", |
||||
"node_generator.h", |
||||
"node_generator_helpers.h", |
||||
"objective_c_generator.h", |
||||
"objective_c_generator_helpers.h", |
||||
"php_generator.h", |
||||
"php_generator_helpers.h", |
||||
"protobuf_plugin.h", |
||||
"python_generator.h", |
||||
"python_generator_helpers.h", |
||||
"python_private_generator.h", |
||||
"ruby_generator.h", |
||||
"ruby_generator_helpers-inl.h", |
||||
"ruby_generator_map-inl.h", |
||||
"ruby_generator_string-inl.h", |
||||
"schema_interface.h", |
||||
], |
||||
external_deps = [ |
||||
"protobuf_clib", |
||||
], |
||||
language = "c++", |
||||
deps = [ |
||||
"//:grpc++_config_proto", |
||||
], |
||||
) |
||||
|
||||
grpc_proto_plugin( |
||||
name = "grpc_cpp_plugin", |
||||
srcs = ["cpp_plugin.cc"], |
||||
deps = [":grpc_plugin_support"], |
||||
) |
||||
|
||||
grpc_proto_plugin( |
||||
name = "grpc_csharp_plugin", |
||||
srcs = ["csharp_plugin.cc"], |
||||
deps = [":grpc_plugin_support"], |
||||
) |
||||
|
||||
grpc_proto_plugin( |
||||
name = "grpc_node_plugin", |
||||
srcs = ["node_plugin.cc"], |
||||
deps = [":grpc_plugin_support"], |
||||
) |
||||
|
||||
grpc_proto_plugin( |
||||
name = "grpc_objective_c_plugin", |
||||
srcs = ["objective_c_plugin.cc"], |
||||
deps = [":grpc_plugin_support"], |
||||
) |
||||
|
||||
grpc_proto_plugin( |
||||
name = "grpc_php_plugin", |
||||
srcs = ["php_plugin.cc"], |
||||
deps = [":grpc_plugin_support"], |
||||
) |
||||
|
||||
grpc_proto_plugin( |
||||
name = "grpc_python_plugin", |
||||
srcs = ["python_plugin.cc"], |
||||
deps = [":grpc_plugin_support"], |
||||
) |
||||
|
||||
grpc_proto_plugin( |
||||
name = "grpc_ruby_plugin", |
||||
srcs = ["ruby_plugin.cc"], |
||||
deps = [":grpc_plugin_support"], |
||||
) |
@ -0,0 +1,52 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2019 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef SRC_COMPILER_CONFIG_PROTOBUF_H |
||||
#define SRC_COMPILER_CONFIG_PROTOBUF_H |
||||
|
||||
#include <grpcpp/impl/codegen/config_protobuf.h> |
||||
|
||||
#ifndef GRPC_CUSTOM_CODEGENERATOR |
||||
#include <google/protobuf/compiler/code_generator.h> |
||||
#define GRPC_CUSTOM_CODEGENERATOR ::google::protobuf::compiler::CodeGenerator |
||||
#define GRPC_CUSTOM_GENERATORCONTEXT \ |
||||
::google::protobuf::compiler::GeneratorContext |
||||
#endif |
||||
|
||||
#ifndef GRPC_CUSTOM_PRINTER |
||||
#include <google/protobuf/io/coded_stream.h> |
||||
#include <google/protobuf/io/printer.h> |
||||
#include <google/protobuf/io/zero_copy_stream_impl_lite.h> |
||||
#define GRPC_CUSTOM_PRINTER ::google::protobuf::io::Printer |
||||
#define GRPC_CUSTOM_CODEDOUTPUTSTREAM ::google::protobuf::io::CodedOutputStream |
||||
#define GRPC_CUSTOM_STRINGOUTPUTSTREAM \ |
||||
::google::protobuf::io::StringOutputStream |
||||
#endif |
||||
|
||||
#ifndef GRPC_CUSTOM_PLUGINMAIN |
||||
#include <google/protobuf/compiler/plugin.h> |
||||
#define GRPC_CUSTOM_PLUGINMAIN ::google::protobuf::compiler::PluginMain |
||||
#endif |
||||
|
||||
#ifndef GRPC_CUSTOM_PARSEGENERATORPARAMETER |
||||
#include <google/protobuf/compiler/code_generator.h> |
||||
#define GRPC_CUSTOM_PARSEGENERATORPARAMETER \ |
||||
::google::protobuf::compiler::ParseGeneratorParameter |
||||
#endif |
||||
|
||||
#endif // SRC_COMPILER_CONFIG_PROTOBUF_H
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue