API Documentation

TChannel

class tchannel.tornado.TChannel(name, hostport=None, process_name=None, known_peers=None, trace=False)[source]

Manages inbound and outbound connections to various hosts.

advertise(routers, name=None, timeout=None)[source]

Make a service available on the Hyperbahn routing mesh.

This will make contact with a Hyperbahn host from a list of known Hyperbahn routers. Additional Hyperbahn connections will be established once contact has been made with the network.

Parameters:
  • router – A seed list of addresses of Hyperbahn routers, e.g., ["127.0.0.1:23000"].
  • name

    The identity of this service on the Hyperbahn.

    This is usually unnecessary, as it defaults to the name given when initializing the TChannel (which is used as your identity as a caller).

Returns:

A future that resolves to the remote server’s response after the first advertise finishes.

Advertisement will continue to happen periodically.

listen(port=None)[source]

Start listening for incoming connections.

A request handler must have already been specified with TChannel.host.

Parameters:port – An explicit port to listen on. This is unnecessary when advertising on Hyperbahn.
Returns:Returns immediately.
Raises AlreadyListeningError:
 If listen was already called.
register(endpoint, scheme=None, handler=None, **kwargs)[source]

Register a handler with this TChannel.

This may be used as a decorator:

app = TChannel(name='foo')

@app.register("hello", "json")
def hello_handler(request, response, tchannel):
    params = yield request.get_body()

Or as a function:

# Here we have a Thrift handler for `Foo::hello`
app.register(Foo, "hello", hello_thrift_handler)
Parameters:
  • endpoint – Name of the endpoint being registered for raw and JSON arg schemes. Reference to the Thrift-generated module for the Thrift arg scheme.
  • scheme – Name of the scheme under which the endpoint is being registered. One of “raw”, “json”, and “thrift”. Defaults to “raw”, except if “endpoint” was a module, in which case this defaults to “thrift”.
  • handler – If specified, this is the handler function. If ignored, this function returns a decorator that can be used to register the handler function.
Returns:

If handler was specified, this returns handler. Otherwise, it returns a decorator that can be applied to a function to register it as the handler.

request(hostport=None, service=None, arg_scheme=None, retry=None, **kwargs)[source]

Initiate a new request through this TChannel.

Parameters:
  • hostport – Host to which the request will be made. If unspecified, a random known peer will be picked. This is not necessary if using Hyperbahn.
  • service – The name of a service available on Hyperbahn. Defaults to an empty string.
  • arg_scheme – Determines the serialization scheme for the request. One of ‘raw’, ‘json’, or ‘thrift’. Defaults to ‘raw’.
  • rety

    One of ‘n’ (never retry), ‘c’ (retry on connection errors), ‘t’ (retry on timeout), ‘ct’ (retry on connection errors and timeouts).

    Defaults to ‘c’.

class tchannel.tornado.RequestDispatcher[source]

A synchronous RequestHandler that dispatches calls to different endpoints based on arg1.

Endpoints are registered using register or the route decorator.

handler = # ...

@handler.route('my_method')
def my_method(request, response, proxy):
    response.write('hello world')
static not_found(request, response, proxy)[source]

Default behavior for requests to unrecognized endpoints.

register(rule, handler, broker=None)[source]

Register a new endpoint with the given name.

@dispatcher.register('is_healthy')
def check_health(request, response, proxy):
    # ...
Parameters:
  • rule

    Name of the endpoint. Incoming Call Requests must have this as arg1 to dispatch to this handler.

    If RequestHandler.FALLBACK is specified as a rule, the given handler will be used as the ‘fallback’ handler when requests don’t match any registered rules.

  • handler – A function that gets called with Request, Response, and the proxy.
  • broker

    Broker injects customized serializer and deserializer into request/response object.

    broker==None means it registers as raw handle. It deals with raw buffer in the request/response.

route(rule, helper=None)[source]

See register for documentation.

class tchannel.tornado.Request(id=None, flags=0, ttl=1000, tracing=None, service=None, headers=None, checksum=None, argstreams=None, scheme=None, endpoint=None)[source]

