<?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 Jerome Ran on Medium]]></title>
        <description><![CDATA[Stories by Jerome Ran on Medium]]></description>
        <link>https://medium.com/@jerome-ran?source=rss-5c63ad963b31------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ijfj7N_3uWvN6laMXfOpEQ.jpeg</url>
            <title>Stories by Jerome Ran on Medium</title>
            <link>https://medium.com/@jerome-ran?source=rss-5c63ad963b31------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:06:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jerome-ran/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[How to Resolve IntelliJ IDEA Command Line Launch Issues on Apple Silicon]]></title>
            <link>https://jerome-ran.medium.com/how-to-resolve-intellij-idea-command-line-launch-issues-on-apple-silicon-8af20779bcdf?source=rss-5c63ad963b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/8af20779bcdf</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[apple-silicon]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[intellij-idea]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Jerome Ran]]></dc:creator>
            <pubDate>Wed, 26 Apr 2023 20:02:34 GMT</pubDate>
            <atom:updated>2023-04-27T09:48:12.966Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Cannot load JVM bundle error when start IntelliJ on Apple Silicon" src="https://cdn-images-1.medium.com/max/1024/1*vhgIcDloPZI3ivdiHe3pjA.png" /></figure><p>IntelliJ IDEA is a popular integrated development environment (IDE) among developers. One way to launch IntelliJ IDEA on Mac is through the command line using the idea command. However, I encountered launch errors using this method on Apple Silicon.</p><h4>What’s the symptom?</h4><p>There is an executable file named idea under Applications/IntelliJ IDEA CE.app/Contents/MacOS.</p><pre>export IDEA_PATH=Applications/IntelliJ\ IDEA\ CE.app/Contents/MacOS<br>export PATH=$IDEA_PATH:$PATH</pre><p>Add these codes to your ~/.zshr or ~/.bash_profile configuration file. Then you can use the idea command to start the IDEA.</p><p>Or you can follow the link below to set command line tool for IntelliJ IDEA.</p><p><a href="https://medium.com/@shaunthomas999/how-to-launch-intellij-idea-from-command-line-ba10443cc1a9">How to launch Intellij IDEA from command line</a></p><p>However, I encountered the following error when I ran the idea command:</p><pre>2023-04-26 22:29:07.720 idea[2555:30418] allVms required 1.8*,1.8+<br>2023-04-26 22:29:07.723 idea[2555:30473] Cannot load JVM bundle: Error Domain=NSCocoaErrorDomain Code=3585 &quot;dlopen_preflight(/Applications/IntelliJ IDEA CE.app/Contents/jbr/Contents/MacOS/libjli.dylib) =&gt; false, &#39;tried: &#39;/Applications/IntelliJ IDEA CE.app/Contents/jbr/Contents/MacOS/libjli.dylib&#39; (mach-o file, but is an incompatible architecture (have (arm64), need (x86_64))), &#39;/usr/lib/libjli.dylib&#39; (no such file)&#39;&quot; UserInfo={NSLocalizedFailureReason=The bundle doesn’t contain a version for the current architecture., NSLocalizedRecoverySuggestion=Try installing a universal version of the bundle., NSFilePath=/Applications/IntelliJ IDEA CE.app/Contents/jbr/Contents/MacOS/libjli.dylib, NSDebugDescription=dlopen_preflight(/Applications/IntelliJ IDEA CE.app/Contents/jbr/Contents/MacOS/libjli.dylib) =&gt; false, &#39;tried: &#39;/Applications/IntelliJ IDEA CE.app/Contents/jbr/Contents/MacOS/libjli.dylib&#39; (mach-o file, but is an incompatible architecture (have (arm64), need (x86_64))), &#39;/usr/lib/libjli.dylib&#39; (no such file)&#39;, NSBundlePath=/Applications/IntelliJ IDEA CE.app/Contents/jbr, NSLocalizedDescription=The bundle “JBR-17.0.6+1-653.34-jcef 17.0.6” couldn’t be loaded because it doesn’t contain a version for the current architecture.}</pre><p>The error message suggests that the version of IntelliJ IDEA I’m trying to run is looking for a version of the Java Virtual Machine (JVM) that is compatible with the x86_64 architecture but cannot find it. Since my system is running on the Apple M1 chip, which uses the ARM64 architecture, the version of the JVM bundled with IntelliJ IDEA may not be compatible with your system’s architecture, causing the error.</p><p>At the first time, I thought it was a version problem, but I tried 2023.1 — macOS Apple Silicon (dmg) and 2022.3.3 — macOS Apple Silicon (dmg), and the problem persists.</p><h4>Solution</h4><p>Please run uname -m command to check the system architecture. On my computer, it returns the following result:</p><pre>x86_64</pre><p>Now the truth is out. My architecture is x86_64, but the IDEA version I downloaded is Apple Silicon, which needs aarc64 architecture. Even though my system is Apple Silicon, my macOS version supports running x86_64 applications through Apple’s Rosetta 2 translation technology.</p><p>So, redownload the x86_64 version IntelliJ IDEA will solve the problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8af20779bcdf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A brief-intro of Kotlin Multiplatform Mobile for iOS/Android Developers]]></title>
            <link>https://jerome-ran.medium.com/a-brief-intro-of-kotlin-multiplatform-mobile-for-ios-android-developers-9d53372dc718?source=rss-5c63ad963b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d53372dc718</guid>
            <category><![CDATA[kotlin-native]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kmm]]></category>
            <dc:creator><![CDATA[Jerome Ran]]></dc:creator>
            <pubDate>Sat, 30 Jan 2021 13:29:32 GMT</pubDate>
            <atom:updated>2021-01-30T13:29:32.454Z</atom:updated>
            <content:encoded><![CDATA[<p>When we talked about Kotlin, we naturally thought of Java and Android. However, this is the tip of the iceberg of Kotlin’s ability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6UkrKQyfPEPy_6ijzaJxWA.jpeg" /></figure><h3>Throw Cognitive Bias</h3><p>Android developers are familiar with Kotlin; it has capable of seamlessly interoperating with Java. The great work is finished by Kotlin Compiler, which compiles the Kotlin code to the same bytecode with Java. But don’t form the cognitive bias that the Kotlin must work with a JVM runtime.</p><p>Kotlin compiler is not just capable of converting Kotlin code to Java bytecode; it has made rapid inroads into multiple platforms, such as iOS, we frameworks, JS, etc. Cross multiple platforms for mobile devices is not a new concept. There are many technologies produced for that, e.g., Ionic, React Native, Flutter. Code once, run anywhere is their philosophy. But in Kotlin, <strong>code common and respect the platform</strong> is the philosophy.</p><p>We need to know about Kotlin Native to figure out how the Kotlin respects platforms. Kotlin Native is a technology for compiling Kotlin code to native binaries, which can run without a virtual machine. It is an LLVM based backend for the Kotlin compiler and native implementation of the Kotlin standard library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t54bYMVTjw3C7mvMHYcCgw.png" /></figure><p>As you can see, there are multiple back-ends(LLVM based) to convert the Kotlin IR to platform-specific code. Kotlin IR, or Kotlin Intermediate Representation, is the new internal representation used by the Kotlin compiler when it parses Kotlin source files.</p><h3>Interoperating with Swift</h3><p>Kotlin can interop with Swift based on Kotlin/Native plugin, so that we can develop common modules for iOS and Android. Use Android Studio to create a KMM application, then AS will configure a multiple mobile project structure for you, like following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*cJRu16EzYNUYhWIsrqFcjg.png" /></figure><p>The shared module is a common module that contains codes can run both in iOS and Android. We can write shared codes under commonMain directory. So how about the platform specific code? How does Kotlin respect the platform? Let’s see the boilerplate code before answering this question.</p><p><em>Code in commonMain:</em></p><pre>// Greeting.kt<br>class Greeting {<br>    fun greeting(): String {<br>        return &quot;Hello, ${Platform().platform}!&quot;<br>    }<br>}</pre><pre>// Platform.kt<br>expect class Platform() {<br>    val platform: String<br>}</pre><p><em>Code in iosMain:</em></p><pre>// Platform.kt<br>import platform.UIKit.UIDevice<br><br>actual class Platform actual constructor() {<br>    actual val platform: String = UIDevice.currentDevice.systemName() + &quot; &quot; + UIDevice.currentDevice.systemVersion<br>}</pre><p>Please notice the keyworks expect and actual , this is Kotlin mechanism of <strong>expected and actual declarations for </strong>platform-specific APIs. Maybe the following graph can have a more intuitive explaination.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yElJsBihA_EMePaTsdSi7Q.png" /></figure><p>As you can see, you can import UIKit and other iOS(macOS) libraries from Kotlin Native. After finishing the code, the Kotlin/Native plugin can build the shared module to a framework for iOS, and what we need is a gradle task:</p><pre>val packForXcode by <em>tasks</em>.<em>creating</em>(Sync::class) <strong>{<br>    </strong><em>group </em>= &quot;build&quot;<br>    val mode = System.getenv(&quot;CONFIGURATION&quot;) ?: &quot;DEBUG&quot;<br>    val sdkName = System.getenv(&quot;SDK_NAME&quot;) ?: &quot;iphonesimulator&quot;<br>    val targetName = &quot;ios&quot; + if (sdkName.<em>startsWith</em>(&quot;iphoneos&quot;)) &quot;Arm64&quot; else &quot;X64&quot;<br>    val framework = <em>kotlin</em>.targets.<em>getByName</em>&lt;KotlinNativeTarget&gt;(targetName).binaries.getFramework(mode)<br>    <em>inputs</em>.property(&quot;mode&quot;, mode)<br>    dependsOn(framework.linkTask)<br>    val targetDir = File(<em>buildDir</em>, &quot;xcode-frameworks&quot;)<br>    from(<strong>{ </strong>framework.outputDirectory <strong>}</strong>)<br>    into(targetDir)<br><strong>}<br><br></strong><em>tasks</em>.getByName(&quot;build&quot;).dependsOn(packForXcode)</pre><p>Run the task will create a shared.framwork for iOS target. And we can have a look at a partion of the framework header:</p><pre>__attribute__((objc_subclassing_restricted))<br>__attribute__((swift_name(&quot;Greeting&quot;)))<br>@interface SharedGreeting : SharedBase<br>- (instancetype)init __attribute__((swift_name(&quot;init()&quot;))) __attribute__((objc_designated_initializer));<br>+ (instancetype)new __attribute__((availability(swift, unavailable, message=&quot;use object initializers instead&quot;)));<br>- (NSString *)greeting __attribute__((swift_name(&quot;greeting()&quot;)));<br>@end;</pre><p>Then we can import and use this framework in the Xcode:</p><pre>import UIKit<br>import shared<br><br>class ViewController: UIViewController {<br><br>    @IBOutlet weak var label: UILabel!<br>    @IBAction func clicked(_ sender: Any) {<br>        let greeting  = Greeting()<br>        label.text = greeting.greeting()<br>    }<br>}</pre><h3><strong>KMM Development</strong></h3><p>A good multiple platform solution should have sophisticated tools or libraries to make the development efficient. The most basement abilities in mobile development are network accessing and database. Accordingly, I will introduce <strong>Ktor</strong> and <strong>SQLDelight</strong>, which are network and database libraries we can use in KMM.</p><h4>SQLDelight</h4><p><a href="https://cashapp.github.io/sqldelight/">SQLDelight</a> generates typesafe kotlin APIs from your SQL statements. It verifies your schema, statements, and migrations at compile-time and provides IDE features like autocomplete and refactoring which make writing and maintaining SQL simple. It’s no need to explain it on Android side. Let’s talk about how it works on iOS. It doesn&#39;t like Core Data, which doesn’t need SQL. It based on <a href="https://www.sqlite.org/index.html">SQLite</a>, a cross-platform C-language library that implements a small, fast, self-contained, high-reliability, full-featured, SQL database engine. You can think that SQLDelight can understand you SQL and generate typesafe APIs so that we can use it easily, and then SQLDelight native part can react our actions on SQLite. Volia! There is a graph to help us understaning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*W-_GAikoH8hauF4NxIMidw.png" /></figure><h4>Ktor</h4><p>A framework for building asynchronous clients and servers. Here we just focus on the client side. Ktor HTTP Client has a common interface but allows to specify an engine that processes the network request.</p><p>In Android, we can choose OkHttp or HttpClient. In iOS, the client use NSURLSession in current.</p><p>The KMM is still in rapid development. And the ecosystem is continuing to improve(we can find more KMM libraries at <a href="https://libs.kmp.icerock.dev/">here</a>). I really agree with the philosophy: <strong>code common and respect the platform</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d53372dc718" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My raw notes on Consul — Beginner’s guide]]></title>
            <link>https://jerome-ran.medium.com/my-raw-notes-on-consul-beginners-guide-11ada1558dc1?source=rss-5c63ad963b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/11ada1558dc1</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[consul]]></category>
            <category><![CDATA[notes]]></category>
            <dc:creator><![CDATA[Jerome Ran]]></dc:creator>
            <pubDate>Thu, 31 Dec 2020 04:09:42 GMT</pubDate>
            <atom:updated>2020-12-31T04:09:42.301Z</atom:updated>
            <content:encoded><![CDATA[<h3>My raw notes on Consul — Beginner’s guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lVo1GiMsCIW6txuQcLpsjQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@dtravisphd?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">David Travis</a> on <a href="https://unsplash.com/s/photos/notes?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Consul is a full-featured service mesh solution that solves the networking and security challenges of operating microservices and cloud infrastructure. It is a distributed system designed to run on a cluster of nodes, which can be a physical server, cloud instance, virtual machine, or container.</p><p>This article records my raw notes in learning Consul as a beginner. I’ll record some common conceptions and experiment on Consul in development mode to try its functionality.</p><h3>Conceptions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8cCMALTTEbOKwCR9h8D90Q.png" /><figcaption>Quote From <a href="https://learn.hashicorp.com/tutorials/consul/get-started?in=consul/getting-started">Here</a></figcaption></figure><p>The set of nodes Consul runs on is called a <strong>datacenter</strong>. Consul has two agent modes in the datacenter, client agent and server agent.</p><p><strong>A client</strong> is a lightweight process that registers services, runs health checks, and forwards queries to servers. So, a client agent must be running on every node in the Consul datacenter.</p><p><strong>A server</strong> is responsible for maintaining Consul’s state, including information about other Consul servers and clients, what services are available for discovery, and which services are allowed to access other services.</p><p>Each datacenter must have at least one server. However, to ensure that Consul’s state is preserved even if a server fails, we should always run three or five servers in production(no more than five of them). The odd number of servers strikes a balance between performance and tolerance.</p><h3>Installation</h3><p>You can install Consul manually on any operating system. The easiest way on macOS is homebrew .</p><pre>brew tap hashicorp/tap<br>brew install hashicorp/tap/consul</pre><p>The first command installs the <a href="https://learn.hashicorp.com/tutorials">HashiCorp</a> tap, a repository of all HashiCorp’s Homebrew packages. The second command installs Consul with hashicorp/tap/consul , which is a signed binary and is automatically updated with every new official release.</p><pre>brew upgrade hashicorp/tap/consul</pre><p>This command updates the Consul.</p><h3>Experiment Consul</h3><p>Now run Consul in development mode(with an in-memory server mode), which isn’t secure or scalable. Start the Consul agent to try most of the Consul’s functionality without extra configuration.</p><h4><strong>Start the Consul Agent in Development Mode</strong></h4><pre>consul agent -dev -node jerome</pre><p>Use -node to specify the node name to avoid DNS failure on OS X because Consul uses the local machine&#39;s hostname as the default node name. DNS queries to the node will not work with Consul if the hostname contains periods.</p><pre>==&gt; Starting Consul agent...<br>           Version: &#39;1.9.1&#39;<br>           Node ID: &#39;a4b4cee7-7e04-b4af-96e4-0a0032f98fff&#39;<br>         Node name: &#39;jerome&#39;<br>        Datacenter: &#39;dc1&#39; (Segment: &#39;&lt;all&gt;&#39;)<br>            Server: true (Bootstrap: false)<br>       Client Addr: [127.0.0.1] (HTTP: 8500, HTTPS: -1, gRPC: 8502, DNS: 8600)<br>      Cluster Addr: 127.0.0.1 (LAN: 8301, WAN: 8302)<br>           Encrypt: Gossip: false, TLS-Outgoing: false, TLS-Incoming: false, Auto-Encrypt-TLS: false</pre><p>The partial logs above report that the Consul agent has started as a server. Now we can access 127.0.0.1:8500 through the browser to see the Consul UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EZ86pfdzrm15YQfcrP6xtQ.png" /></figure><pre>➜  ~ consul members<br>Node    Address         Status  Type    Build  Protocol  DC   Segment<br>jerome  127.0.0.1:8301  alive   server  1.9.1  2         dc1  &lt;all&gt;</pre><p>List the agents in the datacenter. And now there is only one member, our machine.</p><pre>➜  ~ consul leave<br>Graceful leave complete</pre><p>The command consul leave can stop the Consul gracefully.</p><h4><strong>Register a Service</strong></h4><p>The most common way of registering services is to provide a service definition(Another way is HTTP API). Consul loads all configuration files in the configuration directory, which is named consul.d .</p><p>Now run the command mkdir ~/consul.d and write the following content to the file ~/consul.d/web.json .</p><pre>{<br>  &quot;service&quot;: {<br>    &quot;name&quot;: &quot;web&quot;,<br>    &quot;tags&quot;: [<br>      &quot;rails&quot;<br>    ],<br>    &quot;port&quot;: 80<br>  }<br>}</pre><p>Use <em>web.json</em> file to pretend there is a service named <em>web </em>running on port 80. An optional tag is used to find the service later on.</p><pre>cd ~; consul agent -dev -node jerome -enable-script-checks -config-dir=./consul.d</pre><p>Consul cannot read ~ symbol, so we need to go to the home directory at first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hqz2u1xbxXM7sV_szmkNVQ.png" /></figure><p>Now open localhost:8500 we will see the service we defined. In actuality, we never started a web service, but Consul can register services that aren’t running yet.</p><h4><strong>Query a Service</strong></h4><p>We can query services using either the DNS interface or HTTP API.</p><p>First, query the service using the DNS interface. The DNS name of a service registered to the Consul is <strong><em>Name</em></strong><em>.service.consul</em>, where <em>Name</em> is the registered service’s name. So, the DNS name of the service we want to query here is <em>web.service.consul</em>. Consul DNS interface runs by default on port 8600 .</p><pre>➜  ~ dig <a href="http://twitter.com/127">@127</a>.0.0.1 -p 8600 web.service.consul SRV</pre><pre>; &lt;&lt;&gt;&gt; DiG 9.10.6 &lt;&lt;&gt;&gt; <a href="http://twitter.com/127">@127</a>.0.0.1 -p 8600 web.service.consul SRV<br>; (1 server found)<br>;; global options: +cmd<br>;; Got answer:<br>;; -&gt;&gt;HEADER&lt;&lt;- opcode: QUERY, status: NOERROR, id: 59121<br>;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 3<br>;; WARNING: recursion requested but not available</pre><pre>;; OPT PSEUDOSECTION:<br>; EDNS: version: 0, flags:; udp: 4096<br>;; QUESTION SECTION:<br>;web.service.consul.  IN SRV</pre><pre>;; ANSWER SECTION:<br>web.service.consul. 0 IN SRV 1 1 80 jerome.node.dc1.consul.</pre><pre>;; ADDITIONAL SECTION:<br>jerome.node.dc1.consul. 0 IN A 127.0.0.1<br>jerome.node.dc1.consul. 0 IN TXT &quot;consul-network-segment=&quot;</pre><pre>;; Query time: 1 msec<br>;; SERVER: 127.0.0.1#8600(127.0.0.1)<br>;; WHEN: Wed Dec 30 14:14:56 CST 2020<br>;; MSG SIZE  rcvd: 141</pre><p>The SRV record says the web service is running on port 80 and exists on the node jerome.node.dc1.consul .</p><p>Second, query the service using HTTP API.</p><pre>➜  ~ curl <a href="http://localhost:8500/v1/catalog/service/web">http://localhost:8500/v1/catalog/service/web</a></pre><p>We’ll see the services information in JSON style.</p><h4><strong>Update a Service</strong></h4><p>Now we add a health check for the web service. Edit ~/consul.d/web.json like the following.</p><pre>{<br>  &quot;service&quot;: {<br>    &quot;name&quot;: &quot;web&quot;,<br>    &quot;tags&quot;: [<br>      &quot;rails&quot;<br>    ],<br>    &quot;port&quot;: 80,<br>    &quot;check&quot;: {<br>      &quot;args&quot;: [<br>        &quot;curl&quot;,<br>        &quot;localhost&quot;<br>      ],<br>      &quot;interval&quot;: &quot;10s&quot;<br>    }<br>  }<br>}</pre><p>Run consul reload to make Consul aware of the new health check. Then Consul will mark web service as unhealthy because the health check is always failing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LS6McRC84ZXPTLjlLOe0cg.png" /></figure><h4>Connect Services</h4><p>Next, we will use sidecar proxies to connect services within Consul Service Mesh.</p><p>First, we start a Consul-unaware service, which is a basic echo service.</p><pre>brew install socat<br>socat -v tcp-l:8181,fork exec:&quot;/bin/cat&quot;</pre><p>We can use nc 127.0.0.1 8181 to verify that the service has started. Now add a file called socat.json to the ~/consul.d directory with the following content.</p><pre>{<br>  &quot;service&quot;: {<br>    &quot;name&quot;: &quot;socat&quot;,<br>    &quot;port&quot;: 8181,<br>    &quot;connect&quot;: {<br>      &quot;sidecar_service&quot;: {}<br>    }<br>  }<br>}</pre><p>Run consul reload to let Consul read the new configuration file.</p><p>There is a special field named connect . This configuration notifies Consul to register a sidecar proxy for the process on a dynamically allocated port. Consul will not automatically start the sidecar proxy.</p><pre>consul connect proxy -sidecar-for socat</pre><p>The command above will start the sidecar proxy for socat process.</p><p>Second, we connect the service web and socat . Update the web service definition like the following.</p><pre>{<br>  &quot;service&quot;: {<br>    &quot;name&quot;: &quot;web&quot;,<br>    &quot;connect&quot;: {<br>      &quot;sidecar_service&quot;: {<br>        &quot;proxy&quot;: {<br>          &quot;upstreams&quot;: [<br>            {<br>              &quot;destination_name&quot;: &quot;socat&quot;,<br>              &quot;local_bind_port&quot;: 9191<br>            }<br>          ]<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>Add a sidecar proxy configuration with destination service(socat) and port. Consul will register a sidecar proxy for the service web to establish mTLS connections to socat .</p><pre>consul connect proxy -sidecar-for web</pre><p>The command above will start the sidecar proxy for the web.</p><pre>nc 127.0.0.1 9191</pre><p>The command above will let us connect to socat service again on 9191 port.</p><p>The communication between web and socat proxies are encrypted and authorized over a mutual TLS connection, while communication between each service and its sidecar proxy is unencrypted.</p><h4>Intentions</h4><p>Intentions define which services are allowed to communicate with which other services. All communications between services are allowed on development mode by default.</p><pre>consul intention create -deny web socat</pre><p>The command above will create an intention to deny access from the web to socat.</p><pre>nc 127.0.0.1 9191</pre><p>The command above will fail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xYhFdSoRClAhu88nUw5Dog.png" /></figure><pre>consul intention delete web socat</pre><p>The command above will delete the deny intention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bb9mgI6peYbtFThoJ1xOHw.png" /></figure><p>Now, we finished the first step, and I’ll continue to learn how to use Consul in production mode and how it works with other infrastructure tools, such as Kubernetes, Istio, and Envoy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11ada1558dc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang Remote Debugging with Visual Studio Code]]></title>
            <link>https://jerome-ran.medium.com/golang-remote-debugging-with-visual-studio-code-a918de5d83f3?source=rss-5c63ad963b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/a918de5d83f3</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Jerome Ran]]></dc:creator>
            <pubDate>Sat, 26 Dec 2020 08:34:34 GMT</pubDate>
            <atom:updated>2020-12-26T08:34:34.982Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9UPixLKIZ15tJQjENHOCng.jpeg" /></figure><p>When the project grows bigger and more complex, it’s really inconvenient and expendable to prepare all configurations in a local machine. It will be more natural and efficient to debug the application in the remote dev environment directly.</p><p>This tutorial will show you how to build a remote debug environment with Visual Studio Code and solve some problems I suffered.</p><h3>Prerequisites</h3><ul><li>Golang</li><li>Visual Studio Code</li><li>Delve</li><li>ssh</li><li>The remote host (Your dev environment)</li></ul><h3>Install Delve</h3><p><a href="https://github.com/go-delve/delve">Delve</a> is a simple, full-featured debugging tool for Go. Run the following command to install Delve on the remote host.</p><pre>go get github.com/go-delve/delve/cmd/dlv</pre><p>Now we need to debug the remote application to control the debugging process through VS Code. VS Code Golang plugin will connect to the remote debugging server and send all Delve commands to the server for debugging. If you encounter problems with installation, please refer to the <a href="https://github.com/go-delve/delve/tree/master/Documentation/installation">golang installation document</a>. You can find multiple systems installation tutorial.</p><h3>Launch Remote Application</h3><p>We login to the remote host through ssh as usual. Then compile our applications with the following flag to allow Delve to collect advanced debugging information:</p><pre>-gcflags &quot;all=-N -l&quot;</pre><p>Then launch our application and find the process id of the application. If you use docker too, you can find the application process id like this:</p><pre>docker inspect -f &#39;{{.State.Pid}}&#39; &lt;container id&gt;</pre><p>Or, you can use the commandpgrep &lt;process name&gt; to retrieve the id no matter the way you launching applications.</p><h3>Use Delve to Start Debugging Server</h3><p>We’ll use a debugging client in the local machine through the VS Code. So, we need to start the debugging server in the remote host using theheadless option.</p><pre>dlv attach &lt;pid&gt; --listen=:2345 --headless --api-version=2 --log</pre><p>You can see the message like the following if successful:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*fOAPnCLKqaQh9yTKnPEFMg.png" /></figure><p>You can also use the command lsof -i:2345 to check the debugging server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k2CqC3SDbH411FSu4K3fvg.png" /></figure><p>If you encounter the following error:</p><pre>dlv attach error: could not attach to pid Xxx, could not open debug info</pre><p>It means that debug symbols are stripped out of your executable file. You can read the sections’ header to confirm that like following:</p><pre>readelf -S {executable_file}</pre><p>If the output doesn&#39;t include debug symbols like the followings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vE6TMz63zoaqqeGO6M8gBw.png" /></figure><p>Check your build command. In my experience, I used the-s option in the ldflags linker flag. This flag stripped all the symbol tables, including debug symbols.</p><p>Use Ctrl + C should stop the debugging server. However, there is a bug <a href="https://github.com/go-delve/delve/issues/1057">here</a>. We can use pgrep dlv and kill -9 &lt;pid&gt; as a substitute.</p><h3>Prepare Debugging Client</h3><p>Now we come back to our local machine. Open our project in VS Code and ensure the same branch with the remote host.</p><p>Open launch.json in VS Code.</p><pre>{<br>    &quot;name&quot;: &quot;Launch Remote&quot;,<br>    &quot;type&quot;: &quot;go&quot;,<br>    &quot;request&quot;: &quot;attach&quot;<br>    &quot;mode&quot;: &quot;remote&quot;,<br>    &quot;remotePath&quot;: &quot;{remote path}&quot;,<br>    &quot;port&quot;: 2345,<br>    &quot;host&quot;: &quot;{host}&quot;,<br>    &quot;cwd&quot;: &quot;${workspaceFolder}&quot;,<br>    &quot;trace&quot;: &quot;verbose&quot;<br>}</pre><p>Add a configuration like above. The remotePath means the project root path in the remote host. Go to your remote host and cd to your project, then run pwd , the result is the value of remotePath here.</p><p>We can see detailed messages with&quot;trace&quot;: &quot;verbose&quot; configuration in <strong>Debug Console</strong>.</p><p>Pay attention to the host . If you can connect to your remote host directly, then use your host address. In my case, I can only use ssh to access my remote host. So, I need to use ssh local forwarding to access to debug server.</p><pre>ssh -L 127.0.0.1:2345:localhost:2345 &lt;remote host ip&gt; -N</pre><p><strong>Start Debugging Client</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L3eBOZ-Mi71UHZhZcM3M1A.png" /></figure><p>Open <strong>Debug Extension</strong> in VS Code and run <strong>Launch Remote</strong>. You’ll see an overlay control panel in the VS Code like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*tTTz9MWvOqeTtk4BpkMx8w.png" /></figure><p>Now we can add breakpoints and control debugging steps through the VS Code.</p><p><strong>Unverified Breakpoints</strong></p><p>I suffered from this problem by adding breakpoints for the whole day. I checked my configurations, again and again. However, I didn’t find any problem. I always saw the following message at the <strong>Debug Console</strong>.</p><pre>Error on CreateBreakpoint: could not find file /xxx/xxx/xxx.go</pre><p>But I could find the file on the remote host. Finally, I checked my debug build command, and I found the flag trimpath . This flag will remove all file system paths from the resulting executable. So this is the reason why the debugging server cannot find the file. I removed this flag in the debug build solved the problem.</p><p>I hope this helps. Let me know if there are any mistakes or if an update outdated in the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a918de5d83f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Switch FileDownloader to OkDownload Seamlessly]]></title>
            <link>https://jerome-ran.medium.com/switch-filedownloader-to-okdownload-seamlessly-daf0fd2de5cc?source=rss-5c63ad963b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/daf0fd2de5cc</guid>
            <category><![CDATA[download]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[libraries]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jerome Ran]]></dc:creator>
            <pubDate>Fri, 08 Nov 2019 15:21:08 GMT</pubDate>
            <atom:updated>2020-12-25T03:25:15.179Z</atom:updated>
            <content:encoded><![CDATA[<h4>This article will show you how to switch FileDownloader to OkDownload seamlessly as much as possible.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nFLJJB3E9m39z49L3FHolw.jpeg" /></figure><p><a href="https://github.com/lingochamp/FileDownloader"><strong>FileDownloader</strong></a> is an excellent download engine for Android. It has multiple advantages.</p><ul><li>Simple to use.</li><li>Support independent process.</li><li>Download a single task with multiple blocks.</li><li>High-concurrency.</li><li>Support breakpoint.</li></ul><p>These advantages make FileDownloader accessible. However, FileDownloader isn’t lightweight enough, and the unit test coverage is deficient, and it’s tough to test.</p><p>I have to say that independent process support became a disadvantage because Android 8 has more strict limitations for background service. As a result, <strong>FileDownloadService</strong> must be perceptible when starting the download in the background. For compatibility with Android 8 and after, I add a new notification configuration since FileDownloader 1.7.6, and you can refer to <a href="https://github.com/lingochamp/FileDownloader/wiki/Compatibility-of-Android-O-Service">here</a> to know the detail. But it’s terrible to do system compatible work in a library. We cannot solve some bugs from the library’s point of view; for example, issue <a href="https://github.com/lingochamp/FileDownloader/issues/1209">1209</a>.</p><p>For further features and enhances, we develop a new library named <a href="https://github.com/lingochamp/okdownload"><strong>OkDownload</strong></a>. It extends all advantages of FileDownloader and owns more highlights. We’ve provided a detailed <a href="https://github.com/lingochamp/okdownload/wiki/Why-choose-OkDownload">wiki</a> to explain why to choose OkDownload.</p><p>OkDownload is lightweight. You can use the core library like this:</p><pre>// core<br>com.liulishuo.okdownload:okdownload:1.0.7-SNAPSHOT<br>// provide sqlite to store breakpoints<br>com.liulishuo.okdownload:sqlite:1.0.7-SNAPSHOT<br>// provide okhttp to connect to backend<br>com.liulishuo.okdownload:okhttp:1.0.7-SNAPSHOT</pre><p>If you want to use OkDownload, but you’re using FileDownload, you don’t want to rewrite all the code. Just add a new library:</p><pre>// use OkDownload and keep all your FileDownloader code effective<br>com.liulishuo.okdownload:filedownloader:1.0.7-SNAPSHOT</pre><p>I improved this library base on FileDownloader 1.7.7. So it’s better to upgrade your FileDownloader to 1.7.7 and then use this library. And the corresponding OkDownload version is 1.0.7-SNAPSHOT.</p><p>This is a specific example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0286eff49e4233be78ab37e43437153/href">https://medium.com/media/e0286eff49e4233be78ab37e43437153/href</a></iframe><p>Our goal is a seamless switch, so there is no spare change ideally. In most cases, it is. However, there always are some differences that cannot be flattened. The first big problem is the database. Not only FileDownloader but also OkDownload uses the database to save the breakpoint info. In OkDownload, the table structure and data structure is very different from FileDownloader. The migration work is backbreaking. In the meantime, OkDownload doesn’t use temp files, so the old file cannot be used in OkDownload despite the database data is migrated. In other words, the information about unfinished tasks save by FileDownloader will be useless after switching to OkDownload. But this isn’t a big problem for you, because OkDownload will re-download these files, and after that, everything will be fine. I provide a method named <strong>discardFileDownloadDatabase</strong> in the FileDownloader class. You can delete the old database as you wish. By the way, if you customed FileDownloadDatabase, it will not have any effect.</p><p>In FileDownloader, you can customize an <strong>IdGenerator</strong> to determine the task id, and it will not work at OkDownload anymore. Task id isn’t keeping the same. OkDownload may change it in the next start. If you have the logic base on the persisting task id, such as saving task id to the database, you need to change it because the task id is not invariable now. In the FileDownloader demo, we have a TasksManagerDemoActivity class to show how to manages multiple tasks. It did the thing I said before, and I have a <a href="https://github.com/lingochamp/FileDownloader/pull/1297">pull request</a> to show how to solve it.</p><p>OkDownload deprecated and removed many methods; most of them will not have a real influence on you. I sincerely hope you guys can try OkDownload 1.0.7-SNAPSHOT to switch your FileDownloader to OkDownload. And I have shown you a switch example through the <a href="https://github.com/lingochamp/FileDownloader/pull/1297">pull request</a>. It’s effortless for you guys, and I’m looking forward to your feedback; any question can open an issue on OkDownload.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=daf0fd2de5cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>