Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you say in a Thrift IDL that a client should include exactly one of a set of fields in a struct?

Tags:

thrift

Suppose I have defined a struct in an Apache Thrift IDL file which contains two fields. For example:

struct Thing {
  1: optional string name,
  2: optional i32 size
}

This means a client can supply a Thing object with no fields, a name, a size, or a name and a size. But what if I want a Thing object to have either a name or a size (exclusive or)? At the moment I have to use my implementation code to guard against a client supplying a Thing with no fields or both fields; and also document/comment how the client should specify a Thing object.

In short, if someone defines a struct containing various fields, is it possible to express in the IDL itself that you only want exactly one of those fields to be supplied in a client? (I'm using Apache Thrift 0.9.0.) It would be great if you could say something like the following (| = or):

struct Thing {
  1: required (string name | i32 size)
}
like image 429
snark Avatar asked Sep 20 '13 18:09

snark


People also ask

What is a struct in Thrift?

Structs. Thrift structs define a common object – they are essentially equivalent to classes in OOP languages, but without inheritance. A struct has a set of strongly typed fields, each with a unique name identifier. Fields may have various annotations (numeric field IDs, optional default values, etc.)

What is Thrift IDL?

The Thrift interface definition language (IDL) allows for the definition of Thrift Types. A Thrift IDL file is processed by the Thrift code generator to produce code for the various target languages to support the defined structs and services in the IDL file.

What is Thrift protocol?

Thrift is an interface definition language and binary communication protocol used for defining and creating services for numerous programming languages.

Is Thrift an RPC?

Thrift is a lightweight, language-independent software stack with an associated code generation mechanism for RPC. Thrift provides clean abstractions for data transport, data serialization, and application level processing. Thrift was originally developed by Facebook and now it is open sourced as an Apache project.


1 Answers

Use unions:

union Thing {
  1: string name,
  2: i32 size
}

Optional can be omitted, required is not allowed/useful with unions.

Unions have been introduced with 0.9.0 (IIRC) but 0.9.1 has improved support of them.

like image 146
JensG Avatar answered Oct 04 '22 01:10

JensG