<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<title>Posts on Arun&#39;s Blog</title>
		<link>https://arunsori.me/posts/</link>
		<description>Recent content in Posts on Arun&#39;s Blog</description>
		<generator>Hugo -- gohugo.io</generator>
		<language>en-us</language>
		<lastBuildDate>Wed, 18 Nov 2020 21:59:24 +0100</lastBuildDate>
		<atom:link href="https://arunsori.me/posts/index.xml" rel="self" type="application/rss+xml" />
		
		<item>
			<title>Writing a Postgres Foreign Data Wrapper for Clickhouse in Go</title>
			<link>https://arunsori.me/posts/postgres-clickhouse-fdw-in-go/</link>
			<pubDate>Wed, 18 Nov 2020 21:59:24 +0100</pubDate>
			
			<guid>https://arunsori.me/posts/postgres-clickhouse-fdw-in-go/</guid>
			<description>Postgres(hereinafter mentioned as PG) is a pretty cool database with lots of nice features, one of them little known ones is the ability of having Foreign data wrappers (hereinafter mentioned as FDWs).
Clickhouse(hereinafter mentioned as CH) is another amazing database with an altogether different set of features targeted for OLAP use cases.
What are Foreign Data Wrappers (FDWs) then? Well unlike so many names in tech, we can actually infer some idea from the name itself in this case.</description>
			<content type="html"><![CDATA[

<p><a href="https://www.postgresql.org/">Postgres</a>(hereinafter mentioned as PG) is a pretty cool database with lots of nice features, one of them little known ones is the ability of having Foreign data wrappers <a href="https://wiki.postgresql.org/wiki/Foreign_data_wrappers">(hereinafter mentioned as FDWs)</a>.</p>

<p><a href="https://clickhouse.tech/">Clickhouse</a>(hereinafter mentioned as CH) is another amazing database with an altogether different set of features targeted for OLAP use cases.</p>

<h2 id="what-are-foreign-data-wrappers-fdws-then">What are Foreign Data Wrappers (FDWs) then?</h2>

<p>Well unlike so many names in tech, we can actually infer some idea from the name itself in this case.
So FDWs in essence, allows to access <em>foreign</em> <em>data</em> sources inside Postgres(PG) via a set of <a href="https://www.postgresql.org/docs/current/fdwhandler.html">wrapper APIs</a>.</p>

<p>That is, you can access data sitting in a Mysql/SQlite/Clickhouse(<em>any other data source</em>) table inside PG as you would do for a normal PG table. Isn&rsquo;t that amazing!</p>

<p>There are already numerous such FDWs. A list is available <a href="https://wiki.postgresql.org/wiki/Foreign_data_wrappers">here</a>.</p>

<p>One caveat is that the extent of features you can expect from a FDW is dependent on the particular implementation.
We can expect normal read support but other niceties like push-down filters, aggregations or joins, or write support can be missing.</p>

<h2 id="accessing-clickhouse-ch-via-postgres-pg">Accessing Clickhouse(CH) via Postgres(PG)</h2>

<p>Given the existence of so many possibilities of accessing other datastores, wouldn&rsquo;t it be fun if we could access Clickhouse from inside Postgres.</p>

<p>Why would you want to do it! you may ask.</p>

<p>Well one reason could be of course, for <em>fun</em>.</p>

<p>But more realistically, one of the ambitious use cases at <a href="messagebird.com">MessageBird</a>(my employer) was the ability to connect Clickhouse to <a href="looker.com">Looker</a> as no direct integration existed at that time.
It was a bit of a moonshot but we decided to give it a try to see if it would work :)</p>

<p>MessageBird has generously made the full source for our experiment open source! The repository is available <a href="https://github.com/messagebird/clickhouse-postgres-fdw">here</a>.
So you can reference the ideas mentioned in the blog post directly in the code as well :)</p>

<h3 id="now-on-to-writing-one-fdw">Now on to writing one FDW!</h3>

<p>There are already <a href="https://www.postgresql.org/docs/current/fdwhandler.html">documentations</a> on how we should approach this and some simple examples are also available on Github. Most of the full fledged FDWs have their code in open so we can consult them as well.
Note that most of them are written in C becauses the FDW API of PG is in C, which makes sense.
I should highlight one particular <a href="https://github.com/pgspider/sqlite_fdw">FDW</a> that is made for SQLite and has a solid feature set, which helped me a lot while writing the one for Clickhouse.</p>

