Kako koristiti Googleove međuspremnike protokola u Pythonu

Kad se ljudi koji govore različite jezike okupe i razgovaraju, pokušavaju koristiti jezik koji svi u grupi razumiju.

Da bi to postigao, svatko mora svoje misli, koje su obično na materinjem jeziku, prevesti na jezik grupe. Ovo "kodiranje i dekodiranje" jezika, međutim, dovodi do gubitka učinkovitosti, brzine i preciznosti.

Isti koncept prisutan je u računalnim sustavima i njihovim komponentama. Zašto bismo podatke trebali slati u XML-u, JSON-u ili bilo kojem drugom čitljivom formatu ako nema potrebe da razumijemo o čemu oni izravno govore? Sve dok ga možemo izravno prevesti u čitljiv format ako je to izričito potrebno.

Međuspremnici protokola način su kodiranja podataka prije prijevoza, koji učinkovito smanjuje blokove podataka i stoga povećava brzinu prilikom slanja. Apstrahira podatke u jezik i platformi neutralan format.

Sadržaj

  • Zašto su nam potrebni međuspremnici protokola?
  • Što su međuspremnici protokola i kako rade?
  • Međuspremnici protokola u Pythonu
  • Završne napomene

Zašto protokoli?

Početna svrha međuspremnika protokola bila je pojednostavljivanje rada s protokolima zahtjeva / odgovora. Prije ProtoBufa, Google je koristio drugačiji format koji je zahtijevao dodatno postupanje u razvrstavanju poslanih poruka.

Uz to, nove verzije prethodnog formata zahtijevale su od programera da se pobrinu da nove verzije budu razumljive prije zamjene starih, čineći gnjavažu za rad.

Ova je potreba motivirala Google za dizajn sučelja koje rješava upravo te probleme.

ProtoBuf omogućuje uvođenje promjena u protokol bez narušavanja kompatibilnosti. Također, poslužitelji mogu prolaziti oko podataka i izvršavati operacije čitanja podataka bez izmjene njihovog sadržaja.

Budući da je format pomalo samoopisan, ProtoBuf se koristi kao osnova za automatsko generiranje koda za serializatore i deserijalizatore.

Još je jedan zanimljiv slučaj upotrebe kako ga Google koristi za kratkotrajne pozive daljinskih postupaka (RPC) i za ustrajno spremanje podataka u Bigtable. Zbog svog specifičnog slučaja upotrebe, integrirali su RPC sučelja u ProtoBuf. To omogućuje brzo i jednostavno generiranje kvara koda koji se mogu koristiti kao početne točke za stvarnu implementaciju. (Više o ProtoBuf RPC.)

Ostali primjeri gdje ProtoBuf može biti koristan su za IoT uređaje koji su povezani putem mobilnih mreža u kojima količina poslanih podataka mora biti mala ili za aplikacije u zemljama u kojima su velike propusne širine još uvijek rijetke. Slanje korisnog tereta u optimiziranim binarnim formatima može dovesti do primjetnih razlika u troškovima rada i brzini.

Korištenje gzipkompresije u vašoj HTTPS komunikaciji može dodatno poboljšati te mjerne podatke.

Što su međuspremnici protokola i kako rade?

Općenito govoreći, međuspremnici protokola definirano su sučelje za serializaciju strukturiranih podataka. Definira normalizirani način komunikacije, potpuno neovisan o jezicima i platformama.

Google oglašava svoj ProtoBuf ovako:

Međuspremnici protokola su Googleov jezično neutralan, platforma neutralan, proširiv mehanizam za serializaciju strukturiranih podataka - mislite na XML, ali manji, brži i jednostavniji. Vi definirate kako želite da se vaši podaci jednom strukturiraju ...

Sučelje ProtoBuf opisuje strukturu podataka koji se šalju. Strukture korisnog tereta definirane su kao „poruke“ u onome što se naziva proto-datotekama. Te datoteke uvijek završavaju s.protoproduženje.

Na primjer, osnovna struktura datoteke todolist.proto izgleda ovako. Kompletni primjer također ćemo pogledati u sljedećem odjeljku.

syntax = "proto3"; // Not necessary for Python, should still be declared to avoid name collisions // in the Protocol Buffers namespace and non-Python languages package protoblog; message TodoList { // Elements of the todo list will be defined here ... }

Te se datoteke zatim koriste za generiranje klasa integracije ili klasova za jezik po vašem izboru pomoću generatora koda unutar kompajlera protoc. Trenutna verzija, Proto3, već podržava sve glavne programske jezike. Zajednica podržava mnogo više u implementacijama otvorenog koda treće strane.

Generirane klase ključni su elementi međuspremnika protokola. Omogućuju stvaranje elemenata instanciranjem novih poruka, na temelju .protodatoteka, koje se zatim koriste za serializaciju. Kako se to radi s Pythonom detaljno ćemo pogledati u sljedećem odjeljku.

