<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tony Huang on Medium]]></title>
        <description><![CDATA[Stories by Tony Huang on Medium]]></description>
        <link>https://medium.com/@r04922101?source=rss-f91d371b37c1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*r8QMtCXcW7mGjNSOkt8Vzg.png</url>
            <title>Stories by Tony Huang on Medium</title>
            <link>https://medium.com/@r04922101?source=rss-f91d371b37c1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:41:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@r04922101/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Caching Strategies]]></title>
            <link>https://medium.com/@r04922101/caching-strategies-9d3e6695acb3?source=rss-f91d371b37c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d3e6695acb3</guid>
            <category><![CDATA[cache]]></category>
            <dc:creator><![CDATA[Tony Huang]]></dc:creator>
            <pubDate>Sat, 26 Nov 2022 10:41:03 GMT</pubDate>
            <atom:updated>2022-11-26T10:48:38.537Z</atom:updated>
            <content:encoded><![CDATA[<p>Cache is everywhere: processor core cache, memory page and disk cache, DNS cache, HTTP cache like CDN, database cache, browser cache. We can leverage cache to reduce response time, decrease server work load, and absorb spike and uneven load during peak traffic. So what is cache?</p><p>A cache is a fast and temporary storage and stores a subset of expensive data or frequently accessed data in memory so that it speeds up future data retrieval, improves efficiency by avoiding computing complex or resource intensive operations, and saves cost when the information is expensive and we don’t need the information to be alway fresh.</p><p>For example, we use machine learning techniques to tell client’s input sentence intent, which might take several seconds. This is an expensive operation, and it increases backend server’s load. With cache, we can only calculate once, store the result in cache, and return the value. The next time a client asks the same request, we don’t need to spend few seconds calculating the same thing but just read from cache and return the cached copy.</p><h3>When to Use Cache</h3><p>Cache is not always a good choice. Cache may not add values and might degrade the performance in some cases. Be sure that at least your system matches the following criteria:</p><ul><li>The data source behind cache is slow.</li><li>Data doesn’t need to change for each request for some time.</li><li>Frequently accessed more than once.</li><li>Cache hit ratio is high.</li></ul><h3>Caching Strategies</h3><p>There are some caching strategies. Choosing the right one from then can make big difference. How to choose from them depends on data access patterns: read or write heavy, how the data is read/write. For example, system log data is written more frequently than read; user profile is written once and read multiple times.</p><p>Below are some caching strategies:</p><h3>Cache-aside</h3><p>Cache-aside follows the steps:</p><p>1: Client application asks cache.</p><p>2.a: Cache hit → return.</p><p>2.b: Cache miss → ask database → add entry to cache → return.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*FHGhvlUCz_QYxVL0fMlzHA.png" /><figcaption>Cache-aside</figcaption></figure><p>Client application is responsible for reading and writing to database, so the data model in cache can be different from database’s.</p><p>We can see that if cache miss, we need <strong>3 trips</strong>, which is expensive and might be a drawback.</p><p>Cache-aside fits to general purpose and read-heavy system. We always check cache before asking database so that we can avoid expensive database operations.</p><p>Cache-aside is resilient to cache failure: if the cache server goes down, we can still ask database directly.</p><p>Data consistency issue can be mitigated by using different paired writing strategy:</p><ul><li>Write to database directly + apply time to live (TTL) and continue serving stale data until TTL expires. Data might be inconsistent before TTL expires.</li><li>Write to DB + invalidate/update cache.</li><li>Write through.</li></ul><h3>Read-through</h3><p>Read-through is similar to cache aside. There are 2 key differences:</p><ol><li>In cache-aside, client application is responsible for reading and writing data to database, while in read-through, it relies on the library or cache provider to do it</li><li>Cache data model is the same as the database’s.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*UnJgxvHn2RVVnx2zkfY5PA.png" /><figcaption>Read-through</figcaption></figure><p>Both read through and cache aside populate data into cache when the data is first read.</p><p>Read-through works good for read-heavy system when the same data request is performed many times.</p><h3>Write-through</h3><p>Client application is responsible for writing to cache, and then cache writes to database <strong>synchronously</strong>. When write is complete, both cache and database have the same value, and cache <strong>always remains consistent.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*o0_VStbkxy98g8bMfd908Q.png" /><figcaption>Write-through</figcaption></figure><p>Write-through takes extra write latency because it always writes to database.</p><p>When write-through is paired with read-through, we get all benefits from read-through and get data consistency guarantee.</p><p>Data is always written to cache first, but the cached data might never be read. This issue can be mitigated by applying TTL.</p><h3>Write-around</h3><p>Write-around writes to database directly, and only the data that is read makes it into cache.</p><p>When write-around is paired with read-through or cache-aside, we can get good performance for reads and ensure consistency, which works good for situations where data is written once and read less frequently. For example, system log.</p><h3>Write-back (Write-behind)</h3><p>Write-back writes to cache, acknowledges to client, and then cache writes to database <strong>asynchronously</strong>.</p><p>The key differences between write-through are:</p><ul><li>Write-through data is written to cache with update to db <strong>synchronously.</strong></li><li>Write-back data is written to cache with update to db <strong>asynchronously.</strong></li><li>Client get a response faster in write-back because it only needs to write to cache before returning response.</li></ul><p>Write-back improves the write performance, so it works better for write-heavy systems.</p><p>Write-back is resilient to database failure because it writes to database asynchronously.</p><p>When write-back is paired with read-through, it works good for mixed workloads. Write-back not only improves the write performance but also let us always read the most recent updates.</p><p>However, we need to be cautious that if cache goes down, data might be gone permanently.</p><h3>Refresh-ahead</h3><p>Refresh-ahead counts on cache automatically refreshing recently accessed cache entry before its TTL.</p><p>Refresh-ahead can reduce latency as opposed to read-through if the cache can accurately predict which cache entries are likely to be needed in the future.</p><h3>Cache Invalidation</h3><p>Cache invalidation is to mark the data in cache as invalid. Cache is not the source of true of data, but the data source behind it (let’s say a database) is. Once the data in database is updated, the data in cache is invalid, and you will get inconsistent, incorrect information.</p><h3>Final Words</h3><p>We can introduce cache into our system to</p><ul><li>reduce latency</li><li>get better responsiveness</li><li>and decrease backend server workload.</li></ul><p>However, using a cache is not a silver bullet. We need to take the following into consideration:</p><ul><li>Using a cache makes the system complexity higher.</li><li>Data consistency.</li><li>Expiration policy. If there is no expiration policy, cached data will be stored in the memory permanently.</li><li>Eviction policy. Once the cache is full, adding additional items to the cache might cause existing items to be removed. Common eviction policies include least-recently-used (LRU), least-frequently-used (LFU), first-in-first-out (FIFO).</li><li>Single point of failure. A single cache server might be a potential single point of failure.</li><li>We might need to make application changes.</li></ul><h3>References</h3><ol><li><a href="https://codeahoy.com/2017/08/11/caching-strategies-and-how-to-choose-the-right-one/">Caching Strategies and How to Choose the Right One | CodeAhoy</a></li><li><a href="https://codeahoy.com/2022/04/03/cache-invalidation/">Brief Overview of Caching and Cache Invalidation | CodeAhoy</a></li><li><a href="https://github.com/donnemartin/system-design-primer#when-to-update-the-cache">When to Update the Cache</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d3e6695acb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Dependency Management Tools]]></title>
            <link>https://medium.com/@r04922101/python-dependency-management-tools-ac05295ceccd?source=rss-f91d371b37c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac05295ceccd</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[dependency-management]]></category>
            <dc:creator><![CDATA[Tony Huang]]></dc:creator>
            <pubDate>Mon, 17 Oct 2022 09:17:01 GMT</pubDate>
            <atom:updated>2022-10-19T06:37:52.084Z</atom:updated>
            <content:encoded><![CDATA[<p>Developing a software without using third party dependencies is nearly impossible. We always leverage others’ work to to save our efforts, and achieve our goals more easily and quickly. Thus, it is important to manage the dependencies we actually use/need. Installing unnecessary dependencies will lead to large output artifact, and might cause dependency conflicts.</p><p>In this blog, I will go through some Python dependency management tools, and introduce how to install/use them. Hope this blog can help you have a clearer picture of these tools and help you choose one from them for your projects.</p><p>Before jumping into dependency management tools, we need to learn how to use virtual environment to isolate environments for each project, and also use CLI application installation tool to avoid CLI application dependency conflicts.</p><h3>Command-line Applications Installation</h3><h4>pipx</h4><p><em>pipx</em> is a tool to install and run Python command-line packages/applications without causing dependency conflicts. It is roughly like homebrew for MacOS, npx for Javascript.</p><p>pipx uses <em>pip</em> and <em>venv</em>. It focuses on installing packages that can be run from command line as applications.</p><p>pip is a general-purpose installer for libraries and applications without environment isolation, while pipx uses venv to add an environment isolation for each application and its associated packages so that there will be no dependency conflicts and clean installation/uninstallation.</p><p>pipx installs from the same package source as pip, <em>PyPI (Python Package Index)</em>, and it turns PyPI into a big app store for Python applications. pipx can be useful when you want to run another version of the application but do not want to install on your system globally.</p><p><strong>Installation</strong></p><ul><li>On MacOS</li></ul><pre>$ brew install pipx<br>$ pipx ensurepath<br># shell completion, follow the instructions printed with this command<br>$ pipx completions</pre><p>pipx virtual environment location is ~/.local/bin by default.</p><p><strong>Usage</strong></p><ul><li>Install and run the application/package</li></ul><pre># pipx install PACKAGE<br>$ pipx install pip-tools<br># check where pip-tools was installed. It will be $HOME/.local/bin/pip-sync by default<br>$ which pip-sync<br># run the application<br>$ pip-sync --version</pre><ul><li>Run application in temporary/one-time environment</li></ul><pre># pipx run PACKAGE[==VERSION] [ARGS]<br>$ pipx run poetry --version</pre><ul><li>When you want to rerun the application again next time, it will be quick since pipx caches the application for a few days.</li></ul><h3>Virtual Environment</h3><p>Before installing management tools, we need to leverage virtual environment to allow packages are installed in a “isolated environment” rather than being installed globally. If you are looking to installing global command-line tools, consider using <a href="https://packaging.python.org/en/latest/key_projects/#pipx">pipx</a>.</p><p>Virtual environment lets you install packages in an “isolated environment” so to avoid dependency conflicts. Let’s say you want to use a package requests==2.28.0 for an application, but want to use requests==0.9.0 for another application. If you install everything into the global site-packages location, you will unintentionally upgrade the packages that shouldn’t be upgraded.</p><p>I list some common tools for creating virtual environments below:</p><h4>virtualenv</h4><p><em>virtualenv</em> needs to be installed separately.</p><p><strong>Installation</strong></p><pre>$ pipx install virtualenv</pre><p><strong>Usage</strong></p><ul><li>Create a virtual environment</li></ul><pre># create a virtual environment of the same version of virtualenv by default<br># into the destination subdirectory<br># virtualenv DESTINATION<br>$ virtualenv venv</pre><p>If you want to use another Python version for the virtual environment, you can use -p flag to specify the version. Note that you must have the interpreter executable in that version beforehand.</p><pre># use another python version for virtualenv<br># virtualenv --python=PATH_TO_ANOTHER_VERSION_INTERPRETER DST<br>$ virtualenv --python=&quot;$(which python2.6)&quot; venv2.6</pre><ul><li>Activate/deactivate</li></ul><p>If you invoke pip before activating virtual environment, you are still using system pip. After activation, you are calling virtual environment pip. When you want to exit the virtual environment, just use deactivate.</p><pre># source VENV_DIR/bin/activate<br>$ source ./venv/bin/activate<br><br># ...<br><br># exit the virtual environment<br>$ deactivate</pre><h4>venv</h4><p><em>venv</em> is a subset of virtualenv. venv has been integrated into the standard library, and it is default available in Python 3.3 and later.</p><p>As a subset of virtualenv, venv doesn’t offer all features of virtualenv. I just name a few below:</p><ul><li>venv is slower (by not having <a href="https://virtualenv.pypa.io/en/latest/user_guide.html#seeders">app-data installing method</a>).</li><li>venv cannot create virtual environments for arbitrary Python versions.</li></ul><p><strong>Installation</strong></p><p>It has been already integrated to official library, so available by default after Python 3.3</p><p><strong>Usage</strong></p><p>Its usage is similar to virtualenv.</p><ul><li>Create virtual environment</li></ul><pre># python3 -m venv DIR<br>$ python3 -m venv ./.venv</pre><ul><li>Activate/deactivate</li></ul><pre># source VENV_DIR/bin/activate<br>$ source ./.venv/bin/activate<br><br># ...<br><br># exit the virtual environment<br>$ deactivate</pre><h3>Conda</h3><p><em>Conda</em> is a dependency management and virtual environment management system for any language. Conda was created for Python, but now it can package and distribute for any language.</p><p>As an environment manager, Conda can create multiple and different virtual environments with different version of Python easily. On the other hand, as a dependency/package manager, Conda can not only install Python packages but packages in other languages.</p><p>In short, Conda does much more than venv/virtualenv. conda can handle Python thing + non-python softwares. If your requirement includes something beyond Python or multiple versions of Python, then Conda might be useful to you.</p><h3>Dependency Management</h3><h4>Pip</h4><p><em>pip</em> is the package installer for Python. It is automatically included in newer versions of python.</p><p>By default, pip will resolve and download packages from PyPI.</p><p><strong>Usage</strong></p><ul><li>Install a package</li></ul><pre># pip install PACKAGE<br>$ pip install requests</pre><ul><li>Uninstall a package</li></ul><pre># pip uninstall PACKAGE<br>$ pip uninstall requests</pre><ul><li>Install multiple packages using requirements.txt</li></ul><pre># requirements.txt</pre><pre>requests==2.27.0<br>pytest<br>flake8</pre><pre>---</pre><pre>$ pip install -r requirements.txt</pre><p>requirements.txt</p><p>A requirements.txt file is a text file listing pip install arguments. It can also hold the installation result from pip freeze.</p><pre>$ pip freeze &gt; requirements.txt</pre><p>pip freeze is to output installed packages of your current environment in requirements format.</p><ul><li>Upgrade a package</li></ul><pre># pip install --upgrade PACKAGE<br>$ pip install --upgrade requests</pre><h3>Pip-tools</h3><p>pip-tools = pip-compile + pip-sync</p><ul><li>pip-compile It takes either pyproject.toml, setup.cfg, setup.py, or requirements.in to compile a requirements.txt file. If pip-compile finds an existing requirements.txt file that already fulfills the dependencies, then no change will be made (even if any updates available). To build a fresh new requirements.txt, you need to delete requirements.txt first, or provide --upgrade option to ensure the updates will be installed. requirements.txt compiled bypip-compile includes versions for not just the direct dependencies but also for all the transitive dependencies.</li><li>pip-sync Once you have a requirements.txt file, you can use pip-sync to install/uninstall/upgrade the dependencies to your environment. pip-sync takes requirements.txt if no file specified by default.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*GAgA-gMzaJ1dnYcxlh4U7w.png" /><figcaption>pip-tools workflow. Source: <a href="https://github.com/jazzband/pip-tools">jazzband/pip-tools: A set of tools to keep your pinned Python dependencies fresh. (github.com)</a></figcaption></figure><p><strong>Installation</strong></p><pre>$ pipx install pip-tools</pre><p><strong>Usage</strong></p><ul><li>pip-compile</li></ul><ol><li>Use requirements.in</li></ol><pre># requirements.in<br>requests</pre><pre><br>---</pre><pre>$ pip-compile requirements.in</pre><p>Output:</p><pre>#<br># This file is autogenerated by pip-compile with python 3.10<br># To update, run:<br>#<br>#    pip-compile ./requirements.in<br>#<br>certifi==2022.9.24<br>    # via requests<br>charset-normalizer==2.1.1<br>    # via requests<br>idna==3.4<br>    # via requests<br>requests==2.28.1<br>    # via -r ./requirements.in<br>urllib3==1.26.12<br>    # via requests</pre><p>2. Use pyproject.toml</p><pre>[project]<br>name = &quot;my-app&quot;<br>version = &quot;1&quot;<br>dependencies = [&quot;requests&quot;]<br><br>[project.optional-dependencies]<br>dev = [&quot;pytest&quot;]</pre><p>Run pip-compile ./pyproject.toml</p><p>Output:</p><pre>#<br># This file is autogenerated by pip-compile with python 3.10<br># To update, run:<br>#<br>#    pip-compile ./pyproject.toml<br>#<br>certifi==2022.9.24<br>    # via requests<br>charset-normalizer==2.1.1<br>    # via requests<br>idna==3.4<br>    # via requests<br>requests==2.28.1<br>    # via my-cool-django-app (./pyproject.toml)<br>urllib3==1.26.12<br>    # via requests</pre><p>Specify requiring extra dependencies by option — extra:</p><pre>pip-compile --extra dev ./pyproject.toml</pre><p>Output:</p><pre>#<br># This file is autogenerated by pip-compile with python 3.10<br># To update, run:<br>#<br>#    pip-compile --extra=dev ./pyproject.toml<br>#<br>attrs==22.1.0<br>    # via pytest<br>certifi==2022.9.24<br>    # via requests<br>charset-normalizer==2.1.1<br>    # via requests<br>idna==3.4<br>    # via requests<br>iniconfig==1.1.1<br>    # via pytest<br>packaging==21.3<br>    # via pytest<br>pluggy==1.0.0<br>    # via pytest<br>py==1.11.0<br>    # via pytest<br>pyparsing==3.0.9<br>    # via packaging<br>pytest==7.1.3<br>    # via my-app (./pyproject.toml)<br>requests==2.28.1<br>    # via my-app (./pyproject.toml)<br>tomli==2.0.1<br>    # via pytest<br>urllib3==1.26.12<br>    # via requests</pre><p>Options</p><ul><li>-o: output file name</li><li>--extra: extra required dependencies group name</li><li>—-upgrade: try to upgrade all dependencies</li><li>—-pre: allow to resolve pre-release packages</li><li>—-generate-hashes: generate pip 8 hashes, see <a href="https://pip.pypa.io/en/stable/topics/secure-installs/#hash-checking-mode">Hash-checking Mode</a> for more details</li><li>--extra-index-url: add another index URL to search</li><li>pip-sync</li></ul><pre># pip-sync [REQUIREMENTS FILE] [...]<br>$ pip-sync requirements.txt requirements-dev.txt</pre><h3>Poetry</h3><p><em>Poetry</em> replaces requirements.txt, setup.cfg, setup.py, Pipfile with a simple pyproject.toml, and use it to manage/install dependencies.</p><p>By default, poetry creates a virtual environment in {<a href="https://python-poetry.org/docs/configuration/#cache-dir">cache_dir</a>}/virtualenvs, or if you have already activated a virtual environment, poetry would detect and respect it. In the following sections, I have already activated my virtual environment beforehand.</p><p><strong>Installation</strong></p><pre>$ pipx install poetry<br><br># enable oh-my-zsh auto complete<br>$ mkdir $ZSH_CUSTOM/plugins/poetry<br>$ poetry completions zsh &gt; $ZSH_CUSTOM/plugins/poetry/_poetry<br># then add `poetry` plugin to your zshrc</pre><p><strong>Usage</strong></p><ul><li>Interactively create a pyproject.toml by poetry init , output:</li></ul><pre>[tool.poetry]<br>name = &quot;mypackage&quot;<br>version = &quot;0.1.0&quot;<br>description = &quot;poetry init test&quot;<br>authors = [&quot;Tony Huang &lt;r04922101@ntu.edu.tw&gt;&quot;]<br>readme = &quot;README.md&quot;<br><br>[tool.poetry.dependencies]<br>python = &quot;^3.10&quot;<br>requests = &quot;^2.28.1&quot;<br><br>[tool.poetry.group.dev.dependencies]<br>pytest = &quot;^7.1.3&quot;<br><br>[build-system]<br>requires = [&quot;poetry-core&quot;]<br>build-backend = &quot;poetry.core.masonry.api&quot;</pre><p>As you can see in pyproject.toml file, there are a lot of table names starting with tool.poetry. See <a href="https://python-poetry.org/docs/pyproject/">The pyproject.toml file | Documentation | Poetry - Python dependency management and packaging made easy (python-poetry.org)</a> for what each table and each key-value pair mean. I will only introduce some basic usages here.</p><ul><li>Add a new dependency</li></ul><pre># poetry add PACKAGE [...]<br>$ poetry add requests numpy</pre><p>It will automatically finds a suitable version of package and install the package.</p><p>Specify option -G to add the dependency to a group.</p><pre>$ poetry add -G dev flake8 pytest</pre><ul><li>Remove a dependency</li></ul><pre># poetry remove PACKAGE [...]<br>$ poetry remove numpy requests</pre><ul><li>Install all dependencies specified in pyproject.toml</li></ul><pre>$  poetry install</pre><p>By running this command, poetry will read thepoetry.lock file and download dependencies.</p><ul><li>If there is a poetry.lock file, it will use the exact versions defined in poetry.lock to ensure everyone using the library to get the same version of dependencies.</li><li>If there is no poetry.lock file, poetry will resolve the dependencies, install, create poetry.lock file containing all packages and their exact versions information in it.</li></ul><p>Options:</p><ul><li>--with: the optional dependency groups to include</li><li>--without: the optional dependency groups to exclude</li><li>--only: the only dependency group to include</li><li>—-sync: synchronize your environment to match poetry.lock</li></ul><p>If you manually add/remove dependencies in pyproject.toml, run poetry lock to update poetry.lock file and then run poetry install --sync to reflect your changes.</p><ul><li>Update dependencies</li></ul><pre>$  poetry update [PACKAGE] [...]</pre><p>Since poetry.lock prevents you from automatically installing new versions of dependencies, use update command to update.</p><h3>pipenv</h3><p>In my opinion, pipenv = pip + virtualenv. For pip part, pipenv aims to help simplify dependency management for collaborative projects. It uses Pipfile and Pipfile.lock when installing packages like <em>npm</em> uses package.json and package-lock.json. On the other hand, it also creates and manages a virtualenv for projects. With pipenv, you no longer need to use pip and virtualenv separately. Also, you don’t need to use requirements.txt either, but use Pipfile instead.</p><p><strong>Installation</strong></p><pre>$ pipx install pipenv</pre><p><strong>Usage</strong></p><p>Install a package by pipenv install PACAKGE. pipenv will create a virtual environment via virtualenv, install the package into that environment, and generate Pipfile , Pipfile.lock to current directory.</p><p>As the command’s output prompts out, to activate this project’s virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run.</p><pre># pipenv install PACKAGE<br>$ pipenv install requests<br><br># activate virtualenv and run the python script<br>$ pipenv shell<br>$ python main.py<br># exit virtualenv<br>$ deactivate<br><br># alternatively, directly run python script<br>$ pipenv run python main.py</pre><p>main.py:</p><pre>import requests<br><br>response = requests.get(&#39;&lt;https://httpbin.org/ip&gt;&#39;)<br><br>print(&#39;Your IP is {0}&#39;.format(response.json()[&#39;origin&#39;]))</pre><h3>Final Thoughts</h3><p>Let’s take a look at all the dependency management options we have now:</p><ul><li>pip + pip freeze + requirements.txt<br>pip freeze outputs the packages installed in your environment. This might cause some issues if you are just using pip to install/uninstall packages. For example, you install flake8 as your favorite linter for Python, but somehow you don’t like it anymore and want to uninstall it.</li></ul><pre>$ pip install flake8<br>$ pip freeze &gt; before.txt<br><br>$ pip uninstall flake8<br>$ pip freeze &gt; after.txt</pre><p>You will see in after.txt that the dependencies of flake8 are not uninstalled at all even if you don’t need flake8 anymore. This may also cause dependency conflict someday.</p><p>→ Let’s say a dangling package A==1.0.2 has been listed in requirements.txt , and now you want to install another package B depending on A==1.1.8. Then when installing viapip , pip will tell you packages versions have conflicting dependencies.</p><p>Also, requirements.txt generated by pip freeze contains not only the “top-level” dependencies but also secondary dependencies, and so on so forth. It might be annoying, and it can distract your attention from what packages you directly work with.</p><p>Now, you might think about keeping only top-level dependencies in requirements.txt probably solve the above issue. However, once a different version of sub-dependency is released, the result of running pip install -r requirements.txt will result in different packages being installed. As a result, your application might fail, and we learn that we had better still list all dependencies and their exact versions in requirements.txt.</p><p>Thus, using pip, pip freeze, and requirements.txt is not enough so that there are many other dependency management tools around.</p><ul><li>pip-tools<br>pip-tools focuses on building/using requirements.txt. pip-compile input files keep only top-level dependencies, use pip-compile to generate requirements.txt, and use pip-sync to install packages to make sure you only install what you really need.</li><li>poetry<br>poetry uses pyproject.toml but defines extra tables starting with tool.poetry, and it also introduce a lock file poetry.lock to ensure everyone using the library to get the same version of dependencies. Besides, poetry always ensures that you are using a virtual environment, so you won’t mess up global installs.</li><li>pipenv<br>pipenv introduces 2 new files Pipfile and Pipfile.lock aside from requirements.txt, setup.py, setup.cfg, pyproject.toml. Like poetry, pipenv also ensures you are using virtual environment.</li></ul><h3>Appendix</h3><p>In the section below, I’m gonna introduce another tool called pyenv, which is not a dependency management tool but might get users confused by its name. It is used to isolate Python versions.</p><h4>Runtime Version Management</h4><p><strong>Pyenv</strong></p><p><em>pyenv</em> is a tool letting you switch between multiple versions of Python. It is similar to nvm for node.</p><p><strong>Installation</strong></p><pre>$ brew install pyenv</pre><p>Follow the post-installation steps here: <a href="https://github.com/pyenv/pyenv#set-up-your-shell-environment-for-pyenv">Set up your shell environment for Pyenv</a>.</p><p><strong>Usage</strong></p><ul><li>Install additional Python version</li></ul><pre># pyenv install VERSION<br>$ pyenv install 3.10.4</pre><ul><li>Switch Python version</li></ul><pre># only for current shell - pyenv shell VERSION<br>$ pyenv shell 3.8.6<br># for current directory (or its subdirectories) - pyenv local VERSION<br>$ pyenv local 3.9.1<br># globally for your user account - pyenv global VERSION<br>$ pyenv global 3.10.7</pre><ul><li>Uninstall Python versions</li></ul><pre># pyenv uninstall VERSION [...]<br>$ pyenv uninstall 3.10.4</pre><h3>References</h3><ol><li><a href="https://pypa.github.io/pipx/">pipx (pypa.github.io)</a></li><li><a href="https://virtualenv.pypa.io/en/stable/index.html">Virtualenv — virtualenv 20.16.5 documentation (pypa.io)</a></li><li><a href="https://docs.python.org/3/library/venv.html">venv — Creation of virtual environments — Python 3.10.7 documentation</a></li><li><a href="https://packaging.python.org/en/latest/">Python Packaging User Guide — Python Packaging User Guide</a></li><li><a href="https://docs.conda.io/en/latest/">Conda — conda documentation</a></li><li><a href="https://pipenv.pypa.io/en/latest/">Pipenv: Python Dev Workflow for Humans — pipenv 2022.10.10.dev0 documentation (pypa.io)</a></li><li><a href="https://github.com/jazzband/pip-tools">jazzband/pip-tools: A set of tools to keep your pinned Python dependencies fresh. (github.com)</a></li><li><a href="https://python-poetry.org/docs/">Introduction | Documentation | Poetry — Python dependency management and packaging made easy (python-poetry.org)</a></li><li><a href="https://pip.pypa.io/en/stable/">pip documentation v22.2.2 (pypa.io)</a></li><li><a href="https://github.com/pyenv/pyenv">pyenv/pyenv: Simple Python version management (github.com)</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac05295ceccd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[gRPC + Protocol Buffer + Go]]></title>
            <link>https://medium.com/@r04922101/grpc-protocol-buffer-go-47bf2fc6bef0?source=rss-f91d371b37c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/47bf2fc6bef0</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[protocol-buffers]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Tony Huang]]></dc:creator>
            <pubDate>Sun, 09 Oct 2022 14:57:19 GMT</pubDate>
            <atom:updated>2022-10-09T14:57:19.436Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous two posts, we discussed about gRPC and protocol buffer, and all the examples I wrote is in Go. So, in this post, I will give a short recap about how to install required packages for developing gRPC in Go, Also, I will introduce some useful tools to help develop gRPC related works.</p><p>Links to the previous two post can be found here:</p><ul><li><a href="https://medium.com/@r04922101/grpc-70c18cf280a3">gRPC</a></li><li><a href="https://medium.com/@r04922101/protocol-buffer-4c31a336ca1b">Protocol Buffer</a></li></ul><h3>Installation</h3><h4>Protocol Buffer + Go Installation</h4><ul><li><a href="https://go.dev/doc/install">Install Go</a>.</li><li><a href="https://grpc.io/docs/protoc-installation/">Install protocol buffer compiler </a><a href="https://grpc.io/docs/protoc-installation/">protoc</a>.</li><li><a href="https://developers.google.com/protocol-buffers/docs/gotutorial">Install Go protocol buffer plugin</a>.</li></ul><h4>gRPC Protocol Buffer Go Plugin</h4><p>Run go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest to install gRPC plugin.</p><p>Ref: <a href="https://grpc.io/docs/languages/go/quickstart/">Quick start | Go | gRPC</a></p><h4>Generate Go Code</h4><p>Provide the following options for protocol buffer compiler protoc:</p><ul><li>--go-grpc-output: similar to --go-output option.</li><li>--go-grpc-opt: similar to --go-opt option.</li></ul><p>Full example:</p><pre>protoc --go_out={GO_OUT_DIR} --go-grpc_out={GO_GRPC_OUT_DIR} {PROTO_FILE}</pre><h3>Tools and Ecosystems</h3><h4><a href="https://github.com/grpc/grpc-web">grpc-web</a></h4><p>It is a Javascript implementation for browser clients so enables grpc browser support.</p><h4><a href="https://github.com/grpc-ecosystem/grpc-gateway">grpc-gateway</a></h4><p>It is a plugin of protocol buffer compiler <a href="https://github.com/protocolbuffers/protobuf">protoc</a>. It reads .proto files and generate a reverse proxy which translate RESTful HTTP API into gRPC. It can also emit <em>OpenAPI (Swagger)</em> API definitions. It helps provide gRPC and HTTP APIs at the same time.</p><h4><a href="https://github.com/bufbuild/buf">bufbuild/buf</a></h4><p>buf is a CLI tool working with protocol buffers. It can be a linter for .proto files to enforce good structure. Also, it can be a protobuf compiler to generate code.</p><p>It uses a YAML files to define its behavior, to help developers a better control of protocol buffer files and code generation work flow.</p><h4><a href="https://github.com/bloomrpc/bloomrpc">BloomRPC</a></h4><p>BloomRPC is a GUI client for gRPC service. Before Postman supports gRPC calls, I used to use BloomRPC to invoke and test my gRPC services.</p><h4><a href="https://www.postman.com/">Postman</a></h4><p>Postman, needless to say, a very well-known RPC tool. It helps developers design, build, and test APIs. They announced the support for gRPC services in 2022, so if you are familiar with Postman, then you can still stick on it to test your gRPC services without installing other tools now 🎉.</p><h4><a href="https://github.com/fullstorydev/grpcurl">grpcurl</a></h4><p>grpcurl is a CLI tool just like curl, and lets you interact with gRPC servers. If the gPRC server supports reflection, you can easily use grpcurl to test.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47bf2fc6bef0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protocol Buffer]]></title>
            <link>https://medium.com/@r04922101/protocol-buffer-4c31a336ca1b?source=rss-f91d371b37c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c31a336ca1b</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[protocol-buffers]]></category>
            <dc:creator><![CDATA[Tony Huang]]></dc:creator>
            <pubDate>Sun, 09 Oct 2022 09:33:38 GMT</pubDate>
            <atom:updated>2022-10-09T09:33:38.756Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@r04922101/grpc-70c18cf280a3">previous post</a>, we discuss about gRPC. It is not complete without mentioning its IDL — <em>Protocol Buffer</em>. Let’s go through protobol buffer.</p><p>Protocol buffer is Google’s open source mechanism for serializing data. It is smaller and faster comparing to JSON. The current version is proto3.</p><p>Proto file is a text file, and its extension is .proto.</p><p>Use the compiler <a href="https://github.com/protocolbuffers/protobuf">protoc</a> to generate code. The generated code has accessors for each field and methods to serialize/parse the structure to/from bytes.</p><p>gRPC has to use protocol buffer, while protocol buffer is not necessarily combined with gRPC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/0*eJnhQbARn7IMbJXB.png" /><figcaption>Protocol buffer workflow. Source: <a href="https://developers.google.com/protocol-buffers/docs/overview">Overview | Protocol Buffers | Google Developers</a></figcaption></figure><h3>Language Guide</h3><h4>Message</h4><pre>syntax = &quot;proto3&quot;;</pre><pre>message HelloRequest {<br>	reserved 3, 5 to 7;<br>	reserved &quot;phone&quot;, &quot;email&quot;, &quot;address&quot;, &quot;gender&quot;;<br>	string name = 1;<br>	string message = 2;<br>}</pre><ul><li>syntax = proto3 specifies using proto3 syntax.</li><li>HelloRequest defines a <em>message</em> containing 2 fields: name and message, both in string type. A message is a data structure you can define just like a <em>class</em> in OOP.</li><li>Each field in the message has a unique number, called <strong><em>field number</em></strong>. Field number is an identifier in the message binary format. Once the message type is in use, the field number should not be changed, repurposed or reused. This can cause issues if others are still using old version of the same .proto file.<br><a href="https://github.com/r04922101/go-grpc-example/tree/master/updatefield">go-grpc-example/updatefield at master · r04922101/go-grpc-example (github.com)</a></li><li>If you remove a field entirely, you should “<em>reserve</em>” its field number (and/or name) to prevent someone from accidentally reusing the number.</li><li>Note that field number must be in range 1 to 2 ^ 29 -1, while it only takes 1 byte in range 1 through 16, and takes 2 bytes in range 16 through 2047, so reserve some space for frequently occurring fields.</li></ul><h4>Default Values</h4><ul><li>strings: the empty string.</li><li>bytes: empty bytes.</li><li>bools: false.</li><li>numeric types: zero.</li><li>enums: the first defined enum value, which must be 0.</li><li>message fields: the field is not set. For Go, it would be nil.</li><li>repeated fields: empty list.</li></ul><p>⚠️ There is no way to tell a field is explicitly set to its default value or not set at all (e.g., numeric values set to 0 , or boolean value set to false).</p><h4>Enumeration</h4><pre>enum Sports {<br>	option allow_alias = true;<br>	reserved 6, 7;<br>	reserved TENNIS, CYCLING;<br>	UNKNOWN = 0;<br>	BASKETBALL = 1;<br>	BASEBALL = 2;<br>	SOCCER = 3;<br>	TABLE_TENNIS = 4;<br>	PING_PONG = 4; // alias<br>}</pre><ul><li>There <strong>MUST</strong> be a <strong>zero value</strong> as the first element, so that we can use 0 as enum <strong>default value</strong>.</li><li>Use option allow_alias to allow alias, otherwise, the compiler will give an error message.</li><li>Similar to field numbers, once an enum entry has been remove, we need to use reserve to prevent other users reusing it.</li></ul><h4>Importing Definitions</h4><p>If another definition such as a message is defined in another .proto file, we can use import to import that definitions from the file into the current file.</p><pre>import &quot;another_proto.proto&quot;;</pre><p>When you want to move definitions in the original .proto file to a new file, you will not want to change all the import statement occurrences in all other .proto files which is importing the definitions. Instead, you can still keep the original .proto file and use import public statement to forward all the imports to the new location.</p><pre>// original.proto<br>import public new.proto</pre><pre>---</pre><pre>// new.proto<br>// all the definitions are moved to here<br>message HelloRequest {<br>}</pre><pre>---</pre><pre>// client.proto<br>// still importing the original proto file<br>import original.proto</pre><p>When using protocol compiler, in general, you need to specify the directories containing .proto files by using -I/--proto_path flag. If not specified, it will look in the directory where the compiler is invoked.</p><h4>Nested Types and Using Other Message Types</h4><p>We can define a message type in a message type, which is called <em>nested type</em>. As in the example below, User is defined in Result type. If you want to reuse nested type outside the parent message type, you refer it to _Parent_._Type_. As shown in the example, Result.User type can be included in AnotherMessage type.</p><pre>message Response {<br>	// use another message type<br>	repeated Result result = 1;<br>}</pre><pre>enum Sport {<br>	UNKNOWN = 0;<br>	BASEBALL = 1;<br>}</pre><pre>message Result {<br>	// nested type, Result.User<br>	message User {<br>		string name = 1;<br>		string mail = 2;<br>	}<br>	User user = 1;<br>	Sport sport = 2;	<br>}</pre><pre>message AnotherMessage {<br>	// reuse nested message type outside the parent message<br>	Result.User user = 1;<br>	string url = 2;<br>}</pre><h4>Any Type</h4><p>By importing google/protobuf/any.proto, we can use Any type as embedded message types without their .proto definition.</p><h4>Oneof</h4><p>If a message contains multiple fields and only one of those field will be set at the same time, you can use oneof to enforce this behavior and save memory.</p><p>If multiple values are set, the last set value will overwrite the previous ones.</p><p>You can add any fields to oneof except map and repeated fields.</p><pre>message Contact {<br>	oneof contact {<br>		string email = 1;<br>		string phone = 2;<br>		Address address = 3;<br>	}<br>}</pre><pre>message Address {<br>	string country = 1;<br>	string city = 2;<br>	string district = 3;<br>	string detail = 4;<br>}</pre><p>In generated code, you will have accessors to get those values. Moreover, you also get a method to check which value (if any) in the oneof is set.</p><p>After adding or removing a oneof field, when checking the value of a oneof returns None/NOT_SET, it could mean that field has not been set or has been set to another version of oneof, and there is no way to tell the difference.</p><p>💡 If you set a oneof field to the default value (such as setting an int32 oneof field to 0), the &quot;case&quot; of that oneof field will be set, and the value will be serialized on the wire.</p><p><a href="https://github.com/r04922101/go-grpc-example/tree/master/oneof">go-grpc-example/oneof at master · r04922101/go-grpc-example (github.com)</a></p><h4>Map</h4><p>map&lt;key_type, value_type&gt; map_field = N;</p><p>key_type can be integral or string type, and value_type can be any type except another map type.</p><ul><li>Map fields can not be repeated.</li><li>Map ordering is <strong>NOT </strong>guaranteed.</li></ul><h4>Packages</h4><p>package identifier can help prevent name clashes between .proto files.</p><pre>package example</pre><pre>message Example {<br>	string value = 1;<br>}</pre><pre>message Another {<br>	example.Example example = 1;<br>}</pre><p>In Go, specify generated code package by providing option option go_package.</p><h4>Services</h4><p>Defining RPC service interface in .proto files and generating interface code and stub in chosen language let you use your message type in RPC system.</p><pre>service HelloService {<br>		rpc SayHello(HelloRequest) return HelloResponse;<br>}</pre><pre>message HelloRequest {<br>}</pre><pre>message HelloResponse {<br>}</pre><p>Use gRPC or other implementations to integrate into your system.</p><h4>Options</h4><p>Options do not change the overall behavior of a .proto file, but may affect the context in different ways. Complete list of available options: <a href="https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/descriptor.proto">protobuf/descriptor.proto at main · protocolbuffers/protobuf (github.com)</a></p><p>Options can be file-level, message-level, field-level, etc.</p><p>For example, option go_package = mypackage; is a file-level option: the package for generated Go codes. If this option is not specified, the default package will be the package defined in the .proto file.</p><h4>Field Options and Custom Options</h4><p>A field option can be assigned to a field. For example, adding a deprecated option to name field while this option has no actual effect in most languages 😅.</p><pre>message Person {<br>	string name = 1 [deprecated = true]; <br>	string first_name = 2;<br>	string last_name = 3;<br>}</pre><p>We can also define our custom options which most developers might not need. Defining a custom option is actually <em>“extend”</em> the existing messages defined in <a href="https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/descriptor.proto">protobuf/descriptor.proto at main · protocolbuffers/protobuf (github.com)</a>.</p><p>⚠️ Use number in range 50000–99999 for internal used extension field numbers.</p><ul><li>Custom field option</li></ul><pre>extend google.protobuf.FieldOptions {<br>	optional bool must_positive = 50001;<br>}</pre><ul><li>Custom message option</li></ul><pre>extend google.protobuf.MessageOptions {<br>	optional bool allow_nil_values = 50002;<br>}</pre><ul><li>Custom method option</li></ul><pre>extend google.protobuf.MethodOptions {<br>	optional string action  = 50003;<br>}</pre><p><a href="https://github.com/r04922101/go-grpc-example/tree/master/customoption">go-grpc-example/customoption at master · r04922101/go-grpc-example (github.com)</a></p><h4>Updating A Message Type</h4><p>When updating a message, remember the following rules:</p><ul><li>Do <strong>NOT</strong> change the field number for any existing fields.</li><li>If adding a new field, the message generated by old code (without new field) can still be parse by new code <strong>with the new field in default value</strong>. On the other hand, the message generated by new code can also be parsed by old code, while those new fields <strong>become unknown fields</strong> in the old binary.</li><li>Fields can be removed as long as the field number is not used again in the updated message type. You can use reserve statement, add a prefix before the field to denote it shouldn’t be used again, or add a comment above to prevent other users using it accidentally.</li></ul><p>For more compatibility details, see <a href="https://developers.google.com/protocol-buffers/docs/proto3#updating">Language Guide (proto3) | Protocol Buffers | Google Developers</a>.</p><p><a href="https://github.com/r04922101/go-grpc-example/tree/master/updatefield">go-grpc-example/updatefield at master · r04922101/go-grpc-example (github.com)</a></p><h4>Style Guide</h4><ul><li>Line length ≤ 80 characters</li><li>Indent 2 spaces</li><li>Double quote for strings</li><li>Filename should be lower_snake_case</li><li>File content should be in the following manner:<br> — License header<br> — Overview<br> — Syntax<br> — Package<br> — Imports<br> — File options<br> — Everything else</li><li>Package name should be in lowercase</li><li>Use CamelCase (with an initial capital) for message names and enum names</li><li>Use lower_snake_case for field names</li><li>Use plural for repeated fields</li><li>Use UPPER_SNAKE_CASE for enum value names</li><li>The zero value enum should have suffix UNSPECIFIED</li><li>Use CamelCase (with an initial capital) for service names and RPC method names</li></ul><h3>Generating Go Code</h3><p>The generated Go code file extension is .pb.go.</p><h4>Installation</h4><ol><li>Download protocol buffer compiler <a href="https://github.com/protocolbuffers/protobuf/releases">protoc</a>.</li><li>Run go install google.golang.org/protobuf/cmd/protoc-gen-go@latest to install Go protocol buffer plugin. The plugin will be installed in $GOBIN (default to $GOPATH/bin). It must be in your $PATH for protoc to find it.</li></ol><h4>Compile</h4><p>protoc -I=$IMPOR_PROTO_SRC_DIR --go_out=$DST_DIR $PROTO_PATH</p><ul><li>-I/—import_path: specify the directory in which to search for imports.</li><li>—go_out: with this option, protoc compiler will generate Go output in the specified output directory.</li><li>--go_opt: specify options<br>paths=import: default output mode. Output file is placed in a directory named after the Go package’s import path.<br>module=$PREFIX: the output file is placed in a directory named after the Go package’s import path, but the specified directory prefix removed from the output file name.<br>paths=source_relative: the output file is placed in the same directory as the input file</li></ul><p>For example,</p><p>With the following file:</p><pre>./ <br>├── pb<br>│   └── hello.proto</pre><ul><li>Default output mode or paths=import<br>protoc --go_out=. ./pb/hello.proto or protoc -I ./pb --go_out=. hello.proto<br>Generates hello.pb.go in the directory specified in .proto file option go_package. <br>For example,<br>option go_package = &quot;github.com/r04922101/go-grpc-example/pb&quot;;<br>Makes a directory github.com/r04922101/go-grpc/example/pb in current directory, and put hello.pb.go with Go code package pb in it.</li></ul><pre>. <br>├── github.com<br>│   └── r04922101<br>│       └── go-grpc-example<br>│           └── pb<br>│               └── hello.pb.go<br>└── pb<br>    └── hello.proto</pre><ul><li>module=$PREFIX This mode is useful for outputting generated file directly into a Go module.<br>option go_package = &quot;github.com/r04922101/a/b/c/d/e&quot;;<br>protoc --go_out=./ --go_opt=module=github.com/r04922101/a ./pb/hello.proto<br>Generates hello.pb.go with Go code package e in b/c/d/e directory.</li></ul><pre>. <br>├── b <br>│   └── c <br>│       └── d <br>│           └── e <br>│               └── hello.pb.go <br>└── pb<br>     └── hello.proto</pre><p>protoc --go_out=./ --go_opt=module=github.com/r04922101/a/b/c ./pb/hello.proto<br>Generates hello.pb.go with Go code package e in d/e/ directory.</p><pre>. <br>├── d <br>│   └── e <br>│       └── hello.pb.go <br>└── pb <br>    └── hello.proto</pre><p>⚠️ PREFIX here cannot be just github.com/</p><ul><li>paths=source_relative<br>option go_package = &quot;github.com/r04922101/go-grpc-example/pb&quot;;<br>protoc --go_out=./ --go_opt=paths=source_relative ./pb/hello.proto<br>Generates hello.pb.go in pb/ with Go code package pb in pb directory.</li></ul><pre>.<br>└── pb<br>     ├── hello.pb.go<br>     └── hello.proto</pre><p>protoc -I ./pb --go_out=. --go_opt=paths=source_relative hello.proto Generates hello.pb.go with Go code package pb in current directory.</p><pre>. <br>├── hello.pb.go <br>└── pb <br>    └── hello.proto</pre><ul><li>Packages<br>Aside from using option go_package to specify Go package’s import path of generated code, the import path can also be provided on the command line: protoc --go_opt=M${PROTO_FILE}=${GO_IMPORT_PATH}<br>If this option provided, it will override the import package path defined in .proto file.<br>For example,<br>With the following file again:</li></ul><pre>. <br>├── pb <br>│   └── hello.proto</pre><p>In hello.proto, it specifies</p><p>option go_package = &quot;github.com/r04922101/go-grpc-example/pb&quot;;</p><p>protoc --go_out=. --go_opt=Mpb/hello.proto=a/b/c ./pb/hello.proto Makes a directory a/b/c in current directory, and put hello.pb.go with Go code pakcage pb in it.</p><pre>. <br>├── a <br>│   └── b <br>│       └── c <br>│           └── hello.pb.go <br>└── pb <br>    └── hello.proto</pre><p>protoc --go_out=. --go_opt=paths=source_relative --go_opt=Mpb/hello.proto=a/b/c ./pb/hello.proto<br> Generates hello.pb.go with Go code package pb in pb/ directory.</p><pre>.<br>└── pb<br>    ├── hello.pb.go<br>    └── hello.proto</pre><p>💡 The Go import path is not related to the package specifier in .proto file. package is only for protobuf namespace.</p><p>💡 Generated Go field names are using camelCase naming.</p><p>For more details, see <a href="https://developers.google.com/protocol-buffers/docs/reference/go-generated">Go Generated Code | Protocol Buffers | Google Developers</a></p><p>For services defined in .proto files, the Go code generator does <strong>NOT</strong> output for services by default. Use gRPC plugin to support it.</p><h3>References</h3><ol><li><a href="https://grpc.io/">gRPC</a></li><li><a href="https://github.com/grpc/grpc">https://github.com/grpc/grpc</a></li><li><a href="https://en.wikipedia.org/wiki/GRPC">gRPC — Wikipedia</a></li><li><a href="https://developers.google.com/protocol-buffers/docs/overview">Overview | Protocol Buffers | Google Developers</a></li><li><a href="https://developers.google.com/protocol-buffers/docs/proto3">Language Guide (proto3) | Protocol Buffers | Google Developers</a></li><li><a href="https://developers.google.com/protocol-buffers/docs/reference/go-generated">Go Generated Code | Protocol Buffers | Google Developers</a></li><li><a href="https://developers.google.com/protocol-buffers/docs/style">Style Guide | Protocol Buffers | Google Developers</a></li><li><a href="https://developers.google.com/protocol-buffers/docs/gotutorial">Protocol Buffer Basics: Go | Protocol Buffers | Google Developers</a></li><li><a href="https://grpc.io/docs/languages/go/quickstart/">Quick start | Go | gRPC</a></li><li><a href="https://grpc.io/docs/what-is-grpc/introduction/">Introduction to gRPC | gRPC</a></li><li><a href="https://grpc.io/docs/what-is-grpc/core-concepts/">Core concepts, architecture and lifecycle | gRPC</a></li><li><a href="https://grpc.io/docs/guides/auth/">Authentication | gRPC</a></li><li><a href="https://grpc.io/docs/guides/error/">Error handling | gRPC</a></li><li><a href="https://cloud.google.com/apis/design/errors">Errors | Cloud APIs | Google Cloud</a></li><li><a href="https://grpc.io/docs/languages/go/basics/">Basics tutorial | Go | gRPC</a></li><li><a href="https://grpc.io/blog/deadlines/">gRPC and Deadlines | gRPC</a></li><li><a href="https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-metadata.md">grpc-go/grpc-metadata.md at master · grpc/grpc-go (github.com)</a></li><li><a href="https://github.com/fullstorydev/grpcurl">https://github.com/fullstorydev/grpcurl</a></li><li><a href="https://github.com/grpc/grpc/blob/master/doc/server-reflection.md">grpc/server-reflection.md at master · grpc/grpc (github.com)</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c31a336ca1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[gRPC]]></title>
            <link>https://medium.com/@r04922101/grpc-70c18cf280a3?source=rss-f91d371b37c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/70c18cf280a3</guid>
            <category><![CDATA[rpc]]></category>
            <category><![CDATA[grpc]]></category>
            <dc:creator><![CDATA[Tony Huang]]></dc:creator>
            <pubDate>Wed, 05 Oct 2022 03:28:10 GMT</pubDate>
            <atom:updated>2022-10-09T08:57:27.182Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Remote procedure call (RPC)</em> is a mechanism allowing computers communicate with each other. A node can ask another node to do something and return response back. The calling RPC way is just like invoking a function call.</p><p>gRPC is also an RPC just like RESTful APIs, and is also to dealing with sending requests and receiving responses.</p><p>In this post, we will go through what gRPC is, its core concept, why gRPC, authentication, and error handling.</p><h3>gRPC</h3><p>gRPC is a high performance remote procedure call (RPC) framework over HTTP/2 which can run in any environment. gRPC was initially created by Google.</p><p>gRPC generates cross-platform client and server code for many languages, and it enables communication between client and server. The server implements the interface, and it can be called by client interface. We can use it to connect services in a <em>microservice</em> architecture.</p><p>gRPC uses <em>Protocol Buffer</em> as its <em>interface definition language (IDL)</em> to encode data and describe service interface and structure. gRPC also provides a .proto file compiler <a href="https://github.com/protocolbuffers/protobuf">protoc</a> to generate client and server code in the supported languages.</p><p>After writing .proto files, use protocol buffer compiler to generate client and server code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*nQwSVZnLp94CAOZU4WUwzw.png" /><figcaption>gRPC Overview. Source: <a href="https://grpc.io/docs/what-is-grpc/introduction/">Introduction to gRPC | gRPC</a></figcaption></figure><p>gRPC supports synchronous, asynchronous, and streaming calls.</p><h3>Core Concepts</h3><p>gRPC uses protocol buffer as its IDL to define a service, and to specify the methods to be called remotely with parameters and return values/types.</p><h4>Services</h4><ul><li>Unary<br>Client sends a single request, and server returns a single response.</li></ul><pre>rpc SayHello (HelloRequest) returns (HelloResponse) {}</pre><p><a href="https://github.com/r04922101/go-grpc-example/tree/master/unary">go-grpc-example/unary at master · r04922101/go-grpc-example (github.com)</a></p><ul><li>Server streaming<br>Client sends a single request, and receives a stream to read a sequence of message until no more messages. The message <strong>order is guaranteed</strong> within an individual RPC call.</li></ul><pre>rpc SayHello (HelloRequest) returns (stream HelloResponse) {}</pre><p><a href="https://github.com/r04922101/go-grpc-example/tree/master/serverstreaming">go-grpc-example/serverstreaming at master · r04922101/go-grpc-example (github.com)</a></p><ul><li>Client streaming<br>Client sends a sequence of messages to server. Once the client finishes writing, it waits for the server to read them and return its response. The <strong>message order is guaranteed</strong> within an individual RPC call.</li></ul><pre>rpc SayHello(stream HelloRequest) returns (HelloResponse) {}</pre><p><a href="https://github.com/r04922101/go-grpc-example/tree/master/clientstreaming">go-grpc-example/clientstreaming at master · r04922101/go-grpc-example (github.com)</a></p><ul><li>Bidirectional streaming<br>Both client and server send a sequence of messages using a read-write stream. The two streams are independent, so client and server can both read/write in any order at will.</li></ul><pre>rpc SayHello(stream HelloRequest) return (stream HelloResponse) {}</pre><p><a href="https://github.com/r04922101/go-grpc-example/tree/master/bidirectional">go-grpc-example/bidirectional at master · r04922101/go-grpc-example (github.com)</a></p><h4>Using API</h4><p>The gRPC infrastructure encodes/decodes request/response.</p><ul><li>Server needs to implement the generated method code, and runs a gRPC server to handle client calls.</li><li>Client has a <em>stub</em> implementing the same methods as the service, and can just call those methods.</li></ul><h4>RPC Life Cycle</h4><ul><li>Unary<br>1. Once client calls a stub method, server is notified the RPC has been called with client’s metadata, method name, and deadline (if applicable).<br>2. Server can either send its own metadata (must be before any response) back, or wait for client’s request message.<br>3. Once server receives client’s message, server does something to handle the message and returns back a response with status details (status code and optional status message, see <a href="https://github.com/googleapis/googleapis/blob/master/google/rpc/status.proto">googleapis/status.proto at master · googleapis/googleapis (github.com)</a> for more details) and optional trailing metadata.<br>4. If the response status is OK, client gets the response and complete the call.</li><li>Server streaming<br>Similar to unary call, except server returns a stream of message in response. Client completes the call once it has all server’s messages.</li><li>Client streaming<br>Similar to unary call, except client sends a stream of message in request. Note that server does <strong>NOT</strong> need to receive all client’s message before sending response (but typically it waits).</li><li>Bidirectional streaming<br>Similar to unary call, except both client and server send a stream of messages, and the two streams are independent.</li></ul><h4>Deadline/Timeout, Termination, and Cancellation</h4><p>Client can send a deadline/timeout information to server to specify how long it is willing to wait before the RPC is terminated with a DEADLINE_EXCEEDED error.</p><p>In Go, we can just leverage <a href="https://pkg.go.dev/context">context</a> package to set deadline/timeout.</p><p><a href="https://github.com/r04922101/go-grpc-example/tree/master/timeout">go-grpc-example/timeout at master · r04922101/go-grpc-example (github.com)</a></p><p>In terms of termination, client and server both make independent and local determination of the success of a call, and the conclusions might not match. For example, server says it has sent all responses back, while client says the responses arrived after deadline.</p><p>Finally, about cancellation, Either server or client can cancel RPC at any time. A cancellation terminates the RPC immediately.</p><h4>Metadata</h4><p>Metadata is the information about a RPC call (e.g., authentication details) in the form of key-value pairs. The key is in string type, and value is usually in string type but it can also be binary. (In Go, just append -bin to key string)</p><p>Both client and server can provider metadata and send to the other end.</p><p><a href="https://github.com/r04922101/go-grpc-example/tree/master/metadata">go-grpc-example/metadata at master · r04922101/go-grpc-example (github.com)</a></p><h3>Why gRPC</h3><ul><li>Automatically generate client and server code in any of supported languages.</li><li>Payload is compressed into binary → smaller.</li><li>Support synchronous, asynchronous, and streaming calls.</li><li>Once developers agree upon the contract (.proto file), developers can generate both client and server interface, and comply with it → save developers’ time</li><li>Processing payload complexity is lower comparing to RESTful payload in text format (e.g., JSON).</li></ul><p>⚠️ gRPC needs grpc-web to enable browser support.</p><h3>Authentication</h3><h4>SSL/TLS</h4><p>Use SSL/TLS to authenticate server, and encrypt all data transferred between server and client. It also supports client authentication by providing client certificate.</p><p><a href="https://github.com/r04922101/go-grpc-example/tree/master/ssl">go-grpc-example/ssl at master · r04922101/go-grpc-example (github.com)</a></p><h4>ALTS</h4><p><em>Application Layer Transport Security (ALTS)</em> is a mutual authentication and transport encryption system developed by Google, and used to secure RPC communication within Google infrastructure. gRPC supports ALTS is the application is running on GCP. See <a href="https://grpc.io/docs/languages/go/alts/">ALTS authentication | Go | gRPC</a> for more details.</p><h3>Error Handling</h3><h4>Standard Error Model</h4><p>With standard error model, if an error occurs, a status code and an optional error message are returned. All the supported language clients/servers implement this model.</p><p>See <a href="https://github.com/googleapis/googleapis/blob/master/google/rpc/status.proto">googleapis/status.proto at master · googleapis/googleapis (github.com)</a> for more details.</p><h4>Richer Error Model</h4><p>⚠️ Not all languages support it. Check their GitHub repos if interested.</p><p>📝I also tried to use detailed error inTypescript client. See <a href="https://github.com/r04922101/grpc-error">r04922101/grpc-error: Golang, Typescript gRPC status detail error handling (github.com)</a>.</p><p>As we can see in <a href="https://github.com/googleapis/googleapis/blob/master/google/rpc/status.proto">googleapis/status.proto at master · googleapis/googleapis (github.com)</a>:</p><pre>  // A list of messages that carry the error details.  There is a common set of<br>  // message types for APIs to use.<br>  repeated google.protobuf.Any details = 3;</pre><p>We can provide details in google.protobuf.Any type, which can be literally any type. Check <a href="https://github.com/googleapis/googleapis/blob/master/google/rpc/error_details.proto">googleapis/error_details.proto at master · googleapis/googleapis (github.com)</a> for more predefined detailed error types.</p><p>Only provide additional detailed error if it really helps application code handle the error. For example:</p><ul><li>RetryInfo tells when client can retry the request.</li><li>QuotaFailure tells how quota is checked, rate limit exceeded, etc. Might be returned on Code.RESOURCE_EXHAUSTED.</li><li>BadRequest tells how the request violated the API interface, might be returned on Code.INVALID_ARGUMENT.</li></ul><p>Also check <a href="https://cloud.google.com/apis/design/errors#error_payloads">here</a> to see preferred detail error type and status code combinations.</p><h4>Error Codes</h4><p>Check <a href="https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto">googleapis/code.proto at master · googleapis/googleapis (github.com)</a> for more detailed error code definitions. If you are more familiar with HTTP status code, also check <a href="https://cloud.google.com/apis/design/errors#handling_errors">here</a>.</p><p>💡 Client does NOT know the implementation detail of your server. Do NOT reveal implementation detail in response, which is helpless to client.</p><h3>Reflection</h3><p>Server reflection protocol is an extension to help client to construct request without having stub information precompiled into the client. It can help building command line tool to talk to gRPC server.</p><p>Reflection helps</p><ul><li>take in a method with human-readable request</li><li>encode it into binary format</li><li>send to server</li><li>receive response</li><li>decode response to human-readable text</li></ul><h4>Go Reflection</h4><p>grpc-go server reflection is implemented in package <a href="https://github.com/grpc/grpc-go/tree/master/reflection">grpc-go/reflection at master · grpc/grpc-go (github.com)</a>. To enable it, we need to install this package and register server reflection service on gRPC server.</p><p>After registering reflection service, we can also use <a href="https://github.com/fullstorydev/grpcurl">grpcurl</a> to talk to server.</p><p><a href="https://github.com/r04922101/go-grpc-example/tree/master/reflection">go-grpc-example/reflection at master · r04922101/go-grpc-example (github.com)</a></p><h3>References</h3><ol><li><a href="https://grpc.io/">gRPC</a></li><li><a href="https://github.com/grpc/grpc">https://github.com/grpc/grpc</a></li><li><a href="https://en.wikipedia.org/wiki/GRPC">gRPC — Wikipedia</a></li><li><a href="https://developers.google.com/protocol-buffers/docs/overview">Overview | Protocol Buffers | Google Developers</a></li><li><a href="https://developers.google.com/protocol-buffers/docs/proto3">Language Guide (proto3) | Protocol Buffers | Google Developers</a></li><li><a href="https://developers.google.com/protocol-buffers/docs/reference/go-generated">Go Generated Code | Protocol Buffers | Google Developers</a></li><li><a href="https://developers.google.com/protocol-buffers/docs/style">Style Guide | Protocol Buffers | Google Developers</a></li><li><a href="https://developers.google.com/protocol-buffers/docs/gotutorial">Protocol Buffer Basics: Go | Protocol Buffers | Google Developers</a></li><li><a href="https://grpc.io/docs/languages/go/quickstart/">Quick start | Go | gRPC</a></li><li><a href="https://grpc.io/docs/what-is-grpc/introduction/">Introduction to gRPC | gRPC</a></li><li><a href="https://grpc.io/docs/what-is-grpc/core-concepts/">Core concepts, architecture and lifecycle | gRPC</a></li><li><a href="https://grpc.io/docs/guides/auth/">Authentication | gRPC</a></li><li><a href="https://grpc.io/docs/guides/error/">Error handling | gRPC</a></li><li><a href="https://cloud.google.com/apis/design/errors">Errors | Cloud APIs | Google Cloud</a></li><li><a href="https://grpc.io/docs/languages/go/basics/">Basics tutorial | Go | gRPC</a></li><li><a href="https://grpc.io/blog/deadlines/">gRPC and Deadlines | gRPC</a></li><li><a href="https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-metadata.md">grpc-go/grpc-metadata.md at master · grpc/grpc-go (github.com)</a></li><li><a href="https://github.com/fullstorydev/grpcurl">https://github.com/fullstorydev/grpcurl</a></li><li><a href="https://github.com/grpc/grpc/blob/master/doc/server-reflection.md">grpc/server-reflection.md at master · grpc/grpc (github.com)</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70c18cf280a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Injection]]></title>
            <link>https://medium.com/@r04922101/sql-injection-bf4ddfce7e80?source=rss-f91d371b37c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf4ddfce7e80</guid>
            <category><![CDATA[sql-injection]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Tony Huang]]></dc:creator>
            <pubDate>Tue, 04 Oct 2022 02:36:45 GMT</pubDate>
            <atom:updated>2022-10-04T06:43:06.506Z</atom:updated>
            <content:encoded><![CDATA[<p>SQL injection is a most common web hacking, code injection attack technique that manipulates and accesses to your database. We will go through what it is, how to prevent it, and its impact.</p><h3>What is SQL Injection</h3><p>SQL injection occurs when an attacker injects a SQL query via the input data of client application. It enables the attacker to access and manipulate the database.</p><h3>What Causes SQL Injection</h3><p>Input is used to construct dynamic queries without validation, so that the input data can be arbitrary SQL queries. It might lead to loss of confidentiality, authentication, and integrity.</p><h3>How to Prevent</h3><ol><li>Use parameterized queries/prepared statements.</li></ol><p>The following example is incorrect usage:</p><pre>query := fmt.Sprintf(`SELECT * FROM Users WHERE username = &quot;%s&quot; AND password = &quot;%s&quot;`, inputUsername, inputPassword)<br>row := db.QueryRow(query)<br>...</pre><p>Because if the attacker input the username tony and password random&quot; OR &quot;1&quot; = &quot;1, the query will become<br>SELECT * FROM Users WHERE username = &quot;tony&quot; AND password = &quot;random&quot; OR &quot;1&quot; = &quot;1&quot;,<br>in which the &quot;1&quot; = &quot;1&quot; condition is always true, so the query becomes equivalent to<br>SELECT * FROM Users ;<br>the query returns all the user information to the attacker.</p><p>In addition, if the database is connected with an option multiStatements=true, attacker can further delete data from database in the above query by sending<br>random&quot;; DELETE FROM Users; SELECT * FROM Users WHERE &quot;1&quot; = &quot;1<br> to the application. The input will construct the query<br>SELECT * FROM Users WHERE username = &quot;tony&quot; AND password = &quot;random&quot;; DELETE * FROM Users; SELECT * FROM Users WHERE &quot;1&quot; = &quot;1&quot;.</p><p>Developers should never concatenate user controllable input to construct queries, and send to database. Instead, use parameterized queries as the following example:</p><pre>query, err := db.Prepare(&quot;SELECT * FROM Users WHERE username = ? AND password = ?&quot;)<br>rows, err := query.Query(inputUsername, inputPassword);</pre><p>2. Validate input</p><p>Validate all user input the check against an allowed list of input parameters</p><p>3. Use Object Relational Mapping (ORM)</p><p>ORM generates SQL queries so that it prevents developers from writing raw SQL queries as strings.</p><h3>Impacts</h3><p>SQL injection enables attackers to update/insert/delete data. The authentication mechanism could be bypassed, and all data could be manipulated/leaked.</p><h3>Prepared Statements</h3><p>Prepared statement pre-compiles SQL query code, and separate it from data. It can reduce the risk of SQL injection and enhance the efficiency (It benefits from repeatedly use the same query without re-compiling).</p><p>Workflow</p><ul><li>Prepare: application creates a template query command like SELECT * FROM Users WHERE username = ? AND password = ?and sends the template to database.</li><li>Compile: database compiles and stores it without executing it.</li><li>Execute: application provides parameters for the statement and the database executes it.</li></ul><p>All database programming interface should have already implemented prepared statement interface. See the full sample code in Go for example.</p><p>On the other hand, in SQL shell, we can use prepared statements with PREPARE, SET, EXECUTE, and DEALLOCATE PREPARE as follows:</p><pre>mysql&gt; PREPARE mystmt FROM &#39;SELECT * FROM Users WHERE username = ? AND password = ?&#39;;<br>Query OK, 0 rows affected (0.01 sec)<br>Statement prepared<br><br>mysql&gt; SET @username=&#39;tony&#39;;<br>Query OK, 0 rows affected (0.00 sec)<br><br>mysql&gt; SET @password=&#39;huang&#39;;<br>Query OK, 0 rows affected (0.01 sec)<br><br>mysql&gt; EXECUTE mystmt USING @username, @password;<br>+----------+----------+<br>| username | password |<br>+----------+----------+<br>| tony     | huang    |<br>+----------+----------+<br>1 row in set (0.01 sec)<br><br>mysql&gt; deallocate prepare mystmt;<br>Query OK, 0 rows affected (0.02 sec)<br><br>mysql&gt; EXECUTE mystmt USING @username, @password;<br>ERROR 1243 (HY000): Unknown prepared statement handler (mystmt) given to EXECUTE</pre><ul><li>PREPARE: prepares a statement for execution.</li><li>SET: assigns values to variables.</li><li>EXECUTE: executes a prepared statement.</li><li>DEALLOCATE PREPARE: deallocate a prepared statement.</li></ul><h3>Golang Example</h3><h3>Prerequisites</h3><ul><li>Start up a MySQL instance on local machine, and allow empty password. I use docker to run up:</li></ul><pre>docker run -d -p 3306:3306 -e MYSQL_ALLOW_EMPTY_PASSWORD=true mysql:8.0</pre><ul><li>Shell into MySQL instance, create a database db1, a table Users, and insert some data to it.</li></ul><pre>CREATE DATABASE db1;<br>USE db1;<br>CREATE TABLE Users (username varchar(255), password(255)); INSERT INTO Users VALUES (&#39;tony&#39;, &#39;huang&#39;), (&#39;bob&#39;, &#39;alice&#39;), (&#39;foo&#39;, &#39;bar&#39;);</pre><ul><li>Install Go mysql driver</li></ul><pre>go get -u github.com/go-sql-driver/mysql</pre><h3>Full Sample Code</h3><pre>package main</pre><pre>import (<br>	&quot;bufio&quot;<br>	&quot;database/sql&quot;<br>	&quot;fmt&quot;<br>	&quot;log&quot;<br>	&quot;os&quot;<br>	&quot;strings&quot;<br>	&quot;time&quot;</pre><pre>	_ &quot;github.com/go-sql-driver/mysql&quot;<br>)</pre><pre>type User struct {<br>	Username string<br>	Password string<br>}</pre><pre>func printUserRows(rows *sql.Rows) {<br>	for rows.Next() {<br>		user := &amp;User{}<br>		if err := rows.Scan(&amp;user.Username, &amp;user.Password); err != nil {<br>			log.Printf(&quot;failed to scan row: %v&quot;, err)<br>		}<br>		log.Printf(&quot;%+v\\n&quot;, user)<br>	}<br>}</pre><pre>func main() {<br>	db, err := sql.Open(&quot;mysql&quot;, &quot;root@tcp(localhost:3306)/db1?multiStatements=true&quot;)<br>	if err != nil {<br>		log.Fatalf(&quot;failed to open SQL connection: %v&quot;, err)<br>	}<br>	defer db.Close()</pre><pre>	// there is already a row (&quot;tony&quot;, &quot;huang&quot;) in db1.Users<br> 	username := &quot;tony&quot;<br>	var password string</pre><pre>	// read user input password from stdin<br>	reader := bufio.NewReader(os.Stdin)<br>	fmt.Print(&quot;Enter password: &quot;)<br>	password, _ = reader.ReadString(&#39;\\n&#39;)<br>	password = strings.Trim(password, &quot;\\n&quot;)</pre><pre>	// get all db1.Users data<br>	// enter<br>	// &quot; OR &quot;&quot;=&quot;<br>	// to construct<br>	// SELECT * FROM Users WHERE username = &quot;tony&quot; AND password = &quot;&quot; OR &quot;&quot;=&quot;&quot;</pre><pre>	// delete all db1.Users data<br>	// enter<br>	// random&quot;; DELETE FROM Users; SELECT * FROM Users WHERE &quot;1&quot; = &quot;1<br>	// to construct<br>	// SELECT * FROM Users WHERE username = &quot;tony&quot; AND password = &quot;random&quot;; DELETE * FROM Users; SELECT * FROM Users WHERE &quot;1&quot; = &quot;1&quot;<br>	query := fmt.Sprintf(`SELECT * FROM Users WHERE username = &quot;%s&quot; AND password = &quot;%s&quot;`, username, password)<br>	rows, err := db.Query(query)<br>	if err != nil {<br>		log.Fatalf(&quot;failed to query a user from DB: %v&quot;, err)<br>	}<br>	printUserRows(rows)</pre><pre>	// use prepared statement to prevent SQL injection<br>	selectStmt, err := db.Prepare(&quot;SELECT * FROM Users WHERE username = ? AND password = ?&quot;)<br>	if err != nil {<br>		log.Fatalf(&quot;failed to prepare select stmt %v&quot;, err)<br>	}<br>	defer selectStmt.Close()<br>	rows, err = selectStmt.Query(username, password)<br>	if err != nil {<br>		log.Fatalf(&quot;failed to use prepared stmt to query a user from DB: %v&quot;, err)<br>	}<br>	printUserRows(rows)<br>}</pre><h3>References</h3><ol><li><a href="https://www.w3schools.com/sql/sql_injection.asp">SQL Injection (w3schools.com)</a></li><li><a href="https://en.wikipedia.org/wiki/SQL_injection">SQL injection — Wikipedia</a></li><li><a href="https://en.wikipedia.org/wiki/Prepared_statement">Prepared statement — Wikipedia</a></li><li><a href="https://dev.mysql.com/doc/refman/8.0/en/sql-prepared-statements.html">MySQL :: MySQL 8.0 Reference Manual :: 13.5 Prepared Statements</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf4ddfce7e80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LDAP and AD]]></title>
            <link>https://medium.com/@r04922101/ldap-and-ad-1fe59f16edc0?source=rss-f91d371b37c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fe59f16edc0</guid>
            <category><![CDATA[active-directory]]></category>
            <category><![CDATA[ldap]]></category>
            <dc:creator><![CDATA[Tony Huang]]></dc:creator>
            <pubDate>Wed, 21 Sep 2022 04:27:06 GMT</pubDate>
            <atom:updated>2022-09-21T04:27:06.027Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lightweight Directory Access Protocol (LDAP)</h3><p>LDAP is a <strong>protocol</strong> for accessing and maintaining distributed <em>directory services</em> over TCP/IP network.</p><p>The term “lightweight” is used in comparison with <em>X.500</em>, which is a spec for directory services.</p><p>A yellow book (a directory for accessing contact information) is usually an analogy to LDAP service. A yellow book converts a name to the corresponding phone number.</p><p>LDAP services usually also contain usernames and passwords, which allows other applications and services to connect to LDAP server to <strong>authenticate</strong> users.</p><p>Organizations utilize LDAP as a central informative service and allow employees to look up information more easily.</p><p>When we say LDAP, we usually refer to LDAP server or LDAP service, not the protocol itself.</p><h3>Directory Structure</h3><p>A directory contains:</p><ul><li>An entry consists of a set of attributes</li><li>An attribute has a name and one or more values</li><li>An entry has a unique identifier, <em>distinguished name (DN).</em> It is neither an attribute nor a part of the entry. It contains <em>relative distinguished name (RDN)</em>, constructed from other attributes in the entry, followed by the parent entry’s DN.</li></ul><pre>dn: cn=Tony Huang,dc=medium,dc=com<br>cn: Tony Huang<br>mail: r04922101@ntu.edu.tw</pre><p>In the example above, cn=Tony Huang is its RDN, and dc=medium,dc=com is parent entry’s DN.</p><p>A server holds a tree starting from a specific entry and its children. A server can also hold reference to another server. For example, access to cn=r04922101,dc=github,dc=com can return a reference to another server storing that part of directory tree.</p><h3>LDAP Authentication</h3><p>LDAP authentication follows client/server architecture.</p><ul><li>Clients are in a LDAP-enabled system, and sending requests to the LDAP server.</li><li>Server stores not only username/password information but also a collection of attributes such as email, phone number, etc.</li></ul><h3>How it Works in Brief</h3><ul><li>Client sends a request containing user’s credential to server</li><li>Server verifies user’s credential<br>i) If ok, server grants access and returns user’s information stored in the server to client<br>ii) If not, the client is denied</li></ul><h3>Directory Service</h3><p>Directory service is a service that <strong>maps the name of a network resource to its own network address</strong>. A network resource can be folders, users, groups, and etc. Information associated with resource can be stored as a collection of <em>attributes</em>.</p><p>With directory service, user does NOT need to remember the address of a resource but just its name. User can provide only its name and locate its address via directory service.</p><p>Some directory services have access control function.</p><p>A server providing directive service is call <em>directory server</em> or <em>name server</em>.</p><p>DNS, LDAP implementations are directory services.</p><h3>Active Directory (AD)</h3><p><em>Active Directory </em>is a <strong>directory service implementation developed by Microsoft for Windows</strong>. <em>Active Directory Domain Service</em> (<em>AD DS </em>or simply <em>AD</em>) is its core service.</p><p>Similar to LDAP, it provides an interface to manage resources such as users, devices, and so on. AD stores information about resources on the network and allows users to find and use more easily. For example, username/password (authentication), phone number, etc.</p><p>It provides authentication, directory, group and user management, and other services in a Windows environment.</p><p>AD uses LDAP, which means directory access in AD is performed by means of LDAP, and allows LDAP-based applications to work against AD environment.</p><h3>References</h3><ol><li><a href="https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol">Lightweight Directory Access Protocol — Wikipedia</a></li><li><a href="https://en.wikipedia.org/wiki/Directory_service">Directory service — Wikipedia</a></li><li><a href="https://en.wikipedia.org/wiki/Name_server">Name server — Wikipedia</a></li><li><a href="https://itman.pixnet.net/blog/post/26817279">介紹LDAP @ 挨踢人 :: 痞客邦 :: (pixnet.net)</a></li><li><a href="https://jumpcloud.com/blog/what-is-ldap-authentication">LDAP Authentication: What It Is, How It Works — JumpCloud</a></li><li><a href="https://www.youtube.com/watch?v=lp5z8HQGAH8">What is ldap authentication — YouTube</a></li><li><a href="https://connect2id.com/products/ldapauth/auth-explained">LDAP user authentication explained | Connect2id</a></li><li><a href="https://en.wikipedia.org/wiki/Active_Directory">Active Directory — Wikipedia</a></li><li><a href="https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/active-directory-domain-services">Active Directory Domain Services | Microsoft Learn</a></li><li><a href="https://www.okta.com/identity-101/ldap-vs-active-directory/">LDAP vs. Active Directory: What’s the Difference? | Okta</a></li><li>[LDAP vs. Active Directory: Difference Between LDAP and AD — N-able](<a href="https://www.n-able.com/blog/difference-between-ldap-ad#:~:text=AD%20is%20a%20directory%20service%20for%20Microsoft%20that%20makes%20important,and%20authenticate%20access%20to%20it.)">https://www.n-able.com/blog/difference-between-ldap-ad#:~:text=AD is a directory service for Microsoft that makes important,and authenticate access to it.)</a></li><li><a href="https://www.windows-active-directory.com/active-directory-ldap.html">An Introduction to Lightweight Directory Access Protocol (LDAP) (windows-active-directory.com)</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fe59f16edc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Access Control: RBAC, ABAC, ACL]]></title>
            <link>https://medium.com/@r04922101/access-control-rbac-abac-acl-8ed56c94ce1a?source=rss-f91d371b37c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ed56c94ce1a</guid>
            <category><![CDATA[access-control]]></category>
            <category><![CDATA[abac]]></category>
            <category><![CDATA[rbac]]></category>
            <category><![CDATA[acl]]></category>
            <dc:creator><![CDATA[Tony Huang]]></dc:creator>
            <pubDate>Wed, 17 Aug 2022 08:34:00 GMT</pubDate>
            <atom:updated>2022-08-17T08:34:00.849Z</atom:updated>
            <content:encoded><![CDATA[<h3>Access Control: RBAC, ABAC, ACL</h3><h3>Role-Based Access Control (RBAC)</h3><ul><li>RBAC is an approach that restricts system access to authorized users <strong>based on the roles of individual users </strong>within an organization.</li><li>RBAC defines roles with specific set of permissions and to which subjects are assigned, and the role determines which permission the system grants to the user.</li><li>RBAC manages who has access to the resources and what they can do with the resources.</li><li>With RBAC, organizations can decrease their efforts on managing access control because when they hire a new employee, the organization can just assign a role to that employee or switch role the roles of existing employees. Organizations can easily and quickly add and change roles.</li></ul><h3>Example</h3><p>Permission control against a phonebook</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*DcbyDipHURwhKmX538ZHEQ.png" /><figcaption>RBAC Example</figcaption></figure><p>Roles:</p><ul><li>Editor can read and write the phonebook</li><li>Reader can only read the phonebook</li><li>Owner can read, write, delete the phonebook</li></ul><h3>Attribute-Based Access Control (ABAC)</h3><ul><li>ABAC is an approach which evaluates <strong>attributes</strong> associated with the subject, operations, environment attributes.</li><li>ABAC controls access based on attributes. It evaluates a boolean value according to attributes, and tells whether grant or deny the access.</li></ul><h3>Example</h3><p>Only the employees whose ID is less than 100 and is in the library can read the phonebook.</p><h3>Access Control List (ACL)</h3><ul><li>ACL is a <strong>table listing users’ permission assigned to each resources, called rules</strong>. It blocks unauthorized users and allows authorized users to access the resources.</li><li>ACL tells that who can access which subject, and what actions they can perform against it.</li></ul><h3>RBAC vs. ABAC</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*CUVbyhmsbrZ1eHtZQkK2Gw.png" /><figcaption>RBAC vs. ABAC</figcaption></figure><h3>RBAC vs. ACL</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*Ra2K368AHbO9WohpwMqwiQ.png" /><figcaption>RBAC vs. ACL</figcaption></figure><h3>References</h3><ol><li><a href="https://www.imperva.com/learn/data-security/role-based-access-control-rbac/">What is Role-Based Access Control | RBAC vs ACL &amp; ABAC | Imperva</a></li><li><a href="https://en.wikipedia.org/wiki/Role-based_access_control">Role-based access control — Wikipedia</a></li><li>[What is Role-Based Access Control (RBAC)? Definition from SearchSecurity (<a href="http://techtarget.com/">techtarget.com</a>)](<a href="https://www.techtarget.com/searchsecurity/definition/role-based-access-control-RBAC#:~:text=Role%2Dbased%20access%20control%20(RBAC)%20is%20a%20method%20of,doesn&#39;t%20pertain%20to%20them.)">https://www.techtarget.com/searchsecurity/definition/role-based-access-control-RBAC#:~:text=Role-based access control (RBAC) is a method of,doesn’t pertain to them.)</a></li><li><a href="https://www.imperva.com/learn/data-security/access-control-list-acl/">What is Access Control List | ACL Types &amp; Linux vs Windows | Imperva</a></li><li><a href="https://en.wikipedia.org/wiki/Access-control_list">Access-control list — Wikipedia</a></li><li><a href="https://en.wikipedia.org/wiki/Attribute-based_access_control">Attribute-based access control — Wikipedia</a></li><li><a href="https://www.techtarget.com/searchnetworking/definition/access-control-list-ACL">What is Access Control List (ACL)? — SearchSoftwareQuality (techtarget.com)</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ed56c94ce1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SAML Introduction and Comparion]]></title>
            <link>https://medium.com/@r04922101/saml-introduction-and-comparion-9775f8646995?source=rss-f91d371b37c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9775f8646995</guid>
            <category><![CDATA[protocol]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[aml]]></category>
            <dc:creator><![CDATA[Tony Huang]]></dc:creator>
            <pubDate>Tue, 16 Aug 2022 03:17:01 GMT</pubDate>
            <atom:updated>2022-08-16T03:17:01.424Z</atom:updated>
            <content:encoded><![CDATA[<h3>SAML Introduction</h3><p><strong><em>Security Assertion Markup Language</em></strong> is an <strong>XML-based</strong> authentication protocol between <strong><em>service provider (SP)</em></strong> and <strong><em>identity provider (IdP)</em></strong>.</p><p><strong><em>Single-signed-on (SSO)</em></strong> can be implemented with SAML.</p><p>SAML specifies the <strong>content</strong> of the assertion passed from IdP to SP, i.e., SAML specifies <strong>what</strong> but not how.</p><p>With SAML, service provider can contact identity provider to authenticate user who are trying to access secure content, while user can access multiple web application <strong>with only one set of login credential</strong>.</p><p>The most current version of SAML is SAML 2.0.</p><h3>Why SAML</h3><ul><li>Prior to SAML, SSO can be implemented by cookie, however, it was only viable within the <strong>same domain</strong>.</li><li>User can access multiple web application with only one set of login credential → improve user experience.</li><li>Service provider does <strong>NOT</strong> need to know user credential, while identity provider can spend more time on providing secure SAML authentication → increase security.</li></ul><h3>Roles</h3><ul><li>Service provider (SP)<br>Service that user wants to use. It requests and obtains authentication assertion from identity provider</li><li>Identity provider (IdP)<br>Store and confirm user identity. It authenticates user by requesting some information such as username and password from user, and issues assertion to service provider</li><li>Principal/Subject<br>User</li></ul><h3>Flow</h3><p>Take SSO use case as an example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*lVQ37yxSDhi-IZnGADqqLw.png" /><figcaption>SAML flow</figcaption></figure><ol><li>User visits and requests resource from service provider</li><li>Service provider redirects user to identity provider SSO service</li><li>User visits identity provider SSO service with SAML request</li><li>Identity provider parses SAML request</li><li>Identity provider authenticates user (maybe ask login credential such as username and password)</li><li>Identity provider responds user with SAML assertion</li><li>User sends request to service provider again but with SAML assertion this time</li><li>Service provider verifies SAML assertion</li><li>Service provider creates a <strong><em>security context</em></strong> and redirects user to the target resource</li><li>User requests the target resource again</li><li>Since a security context exists, service provider returns the resource to the user agent</li></ol><h3>SAML Assertion</h3><p>Assertion is a message telling service provider that the user is signed in.</p><p>It contains information such as how and when the subject was authenticated, the attributes associated with the subject.</p><h3>SAML vs. OAuth</h3><p>SAML is primarily for <strong>authentication</strong>, while OAuth is for <strong>authorization</strong>.</p><h3>SAML vs. OIDC</h3><p>The end goal of both is the same: user <strong>authentication</strong>.</p><p>The log in flow is basically the same.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb7fc2240274ec9851a3d21d4e02c8da/href">https://medium.com/media/bb7fc2240274ec9851a3d21d4e02c8da/href</a></iframe><h3>How to Choose Between SAML and OIDC</h3><ul><li>Based on what the application developers choose to support.</li><li>Easier to integrate and more quickly to set up so that it is much better with mobile application, single page web → OIDC</li><li>More mature, well developed → SAML</li></ul><h3>References</h3><ol><li><a href="https://en.wikipedia.org/wiki/Security_Assertion_Markup_Language">Security Assertion Markup Language — Wikipedia</a></li><li><a href="https://en.wikipedia.org/wiki/SAML_2.0">SAML 2.0 — Wikipedia</a></li><li>[SAML-based SSO: technical overview — Cloud Identity Help (<a href="http://google.com/">google.com</a>)](<a href="https://support.google.com/cloudidentity/answer/6262987?hl=en#:~:text=Security%20Assertion%20Markup%20Language%20(SAML,trying%20to%20access%20secure%20content.)">https://support.google.com/cloudidentity/answer/6262987?hl=en#:~:text=Security Assertion Markup Language (SAML,trying to access secure content.)</a></li><li><a href="https://www.onelogin.com/learn/saml">SAML Explained in Plain English | OneLogin</a></li><li><a href="https://www.cloudflare.com/zh-tw/learning/access-management/what-is-saml/">What is SAML? | How SAML authentication works | Cloudflare</a></li><li><a href="https://www.onelogin.com/blog/real-difference-saml-oidc">SAML vs OIDC: What’s the Real Difference? | OneLogin Blog</a></li><li><a href="https://www.onelogin.com/learn/oidc-vs-saml">SAML vs OIDC: All You Need to Know | OneLogin</a></li><li><a href="https://www.loginradius.com/blog/identity/saml-or-oidc-for-business/">SAML or OIDC: Which one is Better For Your Business? | LoginRadius Blog</a></li><li><a href="https://auth0.com/intro-to-iam/saml-vs-openid-connect-oidc/">What is OpenID vs SAML? Find out the differences — Auth0</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9775f8646995" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenID Connect (OIDC) Introduction]]></title>
            <link>https://medium.com/@r04922101/openid-connect-oidc-introduction-2d8092ccafa0?source=rss-f91d371b37c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d8092ccafa0</guid>
            <category><![CDATA[oidc]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[protocol]]></category>
            <dc:creator><![CDATA[Tony Huang]]></dc:creator>
            <pubDate>Fri, 12 Aug 2022 08:12:20 GMT</pubDate>
            <atom:updated>2022-08-12T10:19:33.515Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intoduction</h3><p>OpenID connect is on top of OAuth 2.0.</p><p><a href="https://medium.com/@r04922101/oauth-2-0-introduction-and-example-2799be2c8e11">OAuth 2.0 Introduction and Example</a></p><p><strong>(Identity, Authentication) + OAuth 2.0</strong> = OpenID Connect</p><p>OpenID is a standard <strong>authentication</strong> protocol. It allows user to be authenticated by <strong>relying party</strong> using <strong>identity provider</strong> service. With OpenID, user can log in to multiple websites <strong>without having separate identity and password for each</strong>. It can also transfer some <strong>identity attributes</strong> such as name and gender from identify provider to relying party.</p><h3>Why OpenID Connect</h3><p>It eliminates the need for login systems that manage user accounts (username/password). It enables user to log in unrelated websites without having and managing password files.</p><h3>Roles</h3><ul><li>Resource Owner</li><li>Client/Application</li><li>Relying party (RP) A website or an application that wants to verify user’s identity. It outsources user authentication to IDP.</li><li>Identity provider (IDP) Offer user authentication as a service.</li></ul><h3>Flow</h3><p>It’s similar to OAuth 2.0. Take response type = code, scope = openid profile for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*6-VmjrTDFAIq5UgEA0JycA.png" /></figure><ol><li>Resource owner (user) visits the application.</li><li>Application sends a authorization request to authorization server with client ID, redirect URL, scope, response type</li><li>Authorization server asks resource owner to grant access.</li><li>If granted, redirect to redirect URL with code.</li><li>Application asks authorization server to issue an access token by sending code, client ID, client secret.</li><li>Authorization server issues an access token and ID token to application.</li><li>Application frontend can now use the ID token to retrieve user profile. Also frontend cna communicate with protected application backend with ID token , while application backend can verify the ID token and provider its service.</li></ol><h3>ID Token</h3><p>ID token is a <a href="https://jwt.io/introduction">JWT</a>.</p><h3>References</h3><ol><li><a href="https://en.wikipedia.org/wiki/OpenID">OpenID — Wikipedia</a></li><li><a href="https://openid.net/connect/">OpenID Connect | OpenID</a></li><li><a href="https://openid.net/connect/faq/">OpenID Connect FAQ and Q&amp;As | OpenID</a></li><li><a href="https://codeburst.io/openid-connect-client-by-example-76caf6dae55e">OpenID Connect Client by Example. A walk-through of a concrete… | by John Tucker | codeburst</a></li><li>[OAuth and OpenID explained with real life examples | by Albert Starreveld | VX Company | Medium](<a href="https://medium.com/vx-company/oauth-and-openid-explained-with-real-life-examples-bf40daa8049f#:~:text=Logging%20into%20Spotify%20with%20your,those%20details%20to%20identify%20you.)">https://medium.com/vx-company/oauth-and-openid-explained-with-real-life-examples-bf40daa8049f#:~:text=Logging into Spotify with your,those details to identify you.)</a></li><li><a href="https://jwt.io/introduction">JSON Web Token Introduction — jwt.io</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d8092ccafa0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>