<p>But what if we want to be adventurous and write one in Go? Well, it should be possible given the existence of <a href="https://golang.org/cmd/cgo/">CGo</a>.</p>

<p>We can expect that it will not be at all trivial. ;)
There are already attempts on making Postgres Extensions in <a href="https://github.com/liztio/k8s-fdw">Go</a>, which gives a very valuable insight.</p>

<h4 id="setting-up-the-build-process-and-interaction-between-go-and-postgres-c-api">Setting up the build process and interaction between Go and Postgres C API</h4>

<p>First we should familiarize ourselves with the <a href="https://www.postgresql.org/docs/13/extend-pgxs.html">PG Extension Build Infrastructure/PGXS</a> and how to write <a href="https://www.postgresql.org/docs/current/xfunc-c.html#DFUNC">C code</a> for PG.
These are crucial as we would want to integrate the C code with Go, and knowing how the build process works should help us in understanding where our code will fit.</p>

<p>For writing a FDW we have to provide an entry point in form of a <code>struct</code> containing function pointers to the implemented callback functions.
Since we want to write those callback in Go, we can consult documentation for <a href="https://golang.org/cmd/cgo/#hdr-C_references_to_Go">accessing Go functions in C</a>, which says there are specific annotations that should allow us to export go functions outside to the C code.
All the important work is done in these callbacks only.<br />
Now it should be possible to add functions that PG FDW API expects via Go.</p>

<p>But, how will the C code find the callback functions written in Go land ? <a href="https://golang.org/cmd/go/#hdr-Build_modes">Go build modes</a> is the answer.
Directly referencing from the documentation, the <code>-buildmode=c-archive</code> allows us to:</p>

<pre><code>Build the listed main package, plus all packages it imports,
into a C archive file. The only callable symbols will be those
functions exported using a cgo //export comment. Requires
exactly one main package to be listed.
</code></pre>

<p>Perfect! Now, the exported Go functions are available in the <a href="https://linux.die.net/man/1/ar">archive file</a>.
The only remaining thing is to link the archive with C code during build.
Thankfully, <a href="https://www.postgresql.org/docs/13/extend-pgxs.html">PGXS</a> provides a <code>Make</code> variable <code>SHLIB_LINK</code> that can be used to set the shared library used. So we&rsquo;ll use that flag to provide the archive build from Go source files.</p>

<p>You can see it in action <a href="https://github.com/messagebird/clickhouse-postgres-fdw/blob/main/Makefile">here</a>.</p>

<!-- * how linking go code to c via statically linked libraries works ? .a files linking with Go. -->

<!-- And we want a library of sorts which should be callable inside C code. For this we can use go build mode (c-archive), this will create a statically linked archive(see difference btwn shared objects and statically linked libraries and how to build them) -->

<h4 id="understanding-inner-working-of-the-fdw-api-and-their-relation-with-different-query-stages">Understanding inner working of the FDW API and their relation with different Query Stages</h4>

<!-- * Figuring out which stages do what, what do you want and where to look for them -->

<p>To actually write a working FDW, we need to familiarize with the different stages a query goes through in PG and how the API functions play them out.
Postgres has an excellent documentation and moreover since all the <a href="https://github.com/messagebird/clickhouse-postgres-fdw/">source code</a> is open, we can just navigate through the code as well!</p>

<p>It would take more space than a blog post to explain the full internals of Query planner in Postgres and I probably can&rsquo;t describe it well enough.
So, I suggest to go through <a href="https://www.postgresql.org/docs/current/fdw-callbacks.html">the official documentation</a> which is quite excellent and there are many other excellent references on the web.</p>

<p>I&rsquo;ll try to briefly explain the flow of the API functions for the context of this post.
A very basic plan looks like this:</p>

<pre><code>+-------------------------+
|                         |
|                         |
|    GetForeignRelSize    |
|                         |
|                         |
+------------+------------+
             |
             |
             |
+------------v------------+
|                         |
|                         |
|     GetForeignPaths     |
|                         |
|                         |
+------------+------------+
             |
             |
             |
+------------v------------+
|                         |
|                         |
|     GetForeignPlan      |
|                         |
|                         |
+------------+------------+
             |
             |
             |
+------------v------------+
|                         |
|                         |
|     BeginForeignScan    |
|                         |
|                         |
+------------+------------+
             |
             |
             |
+------------v------------+
|                         |
|                         |
|    IterateForeignScan   |
|                         |
|                         |
+-------------------------+
             |
             |
             |