Represents an incoming request to an endpoint.

Request class is used to represent the CallRequestMessage at User’s level. This is going to hide the protocol level message information.

get_body(*args, **kwargs)[source]

Get the body value from the resquest.

Returns:a future contains the deserialized value of body
get_body_s()[source]

Get the raw stream of body.

Returns:the argstream of body
get_header(*args, **kwargs)[source]

Get the header value from the request.

Returns:a future contains the deserialized value of header
get_header_s()[source]

Get the raw stream of header.

Returns:the argstream of header
should_retry_on_error(error)[source]

rules for retry

Parameters:error – ProtocolException that returns from Server
class tchannel.tornado.Response(connection=None, id=None, flags=None, code=None, tracing=None, headers=None, checksum=None, argstreams=None, scheme=None)[source]

An outgoing response.

Response class is used to represent the CallResponseMessage at User’s level. This is going to hide the protocol level message information.

flush()[source]

Flush the response buffer.

No more write or set operations is allowed after flush call.

get_body(*args, **kwargs)[source]

Get the body value from the response.

Returns:a future contains the deserialized value of body
get_body_s()[source]

Get the raw stream of body.

Returns:the argstream of body
get_header(*args, **kwargs)[source]

Get the header value from the response.

Returns:a future contains the deserialized value of header
get_header_s()[source]

Get the raw stream of header.

Returns:the argstream of header
set_body_s(stream)[source]

Set customized body stream.

Note: the body stream can only be changed before the stream is consumed.

Parameters:stream – InMemStream/PipeStream for body
Raises TChannelError:
 Raise TChannelError if the stream is being sent when you try to change the stream.
set_header_s(stream)[source]

Set customized header stream.

Note: the header stream can only be changed before the stream is consumed.

Parameters:stream – InMemStream/PipeStream for header
Raises TChannelError:
 Raise TChannelError if the stream is being sent when you try to change the stream.
write_body(chunk)[source]

Write to header.

Note: whenever write_body is called, the header stream will be closed. write_header method is unavailable.

Parameters:chunk – content to write to body
Raises TChannelError:
 Raise TChannelError if the response’s flush() has been called
write_header(chunk)[source]

Write to header.

Note: the header stream is only available to write before write body.

Parameters:chunk – content to write to header
Raises TChannelError:
 Raise TChannelError if the response’s flush() has been called

Exceptions

exception tchannel.errors.AdvertiseError[source]

Represent advertise failure exception

exception tchannel.errors.AlreadyListeningError[source]

Represents exception from attempting to listen multiple times.

exception tchannel.errors.InvalidChecksumError[source]

Represent invalid checksum type in the message

exception tchannel.errors.InvalidEndpointError[source]

Represent an message containing invalid endpoint.

exception tchannel.errors.InvalidErrorCodeError(code)[source]

Represent Invalid Error Code exception

exception tchannel.errors.InvalidMessageError[source]

Represent an invalid message.

exception tchannel.errors.NoAvailablePeerError[source]

Represents a failure to find any peers for a request.

exception tchannel.errors.ProtocolError(code, description, id=None, tracing=None)[source]

Represent a protocol-level exception

exception tchannel.errors.ReadError[source]

Raised when there is an error while reading input.

exception tchannel.errors.StreamingError[source]

Represent Streaming Message Exception

exception tchannel.errors.TChannelApplicationError(code, args)[source]

The remote application returned an exception.

This is not a protocol error. This means a response was received with the code flag set to fail.

exception tchannel.errors.TChannelError[source]

Represent a TChannel-generated exception.

Thrift

tchannel.thrift.client.client_for(service, service_module, thrift_service_name=None)[source]

Build a client class for the given Thrift service.

The generated class accepts a TChannel and an optional hostport as initialization arguments.

Given CommentService defined in comment.thrift and registered with Hyperbahn under the name “comment”, here’s how this may be used:

from comment import CommentService

CommentServiceClient = client_for("comment", CommentService)

