#ProtocolBuffers
Explore tagged Tumblr posts
Text
CloudFront Now Supports gRPC Calls For Your Applications

Your applications’ gRPC calls are now accepted by Amazon CloudFront.
You may now set up global content delivery network (CDN), Amazon CloudFront, in front of your gRPC API endpoints.
An Overview of gRPC
You may construct distributed apps and services more easily with gRPC since a client program can call a method on a server application on a separate machine as if it were a local object. The foundation of gRPC, like that of many RPC systems, is the concept of establishing a service, including the methods that may be called remotely along with their parameters and return types. This interface is implemented by the server, which also uses a gRPC server to manage client requests. The same methods as the server are provided by the client’s stub, which is sometimes referred to as just a client.
Any of the supported languages can be used to write gRPC clients and servers, which can operate and communicate with one another in a range of settings, including your desktop computer and servers within Google. For instance, a gRPC server in Java with clients in Go, Python, or Ruby can be readily created. Furthermore, the most recent Google APIs will include gRPC interfaces, making it simple to incorporate Google functionality into your apps.
Using Protocol Buffers
Although it can be used with other data formats like JSON, gRPC by default serializes structured data using Protocol Buffers, Google’s well-established open source method.
Establishing the structure for the data you wish to serialize in a proto file a regular text file with a.proto extension is the first step in dealing with protocol buffers. Protocol buffer data is organized as messages, each of which is a brief logical record of data made up of a number of fields, or name-value pairs.
After defining your data structures, you can use the protocol buffer compiler protoc to create data access classes from your proto specification in the language or languages of your choice. These offer methods to serialize and parse the entire structure to and from raw bytes, along with basic accessors for each field, such as name() and set_name(). For example, executing the compiler on the aforementioned example will produce a class named Person if you have selected C++ as your language. This class can then be used to serialize, retrieve, and populate Person protocol buffer messages in your application.
You specify RPC method parameters and return types as protocol buffer messages when defining gRPC services in standard proto files:
Protoc is used by gRPC with a specific gRPC plugin to generate code from your proto file. This includes the standard protocol buffer code for populating, serializing, and retrieving your message types, as well as generated gRPC client and server code.
Versions of protocol buffers
Although open source users have had access to protocol buffers for a while, the majority of the examples on this website use protocol buffers version 3 (proto3), which supports more languages, has a little simplified syntax, and several helpful new capabilities. In addition to a Go language generator from the golang/protobuf official package, Proto3 is presently available in Java, C++, Dart, Python, Objective-C, C#, a lite-runtime (Android Java), Ruby, and JavaScript from the protocol buffers GitHub repository. Additional languages are being developed.
Although proto2 (the current default protocol buffers version) can be used, it advises using proto3 with gRPC instead because it allows you to use all of the languages that gRPC supports and prevents incompatibilities between proto2 clients and proto3 servers.
What is gRPC?
A contemporary, open-source, high-performance Remote Procedure Call (RPC) framework that works in any setting is called gRPC. By supporting pluggable load balancing, tracing, health checking, and authentication, it may effectively connect services both within and between data centers. It can also be used to link devices, browsers, and mobile apps to backend services in the last mile of distributed computing.
A basic definition of a service
Describe your service using Protocol Buffers, a robust language and toolkit for binary serialization.
Launch swiftly and grow
Use the framework to grow to millions of RPCs per second and install the runtime and development environments with only one line.
Works on a variety of platforms and languages
For your service, automatically create idiomatic client and server stubs in several languages and platforms.
Both-way streaming and integrated authentication
Fully integrated pluggable authentication and bi-directional streaming with HTTP/2-based transport
For creating APIs, gRPC is a cutting-edge, effective, and language-neutral framework. Platform-independent service and message type design is made possible by its interface defining language (IDL), Protocol Buffers (protobuf). With gRPC, remote procedure calls (RPCs) over HTTP/2 are lightweight and highly performant, facilitating communication between services. Microservices designs benefit greatly from this since it facilitates effective and low-latency communication between services.
Features like flow control, bidirectional streaming, and automatic code generation for multiple programming languages are all provided by gRPC. When you need real-time data streaming, effective communication, and great performance, this is a good fit. gRPC may be an excellent option if your application must manage a lot of data or the client and server must communicate with low latency. However, compared to REST, it could be harder to master. Developers must specify their data structures and service methods in.proto files since gRPC uses the protobuf serialization standard.
When you put CloudFront in front of your gRPC API endpoints, we see two advantages.
Initially, it permits the decrease of latency between your API implementation and the client application. A global network of more than 600 edge locations is provided by CloudFront, with intelligent routing to the nearest edge. TLS termination and optional caching for your static content are offered by edge locations. Client application requests are sent to your gRPC origin by CloudFront via the fully managed, high-bandwidth, low-latency private AWS network.
Second, your apps gain from extra security services that are set up on edge locations, like traffic encryption, AWS Web Application Firewall’s HTTP header validation, and AWS Shield Standard defense against distributed denial of service (DDoS) assaults.
Cost and Accessibility
All of the more than 600 CloudFront edge locations offer gRPC origins at no extra cost. There are the standard requests and data transfer costs.
Read more on govindhtech.com
#CloudFront#SupportsgRPC#Applications#Google#AmazonCloudFront#distributeddenialservice#DDoS#Accessibility#ProtocolBuffers#gRPC#technology#technews#news#govindhtech
0 notes
Text
Demystifying the protobuf wire format
https://kreya.app/blog/protocolbuffers-wire-format/
0 notes
Photo