+------------v------------+
|                         |
|                         |
|     EndForeignScan      |
|                         |
|                         |
+-------------------------+

</code></pre>

<p>There are other functions in the FDW API that I&rsquo;ve omitted here (like <code>ReScanForeignScan</code>, <code>AnalyzeForeignTable</code>, <code>GetForeignUpperPaths</code>) but a basic FDW can be done with these.
Also note that this path is only concerned with the read queries. To enable writing on the foreign database, there are separate functions that need to be implemented.
You can see how the read path is implemented for our clickhouse FDW <a href="https://github.com/messagebird/clickhouse-postgres-fdw/blob/main/ch_fdw.c">here</a>.</p>

<p>Important ones to take note of to properly implement the read path of a query are:</p>

<ul>
<li><p>GetForeignRelSize: It should be used to determine the estimated number of rows to be scanned on the foreign server. However, it is also used to extract the restriction clauses present in the query presented by PG and to pass them to the foreign server if it can support them.
See this <a href="https://github.com/messagebird/clickhouse-postgres-fdw/blob/a938204f1a5645cd71dd473b5d0e5f56d2a6f831/ch_fdw.go#L180">example</a>.</p></li>

<li><p>GetForeignPlan: It should return the planner node(a data structure that contains the query plan). However, it is also used to extract the target columns that can be fetched from remote/foreign servers and pass that info along with restriction clauses, table names to the next stage.
See this <a href="https://github.com/messagebird/clickhouse-postgres-fdw/blob/a938204f1a5645cd71dd473b5d0e5f56d2a6f831/ch_fdw.go#L275">example</a>.</p></li>

<li><p>BeginForeignScan: It should perform the initalization that is needed to perform the scan on the foreign server, for example: initialize the foreign DB connection, formalize the query running on foreign server and init the state with row iterator to be used in the next stage.
See this <a href="https://github.com/messagebird/clickhouse-postgres-fdw/blob/a938204f1a5645cd71dd473b5d0e5f56d2a6f831/ch_fdw.go#L508">example</a>.</p></li>

<li><p>IterateForeignScan: It should return a row from the foreign server converted to the PG specific structure. This function should convert the foreign server specific data types to PG column data types.
See this <a href="https://github.com/messagebird/clickhouse-postgres-fdw/blob/a938204f1a5645cd71dd473b5d0e5f56d2a6f831/ch_fdw.go#L620">example</a>.</p></li>

<li><p>EndForeignScan: It should clean the state being stored for the query, like row iterators, db connections should be closed.
See this <a href="https://github.com/messagebird/clickhouse-postgres-fdw/blob/a938204f1a5645cd71dd473b5d0e5f56d2a6f831/ch_fdw.go#L760">example</a>.</p></li>
</ul>

<p>This is a very dense overview of the functionality of a <em>basic</em> FDW. It usually helps to look around the other FDWs that are open source to look for ideas of a sample implementation. But it can differ since the foreign server can be of various types.
Usually, if we take databases that support some dialect of SQL then the hardest things are usually figuring out if the restriction clauses are remote safe, which can involve parsing the full expression clauses and then converting them to remote variants.
Converting the foreign server datatypes to PG types is comparatively easy but is very toiling.</p>

<p>You can look into how <a href="https://github.com/messagebird/clickhouse-postgres-fdw/blob/a938204f1a5645cd71dd473b5d0e5f56d2a6f831/ch_fdw.go">clickhouse FDW</a> does this to get an idea, but beware that it could be bug prone, since it hasn&rsquo;t been tested thoroughly.</p>

<p>I&rsquo;ll also suggest getting an idea of commonly used PG datatypes and conventions like <code>OID</code>, <code>Tuple</code>, <code>RelOptInfo</code> or just going over <a href="https://doxygen.postgresql.org/relation_8h.html"><code>relation.h</code></a> reference from PG source code.</p>

<h3 id="few-tips-and-tricks">Few Tips and Tricks</h3>

<p>These are some ideas that I&rsquo;ve seen are fairly used while developing a FDW. Some can help in easy interop between Go and C, whether it is a good idea or not, is up for debate ;)</p>

<h4 id="interfacing-c-macros-within-go">Interfacing C macros within Go</h4>

<p>There are a lot of internal macros in PG source which makes it easier to access system cache, lists, heap tuples etc. which aren&rsquo;t directly callable from Go&rsquo;s userland.<br />
This is because CGo doesn&rsquo;t quite allow directly calling C <code>#define</code> macros.<br />
You can try to simulate the same behaviour using underlying constructs but that can get hairy and cumbersome. Instead one <em>easy</em> idea is to define simple C wrapper functions like</p>