Neovisno o jeziku za serializaciju, poruke su serializirane u binarni format koji se ne opisuje i koji je prilično beskoristan bez početne definicije strukture.

Tada se binarni podaci mogu pohraniti, poslati putem mreže i koristiti na bilo koji drugi način čitljivim podacima poput JSON-a ili XML-a. Nakon prijenosa ili pohrane, byte-stream se može deserijalizirati i vratiti pomoću bilo koje kompajlirane klase protobuf specifične za jezik koju generiramo iz .proto datoteke.

Koristeći Python kao primjer, postupak bi mogao izgledati otprilike ovako:

Prvo stvorimo novi popis zadataka i popunjavamo ga nekim zadacima. Taj se popis zadataka zatim serializira i šalje mrežom, sprema u datoteku ili se trajno pohranjuje u bazu podataka.

Poslani bajtni tok deserijalizira se metodom raščlanjivanja naše kompajlirane klase specifične za jezik.

Većina trenutnih arhitektura i infrastruktura, posebno mikroservisa, temelje se na REST, WebSockets ili GraphQL komunikaciji. Međutim, kada su brzina i učinkovitost bitni, RPC-ovi na niskoj razini mogu napraviti veliku razliku.

Umjesto protokola visokih troškova, možemo koristiti brz i kompaktan način za premještanje podataka između različitih entiteta u našu uslugu bez gubljenja mnogo resursa.

Ali zašto se još uvijek ne koristi svugdje?

Međuspremnici protokola malo su složeniji od ostalih, čovjeku čitljivih formata. To ih čini relativno težim za uklanjanje pogrešaka i integraciju u vaše aplikacije.

Vrijeme ponavljanja u inženjerstvu također se povećava, jer ažuriranja podataka zahtijevaju ažuriranje proto datoteka prije upotrebe.

Treba pažljivo razmotriti jer bi ProtoBuf u mnogim slučajevima mogao biti preinženjerirano rješenje.

Koje alternative imam?

Several projects take a similar approach to Google’s Protocol Buffers.

Google’s Flatbuffers and a third party implementation, called Cap’n Proto, are more focused on removing the parsing and unpacking step, which is necessary to access the actual data when using ProtoBufs. They have been designed explicitly for performance-critical applications, making them even faster and more memory efficient than ProtoBuf.

When focusing on the RPC capabilities of ProtoBuf (used with gRPC), there are projects from other large companies like Facebook (Apache Thrift) or Microsoft (Bond protocols) that can offer alternatives.

Python and Protocol Buffers

Python already provides some ways of data persistence using pickling. Pickling is useful in Python-only applications. It's not well suited for more complex scenarios where data sharing with other languages or changing schemas is involved.

Protocol Buffers, in contrast, are developed for exactly those scenarios.

The .proto files, we’ve quickly covered before, allow the user to generate code for many supported languages.

To compile the .protofile to the language class of our choice, we use protoc, the proto compiler.

If you don’t have the protoc compiler installed, there are excellent guides on how to do that:

  • MacOS / Linux
  • Windows

Once we’ve installed protoc on our system, we can use an extended example of our todo list structure from before and generate the Python integration class from it.

syntax = "proto3"; // Not necessary for Python but should still be declared to avoid name collisions // in the Protocol Buffers namespace and non-Python languages package protoblog; // Style guide prefers prefixing enum values instead of surrounding // with an enclosing message enum TaskState { TASK_OPEN = 0; TASK_IN_PROGRESS = 1; TASK_POST_PONED = 2; TASK_CLOSED = 3; TASK_DONE = 4; } message TodoList { int32 owner_id = 1; string owner_name = 2; message ListItems { TaskState state = 1; string task = 2; string due_date = 3; } repeated ListItems todos = 3; } 

Let’s take a more detailed look at the structure of the .proto file to understand it.

In the first line of the proto file, we define whether we’re using Proto2 or 3. In this case, we’re using Proto3.

The most uncommon elements of proto files are the numbers assigned to each entity of a message. Those dedicated numbers make each attribute unique and are used to identify the assigned fields in the binary encoded output.

One important concept to grasp is that only values 1-15 are encoded with one less byte (Hex), which is useful to understand so we can assign higher numbers to the less frequently used entities. The numbers define neitherthe order of encoding nor the position of the given attribute in the encoded message.

The package definition helps prevent name clashes. In Python, packages are defined by their directory. Therefore providing a package attribute doesn’t have any effect on the generated Python code.

Please note that this should still be declared to avoid protocol buffer related name collisions and for other languages like Java.

Enumerations are simple listings of possible values for a given variable.

In this case, we define an Enum for the possible states of each task on the todo list.

We’ll see how to use them in a bit when we look at the usage in Python.

As we can see in the example, we can also nest messages inside messages.

If we, for example, want to have a list of todos associated with a given todo list, we can use the repeated keyword, which is comparable to dynamically sized arrays.