A Simple gRPC- Java API Implentation Example : https://youtu.be/TR-otP45eYU #grpc #Microservices #protocolbuffers #techtter (at SanFrancisco) https://www.instagram.com/p/CBQ7AFzHdZ6/?igshid=yvxriyh6xysl
0 notes
Text
It’s been awhile y’all
It's been a hot minute since I've documented some of my work, so I guess in keeping with making a main blog post, I'll make a devblog post today too.
cfn-mode / flycheck-cfn
https://gitlab.com/worr/cfn-mode/
I've been an emacs user for some time, and at my current job, I've been hurting for good support for cloudformation templates in my editor. I wrote this mode and flychecker to at least add some basic syntax highlighting and linter support. I'm currently in the process of getting them added to MELPA.
imdb-api
I made a bunch of changes fairly recently to imdb-api, most notably adding front-end support, migrating to Gitlab and migrating to ky after node-requests was deprecated. Normally I'd link patches, but there are too many since my last update. Here's the changelog: https://gitlab.com/worr/node-imdb-api/-/blob/master/CHANGELOG.md
fluent-bit
At work, we discovered an issue where our fluent-bits were sticky to the same instance of fluentd if we turned on keepalive and used a load-balancer.
To mitigate this, I ended up adding a new option to fluent-bit that will recycle keepalive connections after sending a number of messages, to cycle between backend instances periodically.
https://github.com/fluent/fluent-bit/commit/44190c2a1c4b939dc9ecb2908148d38c82a40831
https://github.com/fluent/fluent-bit-docs/commit/8d43b502123e366a1722a0051918ce7d78a8506b
fluentd-s3-plugin
Also at work, we found a case where the fluend plugin for s3 would spend forever trying to upload logs. By default, the naming scheme for the log chunks would be something like <time_slice>_<idx>. The time slice is the time when the log was uploaded, and the idx value is a monotonically increasing integer.
The problem, is that if you have mutliple threads uploading (or multiple fluentd's, or both), they have to check the presence of the filename to ensure that the formulated filename doesn't exist. Additionally, it doesn't track the last-used index, so when doing this check, fluentd will start at 1, check, increment, check again, increment again, etc. This obviously doesn't scale very well when you are outputing a ton of logs.
We fixed this my changing our file format to include a uuid and disabling the behavior to check for collisions.
However, since the defaults are dangerous, I've submitted this PR to try and make things less dangerous for new users (not accepted yet at the time of this writing).
https://github.com/fluent/fluent-plugin-s3/pull/355/files
This works by tracking the last used index in an atomic that's shared between threads. As outlined in the PR, it doesn't solve the whole problem, but it does make the defaults considerably safer.
logging-operator
Perhaps you've noticed a theme with my recent, work-driven contributions. :)
logging-operator is a kubernetes operator to automate adminitration of logging infrastructure in a kubernetes cluster. I've been contributing a bit to it lately, since we adopted it fairly early, and have needed to add a few features to make it work for us.
This first diff adds support not just for the configurable I added to fluent-bit that I mentioned earlier, but exposes all net parameters as configurables.
https://github.com/banzaicloud/logging-operator/commit/3c9e3938590209716918bc7cc197b43b09bb4361
There was a string conversion bug in how the operator would report on prometheus configuration.
https://github.com/banzaicloud/logging-operator/commit/86503b52150cf0dcf62d4b636eb247d0807101e7
We needed to configure where in s3 fluentd was uploading these logs
https://github.com/banzaicloud/logging-operator/commit/29fccfc2b8cee6c38c88fb34cf73a112eeb534de
We also needed way more support for configuring certain scheduling attributes in fluentd and fluentbit
https://github.com/banzaicloud/logging-operator/commit/45dffe5ebb38a3dbba4ecb217235f45c13f7856e
https://github.com/banzaicloud/logging-operator/commit/961fd788bb90f8f46d188a731aac0a916b30f933
https://github.com/banzaicloud/logging-operator/commit/0ec91f72831e1e63bd560224450454b33084553d
I also had to expose a number of these features in their helm charts
https://github.com/banzaicloud/logging-operator/commit/efc74711c5336063a6da72bf39239c57c81c7dff
https://github.com/banzaicloud/logging-operator/commit/f581da2e9daadae9b786362f69d379f8151ad918
https://github.com/banzaicloud/logging-operator/commit/4e74e36dfe7d63212b19401fe645a198734da1fd
wsh
Someone reached out to me privately to report several Solaris 11 compatibility bugs with wsh, my multi-host ssh tool.
Use -std=c11 flag with SunStudio: https://github.com/worr/wsh/commit/b11d2668ef6b85913d1901cfbfe6eb612be69bdc
Don't use __attribute__ with SunStudio, since none of the ones I used were supported: https://github.com/worr/wsh/commit/25ed3fc6fa36a1202e33c8fb36893d03cd5bce8c
Don't unconditionally compile in memset_s (Found because Solaris actually has a libc with this function): https://github.com/worr/wsh/commit/3876745a5cc4bce80d5e9fff0ab70b2dc429287f
This also led to a protobuf PR for better SunStudio support, which it looks like I need to follow up on.
https://github.com/protocolbuffers/protobuf/pull/7049/files
python-fido2
Last post, I mentioned I was working on getting my yubikey to work on OpenBSD. Part of that included adding support in ykman, which also required changes in python-fido2.
First, I added general OpenBSD support
https://github.com/Yubico/python-fido2/pull/82/files
This impl is arguably a bit brittle, since I essentially had to build the device probing for it in scratch from python, using the primitives from libusbhid to probe every uhid(4) device to see if it was a yubikey.
However, some time later, fido(4) was rolled into OpenBSD meaning that this code could be greatly simplified. I think someone reached out to me about this directly? I don't really remember, since it was awhile ago.
https://github.com/Yubico/python-fido2/pull/87/files
What a year
That's basically been the last year or so for me. Honestly, it's been a weird one, and I haven't been able to really do as much OSS as I've wanted to. A lot of it has been through work, which while nice, doesn't touch the types of projects that I want to be doing.
I am working on a gemini server on OpenBSD, which has been feeling quite rewarding, and I have other projects kicking around in my head that I'm going to be following up on.
0 notes
Text
gRPCとは
gRPCってつまり何?
gRPCってつまり何?ってなったので、公式のドキュメントを訳しつつ学んでみた。ほぼ訳のログみたいなもの。
そもRPCとはなにか。
遠隔手続呼出(Remote Procedure call)の略。 あるソフトウェアがネットワークとか通信回線を使って、別のマシンのソフトウェアに処理を依頼すること。
gRPCとは。
モダンなRPCのフレームワークで、以下な特徴があったりする。
サービスの定義がシンプル
ProtocolBuffersを使ってサービスを定義する
サクっと始められてスケールができる
言語とかプラットフォームをまたげる
双方向のストリーミングと認証の統一化
ProtocolBuffersっていうのは、言語とかプラットフォームに依存しないデータ構造のこと。 gRPCでは、IDL(Interface Definition Language)としても、基盤メッセージの構造としても、ProtocolBuffersを使用する。
overview
gRPCでは、クライアントアプリは異なるマシンに乗ったサーバアプリケーションのメソッドを直で呼ぶことができて、サービスとかアプリケーションを作ることを簡単にしてくれている。 多くのRPCシステムのように、gRPCはサービス定義っていう考え方に基づいていて、リモートで呼び出される、パラメータとか返り値を持ったメソッドが明確に指定してある。 サーバサイドではインタフェースを実装し、gRPCサーバは、クライアントの呼び出しをよしなに取り扱ってくれる。 クライアントサイドではスタブを持ち、スタブはサーバと同じメソッドを提供する。
クライアントはスタブを経由して、gRPCサーバにリクエストを送る。 サーバはそれをよしなに処理して、gRPCサーバからクライアントのスタブにレスポンスする。
gRPCのクライアントとサーバは、お互いが様々な環境で対話したり実行したりできるし、gRPCのサポートしている様々な言語で書くことができる。
Protocol Buffersで動く
gRPCはデフォルトでProtocolBuffersを使う。シリアライズしたデータ構造で、JSONなどの他フォーマットとして使うこともできるよ。
はじめに、ProtoFileっていう.proto拡張子のファイルで、シリアライズしたいデータの構造を定義する。 ProtocolBuffersのデータはmessageとして構造化される。 messageは、フィールドって呼ばれているname-valueの一連のペアを含むレコード(logical record)。
以下な感じで書かれる。
message Person { string name = 1; int32 id = 2; bool has_ponycopter = 3; }
データ構造を定義したら、protocol buffer compilerのprotocを使って、protoの定義から好きな言語でアクセスクラスのデータを作る(set_name()とか、name()とか)。こいつらは、それぞれのフィールドに対する、単純なアクセスのためのメソッドで、全ての構造体について、生のバイトにシリアライズしたり、バイトから構造体にパースしたりしてくれる。
次に、gRPCサービスをprotoFileに定義する。RPCメソッドを使ってサービスを定義していく。引数や戻り値には、ProtocolBufferのmessageを使う。 以下な感じで。
// The greeter service definition. service Greeter { // Sends a greeting rpc SayHello (HelloRequest) returns (HelloReply) {} } // The request message containing the user's name. message HelloRequest { string name = 1; } // The response message containing the greetings message HelloReply { string message = 1; }
gRPCはprotocで、protoFileからコードを生成する。そこから、gRPCのクライアントとサーバの、作成済みのコードを得ることができる。
まとめ
gRPCがやってくれることは
クライアントとサーバで共通に使えるインタフェースを定義すること
リクエストやレスポンスの構造を定義すること
実装は、それぞれの言語とかプラットフォームで自由にできる。
定義は.protoファイルで行う。
���クエスト、レスポンスのデータ構造は、messageで定義
提供するサービスはserviceとして定義
メソッドはrpcを使って定義する
参考
https://grpc.io/docs/guides/
0 notes
Photo
Intro to gRPC in C# - How To Get Started, http://ehelpdesk.tk/wp-content/uploads/2020/02/logo-header.png [ad_1] There is a lot of buzz around gR... #.netcore3 #.netcore3.0 #androiddevelopment #angular #api #cgprc #cproto #c #css #dataanalysis #datascience #deeplearning #development #docker #grpcc.netcore #grpcc.netcore3.0 #grpccexample #grpcctutorial #grpcclient #grpcinc #grpcserver #grpc.core #grpc.net.client #grpcserver #iamtimcorey #introtogrpc #iosdevelopment #java #javascript #machinelearning #node.js #protobuf #protocolbuffer #python #react #timcorey #unity #webdevelopment
0 notes
Photo

Just because you can’t code, doesn’t mean you can’t learn. There are many types of #developers. Start by teaching yourself to read the #fineprint. And what #namingconventions you will discover! Plus, they need more help than they let on. #founders AND, you’ll learn who has made a contribution to this platform. #thePword #historylesson #contributors #openlibraries #opensource #openmind #software : #gowalla #Apache #appirater ‘@apple reachability’ #boost #cocoalumberjack @Cocoawithlove #curl @flipboard @flickr ‘@google breakpad’ #EricaSadun #jsmn #JSONKit #cocoanetics @michaelwaterfall #kaboomerang #protocolbuffers #Quasidea ‘#Scifi #Hifi’ #SocketRocket #emojilib : #GO #SWIFT-ly into the Night https://www.instagram.com/p/BwLzA0pJ_v6bzDp4GE1fyYHd9k4QYzYhhtFzSg0/?utm_source=ig_tumblr_share&igshid=129haykqqaw6x
#developers#fineprint#namingconventions#founders#thepword#historylesson#contributors#openlibraries#opensource#openmind#software#gowalla#apache#appirater#boost#cocoalumberjack#curl#ericasadun#jsmn#jsonkit#cocoanetics#kaboomerang#protocolbuffers#quasidea#scifi#hifi#socketrocket#emojilib#go#swift
0 notes
Text
golangでgRPCを使ったAPIServerを作ってみる
from https://developers.eure.jp/eureka-grpc-go
はじめに
この記事は、 eureka Advent Calendar 2017 5日目の記事です。
こんにちは、エウレカでCTO(*Cat Tech Officer)を営む傍、サーバーサイドエンジニアとして 日々生計を立てている@marnie-eureです。
2015年にgRPCが発表されてから、2年が経ちましたね。 国内外の大手企業でのgRPCの事例も増えてきました。
これからのご時勢、gRPCの一つも使えないのでは、愛する猫たちを養っていくことも難しいかもしれない。
そんな危機感にかられたので、今回はふわふわっとgRPCを使ってAPIを作ってみようと思います。
(注) CTO(Chief Tech Officer)は@kaneshinなので 猫以外の話 はそちらにお問い合わせください。
gRPC Basics
gRPC?
gRPCは、Googleによって開発されたRPCフレームワークです。 HTTP/2を使用した通信層(ProtocolBuffersでシリアライズ)とProtocolBuffers(標準)としたテンプレートコードの生成がセットで提供されています。
勿論、HTTP2のstreamもサポートしています。 gRPCのRPC方式は以下の通り。
Unary RPC (1リクエスト1レスポンス)
Server streaming RPC (1つのリクエストに複数レスポンス)
Client streaming RPC (複数のリクエストに一つのレスポンス)
Bidirectional streaming RPC(双方向)
対応言語/platformも幅広く
C++
go
Ruby
Android Java
PHP
Objective-C
等の複数言語をサポートしています。
実装してみる
eurekaでは主にgolangを採用してますので、golangで実装します
前準備
gRPCをインストールします。
go get -u google.golang.org/grpc
protoファイルからコード生成をするコンパイラ(protoc)をインストールします。
protocのダウンロードはos別にこちらから 私の環境がosx-x86_64なので今回は protoc-3.5.0-osx-x86_64.zip を利用します。
PATHの通ったディレクトリに解凍したディレクトリの/bin の中のバイナリを移してあげてください。
protocのGo用のプラグインをインストールします。
go get -u github.com/golang/protobuf/protoc-gen-go
.protoファイルにインターフェースを定義する
gRPCをベースにした開発では、まずはIDLを使ってprotoにAPIの定義を書きます。
ProtocolBuffer以外もサポートはしているようですが、 ツール周りやドキュメントが一番手厚いし、標準に寄り添って行きたい民なので、今回はprotocolBufferで.protoファイルを作ります。
syntax = "proto3"; service Cat { rpc GetMyCat (GetMyCatMessage) returns (MyCatResponse) {} } message GetMyCatMessage { string target_cat = 1; } message MyCatResponse { string name = 1; string kind = 2; }
proto3の型や各言語の型の対応はgoogleのドキュメント、基本のscalar型以外を使いたい場合はgoogle/protobufをimportする感じで。
.proto ファイルからserver、client,interface等のコードを生成する
定義から各言語のベースとなるコードの自動生成をします。
protocコマンドを実行します。
protoc --go_out=plugins=grpc:../pb cat.proto
成功すると xxxx.pb.go が生成されます。
xxxx.pb.go ファイルには、protoで定義した以下が含まれています。
request
response
client,serverのinterface
registerMethod
プラットフォームまたいでも、同一の定義からこの辺のコードが生成できるのは楽ですね proto3のscalar型がgoのtime型やint型などに対応してたら嬉しかったのですが、今時点では対応してなかったのがやや辛み…
protocによるdocument生成
protocでdocumentの生成もできます。わーい。
protoc --doc_out=html,index.html:./ proto/*.proto
pb.goファイルを参照してサーバーとクライアントの実装
生成されたpb.goに含まれるinterfaceに沿って、実処理とserverとclientを実装します
service (実処理)
作られたxxx.pb.goのinterfaceを満たすように実装します。
xxx.pb.go type CatServer interface { GetMyCat(context.Context, *GetMyCatMessage) (*MyCatResponse, error) }
serviceって名称は、公式やprotoの呼称から取ってきただけなのでお好みで。
package service import ( "context" "errors" pb "marnie_playground/grpc-sample/pb" ) type MyCatService struct { } func (s *MyCatService) GetMyCat(ctx context.Context, message *pb.GetMyCatMessage) (*pb.MyCatResponse, error) { switch message.TargetCat { case "tama": //たまはメインクーン return &pb.MyCatResponse{ Name: "tama", Kind: "mainecoon", }, nil case "mike": //ミケはノルウェージャンフォレストキャット return &pb.MyCatResponse{ Name: "mike", Kind: "Norwegian Forest Cat", }, nil } return nil, errors.New("Not Found YourCat") }
server
gRPC関連で書く必要があるコードは
port listen
作った実処理の登録,serve
だけです。interceptor chain等は用途に応じて。
package main import ( "log" "net" pb "marnie_playground/grpc-sample/pb" "marnie_playground/grpc-sample/service" "google.golang.org/grpc" ) func main() { listenPort, err := net.Listen("tcp", ":19003") if err != nil { log.Fatalln(err) } server := grpc.NewServer() catService := &service.MyCatService{} // 実行したい実処理をseverに登録する pb.RegisterCatServer(server, catService) server.Serve(listenPort) }
client
package main import ( "context" "fmt" "log" pb "marnie_playground/grpc-sample/pb" "google.golang.org/grpc" ) func main() { //sampleなのでwithInsecure conn, err := grpc.Dial("127.0.0.1:19003", grpc.WithInsecure()) if err != nil { log.Fatal("client connection error:", err) } defer conn.Close() client := pb.NewCatClient(conn) message := &pb.GetMyCatMessage{"tama"} res, err := client.GetMyCat(context.TODO(), message) fmt.Printf("result:%#v \n", res) fmt.Printf("error::%#v \n", err) }
FactoryMethodとClientInterfaceが提供されているので、Connection作成してメソッドを呼び出すだけです。
ビルド & テスト
出来あがったclientとserverをそれぞれgo build,実行すれば出来上がり。
./client result:&cat.MyCatResponse{Name:"tama", Kind:"mainecoon"} error::<nil>
middleware(interceptor)
logging,auth,recovery的な物はinterceptorとかmiddleware的な物を作ってやれると 既存のプロジェクトからの移行もスムーズかなーと思っていたので、調べてみました。
interceptorは型定義されてますので、下記を満たすようなインターフェースで実装します。
google.golang.org/grpc/interceptor.go //UnaryRPCならこっち type UnaryServerInterceptor func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (resp interface{}, err error) //StreamRPCならこっち type StreamServerInterceptor func(srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error
利用するRPC方式によってgrpc.UnaryServerInterceptor() ないし grpc.StreamInterceptor()で grpc.ServerOptionに変換すればOKです
大雑把なイメージは以下のような感じ。
<br />func MiddlewareFunc(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) // 処理かく } func main() { //中略 middleware := &YourMiddleware{} opt := []grpc.ServerOption{grpc.UnaryInterceptor(MiddlewareFunc)} server := grpc.NewServer(opt...) }
grpc-middleware に何個か実装されたmiddleware(cf. logrus,validator)がありますので、 独自のmiddlewareを実装する場合はこの辺参考にすれば良いのかなと思います
まとめ
主要な通信層の処理は提供されているので、HTTP/2関連の実装は必要ない。
protoからボイラーテンプレートコードやドキュメントも作られるのは楽。
middlewareも増えている。
コードの自動生成によって本来時間をかけるべき、機能実装に集中できる HTTP/2による高速化/stream用途や、protobuff標準でのコード生成という所が包括的に提供されるといった恩恵を受けられるのは大きなメリットだなぁと感じます。
フルスタックフレームワークと較べるのは、主旨が異なるので要件や選定において重視する所次第って感じですが、マイクロフレームワークを使うような構成を検討していたり、ストリーミング通信が要件に含まれているのであれば採用するメリットははあると考えています
細々、下記のような気になる所はありましたが
proto3がgoの型を全て網羅してるわけではなさそうなので、applicationLayerの既存コードの型合わない場合は変換層とか必要そう。
curlでポチッと、みたいなのが使えなくなったので、テストがちょっと大変。grpc-gatewayでも使うべきなのかしら。
まぁデメリットと言うほどではないかな〜って気も。 テスト手段やエコシステム、ミドルウェアは今後、充実していく気もするし、既に必要十分ではあると思うので。
あとがき
今回はチュートリアル的な所と周辺情報を通して基本的な流れと所感を書いてみましたが、 eurekaでは実際に一部のmicro serviceのgRPC導入/移行を進行しています。 (既存コードとの兼ね合いで記事までに間に合いませんでした。てへぺろ
go+gRPCでの開発やeurekaに興味が持てた方(猫愛があれば尚良)は、是非お気軽にお話に来てくだされば!
それでは、2017年も残り少ないですが、日々猫への感謝を忘れず、過ごしていきましょう!!
参考にした資料/Repsitory Thanks!
grpc goDoc grpc.io grpc-middleware grpc-echosystem google/protobuf protocol-buffers docs
https://developers.eure.jp/wp-content/uploads/2016/12/nyan-1.png
0 notes
Link
Spring以前 業務で使うシステムはサーバー間で連携することが多い。2019年現在ではREST apiに対してjsonやprotocolbufferで呼び出す事が当たり前のように行われているが、まだjsonも発見されていない時代はもっと複雑な���組みが取られていた1。異機種間でやりとりするためのCORBAや、機種に依存しないデータプロトコルのASN.1なども利用されていたが、仕様は複雑でそれぞれをハンドリングするライブラリは有償で売られ、ベンダーからサポートを受けながら使用するようなものだった。 RMI Javaの世界ではJava同士でやりとりするためのRMIが定義され、比較的に楽にRPCできるようになった2。とはいえhttpでrestをコールすることに比べたらアホみたいな複雑さである。 https://docs.oracle.com/javase/jp/1.3/guide/rmi/getstart.doc.html J2EE そのRMIの使い方に一定のルールを設け、EJBを始め様々な指針を提示したのがJ2EEである。実装者がそれぞれに試行錯誤して苦労するような無駄は減ったが、代償として仕様はさらに複雑化した。 Spring 獲得できる機能に対して、設定や規約が悪夢のように複雑なJ2EEのアンチテーゼとして登場したのがSpringである。DIと組み合わせることでソースを綺麗に保つことができた。Clientクラスからサーバー上にあるServer#method()を呼び出すソースは以下だ。 class Client { private Server server; public void setServer(Server value) { server = value; } public void action(){ server.method(); } } もちろん適切な設定ファイルが必要になる3。が、開発時はローカル(というか同一JVM内)にあるserver.method()を直接呼び出して検証し、設定ファイルを差し替えるだけででserverの中身がテスト用のモックになったり本番用のリモート呼び出し版になったりするのは便利だった。素のRMIなら開発時もローカルにRMIサーバーを上げてrmi://localhostで接続し、テスト環境では設定ファイルでrmi://serverhostに変更するだけとか、RMIのオーバーヘッドが嫌ならデバッグフラグを立てておき呼び出し時にif文でローカル実行かRPCかを呼び分けるようにする程度だったから、結構な進化である。RMIのオーバーヘッドはhttpに較べればかなり小さいが、開発時にもいちいち上げなければいけないのは面倒だ。メインサービスのhttpは忘れないが、別途rmiserverだけ起動、とかいう手順が必要だと忘れがちになったり、逆に常に同時に立ち上げるスクリプトを使っていると、httpが生きているのにrmiにつながらない時に開発メンバーが「どうすればいいかわからない��状態になることがある。 SpringはDIコンテナではあるが、そのDIでリモート呼出を簡単にしてくれた事に大きな功績があった。このように実装を切り分ける方法にはDIの前にServiceLocatorがあった。先程のサンプルを書き換えるとこうなる。 class Client { private Server server = Locator.find(Service.class); public void action(){ server.method(); } } アプリの初期化時にFactoryに適切なServerクラスのインスタンスを登録しておく。もちろん設定ファイルを見てローカルかリモートか変更できるようになる。デメリットはServiceLocatorに対する依存が発生することだ。細かいことは割愛するがマーチン・ファウラーのブログの日本語訳のリンクを貼っておくので読んでほしい4。 Inversion of Control コンテナと Dependency Injection パターン 歴史は繰り返す メインフレームにダム端末を繋いでいた時代から、コンピュータの性能が向上したことでダウンサイジングがブームとなりUNIXワークステーションやPCで処理を行う流れとなり、管理の煩雑さやセキュリティの問題から巨大なサーバーにシンクライアントや仮想デスクトップで接続するという逆行が起きている。データ通信の世界ではシリアル通信から、同時接続で速度を向上させるためパラレルの通信技術が発展した。しかし技術革新でかなり高い周波数で通信できるようになると、今度は複数ある通信経路の同期をとるのが大変になりシリアル通信のSATAに揺り戻しが起きている。 プログラミング言語の世界も同じだ。C言語が世界を席巻していた頃、可読性の低いソースが氾濫していた。インターネットはまだ普及していないし、接続しても毒にも薬にもならない企業ページか、カウンターcgiの設置された個人ページばかり、最新の情報と言えば雑誌だ5。オンラインのコミュティがないのだからオフラインミーティングもない(Niftyなどのパソコン通信ではオフ会もあった、というかオフ会の言葉の発祥がそのへんだと思う)。よく練られたベストプラクティスが無い中、平凡なプログラマが書くコードというのはそれはもう十人十色で、変数名が意味不明に略されていたり、一つのものに対してもいろんな名前がついていたり、読み解くのに一苦労だ。 ここにC++によるオブジェクト指向の波がやって来る。Cでしか書いたことない人達は「コメントに"//"が使えるC言語」6とか、「困ったらextern Cで書けばいいから」とか言っちゃうし、継承をよくわかってないまま使って単に可読性を悪化させただけだったりした。boostはまだ来ない。オペレーターオーバーロードで演算子の持つ意味が特定のクラスでは異なっていたり、ダイアモンド継承による問題もあった。技術者レベルはCの時代に比べミジンコほどしか上がってないのに、言語の機能と複雑度は爆発的に増えた。 省略名で苦労するなら長い名前でいいじゃん c/c++で蔓延していたユニークな変数名・略名��らの揺り戻しとして「変数名を省略するなブーム」が起きる。過去はみんな640x480のCRT(またはそれ以下の解像度のモノクロ液晶)で仕事をしていたので、変数名が長いとソースの右端が途切れて読みにくかったのである。マウスもなかったし。 Windows95,MacはSystem7-漢字Talk7.5くらいで、800x600や1024x7686英語名での間違いとかもあり、大事なのはプロジェクトで用語辞書を定義して一貫性をもたせることであって名前を省略しなければいいというものでもない。google spreadsheetのようにフリーでwikiよりも気軽に編集できる辞書スプレッドシートが使えるようになった時代背景も大きい。 インターフェース、セッター、ゲッター...「すいませんこれ手で書くの?」 そして、オブジェクトの状態を隠蔽し振る舞いだけ公開しろということでprivateメンバを作成し、publicなgetter/setterを作成するのである。2019年にこれを手打ちしている猿はいないと思うが、Eclipseは随分前から自動生成をサポートし、JavaではLombokによりアノテーションだけで任意のアクセッサをプリコンパイルしてくれ、モダンな言語はproperty機能を備え(Delphiからあったし、なんならC#はDelphiだが)、Scalaではそもそもメンバ変数もpublicにすることが推奨され出した。これは「変数にしとこうと思ったけど、やっぱ関数にする」みたいな時にインターフェースを変えないまま差し込めるからだ。そもそも振る舞いだけ公開するならアクセッサを用意しては駄目で「Tell, Don't Ask」の原則にしたがって相手のオブジェクトに対してやって欲しい命令をだす方が望ましいのである。 XML地獄 さて話をSpringに戻そう。ServiceLocatorでは利用側のプログラムが任意のタイミングで取り出すので、実装を差し替えたいクラスだけ設定しておけばよかった。しかしDIコンテナではDIコンテナがインスタンスを生成し、その生成時にインスタンスは別のDIで差し替え可能なインスタンスを持つため、DIで差し替え可能なメンバーを持つクラスすべてをDIコンテナに登録しなくてはならなかった。そのため登録する項目数はかなり多く、spring起動時に依存関係を解決するため起動は遅かった。でもJ2EEのクソ設計に比べれば随分スマートだったので広く受け入れられた。当時は設定ファイルと言えばxmlで7、Springを始めとしたJava界隈はXML地獄の様相を呈していく。 設定より規約 ここは本題と外れるので余談となるが、このような状況で登場したRuby On Rails(以下RoR)は、設定を多数管理するよりも「規約をつくってそれにのっとっていればうまく動くよ」というスタンスで人口に膾炙し、後にRoRのフォロワーを多数輩出した。XML地獄から脱出する大きなムーブ���ントとなった功績は大きい。ただ「設定より規約」では規約をすべて頭に入れておかないと「これ、どこにも定義されてないんだけどどうやって動いてるの???」となり保守性が悪くなる。少ない規約で運用できるなら非常に有用だと思う。Spring DIに影響されRoRを後追いした日本ローカルなSeasar2では、どちらも劣化コピーだった上にアレがアレだったんで消えた。 アノテーションの是非 SpringはXMLからの脱却に、アノテーションを選択した。確かに設定ファイルは減った。意味不明な設定ファイルの項目があったとき、XMLなら項目名でgrepをかけてどういう処理をしているのか探し出すことができた。アノテーションの場合IDEからコントロールクリックで飛べるが、そこにはアノテーションとしての定義しかなく、実際はDIコンテナからインスタンスを生成する時に、対象となるクラスについているアノテーションを見て挙動を変えるわけで、ベテランじゃないと処理が負えなくなった。 そしてServiceLocatorの事を思い出してほしい。あれにデメリットがあるとされたのは、Locatorに対する依存があるからだ。設定ファイルからアノテーションのに移したということは、アノテーションをimportしアノテーションに依存する。ServiceLocatorに対する最大の優位点まで捨ててしまった。後にCDIとしてDI系のアノテーションが標準化されるが、springがやり始めた時は完全にspring依存で替えの効かないシステムになったのである。 アノテーションの例としてこれを見てほしい。 きしだのはてなより引用: https://nowokay.hatenablog.com/entry/20131108/1383882109 import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.inject.Named; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; @Named @ApplicationScoped @Path("/calc") public class CalcService { @Inject CalcLogic logic; @Path("add") @GET public Result add( @QueryParam("left") int p1, @QueryParam("right") int p2) { int ans = logic.add(p1, p2); return new Result(p1, p2, ans); } } (筆者による改行変更あり) ブログオーナーのきしださんは「便利」とおっしゃられているが、これはJavaにおけるWeb開発、DIの知識があるから「すげー少ない労力でかける」のであって、初見の人からしたら「このアノテーションは一体全部でいくつあって、そのうちどれとどれをマスターしておく必要があるのか、@GETに対しては@POSTや@PUTがあるだろうというのは想像できるが、じゃあ添付ファイルはどうやって取得するの?@Pathはアプリ起動時に自動的にこのクラスが読み込まれてservlet containerのルーティングに登録されるの?とか不安要素いっぱいすぎる。 ここで同じことをするsparkframework8+ServiceLocatorのサンプルを見てほしい。ServiceLocatorはサンプルとしてimport,他に依存するのはSparkframeworkだけである。 import static spark.Spark.*; import com.example.ServiceLocator; public class HelloWorld { public static void main(String[] args) { get("/hello", (req, res) { CalcLogic logic = ServiceLocator.get(CalcLogic.class); int p1 = intParam("left"); int p2 = intParam("right"); int ans = logic.add(p1, p2); return new Result(p1, p2, ans); } } private static int intParam(Request req, String key){ return Integer.valueOf(req.params(key)); } } アノテーションはひとつもなく同じことをしている。static import Spark.*してgetメソッドが使ってしまうあたりは依存関係が明確でないが、IDEでコントロールクリックすれば飛んで処理が追える。膨大なJ2EEやSpringのドキュメントにあらかじめ目を通しておかなくても、実際に書いてあるシンプルなコードから追えるのである。ちなみに上のソースは1行メソッドのためにわざわざintParam()を定義しているので、直に書けば3行短くなる。それより引数でもらってきたp1とp2を返す意味がわからん(だって呼び出し側が渡してきたパラメータなんだから呼び出し側は持ってるでしょ)ので、intParamは残しつつ無駄を省くとこう import static spark.Spark.*; import com.example.ServiceLocator; public class HelloWorld { public static void main(String[] args) { get("/hello", (req, res) { CalcLogic logic = ServiceLocator.get(CalcLogic.class); return new Result(logic.add(intParam("left"), intParam("right"))); } } private static int intParam(Request req, String key){ return Integer.valueOf(req.params(key)); } } おそらくSparkFrameworkの代わりにNinjaFrameworkを使っても似たようなものだろう。学習コストが違いすぎる。Springは当時眩しかったが、今では腐臭を放ち始めている。 Springの終焉 いつ終わっていたのか?Springの作者はRederick "Rod" Johnsonであるが、彼がScala言語を開発しているtypesafeにジョインした2012年、既に作者から見切りをつけられていたのではないだろうか。おそらく創始者としての責任感は感じていただろうから、実際にジョインした2012よりも前の段階から、すでにSpringは最先端の技術ではなく、より良い方法を追求しようとしていたのだと想像する。まあここはあくまで個人の想像だし、本人はまかりまちがっても「いやあ実はSpringなんてとっくに見切っててさあ」なんて思ってても公言できる立場ではないので、確認する術はない。 Micronauts お、マイクロサービス特化のあたらしいフレームワーク?いい線いくのかと思ったけど思想が完全に「Springつらいから軽量Springを作る」になっていてアノテーション使いまくりでやばい。過去にLinusは「Subversionプロジェクトは無意味、CVSからほとんど進化してないのに多大なリソースをつぎ込んでいる」と批判してgitのベースを作ったが、ちょうどそんな漢字だと思う。MicronautsはSpringのつらさをちょっと軽減してくれるだけで、根本的な問題がなにも解決していない 今後 当然「じゃあ何を使うのか」という話になるわけだが、筆者は今の所Kotlin+SparkFramework+Expose(ORM)を使っているものの、ここがゴールだという気は全然しない。まずKotlinってJavaの知識が必要だし、gradleってmavenの知識が必要だし、すごく過渡期の中途半端なプロダクトという感じ。ExposeはマクロのないKotlinではボイラー��レートが多すぎてまだまだつらい。kaptでどうにかなるのか?AndroidのおかげでKotlinは今後もシェアを伸ばすだろうけど、じゃあ全部Kotlinでいいかって言われるとうーん、となる。パターンマッチがないのも辛い、kotlin2.0で入って欲しい。あとJVMがでかくて、せっかくalpineでdocker imageつくってもJVMいれた時点でお腹痛くなってくる。busyboxの意味とは。 今はGoを試そうとしている。今度ジェネリクスも入るらしいからそれを待ちたい。まともなMaybe/Eitherが使えるようになったら良いかもしれないけど、Goの型システムでいけるのだろうか?無理そうな気がする。 言語機能的にはRustくらい欲しいが、Rustが10年後どれくらい使われているかを考えると、業務で使うのは怖い気がする(業種によるけど)。
0 notes
Text
so i understood that even for nice purposes, using protocolbuffer data structures as API arguments (for a client library) is not nice. but when you make it static in API structures, API becomes static but its ok in a microservices enabler environment. yepp its really hard to initialize protocol buffer structures in api calls so need to make it somehow static.
0 notes
Text
ProtocolBuffers 2.6.x 사용하기
Objective C 언어로 ProtocolBuffers 2.2.x 를 이용해 만들었던 프로그램을 2.6.x 버전으로 만들며 했던 삽질기 정리
https://github.com/alexeyxo/protobuf-objc 프로젝트 이용
git clone 명령으로 내려받아 Xcode 를 이용해 빌드
기존 프로젝트에 ProtocolBuffers 프로젝트 추가
#import "ProtocolBuffers.h" 형식으로 변경
Message_Builder 등 _Builder 가 붙어있던 클래스 이름을 모두 MessageBuilder 형식으로 변경
"Build Setting" - "Search Paths" - "Header Search Paths" 에 "protobuf-objc/src/runtime" 추가 후 recursive 선택
"Build Phases" - "Target Dependencies" 에 ProtocolBuffers 추가
"Build Phases" - "Link Binary With Libraries" 에 "libProtocolBuffers.a" 추가 (protobuf-objc/src/runtime/Build/Products/Debug 밑에 있음)
1 note
·
View note
Photo

gRPC framework enables us to define 4 different kinds of APIs which can be used for different use cases. - Unary API - Server Streaming API - Client Streaming API - Bi-directional Streaming API To know more about this API watch the video: https://youtu.be/p-H9T-2lat0 #grpc #streaming #api #protocolbuffers https://www.instagram.com/p/CBF5dGjn6sT/?igshid=1esx09ln4s030
0 notes
Photo

gRPC framework enables us to define 4 different kinds of APIs which can be used for different use cases. - Unary API - Server Streaming API - Client Streaming API - Bi-directional Streaming API To know more about this API watch the video: https://youtu.be/p-H9T-2lat0 #grpc #streaming #api #protocolbuffers https://www.instagram.com/p/CBF5VfAJaOI/?igshid=yurvcba7coji
0 notes