<pre><code>void *wrapper_access_list(void *list, int index){
	return access_list(list, index);
}
</code></pre>

<p>This can now be used directly on Go side. But make sure you cast the results to proper types.</p>

<h4 id="moving-out-c-code">Moving out C code</h4>

<p>There can be a point where writing C code directly in Go source files is not feasible anymore, because increasing the number of commented lines can get incomprehensive after a point.</p>

<p>Moving out C code into separate files and then accessing them in Go can be done as well.<br />
You need to link the Go code with the C symbol definitions that are outside the Go code during build times and it should work.
It can be done by for example, separating the C code into header and source file and including the header file in the Go source code. Now CGo will automatically take care of building the object files.
See it in action <a href="https://github.com/messagebird/clickhouse-postgres-fdw/blob/a938204f1a5645cd71dd473b5d0e5f56d2a6f831/ch_helpers.c">here</a>. For better understanding of different object files, see <a href="https://stackoverflow.com/questions/9688200/difference-between-shared-objects-so-static-libraries-a-and-dlls-so">here</a>.</p>

<h4 id="maintaining-execution-state-of-c-api-inside-go-land">Maintaining execution state of C API inside Go land</h4>

<p>Go doesn&rsquo;t allow passing pointers to Go objects (like maps, slices) to C (which makes sense, with Go being a garbage collected language). See <a href="https://golang.org/cmd/cgo/#hdr-Passing_pointers">this reference</a> for more details.</p>

<p>But we want to maintain states in Go for objects that are being accessed by C code.</p>

<p>One example is database connections and cursor(row iterator). As we would want to access connection as a Go variable or in a PG execution stage we would want to use the same cursor which is being initialized in upper stages (i.e planning).<br />
One trick to make this happen is to keep a map of integers =&gt; Go objects and pass that integer around as we move downstream in the query stages.
This integer is always incremented in the FDW&rsquo;s lifetime (in each stage) and is never reused again in calls to FDW.
For example see it <a href="https://github.com/messagebird/clickhouse-postgres-fdw/blob/a938204f1a5645cd71dd473b5d0e5f56d2a6f831/ch_fdw.go#L73">here</a>.</p>

<h4 id="passing-fdw-state-around-different-stages">Passing FDW state around different stages</h4>

<p>PG FDW API also allows to embed internally private information as an opaque <code>void *</code> that will be passed around in the query stages.<br />
This is quite neat IMHO and saves a lot of time for developers to allow bookkeeping :)<br />
You can pass state around stages by simply providing a <code>void * fdw_state</code> where we can put anything (quite <em>literally</em>).<br />
Clickhouse FDW uses this to pass around query state information like extracted remote safe restriction clauses, table names, column names etc. See this <a href="https://github.com/messagebird/clickhouse-postgres-fdw/blob/a938204f1a5645cd71dd473b5d0e5f56d2a6f831/ch_fdw.go#L196">reference</a>.</p>

<h4 id="type-conversions-between-go-and-c">Type conversions between Go and C</h4>

<!-- * Type conversions btwn Go and C , thinking how would you translate a native DB type in Go to C (date/time, sql package etc) -->

<p>Since we are fetching the results from the Go driver of a DB and then pushing it down to the C API of PG, we need a conversion step between.<br />
Normally, it should be easy for fixed size integers and strings but PG has a large catalogue of datatypes like datetime, time zones, arrays and such. Further the foreign database can also have its own list of datatypes that might not be properly represented as a PG type.<br />
In that case, we have to do the best we can and might have to leave those fancy datatypes out.<br />
For user defined datatypes like variable length strings or arrays, PG has a nice system of input and output <a href="https://www.postgresql.org/docs/13/xtypes.html">function for conversions</a>.<br />
We can rely on these functions for converting the value from Go to C.
See this in action <a href="https://github.com/messagebird/clickhouse-postgres-fdw/blob/a938204f1a5645cd71dd473b5d0e5f56d2a6f831/ch_fdw.go#L784">here</a>.</p>

<h4 id="support-push-down-filters-and-aggregates">Support push down Filters and Aggregates</h4>

<!-- * Expression deparsing is one of the major challenges that would need to be implemented.
* Evaluation of exprs that can be implemented on remote or not (is major required for push down filters)
 -->