To generate usable integration code, we use the proto compiler which compiles a given .proto file into language-specific integration classes. In our case we use the --python-out argument to generate Python-specific code.

protoc -I=. --python_out=. ./todolist.proto

In the terminal, we invoke the protocol compiler with three parameters:

  1. -I: defines the directory where we search for any dependencies (we use . which is the current directory)
  2. --python_out: defines the location we want to generate a Python integration class in (again we use . which is the current directory)
  3. The last unnamed parameter defines the .proto file that will be compiled (we use the todolist.proto file in the current directory)

This creates a new Python file called _pb2.py. In our case, it is todolist_pb2.py. When taking a closer look at this file, we won’t be able to understand much about its structure immediately.

This is because the generator doesn’t produce direct data access elements, but further abstracts away the complexity using metaclasses and descriptors for each attribute. They describe how a class behaves instead of each instance of that class.

The more exciting part is how to use this generated code to create, build, and serialize data. A straightforward integration done with our recently generated class is seen in the following:

import todolist_pb2 as TodoList my_list = TodoList.TodoList() my_list.owner_id = 1234 my_list.owner_name = "Tim" first_item = my_list.todos.add() first_item.state = TodoList.TaskState.Value("TASK_DONE") first_item.task = "Test ProtoBuf for Python" first_item.due_date = "31.10.2019" print(my_list)

It merely creates a new todo list and adds one item to it. We then print the todo list element itself and can see the non-binary, non-serialized version of the data we just defined in our script.

owner_id: 1234 owner_name: "Tim" todos { state: TASK_DONE task: "Test ProtoBuf for Python" due_date: "31.10.2019" }

Each Protocol Buffer class has methods for reading and writing messages using a Protocol Buffer-specific encoding, that encodes messages into binary format.

Those two methods are SerializeToString() and ParseFromString().

import todolist_pb2 as TodoList my_list = TodoList.TodoList() my_list.owner_id = 1234 # ... with open("./serializedFile", "wb") as fd: fd.write(my_list.SerializeToString()) my_list = TodoList.TodoList() with open("./serializedFile", "rb") as fd: my_list.ParseFromString(fd.read()) print(my_list)

In the code example above, we write the Serialized string of bytes into a file using the wb flags.

Since we have already written the file, we can read back the content and Parse it using ParseFromString. ParseFromString calls on a new instance of our Serialized class using the rb flags and parses it.

If we serialize this message and print it in the console, we get the byte representation which looks like this.

b'\x08\xd2\t\x12\x03Tim\x1a(\x08\x04\x12\x18Test ProtoBuf for Python\x1a\n31.10.2019'

Note the b in front of the quotes. This indicates that the following string is composed of byte octets in Python.

If we directly compare this to, e.g., XML, we can see the impact ProtoBuf serialization has on the size.

 1234 Tim   TASK_DONE Test ProtoBuf for Python 31.10.2019   

The JSON representation, non-uglified, would look like this.

{ "todoList": { "ownerId": "1234", "ownerName": "Tim", "todos": [ { "state": "TASK_DONE", "task": "Test ProtoBuf for Python", "dueDate": "31.10.2019" } ] } }

Judging the different formats only by the total number of bytes used, ignoring the memory needed for the overhead of formatting it, we can of course see the difference.

But in addition to the memory used for the data, we also have 12 extra bytes in ProtoBuf for formatting serialized data. Comparing that to XML, we have 171 extra bytes in XML for formatting serialized data.

Without Schema, we need 136 extra bytes in JSON forformattingserialized data.

If we’re talking about several thousands of messages sent over the network or stored on disk, ProtoBuf can make a difference.

However, there is a catch. The platform Auth0.com created an extensive comparison between ProtoBuf and JSON. It shows that, when compressed, the size difference between the two can be marginal (only around 9%).

If you’re interested in the exact numbers, please refer to the full article, which gives a detailed analysis of several factors like size and speed.

An interesting side note is that each data type has a default value. If attributes are not assigned or changed, they will maintain the default values. In our case, if we don’t change the TaskState of a ListItem, it has the state of “TASK_OPEN” by default. The significant advantage of this is that non-set values are not serialized, saving additional space.

If we, for example, change the state of our task from TASK_DONE to TASK_OPEN, it will not be serialized.

owner_id: 1234 owner_name: "Tim" todos { task: "Test ProtoBuf for Python" due_date: "31.10.2019" }

b'\x08\xd2\t\x12\x03Tim\x1a&\x12\x18Test ProtoBuf for Python\x1a\n31.10.2019'

Final Notes

As we have seen, Protocol Buffers are quite handy when it comes to speed and efficiency when working with data. Due to its powerful nature, it can take some time to get used to the ProtoBuf system, even though the syntax for defining new messages is straightforward.

As a last note, I want to point out that there were/are discussions going on about whether Protocol Buffers are “useful” for regular applications. They were developed explicitly for problems Google had in mind.

If you have any questions or feedback, feel free to reach out to me on any social media like twitter or email :)