@gen.coroutine
def post_comment(articleId, msg, hostport=None):
    client = CommentServiceClient(tchannel, hostport)
    yield client.postComment(articleId, CommentService.Comment(msg))
Parameters:
  • service – Name of the Hyperbahn service being called. This is the name with which the service registered with Hyperbahn.
  • service_module – The Thrift-generated module for that service. This usually has the same name as defined for the service in the IDL.
  • thrift_service_name – If the Thrift service has a different name than its module, use this parameter to specify it.
Returns:

An object with the same interface as the service that uses the given TChannel to call the service.

tchannel.thrift.client.generate_method(service_module, service_name, method_name)[source]

Generate a method for the given Thrift service.

Parameters:
  • service_module – Thrift-generated service module
  • service_name – Name of the Thrift service
  • method_name – Method being called

Synchronous Client

class tchannel.sync.client.Response(header, body)
body

Alias for field number 1

header

Alias for field number 0

class tchannel.sync.client.SyncClientOperation(operation, threadloop)[source]

Allows making client operation requests synchronously.

This object acts like tchannel.TChannelClientOperation, but instead uses a threadloop to make the request synchronously.

send(arg1, arg2, arg3)[source]

Send the given triple over the wire.

Parameters:
  • arg1 – String containing the contents of arg1. If None, an empty string is used.
  • arg2 – String containing the contents of arg2. If None, an empty string is used.
  • arg3 – String containing the contents of arg3. If None, an empty string is used.
Return concurrent.futures.Future:
 

Future response from the peer.

class tchannel.sync.client.TChannelSyncClient(name, process_name=None, known_peers=None, trace=False)[source]

Make synchronous TChannel requests.

This client does not support incoming connections or requests- this is a uni-directional client only.

The client is implemented on top of the Tornado-based implementation and starts and stops IOLoops on-demand.

client = TChannelSyncClient()
response = client.request(
    hostport='localhost:4040',
    service='HelloService',
).send(
    'hello', None, json.dumps({"name": "World"})
)
advertise(routers, name=None, timeout=None)[source]

Advertise with Hyperbahn.

Parameters:
  • routers – list of hyperbahn addresses to advertise to.
  • name – service name to advertise with.
  • timeout – backoff period for failed requests.
Returns:

first advertise result.

Raises AdvertiseError:
 

when unable to begin advertising.

request(*args, **kwargs)[source]

Initiate a new request to a peer.

Parameters:
  • hostport – If specified, requests will be sent to the specific host. Otherwise, a known peer will be picked at random.
  • service – Name of the service being called. Defaults to an empty string.
  • service_threshold – If hostport was not specified, this specifies the score threshold at or below which peers will be ignored.
Returns SyncClientOperation:
 

An object with a send(arg1, arg2, arg3) operation.

tchannel.sync.thrift.client_for(service, service_module, thrift_service_name=None)[source]

Build a synchronous client class for the given Thrift service.

The generated class accepts a TChannelSyncClient and an optional hostport as initialization arguments.

Given CommentService defined in comment.thrift and registered with Hyperbahn under the name “comment”, here’s how this might be used:

from tchannel.sync import TChannelSyncClient
from tchannel.sync.thrift import client_for

from comment import CommentService

CommentServiceClient = client_for('comment', CommentService)

tchannel_sync = TChannelSyncClient('my-service')
comment_client = CommentServiceClient(tchannel_sync)

future = comment_client.postComment(
    articleId,
    CommentService.Comment("hi")
)
result = future.result()
Parameters:
  • service – Name of the Hyperbahn service being called.
  • service_module – The Thrift-generated module for that service. This usually has the same name as definied for the service in the IDL.
  • thrift_service_name – If the Thrift service has a different name than its module, use this parameter to specify it.
Returns:

An Thrift-like class, ready to be instantiated and used with TChannelSyncClient.

tchannel.sync.thrift.generate_method(method_name)[source]

Generate a method for a given Thrift service.

Uses the provided TChannelSyncClient’s threadloop in order to convert RPC calls to concurrent.futures

Parameters:method_name – Method being called.
Returns:A method that invokes the RPC using TChannelSyncClient