<p>This is one the nicest features to provide since it will leverage the underlying foreign DB&rsquo;s capability and heavily reduce the amount of bytes travelled over the wire.<br />
Also, this makes the query being done on PG much closer to how it will be done on the foregin DB because otherwise the query will use PG&rsquo;s query planner.</p>

<p>To support push downed filters, we first have to deparse the expression from query clauses and then evaluate if they can be implemented in terms of foreign databases.<br />
I mostly leveraged the existing code that <a href="https://github.com/pgspider/sqlite_fdw">sqlite_fdw</a> has written for the same but tweaked it further to convert the expressions in terms of Clickhouse expressions.
See it in example <a href="https://github.com/messagebird/clickhouse-postgres-fdw/blob/3904e5573ac9585d87021952f4c0ffcddee4c7ff/deparse.go">here</a>.</p>

<p>The functionality can be splitted into two parts, first can be the expression <a href="https://github.com/messagebird/clickhouse-postgres-fdw/blob/3904e5573ac9585d87021952f4c0ffcddee4c7ff/deparse.go#L197">deparsing</a> and second can be the <a href="https://github.com/messagebird/clickhouse-postgres-fdw/blob/3904e5573ac9585d87021952f4c0ffcddee4c7ff/ch_helpers.c#L348">evaluation</a>.</p>

<p>For pushing down aggregations like <code>GROUP BY</code>, the deparse and evaluation are mandatory step but we also have to implement FDW functions like <a href="https://www.postgresql.org/docs/current/fdw-callbacks.html#FDW-CALLBACKS-UPPER-PLANNING"><code>GetForeignUpperPaths</code></a>.</p>

<h2 id="when-this-could-be-a-bad-idea">When this could be a bad idea?</h2>

<p>In order to properly understand the FDW&rsquo;s working and further extension, it is required to understand Postgres internals and it&rsquo;s FDW API.<br />
Further a brief understanding of database design theory is also needed.<br />
If the teams doesn&rsquo;t have such expertise beforehand, this can be a major bottleneck in providing a production grade interface between Foreign DB(like Clickhouse) and PG.<br />
It shouldn&rsquo;t be the case that developers fear the code because it is too magical and they don&rsquo;t understand the inner workings.</p>

<p>Next, if one is assumed to have an understanding, there are the challenges of keeping the C to Go interface calls manageable.<br />
See <a href="https://www.cockroachlabs.com/blog/the-cost-and-complexity-of-cgo/">CGo performance penalties</a> for example. So it is desirable to keep the codebase sane by keeping the amount of C code minimum.<br />
We somehow need to provide a balance between the two.</p>

<p>Further challenges can be:</p>

<ul>
<li>We can try to keep much of the code in Go (involving C interface functions) but we also need to be careful while passing memory chunks from Go to C.<br />
Any <code>Go.CString(...)</code>s aren&rsquo;t claimed back via Go runtime, although in case of C structs PG runtime promises to claim back the memory allocated by palloc as soon as the transaction ends. There are some constructs where we might need to touch PG&rsquo;s HeapTuple memory allocators and manually make sure we free them after use.</li>
<li>New collaborators will need to learn tricks around the converting C structs/datatypes to Go ones(and vice versa) and marshalling/unmarshalling results/arguments of PG C functions.</li>
</ul>

<p>A very extreme way is, To try to keep most of FDW stages in C with only &ldquo;deparsing and type conversions from Go types to C types&rdquo; and &ldquo;Clickhouse query formation&rdquo; in Go, but if the teams lack expertise in C, this may not be a favourable option.</p>

<p>The end result of this experimental project is available <a href="https://github.com/messagebird/clickhouse-postgres-fdw/">here</a>. I hope that other teams will find the code useful.</p>

<p>If these kinds of challenges excites you, <a href="https://messagebird.com">MessageBird</a> is <a href="https://messagebird.com/en/careers/">hiring</a> for lots of attractive roles!</p>

<!-- 
* First stage: receiving options information about remote server and other options from POstgres
getting the relative size of the table:
* Second stage: Building a Foreign scan path (which is usually simple, unless you implement UPPER relation paths or JOIN paths)
* Third stage: Making a foreign plan that would contain the target columns, table names, (conditions, group bys etc)
* fourth stage: Extracting the plan and make connection to Foreign server
* fifth stage: a row iterator from the foreign server that returns the data, this also needs type conversions from native Go types to PG types
* sixth stage: clean up of resources
* advance sstage: Implementing push down aggregations on the foreign server -->
]]></content>
		</item>
		
		<item>
			<title>A brief look at the new Protobuf APIv2 for Golang</title>
			<link>https://arunsori.me/posts/protobuf-apiv2-golang/</link>
			<pubDate>Wed, 15 Apr 2020 20:51:29 +0200</pubDate>
			
			<guid>https://arunsori.me/posts/protobuf-apiv2-golang/</guid>
			<description>There has been a release of a new protobuf API v2 for Golang which provides an entirely different API surface which in turn means that it is backward incompatible. But there are good reasons for that. Many want to access the generated proto Message programmatically and without knowing the concrete type at runtime. The release post describes one such use case, but there exists many in the wild. For example, generating a table schema based on a provided proto Message, which coincidentally shares similarity with my use case.</description>
			<content type="html"><![CDATA[

<p>There has been a <a href="https://blog.golang.org/protobuf-apiv2">release</a> of a new protobuf API v2 for Golang which provides an entirely different API surface which in turn means that it is backward incompatible. But there are <a href="https://docs.google.com/document/d/19kfhro7-CnBdFqFk7l4_HmwaH2JT_Rhw5-2FLWLEGGk/edit?usp=sharing">good</a> <a href="https://docs.google.com/document/d/1epnKUCTeP_yQWmOJgOhELdmQTk8a3VPQGOV9d6RFbt0/edit?usp=sharing">reasons</a> for that.
Many want to access the generated proto <code>Message</code> programmatically and without knowing the concrete type at runtime. The release post describes one such use case, but there exists many in the wild.
For example, generating a table schema based on a provided proto <code>Message</code>, which coincidentally shares similarity with my use case.</p>

<p>So, I recently tried to see if we can migrate to use the new API. Since it is fairly new, there can be a bit of confusion around the whole go-protobuf ecosystem about the support of APIv2.
This post is a result of my efforts to investigate projects(that I regularly use) which need upgradation and a little fun experiment with <code>protoreflect</code> API for minor template-generation.</p>

<p>A very good overview of this new release is on the official <a href="https://developers.google.com/protocol-buffers/docs/reference/go/faq">Protobuf Go reference FAQ page</a>. I highly recommend going through them.</p>

<h3 id="import-path">Import Path</h3>

<p>Most notably, the new import path for APIv2 is changed to <code>google.golang.org/protobuf</code> vs the old one <code>github.com/golang/protobuf/protoc-gen-go</code>.
As mentioned in the original release post, the old API v1 versions will start from the current <a href="https://github.com/golang/protobuf/releases/tag/v1.3.5"><code>v1.3.5</code></a> where as the new APIv2 is starting from <a href="https://github.com/protocolbuffers/protobuf-go/releases/tag/v1.20.0"><code>v1.20.0</code></a>.</p>

<p>Also <code>protoc-gen-go</code> <a href="https://github.com/golang/protobuf">APIv1</a> is implemented in the terms of <a href="https://github.com/protocolbuffers/protobuf-go">APIv2</a> at version <a href="https://github.com/golang/protobuf/releases/tag/v1.4.0-rc.4"><code>1.4.0</code></a> which means just upgrading to the new versions of old API will allow the programs to use the new API.</p>

<h3 id="gotchas-that-i-could-found">Gotchas(that I <em>could</em> found)</h3>

<p>If your project uses a external protobuf configuration/management tool like <a href="https://github.com/uber/prototool"><code>prototool</code></a>, it might take some time to get them to support the new APIv2. For example with prototool, the changed behaviour on new API w.r.t. <a href="https://developers.google.com/protocol-buffers/docs/reference/go-generated#package"><code>go_package</code></a> creates <a href="https://github.com/uber/prototool/issues/549">problems</a>.</p>

<p>If using gRPC with protobuf, only <em>old</em> protoc-gen plugin will support the generation of gRPC stubs for a while and <a href="https://github.com/protocolbuffers/protobuf-go/releases/tag/v1.20.0#v1.20-grpc-support">not the new one</a>.</p>

<p>Also, when using the new API, gRPC version must be upgraded to <a href="https://github.com/grpc/grpc-go#compiling-error-undefined-grpcsupportpackageisversion">1.27.0</a></p>

<p>If using extra whistles like <code>grpc-gateway</code>, those might be still on their way to <a href="https://github.com/grpc-ecosystem/grpc-gateway/pull/1165">upgrade</a> and can prove to be non-trivial.</p>

<h3 id="using-protoreflect">Using <code>protoreflect</code></h3>

<p>Now, onto the fun part.
New APIv2 provides a revamped reflection API that allows access to the <code>Message</code> values as per the protocol buffer type system.
The release post does a good job on describing a use case where we need to iterate through all <em>populated</em> fields of a proto message.</p>

<p>But, what if I wanted to iterate through all fields of a <code>Message</code> irrespective of whether they are populated or not and want to infer their proto type information.
For example, I want to map protobuf type system to another type system, of course for reasons ;)</p>

<p>Let&rsquo;s say I&rsquo;ve a template that looks like this:</p>

<pre><code>var caseTmpl = `

// declared field name as in proto
case %s:

//	(proto generated name)  =&gt;  (a mapped type name)
	message.%s 				= anotherField.(%s)
`
</code></pre>

<p>Here <code>message</code> is a protobuf Message and <code>anotherField</code> is a field that should be assigned to the message but type signature of the field is different.</p>

<p>The first basic attempt:</p>

<pre><code class="language-golang">func generate(message proto.Message) {

	// Returns all Fields/`FieldDescriptors` from the `MessageDescriptor`
	fds := message.ProtoReflect().Descriptor().Fields()
	for i := 0; i &lt; fds.Len(); i++ {
		fd := fds.Get(i)
		//short name
		fieldName := string(fd.Name())
		// json name
		protoField := strings.Title(fd.JSONName())
		// the template is defined above and we pass the string arguments
		// fd.Kind() returns basic Kind/type for the field
		fmt.Printf(caseTmpl, fieldName, protoField, fd.Kind())
	}
}
</code></pre>

<p>We access the <a href="https://pkg.go.dev/google.golang.org/protobuf/reflect/protoreflect?tab=doc#MessageDescriptor"><code>MessageDescriptor</code></a> with the help of the new API and get the list of all fields, which has the type <a href="https://pkg.go.dev/google.golang.org/protobuf/reflect/protoreflect?tab=doc#FieldDescriptors"><code>FieldDescriptors</code></a>.
<code>FieldDescriptors</code> is basically a container type for <a href="https://pkg.go.dev/google.golang.org/protobuf/reflect/protoreflect?tab=doc#FieldDescriptor"><code>FieldDescriptor</code></a>.
<code>FieldDescriptor</code> has all the information regarding the name, type of the underlying field, which we can use to pass into the template.</p>

<p>I relied on the <a href="https://pkg.go.dev/google.golang.org/protobuf/reflect/protoreflect?tab=doc#Kind"><code>fd.Kind()</code></a>&rsquo;s String <a href="https://github.com/protocolbuffers/protobuf-go/blob/v1.20.1/reflect/protoreflect/proto.go#L281">implmentation</a> to get the type name. We can also use a map on the type name itsef if its signature in <code>anotherField</code> is called differently.</p>

<p>This works fine for a very simple proto definition(in terms of type richness).</p>

<pre><code class="language-protobuf">message Customer {
  uint64 id = 1;
  string another_identifier = 2;
}
</code></pre>

<p>and we get output:</p>

<pre><code class="language-golang">case id:
        message.Id = anotherField.(uint64)
case another_identifier:
        message.AnotherIdentifier = anotherField.(string)
</code></pre>

<p>However if we put a nested <code>Message</code> inside the proto definition, the <code>Kind</code> will print them as <code>anotherField.message</code> which is not what we want.
<a href="https://developers.google.com/protocol-buffers/docs/reference/google.protobuf">Well known types</a> are also an embedded <code>Message</code> type.</p>

<p>Next version,</p>

<pre><code class="language-golang">var MapWellKnownTypesToGoTypes = map[protoreflect.FullName]string{
	&quot;google.protobuf.BoolValue&quot;:       &quot;uint8&quot;,
	&quot;google.protobuf.Timestamp&quot;:       &quot;time.Time&quot;,
}

func generate(message proto.Message) {

	fds := message.ProtoReflect().Descriptor().Fields()
	for i := 0; i &lt; fds.Len(); i++ {
		fd := fds.Get(i)
		fieldName := string(fd.Name())
		protoField := strings.Title(fd.JSONName())
		// this _can_ mean WKTs or nested messages
		if fd.Kind() == protoreflect.MessageKind {
			typeStr, wkt := MapWellKnownTypesToGoTypes[fd.Message().FullName()]
			if wkt {
				fmt.Printf(typeStr)
				// WKTs assignment requires a bit more sophistication but is possible. I'll leave that as an exercise.
			} else {
				m := message.ProtoReflect()
				// call it recursively on the nested Message
				// but we need to catch field marked as `repeated` 	
				if fd.Cardinality() != protoreflect.Repeated {
					generate(m.Get(fd).Message().Interface())
				} else {
					repeatedElem := m.Get(fd).List().NewElement()
					// this should be only be possible for nested message fields
					generate(repeatedElem.Message().Interface())
				}
			}
		} else if fd.Kind() == protoreflect.EnumKind {
			// enums can have type `int8`
			fmt.Printf(caseTmpl, fieldName, protoField, &quot;int8&quot;)
		} else {
			fmt.Printf(caseTmpl, fieldName, protoField, fd.Kind())
		}
	}
}
</code></pre>

<p>This works for nested <code>Message</code> fields, but I also added some edge cases for <code>repeated</code> <code>Message</code> field and a separate case for <code>Enum</code>.</p>

<p>An example:</p>

<pre><code class="language-protobuf">message Embed {
	string info = 1;
}

message Customer {
  uint64 id = 1;
  string another_identifier = 2;
  Embed embedded = 3;
}
</code></pre>

<p>and we get output :</p>

<pre><code class="language-golang">case id:
        message.Id = anotherField.(uint64)
case another_identifier:
        message.AnotherIdentifier = anotherField.(string)
case embedded:
		message.Embedded = anotherField.(string)
</code></pre>

<p>However note that this doesn&rsquo;t pick the proper <code>fieldName</code> in the nested message case.
We can fix that by picking the <code>Parent</code> name from <code>FieldDescriptor</code>.
So the final version looks like below.</p>

<pre><code class="language-golang">func generate(message proto.Message) {
	fds := message.ProtoReflect().Descriptor().Fields()
	for i := 0; i &lt; fds.Len(); i++ {
		fd := fds.Get(i)
		fieldName := &quot;&quot;
		protoField := &quot;&quot;
		// in case of nested message
		parentName := string(fd.Parent().Name())
		if parentName != &quot;&quot; {
			fieldName = parentName + &quot;_&quot; + string(fd.Name())
			protoField = string(fd.Parent().Name()) + &quot;.&quot; + strings.Title(fd.JSONName())
		} else {
			fieldName = string(fd.Name())
			protoField = strings.Title(fd.JSONName())
		}

		// this _can_ mean WKTs or nested messages
		if fd.Kind() == protoreflect.MessageKind {
			typeStr, wkt := MapWellKnownTypesToGoTypes[fd.Message().FullName()]
			if wkt {
				fmt.Printf(typeStr)
				// WKTs assignment requires a bit more sophistication but is possible. I'll leave that as an exercise.
			} else {
				m := message.ProtoReflect()
				// call it recursively on the nested field
				if fd.Cardinality() != protoreflect.Repeated {
					// ugh
					generate(m.Get(fd).Message().Interface())
				} else {
					repeatedElem := m.Get(fd).List().NewElement()
					// this should be only be possible for nested message fields
					generate(repeatedElem.Message().Interface())
				}
			}
		} else if fd.Kind() == protoreflect.EnumKind {
			// enums can have type `int8`
			fmt.Printf(caseTmpl, fieldName, protoField, &quot;int8&quot;)
		} else {
			fmt.Printf(caseTmpl, fieldName, protoField, fd.Kind())
		}
	}
}
</code></pre>

<p>And that&rsquo;s it !</p>

<p>I hope this gives a bit more insight into the new <code>protoreflect</code> API. There is a lot of the API surface that I haven&rsquo;t touched but I&rsquo;ll leave that for another post.</p>
]]></content>
		</item>
		
		<item>
			<title>Hello</title>
			<link>https://arunsori.me/posts/hello/</link>
			<pubDate>Tue, 01 Jan 2019 17:04:59 +0100</pubDate>
			
			<guid>https://arunsori.me/posts/hello/</guid>
			<description>Hello, World !
I finally got to setup this space :)
I plan to write a new post every month! Let&amp;rsquo;s see how it works out ;)</description>
			<content type="html"><![CDATA[<p>Hello, World !</p>

<p>I finally got to setup this space :)</p>

<p>I plan to write a new post every month! Let&rsquo;s see how it works out ;)</p>
]]></content>
		</item>
		
	</channel>
</rss>
